text:
#ifndef __WRAPPER_FILTERQUERYEVALUATOR_H__
#define __WRAPPER_FILTERQUERYEVALUATOR_H__

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <sstream>
#include <stdlib.h>
#include "ParserUtility.h"
#include <instantsearch/TypedValue.h>
#include <instantsearch/ResultsPostProcessor.h>
#include "instantsearch/Schema.h"
#include "WrapperConstants.h"
#include "util/exprtk.hpp"
#include "boost/regex.hpp"
#include <boost/algorithm/string.hpp>
#include "RegexConstants.h"
#include "util/Assert.h"
#include "util/DateAndTimeHandler.h"
#include "operation/AttributeAccessControl.h"

using namespace std;
using srch2::instantsearch::TypedValue;
using srch2::instantsearch::FilterType;
using srch2::instantsearch::RefiningAttributeExpressionEvaluator;
using srch2::instantsearch::BooleanOperation;
using srch2::instantsearch::AttributeCriterionOperation;
using srch2::instantsearch::Schema;
using namespace srch2::instantsearch;
namespace srch2 {
namespace httpwrapper {
typedef enum {
    FqKeywordTypeComplex, FqKeywordTypeRange, FqKeywordTypeAssignment
} FqKeywordType;
class QueryExpression {
public:
    std::vector<std::pair<MessageType, string> > *messages;
    virtual bool parse(string &expressionString) = 0;

    virtual bool validate(const Schema & schema, const string& aclRoleValue,
    		const AttributeAccessControl& attributeAcl, bool attrAclOn) = 0;

    virtual bool evaluate(
            std::map<std::string, TypedValue> & nonSearchableAttributeValues)= 0;

	virtual string getUniqueStringForCaching() = 0;
    virtual ~QueryExpression() {
    }
    ;
    std::vector<std::pair<MessageType, string> >* getMessageContainer() {
        return this->messages;
    }

private:
};

/*
 * Example of a RangeQueryExpression is : price:[ 10 TO 100]
 * which means only return those results that : 10 <= result.price <= 100
 */
class RangeQueryExpression: public QueryExpression {
public:
    RangeQueryExpression(std::string field,
            std::vector<std::pair<MessageType, string> > *messages) {
        this->attributeName = field;
        this->negative = false;
        this->messages = messages;
    }

    bool parse(string &expressionString) {
        // it has field. create a vector and populate container->fieldFilter.
        /*
         * Example of this case : -price:[ 10 TO 200 ]
         * The "-" in the beginning means price is NOT in this range.
         */
        ASSERT(this->attributeName.length() > 1);
        boost::algorithm::trim(attributeName);
        if (this->attributeName.at(0) == '-') {
            ASSERT(this->attributeName.length() > 2);
            this->negative = true;
            this->attributeName = this->attributeName.substr(1);
        } else {
            this->negative = false;
        }
        string keyword = "";
        bool hasParsed = parseFqRangeKeyword(expressionString, keyword); // extract the keyword
        if (!hasParsed) {
            // there is parsing error
            std::vector<std::pair<MessageType, string> > *messages;
            this->getMessageContainer()->push_back(
                    make_pair(MessageError,
                            "Invalid syntax to specify range in filterquery."));
            return false;
        }
        // remove trailing ']'
        keyword = keyword.substr(0, keyword.length() - 1);
        boost::algorithm::trim(keyword);
        // get the lower and uppper values.
        return this->setLowerAndUpperValues(keyword);
    }
    bool parseFqRangeKeyword(string &input, string &output) {
        boost::regex re(FQ_RANGE_QUERY_KEYWORD_REGEX_STRING); //TODO: compile this regex when the engine starts.
        return doParse(input, re, output);
    }

    bool validate(const Schema & schema, const string& aclRoleValue,
    		const AttributeAccessControl& attributeAcl, bool attrAclOn) {
        //1. Check to make sure attributeName is a non-searchable attribute
        int attributeId = schema.getRefiningAttributeId(attributeName);
        if (attributeId < 0)
            return false;

        // check whether the attribute is accessible for current role.
        if (attrAclOn && !attributeAcl.isRefiningFieldAccessibleForRole(aclRoleValue, attributeName))
        	return false;

        //2. Check to make sure lower and upper values are consistent with the type
        FilterType attributeType = schema.getTypeOfRefiningAttribute(
                attributeId);
        if (attributeValueLower.compare("*") != 0) {
            if (!validateValueWithType(attributeType, attributeValueLower)) {
                return false;
            }
            // now that it is validated, it should be changed to long representation.
            if(attributeType == srch2::instantsearch::ATTRIBUTE_TYPE_TIME){
            	std::stringstream buffer;
            	buffer << srch2is::DateAndTimeHandler::convertDateTimeStringToSecondsFromEpoch(attributeValueLower);
            	attributeValueLower = buffer.str();
            }else{
				std::string attributeValueLowerLowercase = attributeValueLower;
				std::transform(attributeValueLowerLowercase.begin(), attributeValueLowerLowercase.end(), attributeValueLowerLowercase.begin(), ::tolower);
				attributeValueLower = attributeValueLowerLowercase;
            }
        }

        if (attributeValueUpper.compare("*") != 0) {
            if (!validateValueWithType(attributeType, attributeValueUpper)) {
                return false;
            }
            // now that it is validated, it should be changed to long representation.
            if(attributeType == srch2::instantsearch::ATTRIBUTE_TYPE_TIME){
            	std::stringstream buffer;
            	buffer << srch2is::DateAndTimeHandler::convertDateTimeStringToSecondsFromEpoch(attributeValueUpper);
            	attributeValueUpper = buffer.str();
            }else{
				std::string attributeValueUpperLowercase = attributeValueUpper;
				std::transform(attributeValueUpperLowercase.begin(), attributeValueUpperLowercase.end(), attributeValueUpperLowercase.begin(), ::tolower);
				attributeValueUpper = attributeValueUpperLowercase;
            }
        }
        return true;
    }

    /*
     * Checks the value of a result record to see if
     * it is in the range or not. The interval is closed.
     * For example: a result with value 10 returns true for range [10 TO *]
     */
    bool evaluate(std::map<std::string, TypedValue> & nonSearchableAttributeValues) {
        // first find the value coming from the record
        TypedValue value = nonSearchableAttributeValues[this->attributeName];
        bool lowerBoundCheck = false;
        if (attributeValueLower.compare("*") == 0) {
            lowerBoundCheck = true;
        } else {
            TypedValue lowerBound;
            lowerBound.setTypedValue(value.getType(), attributeValueLower);
            lowerBoundCheck = (lowerBound <= value);
        }

        bool upperBoundCheck = false;
        if (attributeValueUpper.compare("*") == 0) {
            upperBoundCheck = true;
        } else {
            TypedValue upperBound;
            upperBound.setTypedValue(value.getType(), attributeValueUpper);
            upperBoundCheck = (value <= upperBound);
        }

        bool result = lowerBoundCheck && upperBoundCheck;
        if (negative) {
            result = !result;
        }
        return result;
    }

    ~RangeQueryExpression() {
    }

	string getUniqueStringForCaching() {
		stringstream ss;
		ss << attributeName.c_str();
		ss << attributeValueLower.c_str();
		ss << attributeValueUpper.c_str();
		ss << negative;
		return ss.str();
	}

private:
    // the name of the attribute which is checked against the range
    std::string attributeName;
    // the lower bound value
    string attributeValueLower;
    // the upper bound value
    string attributeValueUpper;
    // if the expression has a - in the beginning negative is true
    bool negative;
    bool setLowerAndUpperValues(string &rangeExpression) {
        boost::smatch matches;
        // we do the same thing as SOLR : TO is case sensitive.
        boost::regex fieldDelimeterRegex(FQ_FIELD_KEYWORD_DELIMETER_REGEX_STRING);
        boost::regex_search(rangeExpression, matches, fieldDelimeterRegex);
        if (matches[0].matched) {
            // it has field. create a vector and populate container->fieldFilter.
            string lowerVal = rangeExpression.substr(0, matches.position()); // extract the field
            boost::algorithm::trim(lowerVal);
            this->attributeValueLower = lowerVal;
            string upperVal = rangeExpression.substr(
                    matches.position() + matches.length()); // extract the keyword
            boost::algorithm::trim(upperVal);
            this->attributeValueUpper = upperVal;
            return true;
        } else {
            this->getMessageContainer()->push_back(
                    make_pair(MessageError,
                            "Invalid syntax to specify range in filterquery."));
            return false;
        }
    }
};

class EqualityQueryExpression: public QueryExpression {
public:
    EqualityQueryExpression(std::string field,
            std::vector<std::pair<MessageType, string> > *messages) {
        this->negative = false;
        this->operation = srch2::instantsearch::EQUALS;
        this->attributeName = field;
        this->messages = messages;
    }

    bool parse(string &expressionString) {
        string expression;
        // it has field. create a vector and populate container->fieldFilter.
        ASSERT(this->attributeName.length() > 1);
        if (this->attributeName.at(0) == '-') {
            ASSERT(this->attributeName.length() > 2);
            this->negative = true;
            this->attributeName = this->attributeName.substr(1);
        } else {
            this->negative = false;
        }
        bool isParsed = this->parseFqKeyword(expressionString, expression);
        if (!isParsed) {
            // error
            this->getMessageContainer()->push_back(
                    make_pair(MessageError,
                            "Invalid filter query assignment keyword."));
            return false;
        }
        boost::algorithm::trim(expression);
        this->attributeValue = expression;
        return true;
    }
    bool parseFqKeyword(string &input, string &output) {
        boost::regex re(FQ_ASSIGNMENT_KEYWORD_REGEX_STRING); //TODO: compile this regex when the engine starts.
        return doParse(input, re, output);
    }

    bool validate(const Schema & schema, const string& aclRoleValue,
    		const AttributeAccessControl& attributeAcl, bool attrAclOn) {
        //1. Check to make sure attributeName is a non-searchable attribute
        int attributeId = schema.getRefiningAttributeId(attributeName);
        if (attributeId < 0)
            return false;

        // check whether the attribute is accessible for current role.
        if (attrAclOn && !attributeAcl.isRefiningFieldAccessibleForRole(aclRoleValue, attributeName))
        	return false;

        //2. Check the value to be consistent with type
        FilterType attributeType = schema.getTypeOfRefiningAttribute(
                attributeId);
        if (attributeValue.compare("*") != 0) {
            if (!validateValueWithType(attributeType, attributeValue)) {
                return false;
            }
            // now that it is validated, it should be changed to long representation.
            if(attributeType == srch2::instantsearch::ATTRIBUTE_TYPE_TIME){
            	std::stringstream buffer;
            	buffer << srch2is::DateAndTimeHandler::convertDateTimeStringToSecondsFromEpoch(attributeValue);
            	attributeValue = buffer.str();
            }else{
				std::string attributeValueLowercase = attributeValue;
				std::transform(attributeValueLowercase.begin(), attributeValueLowercase.end(), attributeValueLowercase.begin(), ::tolower);
				attributeValue = attributeValueLowercase;
            }
        }
        return true;
    }

    bool evaluate(std::map<std::string, TypedValue> & nonSearchableAttributeValues) {

        // Compatible with SOLR : * means anything not empty.
        // Because the actual value can contain * if range bound is * we change it
        // to empty string and negate the variable negative.
        if (attributeValue.compare("*") == 0) {
            attributeValue = "";
            negative = !negative;
        }
        // first find the value coming from the record
        TypedValue value = nonSearchableAttributeValues[this->attributeName];

        if (attributeValue.compare("") == 0
                && (value.getType() == srch2is::ATTRIBUTE_TYPE_INT
                        || value.getType() == srch2is::ATTRIBUTE_TYPE_LONG
                        || value.getType() == srch2is::ATTRIBUTE_TYPE_FLOAT
                        || value.getType() == srch2is::ATTRIBUTE_TYPE_DOUBLE)) {
            attributeValue = value.minimumValue().toString() + "";
        }
        TypedValue valueToCheck;
        valueToCheck.setTypedValue(value.getType(), attributeValue);

        bool result = (value == valueToCheck);
        if (!negative) { // no '-' in the beginning of the field
            return result;
        } else {
            return !result;
        }
    }

    ~EqualityQueryExpression() {
    }

	string getUniqueStringForCaching() {
		stringstream ss;
		ss << attributeName.c_str();
		ss << attributeValue.c_str();
		ss << operation;
		ss << negative;
		return ss.str();
	}

private:
    std::string attributeName;
    string attributeValue;
    AttributeCriterionOperation operation;
    bool negative;
};

// this class gets a string which is an expression of nuon-searchable attribute names,it evluates the expression
// based on the TypedValue value of those attributes coming from records.
// NOTE: the expressions only must be based on UNSIGNED or FLOAT non-searchable attributes.
/*
 * Exmaple of ComplexQueryExpression is boolexp$price - discount < income * rate$
 * It accepts any kind of math expression which uses UNSIGNED/FLOAT non-searchable
 * attributes.
 */
class ComplexQueryExpression: public QueryExpression {
public:
    ComplexQueryExpression(
            std::vector<std::pair<MessageType, string> > *messages) {
        this->messages = messages;
    }
    /*
     * this function recevies a expression string.with a trailing '$'. ex. 'Price>10$ AND Popularity:[10 TO 100]'
     * it takes out the expression and stores that in this->parsedExpression.
     * for this example, this->parsedExpression will be 'Price>10' and the expressionString will be modified to 'AND Popularity:[10 TO 100]
     */
    bool parse(string &expressionString) {
        this->parsedExpression = "";
        bool isParsed = this->parseComplxExpression(expressionString,
                this->parsedExpression);
        if (!isParsed) {
            this->getMessageContainer()->push_back(
                    make_pair(MessageError, "Invalid expression query."));
            return false;
        }
        // expressionString is '$ AND Popularity:[10 TO 100]'. remove leading '$'
        expressionString = expressionString.substr(1); // expressionString is now ' AND Popularity:[10 TO 100]'
        boost::algorithm::trim(expressionString);
        // extract the expression, remove the 'boolexp(' and ')' part
        return true;
    }
    bool parseComplxExpression(string &input, string &output) {
        boost::regex re(FQ_COMPLEX_EXPRESSION_REGEX_STRING); //TODO: compile this regex when the engine starts.
        return doParse(input, re, output);
    }

    bool validate(const Schema & schema, const string& aclRoleValue,
    		const AttributeAccessControl& attributeAcl, bool attrAclOn) {
        // insert non-searchable attribute names to the symbol table and let
        // exprtk library do the validation

        const std::map<std::string, unsigned> * nonSearchableAttributes = schema
                .getRefiningAttributes();

        for (std::map<std::string, unsigned>::const_iterator nonSearchableAttribute =
                nonSearchableAttributes->begin();
                nonSearchableAttribute != nonSearchableAttributes->end();
                ++nonSearchableAttribute) {

        	// check whether the attribute is accessible for current role. The last parameter is false
        	// to indicate that the field is refining.
            if (attrAclOn && !attributeAcl.isRefiningFieldAccessibleForRole(aclRoleValue, nonSearchableAttribute->first))
            	continue;

            // Since we only accept integer, long float and double as non-searchable attributes
            // this if-else statement only inserts these non-searchable-attributes into
            // the symbol table. This symbol table is passed to exprtk library.
            if (schema.getTypeOfRefiningAttribute(
                    nonSearchableAttribute->second)
                    == srch2::instantsearch::ATTRIBUTE_TYPE_INT
                    || schema.getTypeOfRefiningAttribute(
                            nonSearchableAttribute->second)
                            == srch2::instantsearch::ATTRIBUTE_TYPE_LONG
                    || schema.getTypeOfRefiningAttribute(
                            nonSearchableAttribute->second)
                            == srch2::instantsearch::ATTRIBUTE_TYPE_FLOAT
                    || schema.getTypeOfRefiningAttribute(
                            nonSearchableAttribute->second)
                            == srch2::instantsearch::ATTRIBUTE_TYPE_DOUBLE) {
                symbolVariables.insert(
                        std::make_pair(nonSearchableAttribute->first, 0)); // zero is just a place holder, so that a variable is allocated in the vector
                symbolTable.add_variable(nonSearchableAttribute->first,
                        symbolVariables[nonSearchableAttribute->first], false);
            }
        }

        // now register the symbol table in the library
        expression.register_symbol_table(symbolTable);

        // now parse the string
        exprtk::parser<double> expressionParser;
        return expressionParser.compile(parsedExpression, expression);
    }

    bool evaluate(std::map<std::string, TypedValue> & nonSearchableAttributeValues) {
        // set values of variables
        for (std::map<std::string, double>::iterator symbol = symbolVariables
                .begin(); symbol != symbolVariables.end(); ++symbol) {
            symbol->second = nonSearchableAttributeValues[symbol->first]
                    .castToFloat();
        }

        float result = this->expression.value();

        if (result == 0) {
            return false;
        }
        return true;
    }

    ~ComplexQueryExpression() {
    }

	string getUniqueStringForCaching() {
		return parsedExpression.c_str();
	}

private:
    string parsedExpression;
    exprtk::expression<double> expression;
    exprtk::symbol_table<double> symbolTable;
    std::map<string, double> symbolVariables;

};
class FilterQueryEvaluator: public RefiningAttributeExpressionEvaluator {
public:

    FilterQueryEvaluator(
            std::vector<std::pair<MessageType, string> > *messages) {
        this->isFqBoolOperatorSet = false;
        this->messages = messages;
        this->termFQBooleanOperator = srch2::instantsearch::BooleanOperatorAND;
    }
    void setOperation(BooleanOperation op) {
        this->termFQBooleanOperator = op;
    }
    bool evaluate(std::map<std::string, TypedValue> & nonSearchableAttributeValues) {
        switch (this->termFQBooleanOperator) {
        case srch2::instantsearch::BooleanOperatorAND:
            for (std::vector<QueryExpression *>::iterator criterion =
                    expressions.begin(); criterion != expressions.end();
                    ++criterion) {
                QueryExpression * qe = *criterion;
                if (!qe->evaluate(nonSearchableAttributeValues)) {
                    return false;
                }
            }
            return true;
        case srch2::instantsearch::BooleanOperatorOR:
            for (std::vector<QueryExpression *>::iterator criterion =
                    expressions.begin(); criterion != expressions.end();
                    ++criterion) {
                QueryExpression * qe = *criterion;
                if (qe->evaluate(nonSearchableAttributeValues)) {
                    return true;
                }
            }
            return false;
        default:
            break;
        }
        ASSERT(false);
        return false;
    }

    bool validate(const Schema & schema, const string& aclRole,
    		const AttributeAccessControl& attributeAcl, bool attrAclOn) {
        for (std::vector<QueryExpression *>::iterator criterion = expressions
                .begin(); criterion != expressions.end(); ++criterion) {
            if (!(*criterion)->validate(schema, aclRole, attributeAcl, attrAclOn)) {
                return false;
            }
        }
        return true;
    }
    /*
     * it looks to see if there is any post processing filter
     * if there is then it fills up the container accordingly
     * Detail: this function will check if a filterquery term is a range, equality or complex term.
     * it calls teh addCriterion method with appropreate trem type.
     * then, it looks for boolean operator, if found, it loops back and repeat the process for other terms.
     * example: 'fq=price:[10 TO 100] AND popularity:[* TO 100] AND Title:algorithm AND boolexp$popularity>20$'
     *
     */
    bool parseAndAddCriterion(string &fq) {
        bool parseNextTerm = true;
        while (parseNextTerm) {
            string fqField;
            /* check the length of fq
             * if lenght is 0 : it's an error.
             */
            if (fq.length() == 0) {
                // fq received here is of length 0
                // raise an error.
                Logger::info(
                        " Parsing error:: expecting filter query term, not found.");
                this->messages->push_back(
                        make_pair(MessageError,
                                "Parse error, expecting filter query term, not found."));
                return false;
            }
            // fq length is not 0.
            //NOTE:example related comments are only valid for the first time iteration inside the while loop
            bool hasParsedParameter = this->parseFqField(fq, fqField);
            if (!hasParsedParameter) {
                // it is not an equality nor a range expression
                // see if it's a complex expression
                string complexStr = "";
                hasParsedParameter = this->parseComplexExpression(fq, complexStr); // checks and removes the boolexp$ string returns true if found boolexp$
                if (!hasParsedParameter) {
                    parseNextTerm = false;
                    Logger::info(" Parsing error:: not a valid filter query");
                    this->messages->push_back(
                            make_pair(MessageError,
                                    "Parse error, not a valid filter query term."));
                    return false;
                }
                Logger::debug(
                        " 'boolexp$' found, possible complex expression query");
                string dummyField = "NO_FIELD";
                hasParsedParameter = this->addCriterion(fq,
                        FqKeywordTypeComplex, dummyField); // NO_FIELD, is a dummy parameter, that will not be used.
                if (!hasParsedParameter) {
                    return false;
                }
                boost::algorithm::trim(fq);
            } else {
                // hasParsedParameter is true, fq is now changed to : '[10 TO 100] AND popularity:[* TO 100] AND Title:algorithm AND boolexp$popularity>20$'
                // fqField is 'price:'
                // remove the ':' from 'price:'
                fqField = fqField.substr(0, fqField.length() - 1);
                boost::algorithm::trim(fqField);
                // check if it's a range query or assignment.
                if ('[' == fq.at(0)) {
                    Logger::debug(" '[' found, possible range expression");
                    string keyword = "";
                    fq = fq.substr(1);
                    hasParsedParameter = this->addCriterion(fq,
                            FqKeywordTypeRange, fqField); // it parses fq for range expression parameters
                    if (!hasParsedParameter) {
                        return false;
                    }
                } else {
                    Logger::debug(
                            " '[' not found, possible equality expression");
                    string keyword = "";
                    hasParsedParameter = this->addCriterion(fq,
                            FqKeywordTypeAssignment, fqField); // it parses fq for range expression parameters
                    if (!hasParsedParameter) {
                        return false;
                    }
                }
            }
            // so far a new term has been parsed.
            // now we will continue with parsing the next operator
            // fq should have been changed to 'AND popularity:[* TO 100] AND Title:algorithm AND boolexp$popularity>20$'
            string boolOperator = "";
            hasParsedParameter = this->parseFqBoolOperator(fq, boolOperator); //
            if (hasParsedParameter) {
                string msgStr = "boolean operator is " + boolOperator;
                Logger::debug(msgStr.c_str());
                parseNextTerm = true;
                Logger::debug("LOOPING AGAIN");
            } else {
                // no boolean operator found.
                // if the fq string length is > 0, throw an error.
                parseNextTerm = false;
                if (fq.length() > 0) {
                    // raise error message
                    Logger::info(
                            " Parsing error:: expecting boolean operator while parsing terms, not found.");
                    this->messages->push_back(
                            make_pair(MessageError,
                                    "Parse error, expecting boolean operator while parsing filter query terms."));
                    return false;
                }
            }
        }
        return true;
    }
    ~FilterQueryEvaluator() {
        for (std::vector<QueryExpression *>::iterator criterion = expressions
                .begin(); criterion != expressions.end(); ++criterion) {
            if (*criterion != NULL) {
                delete *criterion;
            }
        }
    }

	string toString(){
		stringstream ss;
		for(std::vector<QueryExpression *>::iterator queryExpression = expressions.begin();
				queryExpression != expressions.end() ; ++queryExpression){
			ss << (*queryExpression)->getUniqueStringForCaching().c_str();
		}
		return ss.str();
	}
private:
    // each expression is one term (one conjuct or disjunc) of the query
    // for example: for fq= price:[10 TO 100] AND model:JEEP, this vector contains
    // two elements.
    std::vector<QueryExpression *> expressions;
    // for example: for fq= price:[10 TO 100] AND model:JEEP, this member is AND
    bool isFqBoolOperatorSet; // to know if termFQBooleanOperator has been set or not
    std::vector<std::pair<MessageType, string> > *messages;
    BooleanOperation termFQBooleanOperator; // to store the boolean operator for the filterquery terms.

    bool parseFqField(string &input, string &field) {
        boost::regex re(FQ_FIELD_REGEX_STRING); //TODO: compile this regex when the engine starts.
        return doParse(input, re, field);
    }
    bool parseComplexExpression(string &input, string &output) {
        boost::regex re(COMPLEX_TERM_REGEX_STRING); //TODO: compile this regex when the engine starts.
        return doParse(input, re, output);
    }
    bool parseFqBoolOperator(string &input, string &output) {
        boost::regex re(FQ_TERM_BOOL_OP_REGEX_STRING); //TODO: compile this regex when the engine starts.
        bool hasBooleanOperator = doParse(input, re, output);
        if (!this->isFqBoolOperatorSet && hasBooleanOperator) {
            this->populateFilterQueryTermBooleanOperator(output);
            this->isFqBoolOperatorSet = true;
        } else if (this->isFqBoolOperatorSet && hasBooleanOperator) {
            // see if this boolean operator is compatible with the one that is already set.
            if (boost::iequals("OR", output)
                    && srch2::instantsearch::BooleanOperatorOR
                            == this->termFQBooleanOperator) {
                // do nothing.
            } else if (boost::iequals("AND", output)
                    && srch2::instantsearch::BooleanOperatorAND
                            == this->termFQBooleanOperator) {
                // do nothing
            } else {
                // raise warning.
                string termBoolOp = "OR";
                if (srch2::instantsearch::BooleanOperatorAND
                        == this->termFQBooleanOperator) {
                    termBoolOp = "AND";
                }
                this->messages->push_back(
                        make_pair(MessageWarning,
                                "we support either OR or AND but not both between filter query terms. Found"
                                        + output + ", ignoring it and using '+"
                                        + termBoolOp + "'."));
            }
        }
        return hasBooleanOperator;
    }
    void populateFilterQueryTermBooleanOperator(const string &termOperator) {
        /*
         * populates the termFQBooleanOperators in container.
         */
        Logger::debug("inside populateFilterQueryTermBooleanOperators.");
        if (boost::iequals("OR", termOperator)
                || termOperator.compare("||") == 0) {
            this->termFQBooleanOperator =
                    srch2::instantsearch::BooleanOperatorOR;
        } else if (boost::iequals("AND", termOperator)
                || termOperator.compare("&&") == 0) {
            this->termFQBooleanOperator =
                    srch2::instantsearch::BooleanOperatorAND;
        } else {
            // generate MessageWarning and use AND
            this->messages->push_back(
                    make_pair(MessageWarning,
                            "Invalid boolean operator specified as fq term boolean operator "
                                    + termOperator
                                    + ", ignoring it and using 'AND'."));
            this->termFQBooleanOperator =
                    srch2::instantsearch::BooleanOperatorAND;
        }
        Logger::debug(
                "returning from populateFilterQueryTermBooleanOperators.");
    }
    bool addCriterion(std::string &criteriaString, FqKeywordType type,
            string &field) {
        bool isParsable = false;
        switch (type) {
        case FqKeywordTypeRange: {
            RangeQueryExpression * sre = new RangeQueryExpression(field,
                    this->messages);
            isParsable = sre->parse(criteriaString);
            if (!isParsable) {
                return false; // The message is already set in the parse method.
            } else {
                expressions.push_back(sre);
                return true;
            }
        }
        case FqKeywordTypeAssignment: {
            EqualityQueryExpression * sqe = new EqualityQueryExpression(field,
                    this->messages);
            isParsable = sqe->parse(criteriaString);
            if (!isParsable) {
                return false; // The message is already set in the parse method.
            } else {
                expressions.push_back(sqe);
                return true;
            }
        }
        case FqKeywordTypeComplex: {
            ComplexQueryExpression * cqe = new ComplexQueryExpression(
                    this->messages);
            isParsable = cqe->parse(criteriaString);
            if (!isParsable) {
                return false; // The message is already set in the parse method.
            } else {
                expressions.push_back(cqe);
                return true;
            }
        }
        default:
            return false;

        }
    }
}
;

}
}

#endif // __WRAPPER_FILTERQUERYEVALUATOR_H__


text:
<meta charset="UTF-8">
<title>CDERnagAPI.Companion - </title>
<link rel="stylesheet" href="../../style.css">

com.epimorphics.android.myrivers.apis / CDERnagAPI / Companion

Companion

Companion

static class Companion

redpajama_set_name: RedPajamaGithub


text:
/*	$NetBSD: raw_ip.c,v 1.78.2.1 2004/05/10 15:00:12 tron Exp $	*/

/*
 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the project nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

/*
 * Copyright (c) 1982, 1986, 1988, 1993
 *	The Regents of the University of California.  All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. Neither the name of the University nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 *
 *	@(#)raw_ip.c	8.7 (Berkeley) 5/15/95
 */

#include <sys/cdefs.h>
__KERNEL_RCSID(0, "$NetBSD: raw_ip.c,v 1.78.2.1 2004/05/10 15:00:12 tron Exp $");

#include "opt_inet.h"
#include "opt_ipsec.h"
#include "opt_mrouting.h"

#include <sys/param.h>
#include <sys/malloc.h>
#include <sys/mbuf.h>
#include <sys/socket.h>
#include <sys/protosw.h>
#include <sys/socketvar.h>
#include <sys/errno.h>
#include <sys/systm.h>
#include <sys/proc.h>

#include <net/if.h>
#include <net/route.h>

#include <netinet/in.h>
#include <netinet/in_systm.h>
#include <netinet/ip.h>
#include <netinet/ip_var.h>
#include <netinet/ip_mroute.h>
#include <netinet/ip_icmp.h>
#include <netinet/in_pcb.h>
#include <netinet/in_var.h>

#include <machine/stdarg.h>

#ifdef IPSEC
#include <netinet6/ipsec.h>
#endif /*IPSEC*/

#ifdef FAST_IPSEC
#include <netipsec/ipsec.h>
#include <netipsec/ipsec_var.h>			/* XXX ipsecstat namespace */
#endif	/* FAST_IPSEC*/

struct inpcbtable rawcbtable;

int	 rip_pcbnotify __P((struct inpcbtable *, struct in_addr,
    struct in_addr, int, int, void (*) __P((struct inpcb *, int))));
int	 rip_bind __P((struct inpcb *, struct mbuf *));
int	 rip_connect __P((struct inpcb *, struct mbuf *));
void	 rip_disconnect __P((struct inpcb *));

/*
 * Nominal space allocated to a raw ip socket.
 */
#define	RIPSNDQ		8192
#define	RIPRCVQ		8192

/*
 * Raw interface to IP protocol.
 */

/*
 * Initialize raw connection block q.
 */
void
rip_init()
{

	in_pcbinit(&rawcbtable, 1, 1);
}

/*
 * Setup generic address and protocol structures
 * for raw_input routine, then pass them along with
 * mbuf chain.
 */
void
#if __STDC__
rip_input(struct mbuf *m, ...)
#else
rip_input(m, va_alist)
	struct mbuf *m;
	va_dcl
#endif
{
	int proto;
	struct ip *ip = mtod(m, struct ip *);
	struct inpcb_hdr *inph;
	struct inpcb *inp;
	struct inpcb *last = 0;
	struct mbuf *opts = 0;
	struct sockaddr_in ripsrc;
	va_list ap;

	va_start(ap, m);
	(void)va_arg(ap, int);		/* ignore value, advance ap */
	proto = va_arg(ap, int);
	va_end(ap);

	ripsrc.sin_family = AF_INET;
	ripsrc.sin_len = sizeof(struct sockaddr_in);
	ripsrc.sin_addr = ip->ip_src;
	ripsrc.sin_port = 0;
	bzero((caddr_t)ripsrc.sin_zero, sizeof(ripsrc.sin_zero));

	/*
	 * XXX Compatibility: programs using raw IP expect ip_len
	 * XXX to have the header length subtracted, and in host order.
	 * XXX ip_off is also expected to be host order.
	 */
	ip->ip_len = ntohs(ip->ip_len) - (ip->ip_hl << 2);
	NTOHS(ip->ip_off);

	CIRCLEQ_FOREACH(inph, &rawcbtable.inpt_queue, inph_queue) {
		inp = (struct inpcb *)inph;
		if (inp->inp_af != AF_INET)
			continue;
		if (inp->inp_ip.ip_p && inp->inp_ip.ip_p != proto)
			continue;
		if (!in_nullhost(inp->inp_laddr) &&
		    !in_hosteq(inp->inp_laddr, ip->ip_dst))
			continue;
		if (!in_nullhost(inp->inp_faddr) &&
		    !in_hosteq(inp->inp_faddr, ip->ip_src))
			continue;
		if (last) {
			struct mbuf *n;

#if defined(IPSEC) || defined(FAST_IPSEC)
			/* check AH/ESP integrity. */
			if (ipsec4_in_reject_so(m, last->inp_socket)) {
				ipsecstat.in_polvio++;
				/* do not inject data to pcb */
			} else
#endif /*IPSEC*/
			if ((n = m_copy(m, 0, (int)M_COPYALL)) != NULL) {
				if (last->inp_flags & INP_CONTROLOPTS ||
				    last->inp_socket->so_options & SO_TIMESTAMP)
					ip_savecontrol(last, &opts, ip, n);
				if (sbappendaddr(&last->inp_socket->so_rcv,
				    sintosa(&ripsrc), n, opts) == 0) {
					/* should notify about lost packet */
					m_freem(n);
					if (opts)
						m_freem(opts);
				} else
					sorwakeup(last->inp_socket);
				opts = NULL;
			}
		}
		last = inp;
	}
#if defined(IPSEC) || defined(FAST_IPSEC)
	/* check AH/ESP integrity. */
	if (last && ipsec4_in_reject_so(m, last->inp_socket)) {
		m_freem(m);
		ipsecstat.in_polvio++;
		ipstat.ips_delivered--;
		/* do not inject data to pcb */
	} else
#endif /*IPSEC*/
	if (last) {
		if (last->inp_flags & INP_CONTROLOPTS ||
		    last->inp_socket->so_options & SO_TIMESTAMP)
			ip_savecontrol(last, &opts, ip, m);
		if (sbappendaddr(&last->inp_socket->so_rcv,
		    sintosa(&ripsrc), m, opts) == 0) {
			m_freem(m);
			if (opts)
				m_freem(opts);
		} else
			sorwakeup(last->inp_socket);
	} else {
		if (inetsw[ip_protox[ip->ip_p]].pr_input == rip_input) {
			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PROTOCOL,
			    0, 0);
			ipstat.ips_noproto++;
			ipstat.ips_delivered--;
		} else
			m_freem(m);
	}
	return;
}

int
rip_pcbnotify(table, faddr, laddr, proto, errno, notify)
	struct inpcbtable *table;
	struct in_addr faddr, laddr;
	int proto;
	int errno;
	void (*notify) __P((struct inpcb *, int));
{
	struct inpcb *inp, *ninp;
	int nmatch;

	nmatch = 0;
	for (inp = (struct inpcb *)CIRCLEQ_FIRST(&table->inpt_queue);
	    inp != (struct inpcb *)&table->inpt_queue;
	    inp = ninp) {
		ninp = (struct inpcb *)inp->inp_queue.cqe_next;
		if (inp->inp_af != AF_INET)
			continue;
		if (inp->inp_ip.ip_p && inp->inp_ip.ip_p != proto)
			continue;
		if (in_hosteq(inp->inp_faddr, faddr) &&
		    in_hosteq(inp->inp_laddr, laddr)) {
			(*notify)(inp, errno);
			nmatch++;
		}
	}

	return nmatch;
}

void *
rip_ctlinput(cmd, sa, v)
	int cmd;
	struct sockaddr *sa;
	void *v;
{
	struct ip *ip = v;
	void (*notify) __P((struct inpcb *, int)) = in_rtchange;
	int errno;

	if (sa->sa_family != AF_INET ||
	    sa->sa_len != sizeof(struct sockaddr_in))
		return NULL;
	if ((unsigned)cmd >= PRC_NCMDS)
		return NULL;
	errno = inetctlerrmap[cmd];
	if (PRC_IS_REDIRECT(cmd))
		notify = in_rtchange, ip = 0;
	else if (cmd == PRC_HOSTDEAD)
		ip = 0;
	else if (errno == 0)
		return NULL;
	if (ip) {
		rip_pcbnotify(&rawcbtable, satosin(sa)->sin_addr,
		    ip->ip_src, ip->ip_p, errno, notify);

		/* XXX mapped address case */
	} else
		in_pcbnotifyall(&rawcbtable, satosin(sa)->sin_addr, errno,
		    notify);
	return NULL;
}

/*
 * Generate IP header and pass packet to ip_output.
 * Tack on options user may have setup with control call.
 */
int
#if __STDC__
rip_output(struct mbuf *m, ...)
#else
rip_output(m, va_alist)
	struct mbuf *m;
	va_dcl
#endif
{
	struct inpcb *inp;
	struct ip *ip;
	struct mbuf *opts;
	int flags;
	va_list ap;

	va_start(ap, m);
	inp = va_arg(ap, struct inpcb *);
	va_end(ap);

	flags =
	    (inp->inp_socket->so_options & SO_DONTROUTE) | IP_ALLOWBROADCAST
	    | IP_RETURNMTU;

	/*
	 * If the user handed us a complete IP packet, use it.
	 * Otherwise, allocate an mbuf for a header and fill it in.
	 */
	if ((inp->inp_flags & INP_HDRINCL) == 0) {
		if ((m->m_pkthdr.len + sizeof(struct ip)) > IP_MAXPACKET) {
			m_freem(m);
			return (EMSGSIZE);
		}
		M_PREPEND(m, sizeof(struct ip), M_DONTWAIT);
		if (!m)
			return (ENOBUFS);
		ip = mtod(m, struct ip *);
		ip->ip_tos = 0;
		ip->ip_off = htons(0);
		ip->ip_p = inp->inp_ip.ip_p;
		ip->ip_len = htons(m->m_pkthdr.len);
		ip->ip_src = inp->inp_laddr;
		ip->ip_dst = inp->inp_faddr;
		ip->ip_ttl = MAXTTL;
		opts = inp->inp_options;
	} else {
		if (m->m_pkthdr.len > IP_MAXPACKET) {
			m_freem(m);
			return (EMSGSIZE);
		}
		ip = mtod(m, struct ip *);

		/*
		 * If the mbuf is read-only, we need to allocate
		 * a new mbuf for the header, since we need to
		 * modify the header.
		 */
		if (M_READONLY(m)) {
			int hlen = ip->ip_hl << 2;

			m = m_copyup(m, hlen, (max_linkhdr + 3) & ~3);
			if (m == NULL)
				return (ENOMEM);	/* XXX */
			ip = mtod(m, struct ip *);
		}

		/* XXX userland passes ip_len and ip_off in host order */
		if (m->m_pkthdr.len != ip->ip_len) {
			m_freem(m);
			return (EINVAL);
		}
		HTONS(ip->ip_len);
		HTONS(ip->ip_off);
		if (ip->ip_id == 0)
			ip->ip_id = ip_newid();
		opts = NULL;
		/* XXX prevent ip_output from overwriting header fields */
		flags |= IP_RAWOUTPUT;
		ipstat.ips_rawout++;
	}
	return (ip_output(m, opts, &inp->inp_route, flags, inp->inp_moptions,
	     inp->inp_socket, &inp->inp_errormtu));
}

/*
 * Raw IP socket option processing.
 */
int
rip_ctloutput(op, so, level, optname, m)
	int op;
	struct socket *so;
	int level, optname;
	struct mbuf **m;
{
	struct inpcb *inp = sotoinpcb(so);
	int error = 0;

	if (level != IPPROTO_IP) {
		error = ENOPROTOOPT;
		if (op == PRCO_SETOPT && *m != 0)
			(void) m_free(*m);
	} else switch (op) {

	case PRCO_SETOPT:
		switch (optname) {
		case IP_HDRINCL:
			if (*m == 0 || (*m)->m_len < sizeof (int))
				error = EINVAL;
			else {
				if (*mtod(*m, int *))
					inp->inp_flags |= INP_HDRINCL;
				else
					inp->inp_flags &= ~INP_HDRINCL;
			}
			if (*m != 0)
				(void) m_free(*m);
			break;

#ifdef MROUTING
		case MRT_INIT:
		case MRT_DONE:
		case MRT_ADD_VIF:
		case MRT_DEL_VIF:
		case MRT_ADD_MFC:
		case MRT_DEL_MFC:
		case MRT_ASSERT:
			error = ip_mrouter_set(so, optname, m);
			break;
#endif

		default:
			error = ip_ctloutput(op, so, level, optname, m);
			break;
		}
		break;

	case PRCO_GETOPT:
		switch (optname) {
		case IP_HDRINCL:
			*m = m_get(M_WAIT, MT_SOOPTS);
			MCLAIM((*m), so->so_mowner);
			(*m)->m_len = sizeof (int);
			*mtod(*m, int *) = inp->inp_flags & INP_HDRINCL ? 1 : 0;
			break;

#ifdef MROUTING
		case MRT_VERSION:
		case MRT_ASSERT:
			error = ip_mrouter_get(so, optname, m);
			break;
#endif

		default:
			error = ip_ctloutput(op, so, level, optname, m);
			break;
		}
		break;
	}
	return (error);
}

int
rip_bind(inp, nam)
	struct inpcb *inp;
	struct mbuf *nam;
{
	struct sockaddr_in *addr = mtod(nam, struct sockaddr_in *);

	if (nam->m_len != sizeof(*addr))
		return (EINVAL);
	if (TAILQ_FIRST(&ifnet) == 0)
		return (EADDRNOTAVAIL);
	if (addr->sin_family != AF_INET &&
	    addr->sin_family != AF_IMPLINK)
		return (EAFNOSUPPORT);
	if (!in_nullhost(addr->sin_addr) &&
	    ifa_ifwithaddr(sintosa(addr)) == 0)
		return (EADDRNOTAVAIL);
	inp->inp_laddr = addr->sin_addr;
	return (0);
}

int
rip_connect(inp, nam)
	struct inpcb *inp;
	struct mbuf *nam;
{
	struct sockaddr_in *addr = mtod(nam, struct sockaddr_in *);

	if (nam->m_len != sizeof(*addr))
		return (EINVAL);
	if (TAILQ_FIRST(&ifnet) == 0)
		return (EADDRNOTAVAIL);
	if (addr->sin_family != AF_INET &&
	    addr->sin_family != AF_IMPLINK)
		return (EAFNOSUPPORT);
	inp->inp_faddr = addr->sin_addr;
	return (0);
}

void
rip_disconnect(inp)
	struct inpcb *inp;
{

	inp->inp_faddr = zeroin_addr;
}

u_long	rip_sendspace = RIPSNDQ;
u_long	rip_recvspace = RIPRCVQ;

/*ARGSUSED*/
int
rip_usrreq(so, req, m, nam, control, p)
	struct socket *so;
	int req;
	struct mbuf *m, *nam, *control;
	struct proc *p;
{
	struct inpcb *inp;
	int s;
	int error = 0;
#ifdef MROUTING
	extern struct socket *ip_mrouter;
#endif

	if (req == PRU_CONTROL)
		return (in_control(so, (long)m, (caddr_t)nam,
		    (struct ifnet *)control, p));

	if (req == PRU_PURGEIF) {
		in_pcbpurgeif0(&rawcbtable, (struct ifnet *)control);
		in_purgeif((struct ifnet *)control);
		in_pcbpurgeif(&rawcbtable, (struct ifnet *)control);
		return (0);
	}

	s = splsoftnet();
	inp = sotoinpcb(so);
#ifdef DIAGNOSTIC
	if (req != PRU_SEND && req != PRU_SENDOOB && control)
		panic("rip_usrreq: unexpected control mbuf");
#endif
	if (inp == 0 && req != PRU_ATTACH) {
		error = EINVAL;
		goto release;
	}

	switch (req) {

	case PRU_ATTACH:
		if (inp != 0) {
			error = EISCONN;
			break;
		}
		if (p == 0 || (error = suser(p->p_ucred, &p->p_acflag))) {
			error = EACCES;
			break;
		}
		if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
			error = soreserve(so, rip_sendspace, rip_recvspace);
			if (error)
				break;
		}
		error = in_pcballoc(so, &rawcbtable);
		if (error)
			break;
		inp = sotoinpcb(so);
		inp->inp_ip.ip_p = (long)nam;
		break;

	case PRU_DETACH:
#ifdef MROUTING
		if (so == ip_mrouter)
			ip_mrouter_done();
#endif
		in_pcbdetach(inp);
		break;

	case PRU_BIND:
		error = rip_bind(inp, nam);
		break;

	case PRU_LISTEN:
		error = EOPNOTSUPP;
		break;

	case PRU_CONNECT:
		error = rip_connect(inp, nam);
		if (error)
			break;
		soisconnected(so);
		break;

	case PRU_CONNECT2:
		error = EOPNOTSUPP;
		break;

	case PRU_DISCONNECT:
		soisdisconnected(so);
		rip_disconnect(inp);
		break;

	/*
	 * Mark the connection as being incapable of further input.
	 */
	case PRU_SHUTDOWN:
		socantsendmore(so);
		break;

	case PRU_RCVD:
		error = EOPNOTSUPP;
		break;

	/*
	 * Ship a packet out.  The appropriate raw output
	 * routine handles any massaging necessary.
	 */
	case PRU_SEND:
		if (control && control->m_len) {
			m_freem(control);
			m_freem(m);
			error = EINVAL;
			break;
		}
	{
		if (nam) {
			if ((so->so_state & SS_ISCONNECTED) != 0) {
				error = EISCONN;
				goto die;
			}
			error = rip_connect(inp, nam);
			if (error) {
			die:
				m_freem(m);
				break;
			}
		} else {
			if ((so->so_state & SS_ISCONNECTED) == 0) {
				error = ENOTCONN;
				goto die;
			}
		}
		error = rip_output(m, inp);
		if (nam)
			rip_disconnect(inp);
	}
		break;

	case PRU_SENSE:
		/*
		 * stat: don't bother with a blocksize.
		 */
		splx(s);
		return (0);

	case PRU_RCVOOB:
		error = EOPNOTSUPP;
		break;

	case PRU_SENDOOB:
		m_freem(control);
		m_freem(m);
		error = EOPNOTSUPP;
		break;

	case PRU_SOCKADDR:
		in_setsockaddr(inp, nam);
		break;

	case PRU_PEERADDR:
		in_setpeeraddr(inp, nam);
		break;

	default:
		panic("rip_usrreq");
	}

release:
	splx(s);
	return (error);
}


text:
from . import *

class TestBadBuild(IntegrationTest):
    def __init__(self, *args, **kwargs):
        super().__init__('bad_build', configure=False, *args, **kwargs)

    def test_bad_build(self):
        self.configure(returncode=1)


text:
package com.google.android.apps.forscience.ble;

import android.annotation.TargetApi;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanRecord;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.os.ParcelUuid;
import java.util.ArrayList;
import java.util.List;

/** Discovers LE devices using API level 21+ methods. */
@TargetApi(21)
/* package */ class DeviceDiscovererV21 extends DeviceDiscoverer {

  private BluetoothLeScanner scanner;

  private final ScanCallback callback =
      new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
          manageScanResult(result);
        }

        @Override
        public void onBatchScanResults(List<ScanResult> results) {
          for (ScanResult result : results) {
            manageScanResult(result);
          }
        }

        @Override
        public void onScanFailed(int errorCode) {
          // TODO: surface errors.
        }

        private void manageScanResult(ScanResult result) {
          List<String> serviceUuids = new ArrayList<>();
          ScanRecord record = result.getScanRecord();
          if (record != null) {
            List<ParcelUuid> parcelUuids = record.getServiceUuids();
            if (parcelUuids != null) {
              for (ParcelUuid uuid : parcelUuids) {
                serviceUuids.add(uuid.toString());
              }
            }
          }
          addOrUpdateDevice(new NativeDevice(result.getDevice(), serviceUuids), result.getRssi());
        }
      };

  DeviceDiscovererV21(Context context) {
    super(context);
  }

  @Override
  public void onStartScanning(ParcelUuid[] serviceUuids) {
    scanner = getBluetoothAdapter().getBluetoothLeScanner();
    List<ScanFilter> filters = new ArrayList<>();
    for (ParcelUuid uuid : serviceUuids) {
      filters.add(new ScanFilter.Builder().setServiceUuid(uuid).build());
    }
    ScanSettings settings =
        new ScanSettings.Builder().setScanMode(ScanSettings.SCAN_MODE_BALANCED).build();
    scanner.startScan(filters, settings, callback);
  }

  @Override
  public void onStopScanning() {
    if (scanner != null) {
      if (isBluetoothEnabled()) {
        scanner.stopScan(callback);
      }
    }
  }
}


text:
import "../../../../theme/css"
import { render, h } from "preact"

import { foregroundOutsideFeature } from "../../../x_outside_feature/common"

import { newExampleView } from "../../../../theme/action_examples/init"

import { ExamplesEntry } from "../../../../theme/action_examples/x_preact/examples"
import { ReportContainerComponent } from "../../../../theme/action_examples/x_preact/examples/report/container"

render(
    h(ExamplesEntry, {
        view: newExampleView(foregroundOutsideFeature()),
        content: { title: "Report", component: ReportContainerComponent },
    }),
    document.body,
)


text:
  flags_ui::FeatureEntry::SINGLE_VALUE, command_line_switch, switch_value, \
      nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr
#define SINGLE_VALUE_TYPE(command_line_switch) \
  SINGLE_VALUE_TYPE_AND_VALUE(command_line_switch, "")
#define ORIGIN_LIST_VALUE_TYPE(command_line_switch, switch_value) \
  flags_ui::FeatureEntry::ORIGIN_LIST_VALUE, command_line_switch, \
      switch_value, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr
#define SINGLE_DISABLE_VALUE_TYPE_AND_VALUE(command_line_switch, switch_value) \
  flags_ui::FeatureEntry::SINGLE_DISABLE_VALUE, command_line_switch,           \
      switch_value, nullptr, nullptr, nullptr, 0, nullptr, nullptr, nullptr
#define SINGLE_DISABLE_VALUE_TYPE(command_line_switch) \
  SINGLE_DISABLE_VALUE_TYPE_AND_VALUE(command_line_switch, "")
#define ENABLE_DISABLE_VALUE_TYPE_AND_VALUE(enable_switch, enable_value,     \
                                            disable_switch, disable_value)   \
  flags_ui::FeatureEntry::ENABLE_DISABLE_VALUE, enable_switch, enable_value, \
      disable_switch, disable_value, nullptr, 3, nullptr, nullptr, nullptr
#define ENABLE_DISABLE_VALUE_TYPE(enable_switch, disable_switch) \
  ENABLE_DISABLE_VALUE_TYPE_AND_VALUE(enable_switch, "", disable_switch, "")
#define MULTI_VALUE_TYPE(choices)                                          \
  flags_ui::FeatureEntry::MULTI_VALUE, nullptr, nullptr, nullptr, nullptr, \
      nullptr, base::size(choices), choices, nullptr, nullptr
#define FEATURE_VALUE_TYPE(feature)                                          \
  flags_ui::FeatureEntry::FEATURE_VALUE, nullptr, nullptr, nullptr, nullptr, \
      &feature, 3, nullptr, nullptr, nullptr
#define FEATURE_WITH_PARAMS_VALUE_TYPE(feature, feature_variations,            \
                                       feature_trial)                          \
  flags_ui::FeatureEntry::FEATURE_WITH_PARAMS_VALUE, nullptr, nullptr,         \
      nullptr, nullptr, &feature, 3 + base::size(feature_variations), nullptr, \
      feature_variations, feature_trial

#endif  // COMPONENTS_FLAGS_UI_FEATURE_ENTRY_MACROS_H_


text:
package com.linkedin.pinot.core.io.writer.impl;

import com.linkedin.pinot.common.utils.MmapUtils;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import org.apache.commons.io.IOUtils;

public class FixedByteSingleValueMultiColWriter {
  private File file;
  private int cols;
  private int[] columnOffsets;
  private int rows;
  private ByteBuffer byteBuffer;
  private RandomAccessFile raf;
  private int rowSizeInBytes;
  private final boolean ownsByteBuffer;

  public FixedByteSingleValueMultiColWriter(File file, int rows, int cols,
      int[] columnSizes) throws Exception {
    this.file = file;
    this.rows = rows;
    this.cols = cols;
    this.columnOffsets = new int[cols];
    raf = new RandomAccessFile(file, "rw");
    rowSizeInBytes = 0;
    for (int i = 0; i < columnSizes.length; i++) {
      columnOffsets[i] = rowSizeInBytes;
      int colSize = columnSizes[i];
      rowSizeInBytes += colSize;
    }
    int totalSize = rowSizeInBytes * rows;
    byteBuffer = MmapUtils.mmapFile(raf, FileChannel.MapMode.READ_WRITE, 0,
        totalSize, file, this.getClass().getSimpleName() + " byteBuffer");
    ownsByteBuffer = true;
  }

  public FixedByteSingleValueMultiColWriter(ByteBuffer byteBuffer, int rows,
      int cols, int[] columnSizes) throws IOException {
    this.rows = rows;
    this.cols = cols;
    this.columnOffsets = new int[cols];
    rowSizeInBytes = 0;
    for (int i = 0; i < columnSizes.length; i++) {
      columnOffsets[i] = rowSizeInBytes;
      int colSize = columnSizes[i];
      rowSizeInBytes += colSize;
    }
    this.byteBuffer = byteBuffer;
    ownsByteBuffer = false;
  }

  public boolean open() {
    return true;
  }

  public void setChar(int row, int col, char ch) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putChar(offset, ch);
  }

  public void setInt(int row, int col, int i) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putInt(offset, i);
  }

  public void setShort(int row, int col, short s) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putShort(offset, s);
  }

  public void setLong(int row, int col, long l) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putLong(offset, l);
  }

  public void setFloat(int row, int col, float f) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putFloat(offset, f);
  }

  public void setDouble(int row, int col, double d) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.putDouble(offset, d);
  }

  public void setString(int row, int col, String string) {
    setBytes(row, col, string.getBytes(Charset.forName("UTF-8")));
  }

  public void setBytes(int row, int col, byte[] bytes) {
    int offset = rowSizeInBytes * row + columnOffsets[col];
    byteBuffer.position(offset);
    byteBuffer.put(bytes);
  }

  public void close() {
    IOUtils.closeQuietly(raf);
    raf = null;
    if (ownsByteBuffer) {
      MmapUtils.unloadByteBuffer(byteBuffer);
      byteBuffer = null;
    }
  }
}


text:
require 'gaddag'

describe GADDAG, '#find' do
  subject { GADDAG.new }

  context 'given that the words BREAK and AKIN are added' do
    before { subject.add('BREAK') }
    before { subject.add('AKIN') }

    context 'when searching for any word or substring that has not been added' do
      it 'yields no results' do
        expect(subject.find('ZOMBIES')).to be_empty
      end
    end

    context 'when searching for an empty substring' do
      let(:results) { subject.find('') }

      it 'yields all words that have been added' do
        expect(results).to eq(['BREAK', 'AKIN'])
      end
    end

    context 'when searching for the letter E' do
      let(:results) { subject.find('E') }

      it 'yields one result, namely BREAK' do
        expect(results).to eq(['BREAK'])
      end
    end

    context 'when searching for the word BREAK' do
      let(:results) { subject.find('BREAK') }

      it 'yields one result, namely BREAK' do
        expect(results).to eq(['BREAK'])
      end
    end

    context 'when searching for the substring BREA' do
      let(:results) { subject.find('BREA') }

      it 'yields one result, namely BREAK' do
        expect(results).to eq(['BREAK'])
      end
    end

    context 'when searching for the substring REAK' do
      let(:results) { subject.find('REAK') }

      it 'yields one result, namely BREAK' do
        expect(results).to eq(['BREAK'])
      end
    end

    context 'when searching for the substring AK' do
      let(:results) { subject.find('AK') }

      it 'yields two results, namely BREAK and AKIN' do
        expect(results).to eq(['BREAK', 'AKIN'])
      end
    end
  end
end


text:
using System;
using System.Net;
using System.Collections;
using System.Net.Sockets;
using System.Threading;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using System.IO;
using System.Collections.Generic;
using AutoComplete.Classes;
using System.Linq;

namespace LuceneDistributedLearner.TCP_Backend
{
    public class Client
    {
        private string server;
        private Int32 port;
        private TcpClient client;
        private NetworkStream stream;
        private BinaryFormatter formatter;

        public Client(String server, Int32 port)
        {
            this.server = server;
            this.port = port;
            this.client = new TcpClient(server, port);
            this.stream = client.GetStream();
            this.formatter = new BinaryFormatter();
        }

        public void sendMessage(String message)
        {
            Byte[] data = System.Text.Encoding.ASCII.GetBytes(message);
            stream.Write(data, 0, data.Length);

            Console.WriteLine("Sent message..."); //, message);

            // Receive the TcpServer.response.

            // Buffer to store the response bytes.
            data = new Byte[256];

            // String to store the response ASCII representation.
            String responseData = String.Empty;

            // Read the first batch of the TcpServer response bytes.
            Int32 bytes = stream.Read(data, 0, data.Length);
            responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes);
            Console.WriteLine("Received: {0}", responseData);
        }

        public void sendMessage(Object obj)
        {
            Byte[] data;

            List<DataType> x = ((IEnumerable)obj).Cast<DataType>().ToList();

            using (MemoryStream ms = new MemoryStream())
            {
                this.formatter.Serialize(ms, obj);
                data = ms.ToArray();
            }

            stream.Write(data, 0, data.Length);

            Console.WriteLine("[CLIENT] Sent object");
        }

        public void stop()
        {
            // Close everything.
            Console.WriteLine("[CLIENT] Closing client");
            this.stream.Close();
            Console.WriteLine("1");
            this.client.Close();
            Console.WriteLine("2");
        }

        public void sendHeader(String header)
        {

        }

        public void sendObject()
        {

        }
    }
}


text:
@interface LikersViewController ()
@property (strong, nonatomic) NSArray *like_reward_users;

@property (strong, nonatomic) UITableView *myTableView;

@property (strong, nonatomic) ODRefreshControl *myRefreshControl;
@property (strong, nonatomic) NSMutableArray *searchResults;

@end

@implementation LikersViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"赞赏的人";
    _myTableView = ({
        UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableView.backgroundColor = [UIColor clearColor];
        [tableView registerClass:[UserCell class] forCellReuseIdentifier:kCellIdentifier_UserCell];
        tableView.delegate = self;
        tableView.dataSource = self;
        tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [self.view addSubview:tableView];
        [tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self.view);
        }];
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView;
    });

    _myRefreshControl = [[ODRefreshControl alloc] initInScrollView:self.myTableView];
    [_myRefreshControl addTarget:self action:@selector(refresh) forControlEvents:UIControlEventValueChanged];

    [self refresh];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)refresh{
    if (_curTweet.isLoading) {
        return;
    }
    if (_like_reward_users.count <= 0) {
        [self.view beginLoading];
    }
    __weak typeof(self) weakSelf = self;
    [[Coding_NetAPIManager sharedManager] request_Tweet_LikesAndRewards_WithObj:_curTweet andBlock:^(id data, NSError *error) {
        [weakSelf.view endLoading];
        [weakSelf.myRefreshControl endRefreshing];
        if ([data isKindOfClass:[NSDictionary class]]) {
            [weakSelf refreshWithData:data];
        }
    }];
}

- (void)refreshWithData:(NSDictionary *)data{
    if (data[@"likeUsers"]) {
        _curTweet.like_users = [NSObject arrayFromJSON:data[@"likeUsers"] ofObjects:@"User"];
    }
    if (data[@"rewardUsers"]) {
        _curTweet.reward_users = [NSObject arrayFromJSON:data[@"rewardUsers"] ofObjects:@"User"];
    }
    _like_reward_users = [_curTweet like_reward_users];
    [self.myTableView reloadData];
}

#pragma mark Table M
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (_like_reward_users) {
        return [_like_reward_users count];
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UserCell *cell = [tableView dequeueReusableCellWithIdentifier:kCellIdentifier_UserCell forIndexPath:indexPath];

    cell.userIconView.layer.borderColor = [UIColor colorWithHexString:@"0xFFAE03"].CGColor;

    User *curUser = [_like_reward_users objectAtIndex:indexPath.row];
    cell.curUser = curUser;
    cell.usersType = UsersTypeTweetLikers;

    cell.userIconView.layer.borderWidth = [_curTweet rewardedBy:curUser]? 1.0: 0;
    [tableView addLineforPlainCell:cell forRowAtIndexPath:indexPath withLeftSpace:60];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [UserCell cellHeight];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    User *user = [_like_reward_users objectAtIndex:indexPath.row];
    if (kTarget_Enterprise) {
        UserInfoDetailViewController *vc = [[UserInfoDetailViewController alloc] init];
        vc.curUser = user;
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        UserInfoViewController *vc = [[UserInfoViewController alloc] init];
        vc.curUser = user;
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (void)dealloc
{
    _myTableView.delegate = nil;
    _myTableView.dataSource = nil;
}

@end


text:
namespace policy {

namespace {

// Directory inside the profile directory where policy-related resources are
// stored.
const base::FilePath::CharType kPolicy[] = FILE_PATH_LITERAL("Policy");

// Directory under kPolicy, in the user's profile dir, where policy for
// components is cached.
const base::FilePath::CharType kComponentsDir[] =
    FILE_PATH_LITERAL("Components");

}  // namespace

// A KeyedService that wraps a UserCloudPolicyManager.
class UserCloudPolicyManagerFactory::ManagerWrapper : public KeyedService {
 public:
  explicit ManagerWrapper(UserCloudPolicyManager* manager)
      : manager_(manager) {
    DCHECK(manager);
  }
  virtual ~ManagerWrapper() {}

  virtual void Shutdown() OVERRIDE {
    manager_->Shutdown();
  }

  UserCloudPolicyManager* manager() { return manager_; }

 private:
  UserCloudPolicyManager* manager_;

  DISALLOW_COPY_AND_ASSIGN(ManagerWrapper);
};

// static
UserCloudPolicyManagerFactory* UserCloudPolicyManagerFactory::GetInstance() {
  return Singleton<UserCloudPolicyManagerFactory>::get();
}

// static
UserCloudPolicyManager* UserCloudPolicyManagerFactory::GetForBrowserContext(
    content::BrowserContext* context) {
  return GetInstance()->GetManagerForBrowserContext(context);
}

// static
scoped_ptr<UserCloudPolicyManager>
UserCloudPolicyManagerFactory::CreateForOriginalBrowserContext(
    content::BrowserContext* context,
    bool force_immediate_load,
    const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
    const scoped_refptr<base::SequencedTaskRunner>& file_task_runner,
    const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
  UserCloudPolicyManagerFactory* factory = GetInstance();
  // If there's a testing factory set, don't bother creating a new one.
  if (factory->testing_factory_ != NULL)
    return scoped_ptr<UserCloudPolicyManager>();
  return factory->CreateManagerForOriginalBrowserContext(
      context,
      force_immediate_load,
      background_task_runner,
      file_task_runner,
      io_task_runner);
}

// static
UserCloudPolicyManager*
UserCloudPolicyManagerFactory::RegisterForOffTheRecordBrowserContext(
    content::BrowserContext* original_context,
    content::BrowserContext* off_the_record_context) {
  return GetInstance()->RegisterManagerForOffTheRecordBrowserContext(
      original_context, off_the_record_context);
}

void UserCloudPolicyManagerFactory::RegisterTestingFactory(
    TestingFactoryFunction factory) {
  // Can't set a testing factory when a testing factory has already been
  // created, or after UCPMs have already been built.
  DCHECK(!testing_factory_);
  DCHECK(factory);
  DCHECK(manager_wrappers_.empty());
  testing_factory_ = factory;
}

void UserCloudPolicyManagerFactory::ClearTestingFactory() {
  testing_factory_ = NULL;
}

UserCloudPolicyManagerFactory::UserCloudPolicyManagerFactory()
    : BrowserContextKeyedBaseFactory(
        "UserCloudPolicyManager",
        BrowserContextDependencyManager::GetInstance()),
      testing_factory_(NULL) {
  DependsOn(SchemaRegistryServiceFactory::GetInstance());
}

UserCloudPolicyManagerFactory::~UserCloudPolicyManagerFactory() {
  DCHECK(manager_wrappers_.empty());
}

UserCloudPolicyManager*
UserCloudPolicyManagerFactory::GetManagerForBrowserContext(
    content::BrowserContext* context) {
  // In case |context| is an incognito Profile/Context, |manager_wrappers_|
  // will have a matching entry pointing to the manager of the original context.
  ManagerWrapperMap::const_iterator it = manager_wrappers_.find(context);
  return it != manager_wrappers_.end() ? it->second->manager() : NULL;
}

scoped_ptr<UserCloudPolicyManager>
UserCloudPolicyManagerFactory::CreateManagerForOriginalBrowserContext(
    content::BrowserContext* context,
    bool force_immediate_load,
    const scoped_refptr<base::SequencedTaskRunner>& background_task_runner,
    const scoped_refptr<base::SequencedTaskRunner>& file_task_runner,
    const scoped_refptr<base::SequencedTaskRunner>& io_task_runner) {
  DCHECK(!context->IsOffTheRecord());

  // This should never be called if we're using a testing factory.
  // Instead, instances are instantiated via CreateServiceNow().
  DCHECK(!testing_factory_);

  scoped_ptr<UserCloudPolicyStore> store(
      UserCloudPolicyStore::Create(context->GetPath(),
                                   GetPolicyVerificationKey(),
                                   background_task_runner));
  if (force_immediate_load)
    store->LoadImmediately();

  const base::FilePath component_policy_cache_dir =
      context->GetPath().Append(kPolicy).Append(kComponentsDir);

  scoped_ptr<UserCloudPolicyManager> manager;
  manager.reset(new UserCloudPolicyManager(
      store.Pass(),
      component_policy_cache_dir,
      scoped_ptr<CloudExternalDataManager>(),
      base::MessageLoopProxy::current(),
      file_task_runner,
      io_task_runner));
  manager->Init(
      SchemaRegistryServiceFactory::GetForContext(context)->registry());
  manager_wrappers_[context] = new ManagerWrapper(manager.get());
  return manager.Pass();
}

UserCloudPolicyManager*
UserCloudPolicyManagerFactory::RegisterManagerForOffTheRecordBrowserContext(
    content::BrowserContext* original_context,
    content::BrowserContext* off_the_record_context) {
  // Register the UserCloudPolicyManager of the original context for the
  // respective incognito context. See also GetManagerForBrowserContext.
  UserCloudPolicyManager* manager =
      GetManagerForBrowserContext(original_context);
  manager_wrappers_[off_the_record_context] = new ManagerWrapper(manager);
  return manager;
}

void UserCloudPolicyManagerFactory::BrowserContextShutdown(
    content::BrowserContext* context) {
  if (context->IsOffTheRecord())
    return;
  ManagerWrapperMap::iterator it = manager_wrappers_.find(context);
  // E.g. for a TestingProfile there might not be a manager created.
  if (it != manager_wrappers_.end())
    it->second->Shutdown();
}

void UserCloudPolicyManagerFactory::BrowserContextDestroyed(
    content::BrowserContext* context) {
  ManagerWrapperMap::iterator it = manager_wrappers_.find(context);
  if (it != manager_wrappers_.end()) {
    // The manager is not owned by the factory, so it's not deleted here.
    delete it->second;
    manager_wrappers_.erase(it);
  }
}

void UserCloudPolicyManagerFactory::SetEmptyTestingFactory(
    content::BrowserContext* context) {}

bool UserCloudPolicyManagerFactory::HasTestingFactory(
    content::BrowserContext* context) {
  return testing_factory_ != NULL;
}

// If there's a TestingFactory set, then create a service during BrowserContext
// initialization.
bool UserCloudPolicyManagerFactory::ServiceIsCreatedWithBrowserContext() const {
  return testing_factory_ != NULL;
}

void UserCloudPolicyManagerFactory::CreateServiceNow(
    content::BrowserContext* context) {
  DCHECK(testing_factory_);
  manager_wrappers_[context] = new ManagerWrapper(testing_factory_(context));
}

}  // namespace policy


text:
<?php

namespace Xabbuh\PandaClient\Tests\Api;

use PHPUnit\Framework\TestCase;
use Xabbuh\PandaClient\Api\Account;

/**
 * Test the Account class.
 *
 * @author Christian Flothmann <christian.flothmann@xabbuh.de>
 */
class AccountTest extends TestCase
{
    /**
     * Test the Account's getter methods.
     */
    public function testGetter()
    {
        $account = new Account('access-key', 'secret-key', 'api-host');
        $this->assertEquals('access-key', $account->getAccessKey());
        $this->assertEquals('secret-key', $account->getSecretKey());
        $this->assertEquals('api-host', $account->getApiHost());
    }
}


text:
module Endive
  module Support
    class ParamsParser
      require 'cgi'
      class << self

        JSON_TYPE               = 'application/json'
        FORM_TYPE               = 'application/x-www-form-urlencoded'
        CONTENT_TYPE_HEADER_KEY = 'Content-Type'

        def get_params method, headers, query_string, body
          case method
          when :get, :detete, :options
            parse_request query_string
          when :post, :put
            parse_request query_string, headers, body
          end
        end

        def parse_request query_string, headers = nil, body = nil
          complete_request_hash = parse_formencoded(query_string || '')
          return complete_request_hash unless body
          complete_request_hash.merge(parse_post_body(body, headers[CONTENT_TYPE_HEADER_KEY]))
        end

        def parse_post_body body, content_type_header
          content_types = content_type_header ? content_type_header.split(';') : []
          body = body.to_s

          return {} if body.blank?

          return parse_formencoded(body) if content_types.include?(FORM_TYPE)
          return SymHash.new(JSON.parse(body)) if content_types.include?(JSON_TYPE)

          {}
        end

        def parse_formencoded str
          str.split('&').reduce(Endive::Support::SymHash.new) do |p, kv|
            key, value = kv.split('=').map {|s| CGI.unescape s}
            p[key] = value
            p
          end
        end

      end
    end
  end
end


text:
<?php

namespace Kenjis\CodeIgniter_Cli\_Config;

use Aura\Di\Config;
use Aura\Di\Container;

class Dev extends Config
{
    public function define(Container $di)
    {
        ini_set('error_reporting', E_ALL);
        ini_set('display_errors', true);
    }

    public function modify(Container $di)
    {
    }
}


text:
Tablesnap
=========

Theory of Operation
-------------------

Tablesnap is a script that uses inotify to monitor a directory for `IN_MOVED_TO`
events and reacts to them by spawning a new thread to upload that file to
Amazon S3, along with a JSON-formatted list of what other files were in the
directory at the time of the copy.

When running a Cassandra cluster, this behavior can be quite useful as it
allows for automated point-in-time backups of SSTables. Theoretically,
tablesnap should work for any application where files are written to some
temporary location, then moved into their final location once the data is
written to disk. Tablesnap also makes the assumption that files are immutable
once written.

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

This distribution provides a debian/ source directory, allowing it to be built
as a standard Debian/Ubuntu package and stored in a repository. The Debian
package includes an init script that can run and daemonize tablesnap for you.
Tablesnap does not daemonize itself. This is best left to tools like
init, supervisord, daemontools, etc.

There are pre-build binaries for Ubuntu Maverick amd64 and i386 in this PPA:
<https://launchpad.net/~synack/+archive/tablesnap>

	# cat /etc/apt/sources.list.d/tablesnap.list << EOF
	> deb http://ppa.launchpad.net/synack/tablesnap/ubuntu maverick main
	> deb-src http://ppa.launchpad.net/synack/tablesnap/ubuntu maverick main
	> EOF
	# aptitude update

If you are not a Debian/Ubuntu user or do not wish to install the tablesnap
package, you may copy the tablesnap script anywhere you'd like and run it from
there. Tablesnap depends on the pyinotify and boto Python packages. These are
available via "pip install pyinotify; pip install boto;", or as packages from
most common Linux distributions.

Configuration
-------------

All configuration for tablesnap happens on the command line. If you are using
the Debian package, you'll set these options in the `DAEMON_OPTS` variable in
`/etc/default/tablesnap`.

    Usage: tablesnap [options] <bucket> <path> [...]
    Options:
      -h, --help            show this help message and exit
      -k AWS_KEY, --aws-key=AWS_KEY
      -s AWS_SECRET, --aws-secret=AWS_SECRET
      -r, --recursive       Recursively watch the given path(s)s for new SSTables
      -a, --auto-add        Automatically start watching new subdirectories within path(s)
      -B, --backup          Backup existing SSTables to S3 if they're not already there

For example:

	$ tablesnap -k AAAAAAAAAAAAAAAA -s BBBBBBBBBBBBBBBB me.synack.sstables /var/lib/cassandra/data/GiantKeyspace

This would cause tablesnap to use the given Amazon Web Services credentials to
backup the SSTables for my `GiantKeyspace` to the S3 bucket named
`me.synack.sstables`.

Questions, Comments, and Help
-----------------------------
The fine folks in `#cassandra-ops` on `irc.freenode.net` are an excellent
resource for getting tablesnap up and running, and also for solving more
general Cassandra issues.


text:
#include <ndis.h>
#include "KmTypes.h"
#include "NdisMemoryManager.h"

///////////////////////////////////////////////////
// String helper functions
///////////////////////////////////////////////////

PUNICODE_STRING __stdcall CreateString(
    __in            PKM_MEMORY_MANAGER  MemoryManager,
    __in    const   char                *Str);

PUNICODE_STRING __stdcall CopyString(
    __in    PKM_MEMORY_MANAGER  MemoryManager,
    __in    PUNICODE_STRING     SourceString);

BOOLEAN __stdcall StringStartsWith(
    __in    PUNICODE_STRING     String,
    __in    PUNICODE_STRING     SubString);

void __stdcall FreeString(
    __in    PKM_MEMORY_MANAGER  MemoryManager,
    __in    PUNICODE_STRING     String);

PUNICODE_STRING __stdcall AllocateString(
    __in    PKM_MEMORY_MANAGER  MemoryManager,
    __in    USHORT              StringLengthInBytes);

///////////////////////////////////////////////////
// Other helper functions
///////////////////////////////////////////////////

void __stdcall DriverSleep(long msec);

LARGE_INTEGER __stdcall KmGetTicks(
    __in    BOOLEAN SkipFrequency);

NTSTATUS __stdcall KmGetStartTime(
    __out   PKM_TIME    Time);

NTSTATUS __stdcall KmReferenceEvent(
    __in    HANDLE  EventObjectHandle,
    __out   PVOID   *EventObject);

int __stdcall CompareAdapterIds(
    __in    PPCAP_NDIS_ADAPTER_ID   AdapterId1,
    __in    PPCAP_NDIS_ADAPTER_ID   AdapterId2);

#define EqualAdapterIds(AdapterIdPtr1, AdapterIdPtr2) (CompareAdapterIds((AdapterIdPtr1), (AdapterIdPtr2)) == 0)

///////////////////////////////////////////////////
// Network event info helpers
///////////////////////////////////////////////////
NTSTATUS __stdcall NetEventInfo_Allocate(
    __in    PKM_MEMORY_MANAGER  MemoryManager,
    __out   PNET_EVENT_INFO     *EventInfo);

NTSTATUS __stdcall NetEventInfo_FillFromBuffer(
    __in    PVOID           Buffer,
    __in    ULONG           BufferSize,
    __inout PNET_EVENT_INFO EventInfo);

///////////////////////////////////////////////////
// IO buffer helpers
///////////////////////////////////////////////////

#define IOUTILS_PROBE_BUFFER_FLAG_READ	0x1
#define IOUTILS_PROBE_BUFFER_FLAG_WRITE	0x2
#define IOUTILS_PROBE_BUFFER_FLAG_BOTH	0x3
#define IOUTILS_PROBE_BUFFER_FLAG_MIN	IOUTILS_PROBE_BUFFER_FLAG_READ
#define IOUTILS_PROBE_BUFFER_FLAG_MAX	IOUTILS_PROBE_BUFFER_FLAG_BOTH
#define IOUtils_ValidateProbeFlags(Flags) \
    (((Flags) >= IOUTILS_PROBE_BUFFER_FLAG_MIN) && ((Flags) <= IOUTILS_PROBE_BUFFER_FLAG_MAX))

NTSTATUS __stdcall IOUtils_ProbeBuffer(
    __in    PVOID   Buffer,
    __in    ULONG   Length,
    __in    ULONG   Alignment,
    __in    ULONG   Flags);

NTSTATUS __stdcall IOUtils_ValidateAndGetIOBuffers(
    __in	PIRP	Irp,
    __out	PVOID	*InBuffer,
    __out	PULONG	InLength,
    __out	PVOID	*OutBuffer,
    __out	PULONG	OutLength);

#define NetEventString(Value) \
    ((Value) == NetEventSetPower ? "NetEventSetPower" : \
     (Value) == NetEventQueryPower ? "NetEventQueryPower" : \
     (Value) == NetEventQueryRemoveDevice ? "NetEventQueryRemoveDevice" : \
     (Value) == NetEventCancelRemoveDevice ? "NetEventCancelRemoveDevice" : \
     (Value) == NetEventReconfigure ? "NetEventCancelRemoveDevice" : \
     (Value) == NetEventBindList ? "NetEventBindList" : \
     (Value) == NetEventBindsComplete ? "NetEventBindsComplete" : \
     (Value) == NetEventPnPCapabilities ? "NetEventPnPCapabilities" : \
     (Value) == NetEventPause ? "NetEventPause" : \
     (Value) == NetEventRestart ? "NetEventRestart" : \
     (Value) == NetEventPortActivation ? "NetEventPortActivation" : \
     (Value) == NetEventPortDeactivation ? "NetEventPortDeactivation" : \
     (Value) == NetEventIMReEnableDevice ? "NetEventIMReEnableDevice" : \
     (Value) == NetEventNDKEnable ? "NetEventNDKEnable" : \
     (Value) == NetEventNDKDisable ? "NetEventNDKDisable" : \
     (Value) == NetEventFilterPreDetach ? "NetEventFilterPreDetach" : \
     (Value) == NetEventBindFailed ? "NetEventBindFailed" : \
     (Value) == NetEventSwitchActivate ? "NetEventSwitchActivate" : \
     (Value) == NetEventAllowBindsAbove ? "NetEventAllowBindsAbove" : \
     (Value) == NetEventInhibitBindsAbove  ? "NetEventInhibitBindsAbove" : \
     (Value) == NetEventAllowStart ? "NetEventAllowStart" : \
     (Value) == NetEventRequirePause ? "NetEventRequirePause" : \
     (Value) == NetEventUploadGftFlowEntries ? "NetEventUploadGftFlowEntries" : \
     (Value) == NetEventMaximum ? "NetEventMaximum" : \
     "Unknown")


text:
import sys
import web3

import txaio
txaio.use_twisted()

from autobahn import xbr
import argparse
from init_data import ACCOUNTS, OWNER, MARKETS

# getAllMarketChannels(bytes16 marketId)

def main(accounts, owner, initial_transfer=False):
    print('Using XBR token contract address: {}'.format(xbr.xbrtoken.address))
    print('Using XBR network contract address: {}'.format(xbr.xbrnetwork.address))

    # 1) show test accounts
    #
    print('-' * 120)
    print('Test accounts:')
    for ak in accounts:
        acct = accounts[ak]
        balance_eth = w3.eth.getBalance(acct.address)
        balance_xbr = xbr.xbrtoken.functions.balanceOf(acct.address).call()

        # the XBR token has 18 decimal digits
        balance_xbr = int(balance_xbr / 10 ** 18)
        print('    balances of {} {:>20}: {:>30} ETH {:>30} XBR'.format(acct.address, ak, balance_eth, balance_xbr))

    # 2) transfer some tokens (every user gets 1m XBR)
    #
    if initial_transfer:
        print('-' * 120)
        # transfer 50,000 XBR
        for ak, amount in [
            ('marketop1', 50000),
            ('marketop1-marketmaker1', 50000),
            ('seller1', 50000),
            ('seller3', 50000),
            ('buyer1', 50000),
            ('buyer3', 50000),
            ('marketop2', 50000),
            ('marketop2-marketmaker1', 50000),
            ('seller2', 50000),
            ('buyer2', 50000),
        ]:
            acct = accounts[ak]
            balance_eth = w3.eth.getBalance(acct.address)
            balance_xbr = xbr.xbrtoken.functions.balanceOf(acct.address).call()

            # the XBR token has 18 decimal digits
            balance_xbr = int(balance_xbr / 10 ** 18)

            print('Balances of {}: {:>30} ETH, {:>30} XBR'.format(acct.address, balance_eth, balance_xbr))

            if balance_xbr < amount:
                transfer_amount = amount - balance_xbr

                # the XBR token has 18 decimal digits
                raw_amount = transfer_amount * 10 ** 18
                success = xbr.xbrtoken.functions.transfer(acct.address, raw_amount).transact({'from': owner.address, 'gas': 100000})
                if success:
                    print('Transferred {} XBR to {}'.format(transfer_amount, acct.address))
                else:
                    print('Failed to transfer tokens!')
            else:
                print('Address {} already has (at least) {} XBR (current balance {} XBR)'.format(acct.address, amount, balance_xbr))

    # 3) register XBR network members
    #
    print('-' * 120)
    for ak in [
        'marketop1',
        'seller1',
        'seller3',
        'buyer1',
        'buyer3',
        'marketop2',
        'seller2',
        'buyer2',
        ]:
        acct = accounts[ak]
        joined, eula, profile, level = xbr.xbrnetwork.functions.members(acct.address).call()
        if not joined:
            eula = 'QmV1eeDextSdUrRUQp9tUXF8SdvVeykaiwYLgrXHHVyULY'
            profile = ''
            xbr.xbrnetwork.functions.register(eula, profile).transact({'from': acct.address, 'gas': 200000})
            print('New member {} address registered in the XBR Network (eula={}, profile={})'.format(acct.address, eula, profile))
        else:
            print('Address {} is already a member (level={}, eula={}, profile={})'.format(acct.address, level, eula, profile))

    # 4) open XBR markets
    #
    print('-' * 120)
    for market in MARKETS:

        _created, _marketSeq, _owner, _terms, _terms, _maker, _providerSecurity, _consumerSecurity, _marketFee = xbr.xbrnetwork.functions.markets(market['id']).call()

        gas = 2000000
        if _created:
            if _owner != market['owner']:
                print('Market {} already exists, but has wrong owner!! Expected {}, but owner is {}'.format(market['id'], market['owner'], _owner))
            else:
                print('Market {} already exists and has expected owner {}'.format(market['id'], _owner))
        else:
            # bytes16 marketId, string memory terms, string memory meta, address maker,
            # uint256 providerSecurity, uint256 consumerSecurity, uint256 marketFee
            providerSecurity = market['providerSecurity'] * 10 ** 18
            consumerSecurity = market['consumerSecurity'] * 10 ** 18

            xbr.xbrnetwork.functions.createMarket(
                market['id'],
                market['terms'],
                market['meta'],
                market['maker'],
                providerSecurity,
                consumerSecurity,
                market['marketFee']).transact({'from': market['owner'], 'gas': gas})

            print('Market {} created with owner {}!'.format(market['id'], market['owner']))

        print('Market actors:')
        for actor in market['actors']:

            joined, security, meta = xbr.xbrnetwork.functions.getMarketActor(market['id'], actor['addr'], actor['type']).call()
            if joined:
                print('   Account {} is already actor (type={}) in the market'.format(actor['addr'], actor['type']))
            else:
                channel_amount = actor['amount']
                if channel_amount:
                    result = xbr.xbrtoken.functions.approve(xbr.xbrnetwork.address, channel_amount).transact({'from': actor['addr'], 'gas': gas})
                    print('   Approved market security amount {})'.format(int(channel_amount / 10 ** 18)))
                    if not result:
                        print('   Failed to allow transfer of {} tokens for market security!\n{}'.format(int(channel_amount / 10 ** 18), result))
                    else:
                        print('   Allowed transfer of {} XBR from {} to {} as security for joining market'.format(int(channel_amount / 10 ** 18), actor['addr'], xbr.xbrnetwork.address))

                security_bytes = xbr.xbrnetwork.functions.joinMarket(market['id'], actor['type'], actor['meta']).transact({'from': actor['addr'], 'gas': gas})
                if security_bytes:
                    security = web3.Web3.toInt(security_bytes)

                    print('   Actor {} joined market {} as actor type {} (meta {}) with security {}!'.format(actor['addr'], market['id'], actor['type'], actor['meta'], security))

if __name__ == '__main__':
    print('Using web3.py v{}'.format(web3.__version__))

    parser = argparse.ArgumentParser()

    parser.add_argument('--gateway',
                        dest='gateway',
                        type=str,
                        default=None,
                        help='Ethereum HTTP gateway URL or None for auto-select (default: -, means let web3 auto-select).')

    args = parser.parse_args()

    if args.gateway:
        w3 = web3.Web3(web3.Web3.HTTPProvider(args.gateway))
    else:
        # using automatic provider detection:
        from web3.auto import w3

    # check we are connected, and check network ID
    if not w3.isConnected():
        print('Could not connect to Web3/Ethereum at: {}'.format(args.gateway or 'auto'))
        sys.exit(1)
    else:
        print('Connected to provider "{}"'.format(args.gateway or 'auto'))

    # set new provider on XBR library
    xbr.setProvider(w3)

    # now enter main ..
    # main(w3.eth.accounts)
    main(ACCOUNTS, OWNER)


text:
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, HttpResponseRedirect
from django.urls import reverse
from django.views.generic import View
from django.contrib import messages

from suite.models import Club, Event, EventSignIn, JoinRequest
from . import models

class ClubView(LoginRequiredMixin, View):
    template_name = 'dashboard/club_view.html'

    def get(self, request, club_id):
        club = get_object_or_404(Club, pk=club_id)
        reqs = Club.objects.get(pk=club_id).joinrequest_set.all()
        events = Event.objects.get_upcoming_events(club)
        signedInEvents = EventSignIn.objects.get_attended_events(request.user, club)

        return render(request, self.template_name, {'club': club, 'reqs': reqs, 'events': events, 'signedInEvents': signedInEvents})

    def post(self, request, club_id):
        if 'delete' in request.POST:
          event = Event.objects.get(id=request.POST['event_id'])
          event.delete()
          messages.add_message(request, messages.SUCCESS, 'Sucessfully deleted %s.' % event.event_name )

        club = get_object_or_404(Club, pk=club_id)
        reqs = Club.objects.get(pk=club_id).joinrequest_set.all()
        events = Event.objects.get_upcoming_events(club)
        signedInEvents = EventSignIn.objects.get_attended_events(request.user, club)

        return render(request, self.template_name, {'club': club, 'reqs': reqs, 'events': events, 'signedInEvents': signedInEvents})


text:
package net.authorize.data;

import java.io.Serializable;

/**
 * Product shipping address.
 */
public class ShippingAddress extends Address implements Serializable {

	private static final long serialVersionUID = 2L;

	private ShippingAddress() {
		super();
	}

	public static ShippingAddress createShippingAddress() {
		return new ShippingAddress();
	}

}


text:
package com.caricah.iotracah.bootstrap.data.models.subscriptionfilters;

import java.io.*;

/**
 * IotSubscriptionFilter definition.
 *
 * Code generated by Apache Ignite Schema Import utility: 02/25/2016.
 */
public class IotSubscriptionFilter implements Serializable {
    /** */
    private static final long serialVersionUID = 0L;

    /** Value for dateCreated. */
    private java.sql.Timestamp dateCreated;

    /** Value for dateModified. */
    private java.sql.Timestamp dateModified;

    /** Value for isActive. */
    private boolean isActive;

    /** Value for id. */
    private long id;

    /** Value for name. */
    private String name;

    /** Value for isFinal. */
    private boolean isFinal;

    /** Value for partitionId. */
    private String partitionId;

    /** Value for parentId. */
    private Long parentId;

    /**
     * Gets dateCreated.
     *
     * @return Value for dateCreated.
     */
    public java.sql.Timestamp getDateCreated() {
        return dateCreated;
    }

    /**
     * Sets dateCreated.
     *
     * @param dateCreated New value for dateCreated.
     */
    public void setDateCreated(java.sql.Timestamp dateCreated) {
        this.dateCreated = dateCreated;
    }

    /**
     * Gets dateModified.
     *
     * @return Value for dateModified.
     */
    public java.sql.Timestamp getDateModified() {
        return dateModified;
    }

    /**
     * Sets dateModified.
     *
     * @param dateModified New value for dateModified.
     */
    public void setDateModified(java.sql.Timestamp dateModified) {
        this.dateModified = dateModified;
    }

    /**
     * Gets isActive.
     *
     * @return Value for isActive.
     */
    public boolean getIsActive() {
        return isActive;
    }

    /**
     * Sets isActive.
     *
     * @param isActive New value for isActive.
     */
    public void setIsActive(boolean isActive) {
        this.isActive = isActive;
    }

    /**
     * Gets id.
     *
     * @return Value for id.
     */
    public long getId() {
        return id;
    }

    /**
     * Sets id.
     *
     * @param id New value for id.
     */
    public void setId(long id) {
        this.id = id;
    }

    /**
     * Gets name.
     *
     * @return Value for name.
     */
    public String getName() {
        return name;
    }

    /**
     * Sets name.
     *
     * @param name New value for name.
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Gets isFinal.
     *
     * @return Value for isFinal.
     */
    public boolean getIsFinal() {
        return isFinal;
    }

    /**
     * Sets isFinal.
     *
     * @param isFinal New value for isFinal.
     */
    public void setIsFinal(boolean isFinal) {
        this.isFinal = isFinal;
    }

    /**
     * Gets partitionId.
     *
     * @return Value for partitionId.
     */
    public String getPartitionId() {
        return partitionId;
    }

    /**
     * Sets partitionId.
     *
     * @param partitionId New value for partitionId.
     */
    public void setPartitionId(String partitionId) {
        this.partitionId = partitionId;
    }

    /**
     * Gets parentId.
     *
     * @return Value for parentId.
     */
    public Long getParentId() {
        return parentId;
    }

    /**
     * Sets parentId.
     *
     * @param parentId New value for parentId.
     */
    public void setParentId(Long parentId) {
        this.parentId = parentId;
    }

    /** {@inheritDoc} */
    @Override public boolean equals(Object o) {
        if (this == o)
            return true;

        if (!(o instanceof IotSubscriptionFilter))
            return false;

        IotSubscriptionFilter that = (IotSubscriptionFilter)o;

        if (dateCreated != null ? !dateCreated.equals(that.dateCreated) : that.dateCreated != null)
            return false;

        if (dateModified != null ? !dateModified.equals(that.dateModified) : that.dateModified != null)
            return false;

        if (isActive != that.isActive)
            return false;

        if (id != that.id)
            return false;

        if (name != null ? !name.equals(that.name) : that.name != null)
            return false;

        if (isFinal != that.isFinal)
            return false;

        if (partitionId != null ? !partitionId.equals(that.partitionId) : that.partitionId != null)
            return false;

        if (parentId != null ? !parentId.equals(that.parentId) : that.parentId != null)
            return false;

        return true;
    }

    /** {@inheritDoc} */
    @Override public int hashCode() {
        int res = dateCreated != null ? dateCreated.hashCode() : 0;

        res = 31 * res + (dateModified != null ? dateModified.hashCode() : 0);

        res = 31 * res + (isActive ? 1 : 0);

        res = 31 * res + (int)(id ^ (id >>> 32));

        res = 31 * res + (name != null ? name.hashCode() : 0);

        res = 31 * res + (isFinal ? 1 : 0);

        res = 31 * res + (partitionId != null ? partitionId.hashCode() : 0);

        res = 31 * res + (parentId != null ? parentId.hashCode() : 0);

        return res;
    }

    /** {@inheritDoc} */
    @Override public String toString() {
        return "IotSubscriptionFilter [dateCreated=" + dateCreated +
            ", dateModified=" + dateModified +
            ", isActive=" + isActive +
            ", id=" + id +
            ", name=" + name +
            ", isFinal=" + isFinal +
            ", partitionId=" + partitionId +
            ", parentId=" + parentId +
            "]";
    }
}


text:
import sys
import os
agent_lib_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), '../../lib')
sys.path.insert(1, agent_lib_dir)

# stdlib
import re
from datetime import datetime

# test
import unittest

# unit under test
import helpers

class TestHelpers(unittest.TestCase):
    def test_parse_fix_timestamp(self):
        # sane case: timestamp close to now, in the past, same year
        dt_now = datetime(2018, 6, 6, 9, 9, 9)
        parsed = helpers.parse_fix_timestamp('Jun  1 09:09:09', '%b %d %H:%M:%S', dt_now)
        self.assertEqual(2018, parsed.year)
        self.assertLess(parsed, dt_now)

        # edge case: timestamp close to now, in the future, same year
        dt_now = datetime(2018, 6, 6, 9, 9, 9)
        parsed = helpers.parse_fix_timestamp('Jun  7 01:01:01', '%b %d %H:%M:%S', dt_now)
        self.assertEqual(2018, parsed.year)
        self.assertGreater(parsed, dt_now)

        # edge case, timestamp at end of year, now at beginning of year
        dt_now = datetime(2019, 1, 1, 0, 0, 0)
        parsed = helpers.parse_fix_timestamp('Dec 31 23:59:59', '%b %d %H:%M:%S', dt_now)
        self.assertEqual(2018, parsed.year)
        self.assertLess(parsed, dt_now)

        # edge case: timestamp at start of year, now at end of year
        dt_now = datetime(2018, 12, 31, 11, 59, 59)
        parsed = helpers.parse_fix_timestamp('Jan  1 00:00:00', '%b %d %H:%M:%S', dt_now)
        self.assertEqual(2018, parsed.year)
        self.assertLess(parsed, dt_now)

        # sane case: a real timestamp format
        dt_now = datetime(2018, 12, 31, 11, 59, 59)
        parsed = helpers.parse_fix_timestamp('2010-01-01 00:00:00', '%Y-%m-%d %H:%M:%S', dt_now)
        self.assertEqual(2010, parsed.year)