text:
.class Lcom/sec/ims/sms/ISmsService$Stub$Proxy;
.super Ljava/lang/Object;
.source "ISmsService.java"

# interfaces
.implements Lcom/sec/ims/sms/ISmsService;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Lcom/sec/ims/sms/ISmsService$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .locals 0

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    iput-object p1, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .locals 1

    iget-object v0, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public deRegisterForSMSStateChange(ILcom/sec/ims/sms/ISmsServiceEventListener;)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v2, 0x0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v3, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    if-eqz p2, :cond_0

    invoke-interface {p2}, Lcom/sec/ims/sms/ISmsServiceEventListener;->asBinder()Landroid/os/IBinder;

    move-result-object v2

    :cond_0
    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x2

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .locals 1

    const-string/jumbo v0, "com.sec.ims.sms.ISmsService"

    return-object v0
.end method

.method public registerForSMSStateChange(ILcom/sec/ims/sms/ISmsServiceEventListener;)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v2, 0x0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v3, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    if-eqz p2, :cond_0

    invoke-interface {p2}, Lcom/sec/ims/sms/ISmsServiceEventListener;->asBinder()Landroid/os/IBinder;

    move-result-object v2

    :cond_0
    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x1

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public sendDeliverReport(I[B)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v2, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeByteArray([B)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x5

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public sendRPSMMA(ILjava/lang/String;)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v2, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x6

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public sendSMSOverIMS(I[BLjava/lang/String;Ljava/lang/String;I)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v2, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    invoke-virtual {v0, p1}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeByteArray([B)V

    invoke-virtual {v0, p3}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    invoke-virtual {v0, p4}, Landroid/os/Parcel;->writeString(Ljava/lang/String;)V

    invoke-virtual {v0, p5}, Landroid/os/Parcel;->writeInt(I)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x3

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method

.method public sendSMSResponse(ZI)V
    .locals 5
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    const/4 v2, 0x0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v1

    :try_start_0
    const-string/jumbo v3, "com.sec.ims.sms.ISmsService"

    invoke-virtual {v0, v3}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    if-eqz p1, :cond_0

    const/4 v2, 0x1

    :cond_0
    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInt(I)V

    invoke-virtual {v0, p2}, Landroid/os/Parcel;->writeInt(I)V

    iget-object v2, p0, Lcom/sec/ims/sms/ISmsService$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v3, 0x4

    const/4 v4, 0x0

    invoke-interface {v2, v3, v0, v1, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z

    invoke-virtual {v1}, Landroid/os/Parcel;->readException()V
    :try_end_0
    .catchall {:try_start_0 .. :try_end_0} :catchall_0

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    return-void

    :catchall_0
    move-exception v2

    invoke-virtual {v1}, Landroid/os/Parcel;->recycle()V

    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    throw v2
.end method


text:
<?php

namespace EXSyst\Bundle\ApiDocBundle\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\Compiler\PriorityTaggedServiceTrait;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AddDescribersPass implements CompilerPassInterface
{
    use PriorityTaggedServiceTrait;

    public function process(ContainerBuilder $container)
    {
        $describers = $this->findAndSortTaggedServices('exsyst_api_doc.describer', $container);

        $container->getDefinition('exsyst_api_doc.generator')->replaceArgument(0, $describers);
    }
}

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Xml.Serialization;

namespace EZOper.NetSiteUtilities.AopApi
{
    /// <summary>
    /// AntMerchantExpandIndirectOnlineQueryModel Data Structure.
    /// </summary>
    [Serializable]
    public class AntMerchantExpandIndirectOnlineQueryModel : AopObject
    {
        /// <summary>
        /// 受理商户在受理机构下的唯一标识,与sub_merchant_id二选一必传
        /// </summary>
        [XmlElement("external_id")]
        public string ExternalId { get; set; }

        /// <summary>
        /// 商户在支付宝入驻成功后,生成的支付宝内全局唯一的商户编号,与external_id二选一必传
        /// </summary>
        [XmlElement("sub_merchant_id")]
        public string SubMerchantId { get; set; }
    }
}


text:
package com.nfl.glitr.calculator;

import com.nfl.glitr.exception.GlitrException;
import com.nfl.glitr.registry.schema.GlitrFieldDefinition;
import com.nfl.glitr.registry.schema.GlitrMetaDefinition;
import com.nfl.glitr.registry.schema.GraphQLConnectionList;
import graphql.language.*;
import graphql.parser.InvalidSyntaxException;
import graphql.parser.Parser;
import graphql.parser.antlr.GraphqlLexer;
import graphql.schema.*;
import net.objecthunter.exp4j.Expression;
import net.objecthunter.exp4j.ExpressionBuilder;
import org.antlr.v4.runtime.CharStreams;
import org.antlr.v4.runtime.CommonToken;
import org.antlr.v4.runtime.InputMismatchException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_FORMULA_KEY;
import static com.nfl.glitr.util.NodeUtil.COMPLEXITY_IGNORE_KEY;
import static org.apache.commons.lang3.StringUtils.defaultString;

/*
     This class is used as a tool to compute complexity of a graphql string query.
     We can test the query's character limit.
     We can test the query's depth limit.
     We can test the query's overall score.

     * maxCharacterLimit = maximum allowed characters in the query string.
     * maxDepthLimit = maximum allowed depth in the query string.
     * defaultMultiplier = multiplier per depth level
 */

public class QueryComplexityCalculator {

    private static final Logger logger = LoggerFactory.getLogger(QueryComplexityCalculator.class);

    private static final String[] ALPHABET = new String[]{"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"};
    private static final Pattern FORMULA_VARIABLE_PATTERN = Pattern.compile("(#\\{.*?})");
    private static final String FORMULA_VARIABLE_OPEN_TAG = "#{";
    private static final String FORMULA_VARIABLE_CLOSS_TAG = "}";

    private final String QUERY_FIELD = "FIELD";
    private final String MUTATION_DEFINITION = "mutation";

    private final int maxCharacterLimit;
    private final int maxDepthLimit;
    private final int maxScoreLimit;
    private final double defaultMultiplier;
    private final Parser documentParser;
    private GraphQLSchema schema;

    public QueryComplexityCalculator() {
        this.maxCharacterLimit = 10000;
        this.maxDepthLimit = 8;
        this.maxScoreLimit = 500;
        this.defaultMultiplier = 10d;
        this.documentParser = new Parser();
    }

    public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier) {
        this.maxCharacterLimit = maxCharacterLimit;
        this.maxDepthLimit = maxDepthLimit;
        this.maxScoreLimit = maxScoreLimit;
        this.defaultMultiplier = defaultMultiplier;
        this.documentParser = new Parser();
    }

    public QueryComplexityCalculator(int maxCharacterLimit, int maxDepthLimit, int maxScoreLimit, int defaultMultiplier, Parser documentParser) {
        this.maxCharacterLimit = maxCharacterLimit;
        this.maxDepthLimit = maxDepthLimit;
        this.maxScoreLimit = maxScoreLimit;
        this.defaultMultiplier = defaultMultiplier;
        this.documentParser = documentParser;
    }

    public QueryComplexityCalculator withSchema(GraphQLSchema schema) {
        this.schema = schema;
        return this;
    }

    /**
     * @param query - graphql query string
     * @param variables graphQL query variables
     * We want to validate the query or fail fast.
     */
    public void validate(String query, Map<String, Object> variables) {
        if (characterLimitExceeded(query)) {
            throw new GlitrException(String.format("query length has exceeded the maximum of %d characters.", maxCharacterLimit));
        }

        if (depthLimitExceeded(query)) {
            throw new GlitrException(String.format("query depth has exceeded the maximum depth level of %d.", maxDepthLimit));
        }

        if (scoreLimitExceeded(query, variables)){
            throw new GlitrException(String.format("query score has exceeded the maximum score level of %d.", maxScoreLimit));
        }

    }

    /**
     * @param query - graphql query string
     * @return true if the query's length is greater than the maximum allowed number of characters.
     */
    public boolean characterLimitExceeded(String query) {
        return characterScore(query) > maxCharacterLimit;
    }

    /**
     * @param query - graphql query string
     * @return the length of the query string.  If the query is a mutation, we retrieve the return query body of the mutation
     */
    public int characterScore(String query) {
        if (StringUtils.isBlank(query)) {
            throw new GlitrException("query cannot be null or empty");
        }

        try {
            Document document = parseRootNode(query);
            OperationDefinition operationDefinition = getFirstByType(document.getChildren(), OperationDefinition.class)
                    .orElseThrow(() -> new GlitrException("Cannot find 'OperationDefinition' node"));

            if (operationDefinition.getOperation() == OperationDefinition.Operation.MUTATION){
                query = extractReturnQueryFromMutation(operationDefinition);
            }
        } catch (Exception e) {
            logger.error("Cannot parse inbound query", e);
        }

        return query.trim().length();
    }

    /**
     * @param query - graphql query string
     * @return true if the query's depth is greater than the maximum allowed depth.
     */
    public boolean depthLimitExceeded(String query) {
        return depthScore(query) > maxDepthLimit;
    }

    /**
     * @param query - graphql query string
     * @return the maximum depth of the query string
     */
    public int depthScore(String query) {
        if (StringUtils.isBlank(query)) {
            throw new GlitrException("query cannot be null or empty");
        }

        QueryComplexityNode entryPoint = buildComplexityModel(query);
        return calculateMaxDepth(entryPoint);
    }

    /**
     * @param parentNode Root node to recursively iterate and find the deepest child.
     * @return the maximum child depth as an integer.  We start at the queryNode.  We figure out what type of node this is.
     * It can be an OPERATION_DEFINITION, a SELECTION_SET, a FIELD, etc.  If it's a field and not a LEAF, we increase
     * the depth by 1.  A node is considered a LEAF when it doesn't have any children.  We continue and recursively go
     * through each child and figure out what the deepest one is.  The deepest child is what is returned as the maximum depth.
     *
     * Examples
     ******************************************************************************************************************
     ******************************************************************************************************************
     * Depth = 0
     * {
     *     trackName
     * }
     ******************************************************************************************************************
     ******************************************************************************************************************
     * Depth = 1
     * {
     *     playLists{
     *         playListId
     *     }
     * }
     ******************************************************************************************************************
     ******************************************************************************************************************
     * Depth = 2
     * {
     *     playLists{
     *         playListId
     *         tracks{
     *             trackId
     *         }
     *     }
     * }
     ******************************************************************************************************************
     ******************************************************************************************************************
     * Depth = 2
     * {
     *     playLists{
     *         playListId
     *         tracks{
     *             trackId
     *         }
     *         artists{
     *             artistId
     *         }
     *     }
     * }
     ******************************************************************************************************************
     ******************************************************************************************************************
     * Depth = 3
     * {
     *     playLists{
     *         playListId
     *         tracks{
     *             trackId
     *             trackInfo{
     *                 runtime
     *             }
     *         }
     *     }
     * }
     ******************************************************************************************************************
     ******************************************************************************************************************
     */
    private int calculateMaxDepth(QueryComplexityNode parentNode) {
        int depth = 0;
        if (!parentNode.isIgnore() && !isLeaf(parentNode)) {
            depth = 1;
        }

        int maxChildDepth = 0;
        for (QueryComplexityNode childNode : parentNode.getChildren()) {
            final int currentChildDepth = calculateMaxDepth(childNode);
            maxChildDepth = Math.max(maxChildDepth, currentChildDepth);
        }

        depth += maxChildDepth;
        return depth;
    }

    /**
     * @param query graphql query string
     * @param variables graphql query variables
     * @return true if the {@link #queryScore(String, Map) query's score} result is greater than the maximum allowed score.
     */
    public boolean scoreLimitExceeded(String query, Map<String, Object> variables) {
        return queryScore(query, variables) > maxScoreLimit;
    }

    /**
     * <pre>
     *
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {
     *     playLists{    multiplier = 10 (default)
     *         id
     *     }
     * }
     * score = 10
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {
     *     playLists{               multiplier (default) = 10
     *         id
     *         tracks(first:4){     first = 4, multiplier (default) = 10
     *              trackId
     *         }
     *     }
     * }
     * score = (10) + (4 * 10) = 50
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {
     *     playLists{                      multiplier (default) = 10
     *         id
     *         tracks(first:4){            first = 4, multiplier (default) = 10
     *             trackId
     *             trackInfo{              multiplier (default) = 10
     *                 runtime
     *                 authors(first:2){   first = 2, multiplier (default) = 10
     *                     authorName
     *                 }
     *             }
     *         }
     *     }
     * }
     * score = 10 + (4 * 10) + 10 + (2 * 10) = 70
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {
     *     playLists{               multiplier (default) = 10
     *         id
     *         tracks(first:4){     first = 4, multiplier (default) = 10
     *             trackId
     *             trackInfo{       multiplier (default) = 10
     *                 runtime
     *             }
     *         }
     *     }
     * }
     * score = 10 + (4 * 10) + 10 = 60
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {
     *     playLists{               multiplier (default) = 10
     *         id
     *         tracks(first:4){     first = 4, multiplier (default) = 10
     *             trackId
     *             trackInfo{       multiplier (default) = 10
     *                 runtime
     *             }
     *         }
     *     }
     * }
     * score = 10 + (4 * 10) + 10 = 60
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * {@literal @}GlitrQueryComplexity("#{depth} + #{childScore} + #{currentCollectionSize} + #{totalCollectionsSize}
     *                                  + #{maxCharacterLimit} + #{maxDepthLimit} + #{maxScoreLimit} + #{defaultMultiplier} + 5")
     *  private List trackInfo;
     *
     *  #{maxCharacterLimit} = 11, #{maxDepthLimit} = 22, #{maxScoreLimit} = 33, #{defaultMultiplier} = 10
     *
     * {
     *     playLists{                      multiplier (default) = 10
     *         id
     *         tracks(first:4){            first = 4, multiplier (default) = 10
     *             trackId
     *             trackInfo(first:2){     #{depth} = 3, #{childScore} = 10, #{currentCollectionSize} = 2, #{totalCollectionsSize} = 6
     *                 runtime
     *                 author{             multiplier (default) = 10
     *                     authorName
     *                 }
     *             }
     *         }
     *     }
     * }
     * score = 10 + (4 * 10) + (3 + 10 + 2 + 6 + 11 + 22 + 33 + 10 + 5) + 10 = 162
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * </pre>
     * @param query string
     * @param variables graphQL query variables
     * @return query score as an double.  The way the query score is calculated is by summing the multipliers of all nodes.
     **/
    public double queryScore(String query, Map<String, Object> variables) {
        return queryScoreDetails(query, variables).getTotalWeight();
    }

    /**
     *
     * @param query  string
     * @param variables graphQL query variables
     * @return {@link QueryComplexityNode}
     */
    public QueryComplexityNode queryScoreDetails(String query, Map<String, Object> variables) {
        if (StringUtils.isBlank(query)) {
            throw new GlitrException("query cannot be null or empty");
        }

        QueryComplexityNode complexityModel = buildComplexityModel(query);
        return queryScoreDetails(complexityModel, 0, new HashMap<>(), variables);
    }

    private QueryComplexityNode buildComplexityModel(String query) {
        Document document = parseRootNode(query);
        Map<String, Pair<String, List<Selection>>> fragments = getFragments(document);

        OperationDefinition operationDefinition = getFirstByType(document.getChildren(), OperationDefinition.class)
                .orElseThrow(() -> new GlitrException("Cannot find node 'OperationDefinition'"));

        Field queryEntryPoint = getFirstFieldNode(operationDefinition);
        if (queryEntryPoint == null) {
            return new QueryComplexityNode();
        }

        GraphQLFieldDefinition rootSchemaField = getRootSchemaField(query, queryEntryPoint.getName());

        boolean mutationQuery = operationDefinition.getOperation() == OperationDefinition.Operation.MUTATION;
        boolean ignoreField = ignoreFieldOrDefault(rootSchemaField, mutationQuery);

        QueryComplexityNode rootComplexityNode = new QueryComplexityNode(queryEntryPoint.getName());
        rootComplexityNode.setFormula(getGraphQLMeta(rootSchemaField, COMPLEXITY_FORMULA_KEY));
        rootComplexityNode.setIgnore(ignoreField);

        return buildComplexityModel(queryEntryPoint, rootComplexityNode, rootSchemaField, fragments);
    }

    private QueryComplexityNode buildComplexityModel(Node queryNode, QueryComplexityNode queryComplexityParentNode, GraphQLFieldDefinition parentSchemaField, Map<String, Pair<String, List<Selection>>> fragments) {
        for (Node child : (List<Node>) queryNode.getChildren()) {
            if (child instanceof Argument) {
                queryComplexityParentNode.addArgument((Argument) child);
                buildComplexityModel(child, queryComplexityParentNode, parentSchemaField, fragments);

            } else if (child instanceof FragmentSpread) {
                buildComplexityModelForFragmentSpread((FragmentSpread) child, queryComplexityParentNode, parentSchemaField, fragments);

            } else if (child instanceof InlineFragment) {
                buildComplexityModelForInlineFragment((InlineFragment) child, queryComplexityParentNode, parentSchemaField, fragments);

            } else if (child instanceof Field) {
                buildChildComplexityNode((Field) child, queryComplexityParentNode, parentSchemaField, parentSchemaField != null ? parentSchemaField.getType() : null, fragments);

            } else {
                buildComplexityModel(child, queryComplexityParentNode, parentSchemaField, fragments);
            }
        }

        return queryComplexityParentNode;
    }

    private QueryComplexityNode buildComplexityModelForInlineFragment(InlineFragment node, QueryComplexityNode parentComplexityNode, GraphQLFieldDefinition parentSchemaField, Map<String, Pair<String, List<Selection>>> fragments) {
        String typeName = node.getTypeCondition().getName();
        GraphQLObjectType type = ((GraphQLObjectType) schema.getType(typeName));
        for (Selection selection : node.getSelectionSet().getSelections()) {
            buildChildComplexityNode((Field) selection, parentComplexityNode, parentSchemaField, type, fragments);
        }

        return parentComplexityNode;
    }

    private QueryComplexityNode buildComplexityModelForFragmentSpread(FragmentSpread node, QueryComplexityNode parentComplexityNode, GraphQLFieldDefinition parentSchemaField, Map<String, Pair<String, List<Selection>>> fragments) {
        String typeName = node.getName();
        Pair<String, List<Selection>> fragment = fragments.get(typeName);
        if (fragment != null) {
            GraphQLObjectType type = (GraphQLObjectType) schema.getType(fragment.getKey());
            for (Selection selection : fragment.getValue()) {
                buildChildComplexityNode((Field) selection, parentComplexityNode, parentSchemaField, type, fragments);
            }
        }

        return parentComplexityNode;
    }

    private QueryComplexityNode buildChildComplexityNode(Field node, QueryComplexityNode parentComplexityNode, GraphQLFieldDefinition parentSchemaField, GraphQLOutputType currentSchemaFieldType, Map<String, Pair<String, List<Selection>>> fragments) {
        String nodeName = node.getName();
        GraphQLFieldDefinition graphQLObject = getGraphQLObject(currentSchemaFieldType, nodeName);

        QueryComplexityNode childComplexity = new QueryComplexityNode(nodeName);
        childComplexity.setIgnore(ignoreFieldOrDefault(graphQLObject, isConnectionNode(parentSchemaField, nodeName)));
        childComplexity.setFormula(getGraphQLMeta(graphQLObject, COMPLEXITY_FORMULA_KEY));
        parentComplexityNode.addChild(childComplexity);

        buildComplexityModel(node, childComplexity, graphQLObject, fragments);

        return parentComplexityNode;
    }

    private GraphQLFieldDefinition getGraphQLObject(GraphQLOutputType objType, String name) {
        if (objType == null) {
            return null;
        }

        try {
            GraphQLFieldsContainer container = getWrappedContainer(objType);
            if (container != null) {
                return container.getFieldDefinition(name);
            }
        } catch (Exception e) {
            logger.error("Missed ({}) field of ({}) graphQL type", name, objType.getName());
        }

        return null;
    }

    private GraphQLFieldsContainer getWrappedContainer(GraphQLType objType) {
        if (objType instanceof GraphQLModifiedType) {
            return getWrappedContainer(((GraphQLModifiedType) objType).getWrappedType());
        }
        if (objType instanceof GraphQLFieldsContainer) {
            return (GraphQLFieldsContainer) objType;
        }

        logger.error("Not supported graphQLType {} ", objType);
        return null;
    }

    private GraphQLFieldDefinition getRootSchemaField(String query, String entryPoint) {
        if (schema == null) {
            return null;
        }

        boolean mutationQuery = isMutation(query);
        GraphQLObjectType rootType = mutationQuery ? schema.getMutationType() : schema.getQueryType();
        return rootType.getFieldDefinition(entryPoint);
    }

    @SuppressWarnings("unchecked")
    private QueryComplexityNode queryScoreDetails(QueryComplexityNode parentNode, int depth, Map<String, Double> nestedContext, Map<String, Object> queryVariables) {
        Map<String, Double> context = refreshQueryContext(nestedContext, parentNode, queryVariables);
        depth = !parentNode.isIgnore() ? (depth + 1) : depth;

        double childScores = 0d;
        for (QueryComplexityNode currentChild : parentNode.getChildren()) {
            QueryComplexityNode childComplexityNode = queryScoreDetails(currentChild, depth , context, queryVariables);
            childScores += childComplexityNode.getTotalWeight();
        }

        double currentNodeScore = 0d;
        if (!parentNode.isIgnore()) {
            Map<String, Double> nodeContext = buildContext(parentNode, nestedContext, depth, childScores, queryVariables);
            currentNodeScore = extractMultiplierFromListField(parentNode, nodeContext, queryVariables);
            parentNode.setWeight(currentNodeScore);
        }
        parentNode.setTotalWeight(getTotalWeight(parentNode, queryVariables, currentNodeScore, childScores));

        return parentNode;
    }

    private double getTotalWeight(QueryComplexityNode node, Map<String, Object> queryVariables, double currentNodeScore, double childScores) {
        String multiplier = node.getFormula();

        Optional<Integer> listLimit = getLimitArgIfPresent(node, queryVariables);
        if (listLimit.isPresent() && StringUtils.isBlank(multiplier)) {
            double collectionSize = listLimit.get();
            if (childScores != 0) {
                childScores = collectionSize * childScores;
            }
            return (collectionSize * defaultMultiplier) + childScores;
        } else {
            return currentNodeScore + childScores;
        }
    }

    private <T> T getGraphQLMeta(GraphQLFieldDefinition graphQlObject, String name) {
        Optional<Set<GlitrMetaDefinition>> metaDefinitions = Optional.ofNullable(graphQlObject)
                .map(GraphQLFieldDefinition::getDefinition)
                .filter(x -> x instanceof GlitrFieldDefinition)
                .map(x -> ((GlitrFieldDefinition)x).getMetaDefinitions())
                .filter(CollectionUtils::isNotEmpty);

        if (metaDefinitions.isPresent()) {
            return metaDefinitions.get().stream()
                    .filter(metaDefinition -> name.equals(metaDefinition.getName()))
                    .findFirst()
                    .map(metaDefinition -> (T) metaDefinition.getValue())
                    .orElse(null);
        }

        return null;
    }

    private boolean isConnectionNode(GraphQLFieldDefinition graphQlObject, String name) {
        if (graphQlObject == null) {
            return false;
        }

        GraphQLType objType = graphQlObject.getType();
        if (objType instanceof GraphQLConnectionList) {
            return true;
        }

        if (objType instanceof GraphQLObjectType) {
            GraphQLFieldDefinition fieldDefinition = ((GraphQLObjectType) objType).getFieldDefinition(name);
            return fieldDefinition != null && fieldDefinition.getType() instanceof GraphQLConnectionList;
        }

        return false;
    }

    private Map<String, Double> refreshQueryContext(Map<String, Double> queryContext, QueryComplexityNode field, Map<String, Object> queryVariables) {
        int limit = getLimitArgIfPresent(field, queryVariables).orElse(0);

        Double parentCollectionsSize = queryContext.getOrDefault("totalCollectionsSize", 0d);
        Double totalCollectionsSize = parentCollectionsSize + limit;
        queryContext.put("totalCollectionsSize", totalCollectionsSize);

        return new HashMap<>(queryContext);
    }

    private Map buildContext(QueryComplexityNode field, Map<String, Double> queryContext, int depth, double childScores, Map<String, Object> queryVariables) {
        double totalCollectionsSize = queryContext.getOrDefault("totalCollectionsSize", 0d);
        int limit = getLimitArgIfPresent(field, queryVariables).orElse(0);

        Map<String, Double> multiplierContext = new HashMap<>();
        multiplierContext.put("totalCollectionsSize", totalCollectionsSize);
        multiplierContext.put("currentCollectionSize", (double) limit);
        multiplierContext.put("depth", (double) depth);
        multiplierContext.put("childScore", childScores);

        multiplierContext.put("maxCharacterLimit", (double) maxCharacterLimit);
        multiplierContext.put("maxDepthLimit", (double) maxDepthLimit);
        multiplierContext.put("maxScoreLimit", (double) maxScoreLimit);
        multiplierContext.put("defaultMultiplier", defaultMultiplier);

        return multiplierContext;
    }

    private Optional<Integer> getLimitArgIfPresent(QueryComplexityNode node, Map<String, Object> queryVariables) {
        if (CollectionUtils.isEmpty(node.getArguments())) {
            return Optional.empty();
        }

        Optional<Argument> listLimit = node.getArguments().stream()
                .filter(argument -> argument.getName().equals("first"))
                .findFirst();

        Integer limit = null;
        if (listLimit.isPresent()) {
            Value value = listLimit.get().getValue();
            if (value instanceof VariableReference && queryVariables != null) {
                limit = (Integer) queryVariables.get(((VariableReference) value).getName());
            } else if (value instanceof IntValue) {
                limit = ((IntValue) value).getValue().intValue();
            }
        }

        return Optional.ofNullable(limit);
    }

    /**
     *
     * @param query - graphql query string
     * @return the root node.  We parse the query with a graphql library and retrieve a document object.  We filter the
     * document object in search of an OPERATION_DEFINITION.  If the query is a MUTATION we extract the return query
     * from the mutation body.  If it's not a mutation, we parse as is.
     */
    private Document parseRootNode(String query) {
        try {
            return documentParser.parseDocument(query);
        } catch (InvalidSyntaxException e) {
            throw new GlitrException(String.format("Cannot parse query. %s %s", e.getMessage(), query));
        } catch (Exception e) {
            String humanMessage = null;
            if (e.getCause() instanceof InputMismatchException && ((InputMismatchException) e.getCause()).getOffendingToken() instanceof CommonToken) {
                humanMessage = ((CommonToken) ((InputMismatchException) e.getCause()).getOffendingToken()).toString(new GraphqlLexer(CharStreams.fromString(query)));
            }
            throw new GlitrException(String.format("Cannot parse query. %s %s", defaultString(humanMessage), query));
        }
    }

    /**
     *
     * @param document - graphql query represented by document model
     * @return the map where the key is a user specified fragment name and value is a pair of schema type name with field set
     */
    private Map<String, Pair<String, List<Selection>>> getFragments(Document document) {
        Map<String, Pair<String, List<Selection>>> fragments = new HashMap<>();
        List<FragmentDefinition> fragmentDefinitions = getByType(document.getChildren(), FragmentDefinition.class);
        for (FragmentDefinition fragmentDefinition : fragmentDefinitions) {
            getFirstByType(fragmentDefinition.getChildren(), SelectionSet.class)
                    .ifPresent(f -> fragments.put(fragmentDefinition.getName(), Pair.of(fragmentDefinition.getTypeCondition().getName(), f.getSelections())));
        }

        return fragments;
    }

    /**
     * <pre>
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * If the node has an argument called 'first' and has children, we return that integer multiplied by the default multiplier
     * default multiplier = 10
     * {
     *     players(first:5){
     *         playerId
     *     }
     * } == returns 5 * 10 = 50
     * ****************************************************************************************************************
     * ****************************************************************************************************************
     * If the node has an argument called 'first' and annotated by @GlitrQueryComplexity, at the same time - we ignore the 'first' argument and return specified complexity value
     *
     * {@literal @}GlitrQueryComplexity("70")
     *  private List players;
     *
     * {
     *     players(first:5){
     *         playerId
     *     }
     * } == returns 70
     * *****************************************************************************************************************
     * *****************************************************************************************************************
     *
     * *****************************************************************************************************************
     * *****************************************************************************************************************
     * If the node doesn't have an argument but has children, we return the default multiplier
     * {
     *     players{
     *         playerId
     *     }
     * } == returns 10, which is the default multiplier above.
     * *****************************************************************************************************************
     * *****************************************************************************************************************
     *
     * *****************************************************************************************************************
     * *****************************************************************************************************************
     * If the node is a leaf node, we return 0. Exception is if the leaf node is marked with {@link com.nfl.glitr.annotation.GlitrQueryComplexity @GlitrQueryComplexity}.
     * {
     *     playerName
     * }
     * *****************************************************************************************************************
     * *****************************************************************************************************************
     * </pre>
     *
     * @param node The field node we would like to test against
     * @param context mutable current branch context
     * @param queryVariables graphQL query variables
     * @return the multiplier
     *
     **/
    protected double extractMultiplierFromListField(QueryComplexityNode node, Map<String, Double> context, Map<String, Object> queryVariables) {
        String multiplier = node.getFormula();

        // If there is an argument
        Optional<Integer> listLimit = getLimitArgIfPresent(node, queryVariables);
        if (listLimit.isPresent() && StringUtils.isBlank(multiplier)) {
            double collectionSize = listLimit.get();
            return collectionSize * defaultMultiplier;
        }

        // If it has children with no argument
        if (!isLeaf(node) || StringUtils.isNotBlank(multiplier)) {
            return calculateMultiplier(multiplier, context);
        }

        // If its a leaf
        return 0;
    }

    private Double calculateMultiplier(String formula, Map<String, Double> context) {
        if (StringUtils.isBlank(formula)) {
            return defaultMultiplier;
        }

        Matcher matcher = FORMULA_VARIABLE_PATTERN.matcher(formula);
        Map<String,Double> variablesMapping = new HashMap<>();
        for (int i = 0; matcher.find(); i++) {
            String var = matcher.group();
            try {
                String nextVarAlias = ALPHABET[i];
                Double varValue = evaluateContextVariableValue(var, context);
                variablesMapping.put(nextVarAlias, varValue);

                formula = formula.replace(var, nextVarAlias);
            } catch (ArrayIndexOutOfBoundsException e) {
                logger.error("The amount of variables in formula ({}) has been exceeded.", formula);
            } catch (Exception e) {
                logger.error("Cannot evaluate ({}) variable of formula ({}).", var, formula);
            }
        }

        double evaluate = 0;
        try {
            Expression expr = new ExpressionBuilder(formula)
                    .variables(variablesMapping.keySet())
                    .build()
                    .setVariables(variablesMapping);

            evaluate = expr.evaluate();
        } catch (Exception e) {
            logger.error("cannot evaluate query complexity formula ({}).", formula);
        }

        return evaluate;
    }

    private Double evaluateContextVariableValue(String var, Map<String, Double> context) {
        if (StringUtils.isBlank(var)) {
            return 0d;
        }

        var = StringUtils.substringBetween(var, FORMULA_VARIABLE_OPEN_TAG, FORMULA_VARIABLE_CLOSS_TAG);
        Double val = context.get(var);
        if (val == null) {
            logger.error("Doesn't support complexity formula variable ({})", var);
            return 0d;
        }
        return val;
    }

    /**
     * @param node - Node to test against
     * @return  true  --> if the node doesn't have children
     *          false --> if the node has children.
     */
    private boolean isLeaf(Node node) {
        return node.getChildren().isEmpty();
    }

    /**
     * @param node - Node to test against
     * @return  true  --> if the node doesn't have children
     *          false --> if the node has children.
     */
    private boolean isLeaf(QueryComplexityNode node) {
        return node.getChildren().isEmpty();
    }

    public boolean isMutation(String query){
        return query.trim().startsWith(MUTATION_DEFINITION);
    }

    @SuppressWarnings("unchecked")
    private <T> Optional<T> getFirstByType(Collection collection, Class<T> type) {
        for (Object o : collection) {
            if (type.isAssignableFrom(o.getClass())) {
                return Optional.of((T) o);
            }
        }
        return Optional.empty();
    }

    @SuppressWarnings("unchecked")
    private <T> List<T> getByType(Collection collection, Class<T> type) {
        List<T> res = new ArrayList<>();
        for (Object o : collection) {
            if (type.isAssignableFrom(o.getClass())) {
                res.add((T) o);
            }
        }
        return res;
    }

    private Field getFirstFieldNode(OperationDefinition rootNode) {
        return (Field) Optional.ofNullable(rootNode)
                .map(OperationDefinition::getChildren)
                .filter(CollectionUtils::isNotEmpty)
                .flatMap(nodes -> nodes.stream().filter(node -> node instanceof SelectionSet).findFirst())
                .map(Node::getChildren)
                .filter(CollectionUtils::isNotEmpty)
                .flatMap(nodes -> nodes.stream().filter(node -> node instanceof Field).findFirst())
                .orElse(null);
    }

    private boolean ignoreFieldOrDefault(GraphQLFieldDefinition field, boolean defaultValue) {
        Boolean ignore = getGraphQLMeta(field, COMPLEXITY_IGNORE_KEY);
        return Optional.ofNullable(ignore).orElse(defaultValue);
    }

    /**
     * @param mutationNode - graphql mutation node
     * @return the query that is returned by the mutation response body
     */
    private String extractReturnQueryFromMutation(Node mutationNode){
        SelectionSet selectionSet = getFirstByType(mutationNode.getChildren(), SelectionSet.class)
                .orElseThrow(() -> new GlitrException("Cannot find 'SelectionSet' node in " + AstPrinter.printAst(mutationNode)));
        Field field = getFirstByType(selectionSet.getChildren(), Field.class)
                .orElseThrow(() -> new GlitrException("Cannot find 'Field' node in " + AstPrinter.printAst(selectionSet)));
        SelectionSet mutationSelectQuery = getFirstByType(field.getChildren(), SelectionSet.class)
                .orElseThrow(() -> new GlitrException("Cannot find 'Field' node in" + AstPrinter.printAst(field)));
        return AstPrinter.printAst(mutationSelectQuery);
    }

    public int getMaxCharacterLimit() {
        return maxCharacterLimit;
    }

    public int getMaxDepthLimit() {
        return maxDepthLimit;
    }

    public int getMaxScoreLimit() {
        return maxScoreLimit;
    }

    public Double getDefaultMultiplier() {
        return defaultMultiplier;
    }
}


text:
begin
  require File.dirname(__FILE__) + '/lib/association_validation'
rescue LoadError => lE
  raise LoadError, "Failed to load AssociationValidation plugion: #{lE}"
end


text:
using System.Collections;
using System.ComponentModel;

namespace Chapter01.CSharp1
{
    [Description("Listing 1.01")]
    public class Product
    {
        string name;
        public string Name
        {
            get { return name; }
        }

        decimal price;
        public decimal Price
        {
            get { return price; }
        }

        public Product(string name, decimal price)
        {
            this.name = name;
            this.price = price;
        }

        public static ArrayList GetSampleProducts()
        {
            ArrayList list = new ArrayList();
            list.Add(new Product("West Side Story", 9.99m));
            list.Add(new Product("Assassins", 14.99m));
            list.Add(new Product("Frogs", 13.99m));
            list.Add(new Product("Sweeney Todd", 10.99m));
            return list;
        }

        public override string ToString()
        {
            return string.Format("{0}: {1}", name, price);
        }
    }
}


text:
System configuration
====================

The SNMP Proxy Forwarder system consists of two daemons - client and server. Each
accepts a few command-line options and configuration files.

.. _cli_options:

Command-line options
--------------------

Client and server daemons share the same set of command-line options:

.. code-block:: bash

    $ snmpfwd-server.py --help
    Usage: snmpfwd-server.py
        [--help]
        [--version]
        [--debug-snmp=<options>]
        [--debug-asn1=<options>]
        [--daemonize]
        [--process-user=<uname>] [--process-group=<gname>]
        [--pid-file=<file>]
        [--logging-method=<options>]
        [--log-level=<options>]
        [--config-file=<file>]

.. _debug_snmp_cli_option:

**--debug-snmp**
++++++++++++++++

The *--debug-snmp* option makes the daemon emitting detailed log of SNMP protocol
related debugging. Debugging can be enabled for all or for just some of the SNMP
engine subsystems by adding their names to the *--debug-snmp* option.

Recognized SNMP debugging options include:

* *io* -- report raw network traffic
* *msgproc* -- report SNMP message processing
* *secmod* -- report SNMP security module operations
* *mibbuild* -- report on MIB loading and processing
* *mibinstrum* -- report agent MIB operatrions
* *acl* -- report MIB access access control operations
* *proxy* -- report on SNMP version translation operations
* *app* -- application-specific debugging
* *all* -- enable full SNMP debugging

SNMP debugging is fully disabled by default.

.. _debug_asn1_cli_option:

**--debug-asn1**
++++++++++++++++

SNMP is backed by the `ASN.1 <https://en.wikipedia.org/wiki/Abstract_Syntax_Notation_One>`_
for data representation. The *--debug-asn1* option makes the daemon emitting detailed log
of ASN.1 data de/serialization. Debugging can be enabled for either encoder or decoder,
or for everything ASN.1 related by adding their names to the *--debug-asn1* option.

Recognized ASN.1 debugging options include:

* *encoder* -- debug data serialization
* *decoder* -- debug data deserialization
* *all* -- enable full ASN.1 debugging

ASN.1 debugging is fully disabled by default.

.. _daemonize_cli_option:

**--daemonize**
+++++++++++++++

Unless *--daemonize* option is given, the daemon will remain an interactive process.
With the *-daemonize* option, the daemon will detach itself from user terminal,
close down standard I/O streams etc.

.. _process_user_cli_option:
.. _process_group_cli_option:

**--process-user** & **--process-group**
++++++++++++++++++++++++++++++++++++++++

It is generally safer to run daemons under a non-privileged user. However, it may
be necessary to, at least, start SNMP Proxy Forwarder parts as root to let
the process bind to privileged ports (161/udp for SNMP by default).

In this case it may make sense to drop process privileges upon initialization
by becoming *--process-user* belonging to *--process-group*.

.. _pid_file_cli_option:

**--pid-file**
++++++++++++++

Especially when running in *--daemonize** mode, it might be handy to keep
track of UNIX process ID allocated to the running daemon. Primarily, this
can be used for killing or restarting the process.

The *--pid-file** option can be used to specify a disk file where daemon
would store its PID.

.. _logging_method_cli_option:

**--logging-method**
++++++++++++++++++++

SNMP Proxy Forwarder daemons can log using one of the following methods.
The default is *stderr*.

**--logging-method=syslog**
~~~~~~~~~~~~~~~~~~~~~~~~~~~

The *syslog* logging method requires the following sub-options:

.. code-block:: bash

    --logging-method=syslog:facility[:address[:port:[tcp|udp]]]]

Where:

* *facility* -- one of the recognized syslog service `facilities <https://en.wikipedia.org/wiki/Syslog#Facility>`_
* *address* -- can be either an absolute path to a local socket or network address where syslog service is listening (optional)
* *port* -- if network address of the syslog service is used for *address*, *port* be a TCP or UDP port number (optional)
* *tcp* or *udp* -- TCP (stream) or UDP (datagram) protocol to use for syslog service communication (optional)

**--logging-method=file**
~~~~~~~~~~~~~~~~~~~~~~~~~

The *file* logging method redirects daemon logging into a local file. The log file
could be made automatically rotated based on time or size criteria.

The following sub-options are supported:

.. code-block:: bash

    --logging-method=file:path[:criterion]

Where:

* *path* -- path to a log file
* *criterion* -- should consist of a number followed by one of the specifiers:

  - *k* -- rotate when file size exceeds N kilobytes
  - *m* -- rotate when file size exceeds N megabytes
  - *g* -- rotate when file size exceeds N gigabytes
  - *S* -- rotate when file age exceeds N seconds
  - *M* -- rotate when file age exceeds N minutes
  - *H* -- rotate when file age exceeds N hours
  - *D* -- rotate when file age exceeds N days

**--logging-method=stdout/stderr**
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

When *stdout* or *stderr* logging methods are used, daemon log messages are directed
to either process standard output or standard error stream.

**--logging-method=null**
~~~~~~~~~~~~~~~~~~~~~~~~~

The *null* logging method completely inhibits all daemon logging.

.. _log_level_cli_option:

**--log-level**
+++++++++++++++

The *--log-level* option limits the minimum severity of the log messages
to actually log.

Recognized log levels are:

* *debug* -- log at all levels
* *info* - log informational and error messages only
* *error* - log error messages only

.. _config_file_cli_option:

**--config-file**
+++++++++++++++++

The *--config-file* option specifies path to daemon `configuration file <configuration_files>`_.

.. _configuration_files:

Configuration files
-------------------

The configuration file is composed of a set of option/value pairs possibly
enclosed into blocks. Blocks provide lexical scopes for options. Blocks names
have no pre-defined meaning and serve as hints to a human reader.

Options are distinguished from values by trailing colon (:). There may be
several whitespace-separated values assigned to option.

For example:

.. code-block:: bash

    test-option: global-default-value

    outermost-block
    {
        test-option: a-bit-more-specific-value

        more-specific-block
        {
            test-option: specific-value

            very-concrete-settings
            {
                test-option: highly-specific-value
            }
        }
    }

Evaluating the above configuration for *test-option* would yield:

.. code-block:: bash

    READ .test-option -> global-default-value
    READ .outermost-block.test-option -> a-bit-more-specific-value
    READ .outermost-block.more-specific-block.test-option -> specific-value
    READ .outermost-block.more-specific-block.test-option.very-concrete-settings.test-option -> highly-specific-value

Options specified inside a block apply to their current scopes as
well as to all nested scopes unless the same option exists there:

.. code-block:: bash

    outermost-block
    {
        test-option: test-value

        more-specific-block
        {
        }
    }

Evaluating the above configuration for *test-option* would yield:

.. code-block:: bash

    READ .test-option -> ERROR
    READ .outermost-block.test-option -> test-value
    READ .outermost-block.more-specific-block.test-option -> test-value

Server and client parts of the system consume their own configuration file.
Many options are applicable to both client and server, though some options
are specific to either parts of the system.

Some of the options only make sense inside a block while some can only be of
global scope.

.. toctree::
   :maxdepth: 2

   server-configuration
   client-configuration
   macro

.. _plugins:

Plugins
-------

Both :ref:`client <plugin-options-client-chapter>` and
:ref:`server <plugin-options-server-chapter>` parts of SNMP Proxy Forwarder
can be configured to pass PDUs through a chain of plugin modules.
A plugin module can modify or replace passing PDU or take any other
action of its choice.

Each plugin module is a Python code snippet executing within the
context of a single SNMP query and exposing a few entry points for
the server or client parts of SNMP Proxy Forwarder to invoke it at
the key points of SNMP PDU processing.

You can run the same or different plugin modules at both client
and server. The choice of plugin runner probably depends on the
system architecture, load distribution and security considerations.

.. toctree::
   :maxdepth: 2
   :glob:

   plugins/*

Examples
--------

.. toctree::
   :maxdepth: 2
   :glob:

   examples/*


text:
package ru.pravvich.timeMoreClients;

class TimeZoneCline {
    private final float start;
    private final float finish;
    private int amountCline = 1;

    public int getAmountCline() {
        return amountCline;
    }

    TimeZoneCline(float start, float finish) {
        this.start = start;
        this.finish = finish;
    }

    TimeZoneCline incrementAmountClients() {
        ++this.amountCline;
        return this;
    }

    float getStart() {
        return start;
    }

    float getFinish() {
        return finish;
    }

    @Override
    public String toString() {
        return "TimeZoneCline{" +
                "start=" + start +
                ", finish=" + finish +
                '}';
    }
}


text:
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <vector>

#include "base/bind.h"
#include "base/memory/raw_ptr.h"
#include "base/time/time.h"
#include "base/timer/lap_timer.h"
#include "components/viz/common/quads/compositor_render_pass.h"
#include "components/viz/common/quads/draw_quad.h"
#include "components/viz/common/quads/texture_draw_quad.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/perf/perf_result_reporter.h"
#include "third_party/skia/include/core/SkBlendMode.h"

namespace viz {
namespace {

static const int kTimeLimitMillis = 2000;
static const int kWarmupRuns = 5;
static const int kTimeCheckInterval = 10;

constexpr char kMetricPrefixDrawQuad[] = "DrawQuad.";
constexpr char kMetricIterateResourcesRunsPerS[] = "iterate_resources";

ResourceId NextId(ResourceId id) {
  return ResourceId(id.GetUnsafeValue() + 1);
}

perf_test::PerfResultReporter SetUpDrawQuadReporter(const std::string& story) {
  perf_test::PerfResultReporter reporter(kMetricPrefixDrawQuad, story);
  reporter.RegisterImportantMetric(kMetricIterateResourcesRunsPerS, "runs/s");
  return reporter;
}

SharedQuadState* CreateSharedQuadState(CompositorRenderPass* render_pass) {
  gfx::Transform quad_transform = gfx::Transform(1.0, 0.0, 0.5, 1.0, 0.5, 0.0);
  gfx::Rect content_rect(26, 28);
  gfx::Rect visible_layer_rect(10, 12, 14, 16);
  bool are_contents_opaque = false;
  float opacity = 1.f;
  int sorting_context_id = 65536;
  SkBlendMode blend_mode = SkBlendMode::kSrcOver;

  SharedQuadState* state = render_pass->CreateAndAppendSharedQuadState();
  state->SetAll(quad_transform, content_rect, visible_layer_rect,
                gfx::MaskFilterInfo(), /*clip_rect=*/absl::nullopt,
                are_contents_opaque, opacity, blend_mode, sorting_context_id);
  return state;
}

class DrawQuadPerfTest : public testing::Test {
 public:
  DrawQuadPerfTest()
      : timer_(kWarmupRuns,
               base::Milliseconds(kTimeLimitMillis),
               kTimeCheckInterval) {}

  void CreateRenderPass() {
    render_pass_ = CompositorRenderPass::Create();
    SharedQuadState* new_shared_state(
        CreateSharedQuadState(render_pass_.get()));
    shared_state_ = render_pass_->CreateAndAppendSharedQuadState();
    *shared_state_ = *new_shared_state;
  }

  void CleanUpRenderPass() {
    render_pass_.reset();
    shared_state_ = nullptr;
  }

  void GenerateTextureDrawQuads(int count, std::vector<DrawQuad*>* quads) {
    for (int i = 0; i < count; ++i) {
      auto* quad = render_pass_->CreateAndAppendDrawQuad<TextureDrawQuad>();
      gfx::Rect rect(0, 0, 100, 100);
      bool needs_blending = false;
      ResourceId resource_id{1};
      bool premultiplied_alpha = true;
      gfx::PointF uv_top_left(0, 0);
      gfx::PointF uv_bottom_right(1, 1);
      SkColor4f background_color = SkColors::kRed;
      float vertex_opacity[4] = {1.f, 1.f, 1.f, 1.f};
      bool y_flipped = false;
      bool nearest_neighbor = true;

      quad->SetNew(shared_state_, rect, rect, needs_blending, resource_id,
                   premultiplied_alpha, uv_top_left, uv_bottom_right,
                   background_color, vertex_opacity, y_flipped,
                   nearest_neighbor, /*secure_output_only=*/false,
                   gfx::ProtectedVideoType::kClear);
      quads->push_back(quad);
    }
  }

  void RunIterateResourceTest(const std::string& story, int quad_count) {
    CreateRenderPass();
    std::vector<DrawQuad*> quads;
    GenerateTextureDrawQuads(quad_count, &quads);

    timer_.Reset();
    do {
      for (auto* quad : quads) {
        for (ResourceId& resource_id : quad->resources)
          resource_id = NextId(resource_id);
      }
      timer_.NextLap();
    } while (!timer_.HasTimeLimitExpired());

    auto reporter = SetUpDrawQuadReporter(story);
    reporter.AddResult(kMetricIterateResourcesRunsPerS, timer_.LapsPerSecond());
    CleanUpRenderPass();
  }

 private:
  std::unique_ptr<CompositorRenderPass> render_pass_;
  raw_ptr<SharedQuadState> shared_state_;
  base::LapTimer timer_;
};

TEST_F(DrawQuadPerfTest, IterateResources) {
  RunIterateResourceTest("10_quads", 10);
  RunIterateResourceTest("100_quads", 100);
  RunIterateResourceTest("500_quads", 500);
}

}  // namespace
}  // namespace viz


text:
namespace mn {
    namespace SerialFiller {

        class LengthOfTopicTooLong : public SerialFillerException {
        public:

            LengthOfTopicTooLong(ByteArray packet, uint32_t statedLengthInBytes, ByteArray::size_type availableBytes) :
                    SerialFillerException("Stated length of topic was too long. Stated length = " +
                                          std::to_string(statedLengthInBytes) +
                    ", available num. bytes for topic = " + std::to_string(availableBytes) + ".") {
                packet_ = packet;
                statedLengthInBytes_ = statedLengthInBytes;
                availableBytes_ = availableBytes;
            };

            ByteArray packet_;
            uint32_t statedLengthInBytes_;
            ByteArray::size_type availableBytes_;
        };
    } // namespace SerialFiller
} // namespace mn

#endif // #ifndef MN_SERIAL_FILLER_LENGTH_OF_TOPIC_TOO_LONG_H_


text:
from .resource_meta import ResourceMeta

class Resource(metaclass=ResourceMeta):
    pass


text:
// Copyright (c) 2007-2018 ppy Pty Ltd <contact@ppy.sh>.
// Licensed under the MIT Licence - https://raw.githubusercontent.com/ppy/osu/master/LICENCE

using osu.Game.Overlays.Profile.Sections.Recent;

namespace osu.Game.Overlays.Profile.Sections
{
    public class RecentSection : ProfileSection
    {
        public override string Title => "Recent";

        public override string Identifier => "recent_activity";

        public RecentSection()
        {
            Children = new[]
            {
                new PaginatedRecentActivityContainer(User, null, @"This user hasn't done anything notable recently!"),
            };
        }
    }
}


text:
using BonTemps.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace BonTemps.Services
{
	public class PersonService
	{
		private ApplicationDbContext db = new ApplicationDbContext();

		public Person GetPerson(string email)
		{
			return db.Persons.FirstOrDefault(_ => _.Email == email);
		}

		public void UpdatePerson(Person person)
		{
			db.Entry(person).State = System.Data.Entity.EntityState.Modified;
		}
	}
}


text:
package config

// EtcdEndpoints represents the etcd servers to connect to.
var EtcdEndpoints []string

// QueueName represents the queue name to listen to for ECS events. Formatted as
// a URI with the scheme determining the type.  For example sqs://name or kinesis://name
var QueueNameURI string

// CSSBindAddr represents the address CSS listens on.
var CSSBindAddr string

// PrintVersion represents the flag to set when printing version information.
var PrintVersion bool


text:
namespace base {

namespace {

struct PermissionInfo {
  PSECURITY_DESCRIPTOR security_descriptor;
  ACL dacl;
};

// Gets a blob indicating the permission information for |path|.
// |length| is the length of the blob.  Zero on failure.
// Returns the blob pointer, or NULL on failure.
void* GetPermissionInfo(const FilePath& path, size_t* length) {
  DCHECK(length != NULL);
  *length = 0;
  PACL dacl = NULL;
  PSECURITY_DESCRIPTOR security_descriptor;
  if (GetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()),
                           SE_FILE_OBJECT,
                           DACL_SECURITY_INFORMATION, NULL, NULL, &dacl,
                           NULL, &security_descriptor) != ERROR_SUCCESS) {
    return NULL;
  }
  DCHECK(dacl != NULL);

  *length = sizeof(PSECURITY_DESCRIPTOR) + dacl->AclSize;
  PermissionInfo* info = reinterpret_cast<PermissionInfo*>(new char[*length]);
  info->security_descriptor = security_descriptor;
  memcpy(&info->dacl, dacl, dacl->AclSize);

  return info;
}

// Restores the permission information for |path|, given the blob retrieved
// using |GetPermissionInfo()|.
// |info| is the pointer to the blob.
// |length| is the length of the blob.
// Either |info| or |length| may be NULL/0, in which case nothing happens.
bool RestorePermissionInfo(const FilePath& path, void* info, size_t length) {
  if (!info || !length)
    return false;

  PermissionInfo* perm = reinterpret_cast<PermissionInfo*>(info);

  DWORD rc = SetNamedSecurityInfo(const_cast<wchar_t*>(path.value().c_str()),
                                  SE_FILE_OBJECT, DACL_SECURITY_INFORMATION,
                                  NULL, NULL, &perm->dacl, NULL);
  LocalFree(perm->security_descriptor);

  char* char_array = reinterpret_cast<char*>(info);
  delete [] char_array;

  return rc == ERROR_SUCCESS;
}

std::unique_ptr<wchar_t[]> ToCStr(const std::basic_string<wchar_t>& str) {
  size_t size = str.size() + 1;
  std::unique_ptr<wchar_t[]> ptr = std::make_unique<wchar_t[]>(size);
  wcsncpy(ptr.get(), str.c_str(), size);
  return ptr;
}

}  // namespace

bool DieFileDie(const FilePath& file, bool recurse) {
  // It turns out that to not induce flakiness a long timeout is needed.
  const int kIterations = 25;
  const TimeDelta kTimeout = TimeDelta::FromSeconds(10) / kIterations;

  if (!PathExists(file))
    return true;

  // Sometimes Delete fails, so try a few more times. Divide the timeout
  // into short chunks, so that if a try succeeds, we won't delay the test
  // for too long.
  for (int i = 0; i < kIterations; ++i) {
    if (DeleteFile(file, recurse))
      return true;
    PlatformThread::Sleep(kTimeout);
  }
  return false;
}

void SyncPageCacheToDisk() {
  // Approximating this with noop. The proper implementation would require
  // administrator privilege:
  // https://docs.microsoft.com/en-us/windows/desktop/api/FileAPI/nf-fileapi-flushfilebuffers
}

bool EvictFileFromSystemCache(const FilePath& file) {
  base::win::ScopedHandle file_handle(
      CreateFile(file.value().c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL,
                 OPEN_EXISTING, FILE_FLAG_NO_BUFFERING, NULL));
  if (!file_handle.IsValid())
    return false;

  // Re-write the file time information to trigger cache eviction for the file.
  // This function previously overwrote the entire file without buffering, but
  // local experimentation validates this simplified and *much* faster approach:
  // [1] Sysinternals RamMap no longer lists these files as cached afterwards.
  // [2] Telemetry performance test startup.cold.blank_page reports sane values.
  BY_HANDLE_FILE_INFORMATION bhi = {0};
  CHECK(::GetFileInformationByHandle(file_handle.Get(), &bhi));
  CHECK(::SetFileTime(file_handle.Get(), &bhi.ftCreationTime,
                      &bhi.ftLastAccessTime, &bhi.ftLastWriteTime));
  return true;
}

// Deny |permission| on the file |path|, for the current user.
bool DenyFilePermission(const FilePath& path, DWORD permission) {
  PACL old_dacl;
  PSECURITY_DESCRIPTOR security_descriptor;

  std::unique_ptr<TCHAR[]> path_ptr = ToCStr(path.value());
  if (GetNamedSecurityInfo(path_ptr.get(), SE_FILE_OBJECT,
                           DACL_SECURITY_INFORMATION, nullptr, nullptr,
                           &old_dacl, nullptr,
                           &security_descriptor) != ERROR_SUCCESS) {
    return false;
  }

  std::unique_ptr<TCHAR[]> current_user = ToCStr(std::wstring(L"CURRENT_USER"));
  EXPLICIT_ACCESS new_access = {
      permission,
      DENY_ACCESS,
      0,
      {nullptr, NO_MULTIPLE_TRUSTEE, TRUSTEE_IS_NAME, TRUSTEE_IS_USER,
       current_user.get()}};

  PACL new_dacl;
  if (SetEntriesInAcl(1, &new_access, old_dacl, &new_dacl) != ERROR_SUCCESS) {
    LocalFree(security_descriptor);
    return false;
  }

  DWORD rc = SetNamedSecurityInfo(path_ptr.get(), SE_FILE_OBJECT,
                                  DACL_SECURITY_INFORMATION, nullptr, nullptr,
                                  new_dacl, nullptr);
  LocalFree(security_descriptor);
  LocalFree(new_dacl);

  return rc == ERROR_SUCCESS;
}

bool MakeFileUnreadable(const FilePath& path) {
  return DenyFilePermission(path, GENERIC_READ);
}

bool MakeFileUnwritable(const FilePath& path) {
  return DenyFilePermission(path, GENERIC_WRITE);
}

FilePermissionRestorer::FilePermissionRestorer(const FilePath& path)
    : path_(path), info_(NULL), length_(0) {
  info_ = GetPermissionInfo(path_, &length_);
  DCHECK(info_ != NULL);
  DCHECK_NE(0u, length_);
}

FilePermissionRestorer::~FilePermissionRestorer() {
  if (!RestorePermissionInfo(path_, info_, length_))
    NOTREACHED();
}

}  // namespace base