text:
package org.apache.fineract.portfolio.savings.data;

import java.math.BigDecimal;
import java.util.Collection;
import java.util.HashSet;

import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.fineract.infrastructure.core.data.EnumOptionData;
import org.apache.fineract.organisation.monetary.data.CurrencyData;
import org.apache.fineract.organisation.staff.data.StaffData;
import org.apache.fineract.portfolio.charge.data.ChargeData;
import org.apache.fineract.portfolio.tax.data.TaxGroupData;
import org.joda.time.LocalDate;

/**
 * Immutable data object representing a savings account.
 */
public class SavingsAccountData {

    private final Long id;
    private final String accountNo;
    private final EnumOptionData depositType;
    private final String externalId;
    private final Long groupId;
    private final String groupName;
    private final Long clientId;
    private final String clientName;
    private final Long savingsProductId;
    private final String savingsProductName;
    private final Long fieldOfficerId;
    private final String fieldOfficerName;
    private final SavingsAccountStatusEnumData status;
    private final SavingsAccountSubStatusEnumData subStatus;
    private final SavingsAccountApplicationTimelineData timeline;
    private final CurrencyData currency;
    private final BigDecimal nominalAnnualInterestRate;
    private final EnumOptionData interestCompoundingPeriodType;
    private final EnumOptionData interestPostingPeriodType;
    private final EnumOptionData interestCalculationType;
    private final EnumOptionData interestCalculationDaysInYearType;
    private final BigDecimal minRequiredOpeningBalance;
    private final Integer lockinPeriodFrequency;
    private final EnumOptionData lockinPeriodFrequencyType;
    private final boolean withdrawalFeeForTransfers;
    private final boolean allowOverdraft;
    private final BigDecimal overdraftLimit;
    private final BigDecimal minRequiredBalance;
    private final boolean enforceMinRequiredBalance;
    private final BigDecimal minBalanceForInterestCalculation;
    private final BigDecimal onHoldFunds;
    private final boolean withHoldTax;
    private final TaxGroupData taxGroup;
    private final LocalDate lastActiveTransactionDate;
    private final boolean isDormancyTrackingActive;
    private final Integer daysToInactive;
    private final Integer daysToDormancy;
    private final Integer daysToEscheat;

    // associations
    private final SavingsAccountSummaryData summary;
    @SuppressWarnings("unused")
    private final Collection<SavingsAccountTransactionData> transactions;

    private final Collection<SavingsAccountChargeData> charges;

    // template
    private final Collection<SavingsProductData> productOptions;
    private final Collection<StaffData> fieldOfficerOptions;
    private final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions;
    private final Collection<EnumOptionData> interestPostingPeriodTypeOptions;
    private final Collection<EnumOptionData> interestCalculationTypeOptions;
    private final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions;
    private final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions;
    private final Collection<EnumOptionData> withdrawalFeeTypeOptions;
    private final Collection<ChargeData> chargeOptions;

    @SuppressWarnings("unused")
    private final SavingsAccountChargeData withdrawalFee;
    @SuppressWarnings("unused")
    private final SavingsAccountChargeData annualFee;
    private final BigDecimal nominalAnnualInterestRateOverdraft;
    private final BigDecimal minOverdraftForInterestCalculation;

    public static SavingsAccountData instance(final Long id, final String accountNo, final EnumOptionData depositType,
            final String externalId, final Long groupId, final String groupName, final Long clientId, final String clientName,
            final Long productId, final String productName, final Long fieldOfficerId, final String fieldOfficerName,
            final SavingsAccountStatusEnumData status, SavingsAccountSubStatusEnumData subStatus, final SavingsAccountApplicationTimelineData timeline,
            final CurrencyData currency, final BigDecimal interestRate,
            final EnumOptionData interestCompoundingPeriodType, final EnumOptionData interestPostingPeriodType,
            final EnumOptionData interestCalculationType, final EnumOptionData interestCalculationDaysInYearType,
            final BigDecimal minRequiredOpeningBalance, final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType,
            final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary, final boolean allowOverdraft,
            final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance,
            final boolean enforceMinRequiredBalance, final BigDecimal minBalanceForInterestCalculation,
            final BigDecimal onHoldFunds, final BigDecimal nominalAnnualInterestRateOverdraft,
            final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup,
            final LocalDate lastActiveTransactionDate, final boolean isDormancyTrackingActive, final Integer daysToInactive,
            final Integer daysToDormancy, final Integer daysToEscheat) {

        final Collection<SavingsProductData> productOptions = null;
        final Collection<StaffData> fieldOfficerOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;

        final Collection<SavingsAccountTransactionData> transactions = null;
        final Collection<SavingsAccountChargeData> charges = null;
        final Collection<ChargeData> chargeOptions = null;

        return new SavingsAccountData(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId,
                productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, interestRate,
                interestCompoundingPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType,
                minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions,
                productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit,
                minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds,
                nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup,
                lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat);
    }

    public static SavingsAccountData lookup(final Long accountId, final String accountNo, final EnumOptionData depositType) {

        final String externalId = null;
        final Long productId = null;
        final Long groupId = null;
        final Long clientId = null;
        final String clientName = null;
        final String groupName = null;
        final String productName = null;
        final Long fieldOfficerId = null;
        final String fieldOfficerName = null;
        final SavingsAccountStatusEnumData status = null;
        final SavingsAccountApplicationTimelineData timeline = null;
        final CurrencyData currency = null;
        final BigDecimal nominalAnnualInterestRate = null;
        final EnumOptionData interestPeriodType = null;
        final EnumOptionData interestPostingPeriodType = null;
        final EnumOptionData interestCalculationType = null;
        final EnumOptionData interestCalculationDaysInYearType = null;
        final BigDecimal minRequiredOpeningBalance = null;
        final Integer lockinPeriodFrequency = null;
        final EnumOptionData lockinPeriodFrequencyType = null;
        // final BigDecimal withdrawalFeeAmount = null;
        // final EnumOptionData withdrawalFeeType = null;
        final boolean withdrawalFeeForTransfers = false;
        // final BigDecimal annualFeeAmount = null;
        // final MonthDay annualFeeOnMonthDay = null;
        // final LocalDate annualFeeNextDueDate = null;
        final boolean allowOverdraft = false;
        final BigDecimal overdraftLimit = null;
        final BigDecimal nominalAnnualInterestRateOverdraft = null;
        final BigDecimal minOverdraftForInterestCalculation = null;
        final BigDecimal minRequiredBalance = null;
        final boolean enforceMinRequiredBalance = false;
        final BigDecimal minBalanceForInterestCalculation = null;
        final BigDecimal onHoldFunds = null;

        final SavingsAccountSummaryData summary = null;
        final Collection<SavingsAccountTransactionData> transactions = null;

        final Collection<SavingsProductData> productOptions = null;
        final Collection<StaffData> fieldOfficerOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;

        final Collection<SavingsAccountChargeData> charges = null;
        final Collection<ChargeData> chargeOptions = null;
        final boolean withHoldTax = false;
        final TaxGroupData taxGroup = null;
        final SavingsAccountSubStatusEnumData subStatus = null;
        final LocalDate lastActiveTransactionDate = null;
        final boolean isDormancyTrackingActive = false;
        final Integer daysToInactive = null;
        final Integer daysToDormancy = null;
        final Integer daysToEscheat = null;

        return new SavingsAccountData(accountId, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId,
                productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate,
                interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType,
                minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions,
                productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit,
                minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds,
                nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup,
                lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat);
    }

    public static SavingsAccountData lookupWithProductDetails(final Long accountId, final String accountNo,
            final EnumOptionData depositType, final Long productId, final String productName, final SavingsAccountStatusEnumData status) {

        final String externalId = null;
        final Long groupId = null;
        final Long clientId = null;
        final String clientName = null;
        final String groupName = null;
        final Long fieldOfficerId = null;
        final String fieldOfficerName = null;
        final SavingsAccountApplicationTimelineData timeline = null;
        final CurrencyData currency = null;
        final BigDecimal nominalAnnualInterestRate = null;
        final EnumOptionData interestPeriodType = null;
        final EnumOptionData interestPostingPeriodType = null;
        final EnumOptionData interestCalculationType = null;
        final EnumOptionData interestCalculationDaysInYearType = null;
        final BigDecimal minRequiredOpeningBalance = null;
        final Integer lockinPeriodFrequency = null;
        final EnumOptionData lockinPeriodFrequencyType = null;
        // final BigDecimal withdrawalFeeAmount = null;
        // final EnumOptionData withdrawalFeeType = null;
        final boolean withdrawalFeeForTransfers = false;
        // final BigDecimal annualFeeAmount = null;
        // final MonthDay annualFeeOnMonthDay = null;
        // final LocalDate annualFeeNextDueDate = null;
        final boolean allowOverdraft = false;
        final BigDecimal overdraftLimit = null;
        final BigDecimal nominalAnnualInterestRateOverdraft = null;
        final BigDecimal minOverdraftForInterestCalculation = null;
        final BigDecimal minRequiredBalance = null;
        final boolean enforceMinRequiredBalance = false;
        final BigDecimal minBalanceForInterestCalculation = null;
        final BigDecimal onHoldFunds = null;

        final SavingsAccountSummaryData summary = null;
        final Collection<SavingsAccountTransactionData> transactions = null;

        final Collection<SavingsProductData> productOptions = null;
        final Collection<StaffData> fieldOfficerOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;

        final Collection<SavingsAccountChargeData> charges = null;
        final Collection<ChargeData> chargeOptions = null;
        final boolean withHoldTax = false;
        final TaxGroupData taxGroup = null;
        final SavingsAccountSubStatusEnumData subStatus = null;
        final LocalDate lastActiveTransactionDate = null;
        final boolean isDormancyTrackingActive = false;
        final Integer daysToInactive = null;
        final Integer daysToDormancy = null;
        final Integer daysToEscheat = null;

        return new SavingsAccountData(accountId, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId,
                productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate,
                interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType,
                minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions,
                productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit,
                minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds,
                nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup,
                lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat);
    }

    public static SavingsAccountData withTemplateOptions(final SavingsAccountData account, final SavingsAccountData template,
            final Collection<SavingsAccountTransactionData> transactions, final Collection<SavingsAccountChargeData> charges) {

        if (template == null) {
            final Collection<SavingsProductData> productOptions = null;
            final Collection<StaffData> fieldOfficerOptions = null;
            final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
            final Collection<EnumOptionData> interestCalculationTypeOptions = null;
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
            final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
            final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;
            final Collection<ChargeData> chargeOptions = null;

            return withTemplateOptions(account, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                    interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                    lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, transactions, charges, chargeOptions);
        }

        return new SavingsAccountData(account.id, account.accountNo, account.depositType, account.externalId, account.groupId,
                account.groupName, account.clientId, account.clientName, account.savingsProductId, account.savingsProductName,
                account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline,
                account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType,
                account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType,
                account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers,
                account.summary, transactions, template.productOptions, template.fieldOfficerOptions,
                template.interestCompoundingPeriodTypeOptions, template.interestPostingPeriodTypeOptions,
                template.interestCalculationTypeOptions, template.interestCalculationDaysInYearTypeOptions,
                template.lockinPeriodFrequencyTypeOptions, template.withdrawalFeeTypeOptions, charges, template.chargeOptions, account.allowOverdraft,
                account.overdraftLimit, account.minRequiredBalance, account.enforceMinRequiredBalance,
                account.minBalanceForInterestCalculation, account.onHoldFunds, account.nominalAnnualInterestRateOverdraft,
                account.minOverdraftForInterestCalculation, account.withHoldTax, account.taxGroup,
                account.lastActiveTransactionDate, account.isDormancyTrackingActive, account.daysToInactive,
                account.daysToDormancy, account.daysToEscheat);
    }

    public static SavingsAccountData withTemplateOptions(final SavingsAccountData account,
            final Collection<SavingsProductData> productOptions, final Collection<StaffData> fieldOfficerOptions,
            final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
            final Collection<EnumOptionData> interestCalculationTypeOptions,
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions,
            final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions, final Collection<EnumOptionData> withdrawalFeeTypeOptions,
            final Collection<SavingsAccountTransactionData> transactions, final Collection<SavingsAccountChargeData> charges,
            final Collection<ChargeData> chargeOptions) {

        return new SavingsAccountData(account.id, account.accountNo, account.depositType, account.externalId, account.groupId,
                account.groupName, account.clientId, account.clientName, account.savingsProductId, account.savingsProductName,
                account.fieldOfficerId, account.fieldOfficerName, account.status, account.subStatus, account.timeline,
                account.currency, account.nominalAnnualInterestRate, account.interestCompoundingPeriodType,
                account.interestPostingPeriodType, account.interestCalculationType, account.interestCalculationDaysInYearType,
                account.minRequiredOpeningBalance, account.lockinPeriodFrequency, account.lockinPeriodFrequencyType, account.withdrawalFeeForTransfers,
                account.summary, transactions, productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, account.allowOverdraft,
                account.overdraftLimit, account.minRequiredBalance, account.enforceMinRequiredBalance,
                account.minBalanceForInterestCalculation, account.onHoldFunds, account.nominalAnnualInterestRateOverdraft,
                account.minOverdraftForInterestCalculation, account.withHoldTax, account.taxGroup, account.lastActiveTransactionDate,
                account.isDormancyTrackingActive, account.daysToInactive, account.daysToDormancy, account.daysToEscheat);
    }

    public static SavingsAccountData withClientTemplate(final Long clientId, final String clientName, final Long groupId,
            final String groupName) {

        final Long id = null;
        final String accountNo = null;
        final EnumOptionData depositType = null;
        final String externalId = null;
        final Long productId = null;
        final String productName = null;
        final Long fieldOfficerId = null;
        final String fieldOfficerName = null;
        final SavingsAccountStatusEnumData status = null;
        final SavingsAccountApplicationTimelineData timeline = null;
        final CurrencyData currency = null;
        final BigDecimal nominalAnnualInterestRate = null;
        final EnumOptionData interestPeriodType = null;
        final EnumOptionData interestPostingPeriodType = null;
        final EnumOptionData interestCalculationType = null;
        final EnumOptionData interestCalculationDaysInYearType = null;
        final BigDecimal minRequiredOpeningBalance = null;
        final Integer lockinPeriodFrequency = null;
        final EnumOptionData lockinPeriodFrequencyType = null;
        // final BigDecimal withdrawalFeeAmount = null;
        // final EnumOptionData withdrawalFeeType = null;
        final boolean withdrawalFeeForTransfers = false;
        // final BigDecimal annualFeeAmount = null;
        // final MonthDay annualFeeOnMonthDay = null;
        // final LocalDate annualFeeNextDueDate = null;
        final boolean allowOverdraft = false;
        final BigDecimal overdraftLimit = null;
        final BigDecimal nominalAnnualInterestRateOverdraft = null;
        final BigDecimal minOverdraftForInterestCalculation = null;
        final BigDecimal minRequiredBalance = null;
        final boolean enforceMinRequiredBalance = false;
        final BigDecimal minBalanceForInterestCalculation = null;
        final BigDecimal onHoldFunds = null;
        final boolean withHoldTax = false;
        final TaxGroupData taxGroup = null;

        final SavingsAccountSummaryData summary = null;
        final Collection<SavingsAccountTransactionData> transactions = null;

        final Collection<SavingsProductData> productOptions = null;
        final Collection<StaffData> fieldOfficerOptions = null;
        final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestPostingPeriodTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationTypeOptions = null;
        final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions = null;
        final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions = null;
        final Collection<EnumOptionData> withdrawalFeeTypeOptions = null;

        final Collection<SavingsAccountChargeData> charges = null;
        final Collection<ChargeData> chargeOptions = null;
        final SavingsAccountSubStatusEnumData subStatus = null;
        final LocalDate lastActiveTransactionDate = null;
        final boolean isDormancyTrackingActive = false;
        final Integer daysToInactive = null;
        final Integer daysToDormancy = null;
        final Integer daysToEscheat = null;

        return new SavingsAccountData(id, accountNo, depositType, externalId, groupId, groupName, clientId, clientName, productId,
                productName, fieldOfficerId, fieldOfficerName, status, subStatus, timeline, currency, nominalAnnualInterestRate,
                interestPeriodType, interestPostingPeriodType, interestCalculationType, interestCalculationDaysInYearType,
                minRequiredOpeningBalance, lockinPeriodFrequency, lockinPeriodFrequencyType, withdrawalFeeForTransfers, summary, transactions,
                productOptions, fieldOfficerOptions, interestCompoundingPeriodTypeOptions,
                interestPostingPeriodTypeOptions, interestCalculationTypeOptions, interestCalculationDaysInYearTypeOptions,
                lockinPeriodFrequencyTypeOptions, withdrawalFeeTypeOptions, charges, chargeOptions, allowOverdraft, overdraftLimit,
                minRequiredBalance, enforceMinRequiredBalance, minBalanceForInterestCalculation, onHoldFunds,
                nominalAnnualInterestRateOverdraft, minOverdraftForInterestCalculation, withHoldTax, taxGroup,
                lastActiveTransactionDate, isDormancyTrackingActive, daysToInactive, daysToDormancy, daysToEscheat);
    }

    private SavingsAccountData(final Long id, final String accountNo, final EnumOptionData depositType, final String externalId,
            final Long groupId, final String groupName, final Long clientId, final String clientName, final Long productId,
            final String productName, final Long fieldofficerId, final String fieldofficerName, final SavingsAccountStatusEnumData status,
            final SavingsAccountSubStatusEnumData subStatus, final SavingsAccountApplicationTimelineData timeline, final CurrencyData currency,
            final BigDecimal nominalAnnualInterestRate, final EnumOptionData interestPeriodType,
            final EnumOptionData interestPostingPeriodType, final EnumOptionData interestCalculationType,
            final EnumOptionData interestCalculationDaysInYearType, final BigDecimal minRequiredOpeningBalance,
            final Integer lockinPeriodFrequency, final EnumOptionData lockinPeriodFrequencyType,
            final boolean withdrawalFeeForTransfers, final SavingsAccountSummaryData summary,
            final Collection<SavingsAccountTransactionData> transactions, final Collection<SavingsProductData> productOptions,
            final Collection<StaffData> fieldOfficerOptions,
            final Collection<EnumOptionData> interestCompoundingPeriodTypeOptions,
            final Collection<EnumOptionData> interestPostingPeriodTypeOptions,
            final Collection<EnumOptionData> interestCalculationTypeOptions,
            final Collection<EnumOptionData> interestCalculationDaysInYearTypeOptions, final Collection<EnumOptionData> lockinPeriodFrequencyTypeOptions,
            final Collection<EnumOptionData> withdrawalFeeTypeOptions, final Collection<SavingsAccountChargeData> charges, final Collection<ChargeData> chargeOptions,
            final boolean allowOverdraft, final BigDecimal overdraftLimit, final BigDecimal minRequiredBalance,
            final boolean enforceMinRequiredBalance, final BigDecimal minBalanceForInterestCalculation,
            final BigDecimal onHoldFunds, final BigDecimal nominalAnnualInterestRateOverdraft,
            final BigDecimal minOverdraftForInterestCalculation, final boolean withHoldTax, final TaxGroupData taxGroup,
            final LocalDate lastActiveTransactionDate, final boolean isDormancyTrackingActive, final Integer daysToInactive,
            final Integer daysToDormancy, final Integer daysToEscheat) {
        this.id = id;
        this.accountNo = accountNo;
        this.depositType = depositType;
        this.externalId = externalId;
        this.groupId = groupId;
        this.groupName = groupName;
        this.clientId = clientId;
        this.clientName = clientName;
        this.savingsProductId = productId;
        this.savingsProductName = productName;
        this.fieldOfficerId = fieldofficerId;
        this.fieldOfficerName = fieldofficerName;
        this.status = status;
        this.subStatus = subStatus;
        this.timeline = timeline;
        this.currency = currency;
        this.nominalAnnualInterestRate = nominalAnnualInterestRate;
        this.interestCompoundingPeriodType = interestPeriodType;
        this.interestPostingPeriodType = interestPostingPeriodType;
        this.interestCalculationType = interestCalculationType;
        this.interestCalculationDaysInYearType = interestCalculationDaysInYearType;
        this.minRequiredOpeningBalance = minRequiredOpeningBalance;
        this.lockinPeriodFrequency = lockinPeriodFrequency;
        this.lockinPeriodFrequencyType = lockinPeriodFrequencyType;
        // this.withdrawalFeeAmount = withdrawalFeeAmount;
        // this.withdrawalFeeType = withdrawalFeeType;
        this.withdrawalFeeForTransfers = withdrawalFeeForTransfers;
        // this.annualFeeAmount = annualFeeAmount;
        // this.annualFeeOnMonthDay = annualFeeOnMonthDay;
        // this.annualFeeNextDueDate = annualFeeNextDueDate;

        this.summary = summary;
        this.transactions = transactions;

        this.productOptions = productOptions;
        this.fieldOfficerOptions = fieldOfficerOptions;
        this.interestCompoundingPeriodTypeOptions = interestCompoundingPeriodTypeOptions;
        this.interestPostingPeriodTypeOptions = interestPostingPeriodTypeOptions;
        this.interestCalculationTypeOptions = interestCalculationTypeOptions;
        this.interestCalculationDaysInYearTypeOptions = interestCalculationDaysInYearTypeOptions;
        this.lockinPeriodFrequencyTypeOptions = lockinPeriodFrequencyTypeOptions;
        this.withdrawalFeeTypeOptions = withdrawalFeeTypeOptions;

        this.charges = charges;// charges associated with Savings account
        // charges available for adding to Savings account
        this.chargeOptions = chargeOptions;

        this.withdrawalFee = getWithdrawalFee();

        this.annualFee = getAnnualFee();
        this.allowOverdraft = allowOverdraft;
        this.overdraftLimit = overdraftLimit;
        this.nominalAnnualInterestRateOverdraft = nominalAnnualInterestRateOverdraft;
        this.minOverdraftForInterestCalculation = minOverdraftForInterestCalculation;
        this.minRequiredBalance = minRequiredBalance;
        this.enforceMinRequiredBalance = enforceMinRequiredBalance;
        this.minBalanceForInterestCalculation = minBalanceForInterestCalculation;
        this.onHoldFunds = onHoldFunds;
        this.withHoldTax = withHoldTax;
        this.taxGroup = taxGroup;
        this.lastActiveTransactionDate = lastActiveTransactionDate;
        this.isDormancyTrackingActive = isDormancyTrackingActive;
        this.daysToInactive = daysToInactive;
        this.daysToDormancy = daysToDormancy;
        this.daysToEscheat = daysToEscheat;
    }

    private SavingsAccountChargeData getWithdrawalFee() {
        for (SavingsAccountChargeData charge : this.charges()) {
            if (charge.isWithdrawalFee()) return charge;
        }
        return null;
    }

    private SavingsAccountChargeData getAnnualFee() {
        for (SavingsAccountChargeData charge : this.charges()) {
            if (charge.isAnnualFee()) return charge;
        }
        return null;
    }

    public Long id() {
        return this.id;
    }

    public Long clientId() {
        return this.clientId;
    }

    public Long groupId() {
        return this.groupId;
    }

    public Long productId() {
        return this.savingsProductId;
    }

    public CurrencyData currency() {
        return this.currency;
    }

    @Override
    public boolean equals(final Object obj) {

        if (obj == null) { return false; }
        if (obj == this) { return true; }
        if (obj.getClass() != getClass()) { return false; }
        final SavingsAccountData rhs = (SavingsAccountData) obj;
        return new EqualsBuilder().append(this.id, rhs.id).append(this.accountNo, rhs.accountNo).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(this.id).append(this.accountNo).toHashCode();
    }

    public Collection<SavingsAccountChargeData> charges() {
        return (this.charges == null) ? new HashSet<SavingsAccountChargeData>() : this.charges;
    }
}


text:
/*
  Copyright 2011  Dean Camera (dean [at] fourwalledcubicle [dot] com)

  Permission to use, copy, modify, distribute, and sell this
  software and its documentation for any purpose is hereby granted
  without fee, provided that the above copyright notice appear in
  all copies and that both that the copyright notice and this
  permission notice and warranty disclaimer appear in supporting
  documentation, and that the name of the author not be used in
  advertising or publicity pertaining to distribution of the
  software without specific, written prior permission.

  The author disclaim all warranties with regard to this
  software, including all implied warranties of merchantability
  and fitness.  In no event shall the author be liable for any
  special, indirect or consequential damages or any damages
  whatsoever resulting from loss of use, data or profits, whether
  in an action of contract, negligence or other tortious action,
  arising out of or in connection with the use or performance of
  this software.
*/

/** \file
 *
 *  Header file for RFCOMMControl.c.
 */

#ifndef _RFCOMM_CONTROL_H_
#define _RFCOMM_CONTROL_H_

	/* Includes: */
		#include <avr/io.h>
		#include <avr/pgmspace.h>
		#include <string.h>
		#include <stdbool.h>
		#include <stdio.h>

		#include <LUFA/Common/Common.h>
		#include <LUFA/Drivers/Peripheral/Serial.h>

		#include "BluetoothStack.h"
		#include "RFCOMM.h"

	/* Macros: */
		#define RFCOMM_SIGNAL_FC               (1 << 1)
		#define RFCOMM_SIGNAL_RTC              (1 << 2)
		#define RFCOMM_SIGNAL_RTR              (1 << 3)
		#define RFCOMM_SIGNAL_IC               (1 << 6)
		#define RFCOMM_SIGNAL_DV               (1 << 7)

		#define RFCOMM_CONFIG_REMOTESIGNALS    (1 << 0)
		#define RFCOMM_CONFIG_LOCALSIGNALS     (1 << 1)
		#define RFCOMM_CONFIG_LOCALSIGNALSSENT (1 << 2)
		#define RFCOMM_CONFIG_ABMMODESET       (1 << 3)

	/* Enums: */
		enum RFCOMM_Control_Commands_t
		{
			RFCOMM_Control_Test                    = (0x20 >> 2),
			RFCOMM_Control_FlowControlEnable       = (0xA0 >> 2),
			RFCOMM_Control_FlowControlDisable      = (0x60 >> 2),
			RFCOMM_Control_ModemStatus             = (0xE0 >> 2),
			RFCOMM_Control_RemotePortNegotiation   = (0x90 >> 2),
			RFCOMM_Control_RemoteLineStatus        = (0x50 >> 2),
			RFCOMM_Control_DLCParameterNegotiation = (0x80 >> 2),
			RFCOMM_Control_NonSupportedCommand     = (0x10 >> 2),
		};

	/* Type Defines: */
		typedef struct
		{
			unsigned EA   : 1;
			unsigned CR   : 1;
			unsigned DLCI : 6;
		} RFCOMM_Address_t;

		typedef struct
		{
			RFCOMM_Address_t Address;
			uint8_t          Control;
		} RFCOMM_Header_t;

		typedef struct
		{
			unsigned EA      : 1;
			unsigned CR      : 1;
			unsigned Command : 6;
		} RFCOMM_Command_t;

		typedef struct
		{
			uint8_t  DLCI;
			unsigned FrameType        : 4;
			unsigned ConvergenceLayer : 4;
			uint8_t  Priority;
			uint8_t  ACKTimerTicks;
			uint16_t MaximumFrameSize;
			uint8_t  MaxRetransmissions;
			uint8_t  RecoveryWindowSize;
		} RFCOMM_DPN_Parameters_t;

		typedef struct
		{
			RFCOMM_Address_t Channel;
			uint8_t          Signals;
			uint8_t          BreakSignal;
		} RFCOMM_MSC_Parameters_t;

	/* Function Prototypes: */
		void RFCOMM_ProcessControlCommand(const uint8_t* Command,
		                                  Bluetooth_Channel_t* const Channel);

		#if defined(INCLUDE_FROM_RFCOMM_CONTROL_C)
			static void RFCOMM_ProcessTestCommand(const RFCOMM_Command_t* const CommandHeader,
			                                      const uint8_t CommandDataLen,
			                                      const uint8_t* CommandData,
			                                      Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessFCECommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessFCDCommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessMSCCommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t CommandDataLen,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessRPNCommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessRLSCommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
			static void RFCOMM_ProcessDPNCommand(const RFCOMM_Command_t* const CommandHeader,
			                                     const uint8_t* CommandData,
			                                     Bluetooth_Channel_t* const ACLChannel);
		#endif

#endif

redpajama_set_name: RedPajamaGithub


text:
@interface BBShareCell : UICollectionViewCell

@property (weak, nonatomic) IBOutlet BBShareCellView *mainView;

@end


text:
marp: true

---

<style>
img[alt~="center"] {
  display: block;
  margin: 0 auto;
}
</style>

# Neural Networks

<!--
So far we have used classic machine learning models. These models are powerful and have proven useful for a wide range of applications.

It's likely you have heard about neural networks and deep learning. These concepts are in vogue right now. Depending on your perspective, deep learning and neural networks are either going to be a giant leap forward for humanity, are going to destroy us all, or are over-hyped tools with limited application.

There is likely a little bit of truth to each of these opinions.
-->

---

# Neural Networks: Good?

![center](res/car.jpg)

<!--
Deep learning is a giant leap forward for humanity. We can now program machines to excel at tasks that we once thought only humans could master. Computers can drive cars, interpret medical imaging, create art, and play complex games at a human expert-level or better.

* Image name: res/car.jpg
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/car.jpg
  * Source https://pixabay.com/photos/vehicle-autonomous-4759347/ by Author Falco / https://pixabay.com/users/falco-81448/ under License https://pixabay.com/service/license/.
-->

---

# Neural Networks: Bad?

![center](res/terminator.jpg)

<!--
There is also the fear that deep learning will have huge negative impacts on society. The images of a terminator are likely overblown, but there is real concern that advanced deep learning algorithms will have negative effects on some people.

Disruptive technologies like self-driving cars will displace millions of workers.

Societal bias, conscious or not, can become encoded in deep learning algorithms, multiplying and normalizing the negative effects that have existed for decades.

When using deep learning, great care must be taken to remove bias and to understand the implications of mass application of the algorithms.

* Image name: res/terminator.jpg
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/terminator.jpg
  * Source https://pixabay.com/illustrations/bot-cyborg-robot-helper-arm-chair-4875211/ by Author Sergeitokmakov / Sergei Tokmakov https://pixabay.com/users/sergeitokmakov-3426571/ under License https://pixabay.com/service/license/.
-->

---

# Neural Networks: Hype?

![center](res/hype.jpg)

<!--
And finally, there are those who think deep learning and neural networks are just hype. For every person who thinks a technological revolution is around the corner, there is another pointing out how specialized and controlled the environment has to be for machine learning algorithms to perform well.

Deep learning doesn't progress at an even pace. We are currently in a deep learning boom, but this has happened before. There have been a few "AI winters" where researchers thought that we were on the cusp of a revolution, only to have research in neural networks go dormant for a while.

We'd like to think that this time might be different. Computation is finally fast enough and has enough scale that algorithms designed decades ago can finally be implemented and trained in an effective manner.

Only time will tell if deep learning can live up to expectations. What we can do now is learn about it, be thoughtful about how we train and use it, and continue to innovate cautiously.

* Image name: res/hype.jpg
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/hype.jpg
  * Source https://unsplash.com/photos/NrtC3y108Ys by Author Verena Yunita Yapi https://unsplash.com/@verenayunita under License https://unsplash.com/license.
-->

---

# History & Motivation

<!--
Let's first look at some history and motivation for neural networks.
-->

---

# Neural Networks: Inspired by Nature

![center](res/nature.png)

<!--
We've talked about what people think neural networks can and cannot do, but we really haven't talked about what neural networks are. And why are they even called neural networks?

Nature can be a source of inspiration. Birds inspired man to fly. The burdock plant was the inspiration for velcro. Even in the computer science realm we hear references to trees, forests, and other things that occur in nature.

* Image name: res/nature.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/nature.png
  * Source https://pixabay.com/photos/burdock-thistle-prickly-stick-barb-745306/ by Author nidan / Heiko Stein https://pixabay.com/users/nidan-455298/ under License https://pixabay.com/service/license/.
  * Source https://pixabay.com/photos/nike-baby-shoes-shoe-baby-velcro-1201595/ by Author FotoRieth https://pixabay.com/users/fotorieth-837884/ under License https://pixabay.com/service/license/.
  * Source https://pixabay.com/photos/bird-seagull-flying-wings-gull-3158784/ by Author Atlantios / Antonios Ntoumas https://pixabay.com/users/atlantios-4957810/ under License https://pixabay.com/service/license/.
  * Source https://pixabay.com/photos/plane-aircraft-take-off-sky-50893/ by Author Holgi / Holger Detje https://pixabay.com/users/holgi-5825/ under License https://pixabay.com/service/license/.
-->

---

# Neural Networks: Inspired by Nature

![center](res/neuron.png)

<!--
Similar to the examples in the last slide, neural networks are inspired by nature. The brain contains a massive network of neurons that send electrical signals that activate other neurons. Through this network we are able to think.

This is the building block of the brain: a neuron.

A neuron is just a cell with a nucleus and cell body like any other cell. One of the distinguishing features of the neuron is the 'axon,' which is the long tail of the neuron. The tip of the axon has synaptic terminals that attach to other neuron bodies. A neuron body receives signals from the synapse of neurons before it. When those signals reach a critical point within a fixed period of time, the receiving neuron fires, sending a signal to later neurons.

Neural networks were inspired by neurons and connections between neurons in the brain, hence the name.

* Image name: res/neuron.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/neuron.png
  * Source https://pixabay.com/vectors/neuron-nerve-cell-axon-dendrite-296581/ by Author Clker-Free-Vector-Images https://pixabay.com/users/clker-free-vector-images-3736/ under License https://pixabay.com/service/license/.
-->

---

# Neural Networks: Inspired by Nature
![center](res/neurons.jpg)

<!--
This builds a web of neurons called a "neural network."

This simplification of the brain signaling pathway led to research into "artificial neural networks" with different types of neurons.

Beyond this network effect, the concept of neural networks tends to break away from biology. Similarly, birds inspired flight, but modern airplanes don't flap their wings.

We find inspiration in nature. We don't have to copy it.

* Image name: res/neurons.jpg
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/neurons.jpg
  * Source https://pixabay.com/illustrations/neurons-brain-cells-brain-structure-1773922/ by Author geralt / Gerd Altmann https://pixabay.com/users/geralt-9301/ under License https://pixabay.com/service/license/.
-->

---

# Neural Networks: Cutting Edge

![center](res/einstein.jpg)

<!--
When did neural networks originate? The 1940s.

1940s! I thought neural networks were cutting edge?

Many of the fundamental algorithms we use today are rooted in thought experiments from the 1940s, but it has been a long journey from then to where we are today.

The computing power and data storage that we have today is nearly unimaginable compared to what was available even in the recent past. Also, many of the early ideas were foundational, but they have been improved upon over time.

The idea of deep learning is not new. There were even a few "AI winters" over the last 80 years that stalled development and research in deep learning. It feels like we might finally be at a point where the theoretical ideas of the past can be fulfilled with the technologies of today.

* Image name: res/einstein.jpg
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/einstein.jpg
  * Source https://pixabay.com/photos/albert-einstein-scientists-physicist-62931/ by Author WikiImages https://pixabay.com/users/wikiimages-1897/ under License https://pixabay.com/service/license/.
-->

---

# Artificial Neural Networks (ANN)

<!--
Today we will talk about artificial neural networks. These are computational networks inspired by biological systems.

ANN is a big umbrella. There are "feed-forward" networks. There is a concept of "backpropagation." And there are specific types of networks such as convolutional neural networks (CNN) and recurrent neural networks (RNN) that we will look at in more detail in future units.
-->

---

# Artificial Neural Networks (ANN)

![center](res/ann.png)

<!--
These are the typical diagrams you see to depict an artificial neural network. On the left we have our "input layer." This is where we feed our feature data into the model. In these two diagrams, there are three features (depicted by the two blue dots on the far left of the schematic).

The feature information then flows into "hidden layers." In these hidden layers, mathematical operations are performed to extract patterns from the feature data. We'll talk more about this math on future slides.

Finally, the transformed feature data flows to the output layer, which returns our predicted target values.

The main idea is that if neurons in one layer "fire." Then, using the connections to the next layer, we can determine which neurons in the next layer will fire. For now, it is useful to think of a neuron firing as a 1 and not firing as a 0. It is true that more sophisticated neural networks take into account the intensity of a "fire" (i.e., fired at 50% vs fired at 100%), but for the sake of discussion, let's stick with the 1 or 0 model.

* Image name: res/ann.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/ann.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/ann.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron

![center](res/perceptron.png)

<!--
In 1958, an American psychologist named Frank Rosenblatt attempted to build a machine called a perceptron.

We can think of the perceptron as the building block of neural networks. The perceptron has no hidden layers. We feed our features into the left side, do computation, and receive a predicted target.

This looks strikingly similar to the models we've been building in this course. And that's no accident! We can think of a linear regression model as a perceptron.

But what are those mystery computations that take place on the black lines? There are weights, w_{1}, ..., w_{m}, that are used in these computations. How does that work? Let's look closer at what's happening behind the scenes along those black lines.

* Image name: res/perceptron.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron

![center](res/perceptron2.png)

<!--
The green and blue compartments show the computations taking place in the connections between the input layer and output layer of a perceptron.

The features are denoted by x_{i}. The weights w_{i} are playing the same role as the weights in our linear regression model. If we build a weight vector W = [w_{1}, w_{2}, ..., w_{m}] and a feature vector X = [x_{1}, x_{2}, ..., x_{m}], then the green computation is simply W^{T}X + b (which is exactly the same as the target in a regression model: bias + w_{1}x_{1} + w_{2}x_{2} + ... + w_{m}x_{m}).

This information is then sent to an "activation function," which uses the information from the green computation to determine whether or not the next neuron should fire. In a linear regression example, the activation function might be f(x) = x. In other words, the activation function plays no role. But let's look at a slightly more interesting example and walk through these details in a little more depth.

* Image name: res/perceptron2.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron2.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron2.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example.png)

<!--
Suppose we want to predict whether an individual will start studying machine learning. Our features are given by:
x_{1} = will the person make more money?
x_{2} = does the person love programming and mathematics?
x_{3} = does the person have a project that would benefit from ML?

We compute W^{T}X = w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{3} + bias.

Now assume that we will say "yes": the person will study machine learning if the result is >= 0 and "no": the person will not study machine learning if the result is < 0.

*It might be helpful to flip back to the previous slide and explain that the specific activation function we're working with in this example is f(x) = 1 if W^{T}X + b >= 0 and f(x) = 0 if W^{T}X + b < 0. Also, for notational convenience, we flip the sign of b and write w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{3} - b going forward. If we use this model, then the algorithm will learn a negated form of b.*

That is, we ask is w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{3} - bias >= 0? Which is the same as asking is w_{1}x_{1} + w_{2}x_{2} + w_{3}x_{3} >= b. For convenience, we have relabeled b as -b.

* Image name: res/perceptron_example.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Machine Learning Process

1. Infer/Predict/Forecast
1. Calculate Error/Loss/Cost
1. Train/Learn
1. Iterate (until some stopping condition)

<!--
Let's recall the general machine learning process. This is the same process that we use for all ML models.
-->

---

# Perceptron Example

![center](res/perceptron_example_01.png)

<!--
Let's assume we already have our weights and bias. We say that x_{1} and x_{2} have an equal impact on a person's decision to study ML, and they both have weight 2. Assume that x_{3} is three times as important in a person's decision to study ML, so its weight is 6. Now let's assume the bias is 5. In other words, we are thresholding at 5, and we say if W^{T}X >= 5, then the person will study machine learning. If W^{T}X < 5, then the person will not study machine learning.

Let's take a second to think about these numbers critically and see what they really mean.

* Image name: res/perceptron_example_01.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_01.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_01.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example_02.png)

<!--

Let's assume a particular person, Kelly, does not stand to make more money by studying ML and she does not like programming and math (x_{1} = x_{2} = 0). But assume that Kelly does have a project that would benefit from ML (x_{3} = 1).

* Image name: res/perceptron_example_02.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_02.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_02.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example_03.png)

<!--
Computing W^{T}X we get 6.

We check that 6 is >= 5, so we say "yes": Kelly will study machine learning.

* Image name: res/perceptron_example_03.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_03.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_03.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example_04.png)

<!--
Now let's assume we have another person, Riley, who will make more money in her job by learning ML and she does like programming and math (x_{1} = x_{2} = 1), but she does not have a project that would benefit from ML (x_{3}=0).

* Image name: res/perceptron_example_04.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_04.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_04.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example_05.png)

<!--
Computing W^{T}X we get 4.

We check that 4<5, so the model predicts "no": Riley will not study ML.

In general, this is how we feed input data into our model. If the model had already finished learning the weights and bias, then this is how we would generate our predicted targets.

* Image name: res/perceptron_example_05.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_05.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_05.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Networks With Hidden Layers

![center](res/hidden_layers.png)

<!--
If we had a network with more layers, then the same process is happening between each layer. We can think of this as many perceptrons stacked on top of each other.

For example, in the input layer we have X = [x_{1}, ..., x_{m}]. All these nodes are connected to node h_{1}^{1}. There are weights assigned to each of these that we can combine into a vector, W_{1}^{1}. Then W_{1}^{1}^{T}X + b can be thought of as a perceptron.

Similarly, all the nodes in the first hidden layer are connected to h_{1}^{2}. All these connections have their own individual weights. And this part of the network can be thought of as its own perceptron.

Thus, feeding data through the hidden layers is equivalent to a composition of many matrix multiplications.

* Image name: res/hidden_layers.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/hidden_layers.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/hidden_layers.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Perceptron Example

![center](res/perceptron_example_06.png)

<!--
But how does the model actually update the weights and bias during the learning process?

Let's look back at our example. Note that both of these samples were technically training data. From our dataset, we know that both Kelly and Riley did study ML (y=1), but for Kelly we predicted \hat{y} = 1, and for Riley we predicted \hat{y} = 0. So Kelly's prediction was correct, while Riley's was not correct.

Now the model needs to adjust the weights. It seems like if a person stands to make more money from studying ML AND they love programming and math, then the model should predict a 1 (whether or not they have a current project that would benefit from ML).

So the model needs to update the weights and bias via some optimization algorithm like gradient descent. In order to compute the derivative (gradient) to discern the direction of steepest descent, we will need to unravel the many compositions of matrix multiplication. If you remember your calculus, how do we take the derivative of a composition? The chain rule! That is effectively what backpropagation does. It is a way to compute the gradient when many chain rules are involved through each layer of the network.

* Image name: res/perceptron_example_06.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_06.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/perceptron_example_06.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Machine Learning Process

1. Infer/Predict/Forecast
    * Compute f(X, W, B) - compositions of f and lots of matrix mult
1. Calculate Error/Loss/Cost
    * MSE, MAE, etc.
1. Train/Learn
    * Change W and B in direction to minimize cost
    * Gradient descent -> derivative -> chain rule -> backpropagation
1. Iterate (until some stopping condition)

<!--
Let's put everything together and summarize how a neural network will learn in general. It shouldn't surprise you that it's the same machine learning process that we've been working with for all our models. Now we've just filled it with some high-level details of each step for neural networks.
-->

---

# Issues with this plan?

````
f(x) =  1 if x ≥ 0
        0 if x < 0
````

The step function, f, is not the greatest activation function.
* `f` is not differentiable at 0
* `f'(x) = 0` for all x other than 0
* `f` only returns 0 or 1 (as opposed to a confidence)

<!--
There are many possible activation functions, and some work better than others in certain situations.

Let's take a closer look at the activation function we used in our simple example. This function is called a step-function.

There are a few drawbacks to using the step-function.
* f is not differentiable at 0. This could create problems for gradient descent when we need to take a derivative.
* f'(x) is 0 whenever x is not 0. This could also create problems for gradient descent. If we ever multiply by f'(x), the entire function will go to 0, which means no slope. So it can be hard to determine the direction of steepest descent.
* f only returns a no or a yes. It would be preferable for f to return a continuous value between 0 and 1. For example, if f returned .9, then we would say that we're 90% confident the answer is "yes, this person will study ML." That is far more powerful than just returning a "yes" or "no." We will discuss this further in the section on classification.

-->

---

# Sigmoid

![center](res/sigmoid.png)

<!--
The sigmoid function is a far more popular activation function, as it addresses the issues we just discussed with the step-function. Again, we will talk more about this when we get to classification.

* Image name: res/sigmoid.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/sigmoid.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/sigmoid.png by Author Google LLC under License Copyright [2020] Google LLC.
-->

---

# Activation Functions

![center](res/neurnet10.png)

<!--
The choice of activation function is important. RELU makes differentiation difficult, but it actually works really well in practice. The other functions are also very useful.

It is important to note that why certain activation functions behave in certain ways is an active area of research. People are testing new ones every day. Sometimes there is good theoretical justification for using a particular activation function, and sometimes we use a particular activation function simply because it trained quickly and gave us good results in practice.

* Image name: res/neurnet10.png
  * Repo link: https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/neurnet10.png
  * Source https://github.com/google/applied-machine-learning-intensive/tree/master/content/03_regression/07_neural_networks/res/neurnet10.png by Author Google LLC under License Copyright [2020] Google LLC.
-->


text:
cask "font-tenali-ramakrishna" do
  version :latest
  sha256 :no_check

  url "https://github.com/google/fonts/raw/main/ofl/tenaliramakrishna/TenaliRamakrishna-Regular.ttf",
      verified: "github.com/google/fonts/"
  name "Tenali Ramakrishna"
  homepage "https://fonts.google.com/specimen/Tenali+Ramakrishna"

  font "TenaliRamakrishna-Regular.ttf"
end


text:
package org.voovan.docker.message.task.atom;

/**
 *
 * @author helyho
 * <p>
 * DockerFly Framework.
 * WebSite: https://git.oschina.net/helyho/JDocker
 * Licence: Apache v2 License
 */
public class ContainerStatus {
    private String containerId;
    private String pid;

    public String getContainerId() {
        return containerId;
    }

    public void setContainerId(String containerId) {
        this.containerId = containerId;
    }

    public String getPid() {
        return pid;
    }

    public void setPid(String pid) {
        this.pid = pid;
    }
}


text:
[ ![Download](https://travis-ci.com/CactusSoft/Cactus.Fileserver.svg?branch=develop) ](https://travis-ci.com/CactusSoft/Cactus.Fileserver)
[ ![Download](https://codecov.io/gh/CactusSoft/Cactus.Fileserver/graph/badge.svg) ](https://codecov.io/gh/CactusSoft/Cactus.Fileserver)

Simple lib for fast building your own file storage microservice. Implemented as OWIN handler for Katana as welll as Asp.NetCore.

Look at LocalFileserverExample for details.

Features:
- HTTP POST (multipart & not) to upload a file
- HTTP DELETE to drop a file
- Supporting S3 & Azure BLOB storages. Returns direct URL to stored file.
- Flexible piplene for new adding files
- Supports local filesystem storage for simple projects & dev environment


text:
require 'spec_helper'

describe AdvisoryRepository do
  let(:mock_advisories) do
    advisories = [double('actionpack_1'), double('activerecord_1'), double('actionpack_2')]
    advisories[0].stub(:gem).and_return('actionpack')
    advisories[1].stub(:gem).and_return('activerecord')
    advisories[2].stub(:gem).and_return('actionpack')
    advisories
  end
  subject { AdvisoryRepository.new(mock_advisories)}

  context '#[]' do
    it 'returns gem advisory' do
      advisories = subject['activerecord']
      advisories.length.should == 1
      advisories[0] == mock_advisories[1]
    end

    it 'groups advisories by gem' do
      advisories = subject['actionpack']
      advisories.length.should == 2
      advisories[0] == mock_advisories[0]
      advisories[1] == mock_advisories[2]
    end

    it 'returns empty array when gem not found' do
      subject['unknown'].should == []
    end
  end

  context '#check_for_unsafe_versions' do
    it 'returns empty array if no advisories found' do
      spec = Bundler::LazySpecification.new('unknown', '2.3.5', nil)
      subject.check_for_unsafe_versions(spec).should == []
    end

    it 'returns empty array if no vulnerable versions found' do
      mock_advisories[0].should_receive(:version_safe?).and_return(true)
      mock_advisories[2].should_receive(:version_safe?).and_return(true)

      spec = Bundler::LazySpecification.new('actionpack', '2.3.5', nil)
      subject.check_for_unsafe_versions(spec).should == []
    end

    it 'returns advisory for vulnerable version' do
      mock_advisories[0].should_receive(:version_safe?).and_return(true)
      mock_advisories[2].should_receive(:version_safe?).and_return(false)

      spec = Bundler::LazySpecification.new('actionpack', '2.3.5', nil)
      subject.check_for_unsafe_versions(spec).should == [mock_advisories[2]]
    end

    it 'returns array of all vulnerable versions' do
      mock_advisories[0].should_receive(:version_safe?).and_return(false)
      mock_advisories[2].should_receive(:version_safe?).and_return(false)

      spec = Bundler::LazySpecification.new('actionpack', '2.3.5', nil)
      subject.check_for_unsafe_versions(spec).should == [mock_advisories[0], mock_advisories[2]]
    end
  end

  context '#load' do
    let(:cli) { double('cli')}
    it "gets advisory store if it doesn't exist" do
      cli.stub(:git_dir).and_return('/git_dir')
      cli.stub(:advisory_url).and_return('http://advisory-url')

      AdvisoryRepository.should_receive(:git_dir_exists?).with('/git_dir').and_return(false)
      AdvisoryRepository.should_receive(:clone_advisory_repo).with('http://advisory-url', '/git_dir').and_return(['success', 0])
      AdvisoryRepository.should_receive(:advisory_files).with('/git_dir').and_return(%w(file1 file2))

      Advisory.should_receive(:load).with('file1').and_return(mock_advisories[0])
      Advisory.should_receive(:load).with('file2').and_return(mock_advisories[2])

      repo = AdvisoryRepository.load(cli)
      repo['actionpack'].length.should == 2
    end

    it 'uses existing store' do
      cli.stub(:git_dir).and_return('/git_dir')
      cli.stub(:advisory_url).and_return('http://advisory-url')

      AdvisoryRepository.should_receive(:git_dir_exists?).with('/git_dir').and_return(true)
      AdvisoryRepository.should_receive(:update_git_dir).with('/git_dir').and_return(['success', 0])
      AdvisoryRepository.should_receive(:advisory_files).and_return(%w(file1 file2))

      Advisory.should_receive(:load).with('file1').and_return(mock_advisories[0])
      Advisory.should_receive(:load).with('file2').and_return(mock_advisories[2])

      repo = AdvisoryRepository.load(cli)
      repo['actionpack'].length.should == 2
    end

    it 'throws an error when clone fails' do
      cli.stub(:git_dir).and_return('/git_dir')
      cli.stub(:advisory_url).and_return('http://advisory-url')

      AdvisoryRepository.should_receive(:git_dir_exists?).with('/git_dir').and_return(false)
      AdvisoryRepository.should_receive(:clone_advisory_repo).with('http://advisory-url', '/git_dir').and_return(['git clone failed', 1])

      expect { AdvisoryRepository.load(cli) }.to raise_error(RepositoryDownloadException, 'git clone failed')
    end

    it 'throws an error when update fails' do
      cli.stub(:git_dir).and_return('/git_dir')
      cli.stub(:advisory_url).and_return('http://advisory-url')

      AdvisoryRepository.should_receive(:git_dir_exists?).with('/git_dir').and_return(true)
      AdvisoryRepository.should_receive(:update_git_dir).with('/git_dir').and_return(['git update failed', 1])

      expect { AdvisoryRepository.load(cli) }.to raise_error(RepositoryUpdateException, 'git update failed')
    end
  end

  context '#execute' do
    it 'can run a valid command and get stdout and exit code' do
      output, exit_code = AdvisoryRepository.send(:execute, 'echo TEST')
      output.should == "TEST\n"
      exit_code.should == 0
    end

    it 'can a run an invalid command and get stdout and exit code' do
      output, exit_code = AdvisoryRepository.send(:execute, 'ls 45fdgfg')
      output.should == "ls: cannot access 45fdgfg: No such file or directory\n"
      exit_code.should == 2
    end

    it 'can run an valid command and get stderr and exit code' do
      output, exit_code = AdvisoryRepository.send(:execute, 'ruby -e \'warn "This message goes to stderr"\'')
      output.should == "This message goes to stderr\n"
      exit_code.should == 0
    end
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:layout_height="wrap_content"
    android:background="@drawable/selector_medium_high"
    android:orientation="horizontal">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rowIcon"
        android:paddingLeft="16dp"
        android:src="@drawable/ic_launcher"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="4dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/rowText" />

</LinearLayout>


text:
id: ps-wechatpay
title: Payment Method - Wechat Pay
permalink: payment-method/wechatpay
sectionid: docs-ps
---

Wechat Pay

WeChat Pay is a digital wallet service incorporated into WeChat, which allows users to perform payments with WeChat application.

***

## Payment flow

* Use WeChat application to scan QR code.

* Confirm and complete payment in WeChat application.

* Paymentwall payment result page.

#### Wechat Pay

***

|name|description|
|:--|:--|
|Countries| Globally except [sanctioned countries and entities](https://www.paymentwall.com/faq/sanctioned-countries-and-entities) |
|Type|E-Wallets|
|Processing currencies|[CNY](https://en.wikipedia.org/wiki/Renminbi)|
|Supported currencies| Refer to [currency codes](/reference/currencies)|
|Payment confirmation time|Instant|
|Payout time frame| NET 30|
|Chargebacks|Yes|
|Refunds|Yes|
|Onboarding required|Yes|
|Recurring Payments|No|
|Mobile UI|Yes, Native UI available with [Mobile SDK](/mobile/home)|
|Opens new window|No|
|Min Transaction Limit|0.3 USD or equivalent currencies|

***

Available models:

* **Merchant**.

Included with your Paymentwall account.

* **MOR**.

[Terminal 3](https://www.terminal3.com/).


text:
Spotfire can read table data from different type of files.

But there are two native Spotfire formats:

- STDF (Spotfire Text Data File) format
- SBDF (Spotfire Binary Data File) format

Both supported by the [Rocket Table](https://xantorohara.github.io/rocket-table/)

Rocket Table is a lightweight table viewer for files in SAS7BDAT, SBDF, STDF and CSV formats.
It supports sime nice features like: filtering, sorting, highlighting.
It is cross-platform and minimalistic.

So if you have *\*.sbdf* or *\*.stdf* files, but don't have Spotfire,
you are able to read these files using this application.

![Rocket Table](https://xantorohara.github.io/howto-spotfire/spotfire-sbdf-stdf-reader/screen.png)


text:
FROM gcr.io/oss-fuzz-base/base-builder-python

RUN git clone \
	--depth 1 \
	--branch main \
	https://github.com/mozilla/bleach.git

WORKDIR bleach

RUN git clone --depth 1 https://github.com/google/fuzzing
RUN cat fuzzing/dictionaries/html.dict > $OUT/linkify_fuzzer.dict
RUN cat fuzzing/dictionaries/html.dict > $OUT/sanitize_fuzzer.dict

COPY build.sh sanitize_fuzzer.py linkify_fuzzer.py $SRC/


text:
package com.zooz.common.client.ecomm.beans.responses;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zooz.common.client.ecomm.beans.server.response.ZoozServerResponse;
import com.zooz.common.client.ecomm.control.Controller;
import org.junit.*;
import org.junit.rules.TestName;

import java.io.IOException;

/**
 * Tests parsing of GetPaymentMethods responses
 */
public class GetPaymentMethodsTest extends ResponseTestBase<GetFundSourcesResponse> {

    @Rule
    public TestName name = new TestName();

    @BeforeClass
    public static void setup() throws IOException {

    }

    @AfterClass
    public static void tearDown() {

    }

    @Before
    public void beforeEachTest() {

    }

    /**
     * Tests parsing of GetPaymentMethods responses.
     * The test reads files with json strings from ./src/test/resources/v_[version_number]/getfundsourcesresponse.
     * To read files from a different location add -DdataDir=[path_to_data]. The data directory should be in the same structure as in the resource directory.
     */
    @Test
    public void parseResponse_GetPaymentMethods() {

        basicFlow(GetFundSourcesResponse.class.getSimpleName());

    }

    @Override
    public ZoozServerResponse<GetFundSourcesResponse> getResponseObject(String json, Controller controller) throws IOException {
        ZoozServerResponse<GetFundSourcesResponse> o;
        o = controller.parseResponse(json, new TypeReference<ZoozServerResponse<GetFundSourcesResponse>>() {

        });
        return o;
    }

    @Override
    public void checkAdditionalSuccessFields(ZoozResponseObject o, String fileName) {
        GetFundSourcesResponse res = (GetFundSourcesResponse)o;
        checkPaymentMethods(res.getPaymentMethods(),fileName);

    }

    @Override
    public void checkAdditionalErrorFields(ZoozResponseObject o, String fileName) {

    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<beans 	xmlns="http://xmlns.jcp.org/xml/ns/javaee"
		xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
		xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
							http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
		version="1.1" bean-discovery-mode="all">

	<scan>
		<!--
			Exclude all persistent entities is considered a best practice in most cases.
			See more details at:
			http://www.cdi-spec.org/faq/#accordion12
		-->
		<exclude name="com.consultafacil.model.*"></exclude>
	</scan>
</beans>


text:
package sxkeji.net.dailydiary.utils;

import android.text.TextUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 添加是否为Null判断的Map类,简化请求服务器前参数检查
 * Created by zhangshixin on 2015/11/26.
 * Blog : http://blog.csdn.net/u011240877
 *
 * @description Codes there always can be better.
 */
public class MapUtils {
    private Map<String,String> map;
    private MapUtils(Map<String, String> map){
        this.map = map;
    }
    public static MapUtils builder(Map<String,String> map){
        return new MapUtils(map);
    }
    public Map<String, String> checkEmptyMap(Map<String, String> map) {
        HashMap<String, String> resultMap = new HashMap<>();
        for (String key :
                map.keySet()) {
            String vaule = map.get(key);
            if (!TextUtils.isEmpty(vaule)) {
                resultMap.put(key, vaule);
            }
        }
        return resultMap;
    }
    public MapUtils put(String key,String value){
        if(!TextUtils.isEmpty(key) && !TextUtils.isEmpty(value) && map != null){
            map.put(key,value);
        }
        return this;
    }
}


text:
Describe "Write-RsFolderContent" {

    Context "Write-RsFolderContent with min parameters" {
        $folderName = 'SutWriteRsFolderContentMinParameters' + [guid]::NewGuid()
        New-RsFolder -Path / -FolderName $folderName
        $folderPath = '/' + $folderName
        $localReportPath = (Get-Item -Path ".\").FullName + '\Tests\CatalogItems\testResources'
        Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath

        It "Should upload a local report in Report Server" {
            $uploadedReport = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'Report'
            $uploadedReport.Name | Should Be 'emptyReport'
        }

        It "Should upload a local RsDataSource in Report Server" {
            $uploadedDataSource = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'DataSource'
            $uploadedDataSource.Name | Should Be 'SutWriteRsFolderContent_DataSource'
        }

        It "Should upload a local DataSet in Report Server" {
            $uploadedDataSet = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'DataSet'
            $uploadedDataSet.Name | Should Be 'UnDataset'
        }
        # Removing folders used for testing
        Remove-RsCatalogItem -RsFolder $folderPath -Confirm:$false
    }

    Context "Write-RsFolderContent with ReportServerUri parameter" {
        $folderName = 'SutWriteRsFolderContentReportServerUri' + [guid]::NewGuid()
        New-RsFolder -Path / -FolderName $folderName
        $folderPath = '/' + $folderName
        $localReportPath = (Get-Item -Path ".\" -Verbose).FullName + '\Tests\CatalogItems\testResources'
        $reportServerUri = 'http://localhost/reportserver'
        Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath -ReportServerUri $reportServerUri
        $uploadedReport = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'Report'
        It "Should upload a local report in Report Server with ReportServerUri Parameter" {
            $uploadedReport.Name | Should Be 'emptyReport'
        }
        # Removing folders used for testing
        Remove-RsCatalogItem -RsFolder $folderPath -Confirm:$false
    }

    Context "Write-RsFolderContent with Proxy Parameter" {
        $folderName = 'SutWriteRsFolderContentProxy' + [guid]::NewGuid()
        New-RsFolder -Path / -FolderName $folderName
        $folderPath = '/' + $folderName
        $localReportPath = (Get-Item -Path ".\" -Verbose).FullName + '\Tests\CatalogItems\testResources'
        $proxy = New-RsWebServiceProxy
        Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath -Proxy $proxy
        $uploadedReport = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'Report'
        It "Should upload a local report in Report Server with Proxy Parameter" {
            $uploadedReport.Name | Should Be 'emptyReport'
        }
        # Removing folders used for testing
        Remove-RsCatalogItem -RsFolder $folderPath -Confirm:$false
    }

    Context "Write-RsFolderContent with Proxy and ReportServerUri" {
        $folderName = 'SutWriteRsFolderContentAll' + [guid]::NewGuid()
        New-RsFolder -Path / -FolderName $folderName
        $folderPath = '/' + $folderName
        $localReportPath = (Get-Item -Path ".\" -Verbose).FullName + '\Tests\CatalogItems\testResources'
        $proxy = New-RsWebServiceProxy
        $reportServerUri = 'http://localhost/reportserver'
        Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath -Proxy $proxy -ReportServerUri $reportServerUri
        $uploadedReport = (Get-RsFolderContent -RsFolder $folderPath ) | Where-Object TypeName -eq 'Report'
        It "Should upload a local report in Report Server with ReportServerUri and Proxy Parameters" {
            $uploadedReport.Name | Should Be 'emptyReport'
        }
        # Removing folders used for testing
        Remove-RsCatalogItem -RsFolder $folderPath -Confirm:$false
    }

    Context "Write-RsFolderContent with Recurse Parameter" {
        $folderName = 'SutWriteRsFolderContentRecurse' + [guid]::NewGuid()
        New-RsFolder -Path / -FolderName $folderName
        $folderPath = '/' + $folderName
        $localReportPath = (Get-Item -Path ".\" -Verbose).FullName + '\Tests\CatalogItems\testResources'
        Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath -Recurse
        It "Should upload a local subFolder with Recurse Parameter" {
            $uploadedFolders = (Get-RsFolderContent -RsFolder $folderPath -Recurse ) | Where-Object TypeName -eq 'Folder' | Sort-Object -Property Name -Descending
            $uploadedFolders.Count | Should Be 3
            $uploadedFolders[0].Name | Should Be 'testResources2'
            $uploadedFolders[1].Name | Should Be 'imagesResources'
            $uploadedFolders[2].Name | Should Be 'datasources'
        }

        It "Should upload a report that is in a folder and a second report that is in a subfolder" {
            $uploadedReports = (Get-RsFolderContent -RsFolder $folderPath -Recurse ) | Where-Object TypeName -eq 'Report'
            $uploadedReports.Count | Should Be 4
        }

        It "Should upload a local RsDataSource in Report Server" {
            $uploadedDataSource = (Get-RsFolderContent -RsFolder $folderPath -Recurse ) | Where-Object TypeName -eq 'DataSource'
            $uploadedDataSource.Name | Should Be 'SutWriteRsFolderContent_DataSource'
        }

        It "Should upload a local DataSet in Report Server" {
            $uploadedDataSet = (Get-RsFolderContent -RsFolder $folderPath -Recurse ) | Where-Object TypeName -eq 'DataSet'
            $uploadedDataSet.Name | Should Be 'UnDataset'
        }

        #Re-write folder with recurse.
        It "Should not fail because folder already exists" {
            { Write-RsFolderContent -Path $localReportPath -RsFolder $folderPath -Recurse -Overwrite } | Should Not Throw
        }

        # Removing folders used for testing
        Remove-RsCatalogItem -RsFolder $folderPath -Confirm:$false
    }
}


text:
import sys

try:
    import json
except ImportError:
    import simplejson as json

try:
    config_file = file("/etc/mailsync.conf").read()
    config = json.loads(config_file)
except Exception, err:
    print "There was an error in your configuration file (/etc/mailsync.conf)"
    raise err

_web_app = config.get("web_app", {})
host = _web_app.get("host", "http://127.0.0.1")

if not host.startswith("http"):
    host = "http://{0}".format(host)

WEB_APP = {
    "host": host,
    "port": _web_app.get("port", 4321)
}

PROXY = config.get("proxy", None) # Relative baseurl if True

SQLITE_PATH = config.get("sqlite_path", "/usr/local/mailsync/mailsync.db")
LOGFILE_PATH = config.get("logfile_path", "/usr/local/mailsync/mailsync.log")

TIMEZONE = config.get("timezone","UTC")

ROWS = config.get("rows", 3)

# validate database settings
def str_to_bool(val):
	if val == "true":
		return True
	else: #val == "false":
		return False

_database = config.get("database", {
	"decode": {
		"skip": True,
		"ignore": False,
		"replace": False,
		"encoding": "utf-8"
	},
	"encode": {
		"skip": True,
		"encoding": "utf-8"
	}
})

_database_decode = _database.get("decode", {
	"decode": {
		"skip": True,
		"ignore": False,
		"replace": False,
		"encoding": "utf-8"
	}
})

_database_decode_skip = _database_decode.get("skip", False)
if not _database_decode_skip in ("true", "false"):
	_database_decode_skip = True
else:
	_database_decode_skip = (str_to_bool(_database_decode_skip))

_database_decode_ignore = _database_decode.get("ignore", False)
if not _database_decode_ignore in ("true", "false"):
	_database_decode_ignore = False
else:
	_database_decode_ignore = (str_to_bool(_database_decode_ignore))

_database_decode_replace = _database_decode.get("replace", False)
if not _database_decode_replace in ("true", "false"):
	_database_decode_replace = False
else:
	_database_decode_replace = (str_to_bool(_database_decode_replace))

_database_encode = _database.get("encode", {
	"skip": True,
	"encoding": "utf-8"
})

_database_encode_skip = _database_encode.get("skip", False)
if not _database_encode_skip in ("true", "false"):
	_database_encode_skip = True
else:
	_database_encode_skip = (str_to_bool(_database_encode_skip))

DATABASE = {
	"decode": {
		"skip": _database_decode_skip,
		"ignore": _database_decode_ignore,
		"replace": _database_decode_replace,
		"encoding": _database_decode.get("encoding")
	},
	"encode": {
		"skip": _database_encode_skip,
		"encoding": _database_encode.get("encoding")
	}
}


text:
<!DOCTYPE html>

<meta charset=utf-8>
<title>Text shaping must be broken across inline box boundaries at a bidi isolation boundary</title>
<link rel=match href="reference/boundary-shaping-008.ref.html">
<link rel=help href="https://drafts.csswg.org/css-text/#boundary-shaping">

office


text:
 # PHYS227 CW 11

**Author(s):** Michael Seaman, Taylor Patti, Austin Ayers, Chinmai Raman, Andrew Malfavon

[![Build Status](https://travis-ci.org/chapman-phys227-2016s/cw-11-classwork-team.svg?branch=master)](https://travis-ci.org/chapman-phys227-2016s/cw-11-classwork-team)

**Due date:** 2016/05/03

## Specification

Consider a ball of mass $m$ with horizontal coordinate $x$ rolling in a double-well potential $V(x) = x^4/4 - x^2/2$. (This is sometimes called the "sombrero" potential. Plot it to see why, for $x\in[-1.5,1.5]$.) This potential produces a force $f_{\text{hat}}(x) = -V'(x) = -x^3 + x$ on the rolling ball. Suppose the ball also has slight friction, so experiences a drag force $f_{\text{drag}}(\dot{x}) = -\delta \dot{x}$. With these forces we thus expect the ball to roll down the sides of the sombrero potential and settle in one of the two stable wells. However, this is boring, so instead we are going to shake the hat back and force periodically with a driving force $f_{\text{drive}}(t) = F\cos(\omega t)$. For small driving forces $F$, this should simply jiggle the ball back and forth at the bottom of one of the stable wells. Our task will be to explore what happens for larger driving forces $F$.

Note that according to Newton's second law, the ball must satisfy the equation of motion: $$m\ddot{x} = f_{\text{hat}}(x) + f_{\text{drag}}(\dot{x}) + f_{\text{drive}}(t) = x - x^3 - \delta \dot{x} + F\cos(\omega t)$$
This system is known as a nonlinear "Duffing oscillator," and can be split into a set of two coupled first-order ODEs:
$$\dot{x}(t) = y(t)$$
$$m\dot{y}(t) = -\delta y(t) + x(t) - x^3(t) + F\cos(\omega t)$$
Your task will be to work together to solve these equations numerically, for $m=1$, $\delta = 0.25$, and $\omega = 1$. Use a time-step size of $\Delta t = 0.001$ with 4th-order Runge-Kutta for precision. Implement your code in a python file ```sombrero.py``` with suitable test functions.

Write a joint notebook ```cw11.ipynb``` that summarizes the following investigations.

1. For $F = 0.18$, plot $x(t)$ for $t\in[0,2\pi\, 50]$, with $x(0) = -0.9$ and $y(0) = 0$. Plot the parametric curve $(x(t),y(t))$ in the x-y plane for the same time range.  Plot a scatter plot of the points $(x(t),y(t))$, with specific $t = n 2\pi$ for $n = 0,1,\ldots,50$. (This last type of plot is known as a "Poincare section" of the parametric curve.)  Interpret your results.
1. Repeat the first question, but for $x(0) = 0.9$ and $y(0) = 0$.  What is different?  Interpret your results.
1. Repeat the first question, but for $F = 0.25$, $x(0) = 0.2$, and $y(0) = 0.1$.  What is different?  Plot what happens if you change to $x(0) = 0.201$. How do you interpret this physically?
1. Repeat the first question, but for $F = 0.4$, $x(0) = 0$, and $y(0) = 0$.  What is different now?  What happens when you tweak the initial conditions?  How do you interpret this physically?
1. For the previous problem, extend the time range to $t\in[0,2\pi\, 1000]$.  What is the structure of the Poincare section?

Your homework this week will be to finish this classwork assignment, and then use it to create high-resolution plots of the Poincare section.

## Assessment

This was a good assignment. So said all.

## Honor Pledge

I pledge that all the work in this repository is my own with only the following exceptions:

* Content of starter files supplied by the instructor;
* Code borrowed from another source, documented with correct attribution in the code and summarized here.

Signed,

Michael Seaman, Taylor Patti, Austin Ayers, Chinmai Raman, Andrew Malfavon