text:
package com.formkiq.core.api;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.InvalidDataAccessApiUsageException;
import org.springframework.http.HttpStatus;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.oauth2.provider.ClientRegistrationException;
import org.springframework.security.oauth2.provider.NoSuchClientException;
import org.springframework.util.StringUtils;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;

import com.formkiq.core.service.AuthenticationFailureException;
import com.formkiq.core.service.FormAccessDeniedException;
import com.formkiq.core.service.InvalidJSONException;
import com.formkiq.core.service.InvalidRequestBodyException;
import com.formkiq.core.service.PreconditionFailedException;
import com.formkiq.core.service.SaveActionException;
import com.formkiq.core.service.ServerRequestNotSupported;
import com.formkiq.core.service.SystemPropertyService;
import com.formkiq.core.service.crypto.InvalidLicenseException;
import com.formkiq.core.service.dto.ApiMessageResponse;
import com.formkiq.core.service.dto.SystemConfig;
import com.formkiq.core.service.sign.SigningMissingSignatureException;
import com.formkiq.core.service.workflow.FormErrorException;
import com.formkiq.core.util.NotFoundException;
import com.formkiq.forms.service.InvalidEmailException;
import com.formkiq.webflow.FlowNotFoundException;

/**
 * Error Handling Controller.
 *
 */
@ControllerAdvice(annotations = RestController.class)
public class ErrorHandlingController {

    /** Logger. */
    private static final Logger LOG = Logger
            .getLogger(ErrorHandlingController.class.getName());

    /**
     * AuthenticationFailureException handler.
     * @param ex AuthenticationFailureException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AuthenticationFailureException.class)
    @ResponseBody
    public static ApiMessageResponse handleAuthenticationFailureException(
            final AuthenticationFailureException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * BadCredentialsException handler.
     * @param e {@link BadCredentialsException}
     * @return ApiStringResponse
     */
    @ExceptionHandler(BadCredentialsException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public static ApiMessageResponse handleBadCredentialsException(
            final BadCredentialsException e) {
        LOG.log(Level.INFO, e.getMessage(), e);
        return new ApiMessageResponse(e.getMessage());
    }

    /**
     * ClassNotFoundException handler.
     * @param ex {@link ClassNotFoundException}
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(ClassNotFoundException.class)
    @ResponseBody
    public static ApiMessageResponse handleClassNotFoundException(
            final ClassNotFoundException ex) {
        return new ApiMessageResponse(ex.getMessage()  + " not found.");
    }

    /**
     * ClientRegistrationException handler.
     * @param ex ClientRegistrationException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(ClientRegistrationException.class)
    @ResponseBody
    public static ApiMessageResponse handleClientRegistrationException(
            final ClientRegistrationException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * {@link FormErrorException} handler.
     * @param ex {@link FormErrorException}
     * @return {@link Map}
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(FormErrorException.class)
    @ResponseBody
    public static Map<String, String> handleFormErrorException(
            final FormErrorException ex) {
        return ex.getErrors();
    }

    /**
     * {@link FileNotFoundException} handler.
     * @param ex {@link FileNotFoundException}
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(FileNotFoundException.class)
    @ResponseBody
    public static ApiMessageResponse handleFileNotFoundException(
            final FileNotFoundException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * FormAccessDeniedException handler.
     * @return ApiStringResponse
     */
    @ExceptionHandler(FormAccessDeniedException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ResponseBody
    public static ApiMessageResponse handleFormAccessDeniedException() {
        return new ApiMessageResponse("Permission Denied");
    }

    /**
     * {@link NotFoundException} handler.
     * @param ex {@link NotFoundException}
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(NotFoundException.class)
    @ResponseBody
    public static ApiMessageResponse handleNotFoundException(
            final NotFoundException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * InvalidDataAccessApiUsageException handler.
     * @param ex {@link InvalidDataAccessApiUsageException}
     * @return {@link ApiMessageResponse}
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidDataAccessApiUsageException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidDataAccessApiUsageException(
            final InvalidDataAccessApiUsageException ex) {
        LOG.log(Level.WARNING, ex.getMessage(), ex);
        return new ApiMessageResponse("Invalid Request");
    }

    /**
     * InvalidEmailException handler.
     * @param ex InvalidEmailException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    @ExceptionHandler(InvalidEmailException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidEmailException(
            final InvalidEmailException ex) {
        return new ApiMessageResponse(
                "invalid email address '" + ex.getInvalidEmail() + "'");
    }

    /**
     * InvalidJSONException handler.
     * @param ex InvalidJSONException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidJSONException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidJSONException(
            final InvalidJSONException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse("invalid json");
    }

    /**
     * InvalidLicenseException handler.
     * @param ex InvalidLicenseException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(InvalidLicenseException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidLicenseException(
            final InvalidLicenseException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * AuthenticationFailureException handler.
     * @param ex {@link InvalidMediaTypeException}
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidMediaTypeException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidMediaTypeException(
            final InvalidMediaTypeException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * InvalidRequestBodyException handler.
     * @param ex InvalidRequestBodyException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(InvalidRequestBodyException.class)
    @ResponseBody
    public static ApiMessageResponse handleInvalidRequestBodyException(
            final InvalidRequestBodyException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * NoSuchClientException handler.
     * @param ex NoSuchClientException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(NoSuchClientException.class)
    @ResponseBody
    public static ApiMessageResponse handleNoSuchClientException(
            final NoSuchClientException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * ServerRequestNotSupported handler.
     * @param ex ServerRequestNotSupported
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_FOUND)
    @ExceptionHandler(ServerRequestNotSupported.class)
    @ResponseBody
    public static ApiMessageResponse handleServerRequestNotSupported(
            final ServerRequestNotSupported ex) {
        return new ApiMessageResponse("Server does not support request");
    }

    /**
     * SigningMissingSignatureException handler.
     * @param ex SigningMissingSignatureException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    @ExceptionHandler(SigningMissingSignatureException.class)
    @ResponseBody
    public static ApiMessageResponse handleSigningMissingSignatureException(
            final SigningMissingSignatureException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /** SystemPropertyService. */
    @Autowired
    private SystemPropertyService propertyService;

    /** MailSender. */
    @Autowired
    private MailSender mailSender;

    /**
     * Handler for Access Denied Exception.
     * @param ex AccessDeniedException
     * @return ApiMessageResponse
     */
    @ResponseBody
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    @ExceptionHandler(AccessDeniedException.class)
    public ApiMessageResponse handleAccessDenied(
            final AccessDeniedException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * Exception handler.
     * @param ex Exception
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ApiMessageResponse handleExceptions(final Exception ex) {

        LOG.log(Level.SEVERE, ex.getMessage(), ex);

        if (!isIgnoreException(ex)) {

            try {

                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                ex.printStackTrace(pw);

                SystemConfig config = this.propertyService.getSystemConfig();
                String host = config.getHostname();

                SimpleMailMessage msg = new SimpleMailMessage();
                msg.setSubject("Exception in FormKiQ: " + host);
                msg.setText(sw.toString());

                String email = config.getErroremail();

                try {
                    msg.setTo(email);
                    this.mailSender.send(msg);
                } catch (Exception e) {
                    LOG.log(Level.SEVERE, "Unable to send email.", e);
                }

            } catch (Exception e) {

                LOG.log(Level.SEVERE, e.getMessage(), e);
            }
        }

        return new ApiMessageResponse(
                "unable to process request");
    }

    /**
     * FlowNotFoundException handler.
     *
     * @param ex FlowNotFoundException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(FlowNotFoundException.class)
    @ResponseBody
    public ApiMessageResponse handleFlowNotFoundException(
            final FlowNotFoundException ex) {
        LOG.log(Level.FINEST, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * Handle handleIllegalArgumentException.
     * @param ex IllegalArgumentException
     * @return ApiMessageResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseBody
    public ApiMessageResponse handleIllegalArgumentException(
            final IllegalArgumentException ex) {
        String msg = ex.getMessage();

        if (!StringUtils.isEmpty(msg) && msg.startsWith("No enum constant ")) {
            msg = msg.substring(msg.lastIndexOf(".") + 1);
        }

        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(msg);
    }

    /**
     * MissingServletRequestParameterException handler.
     *
     * @param ex MissingServletRequestParameterException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    @ResponseBody
    public ApiMessageResponse handleMissingServletRequestParameterException(
            final MissingServletRequestParameterException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        return new ApiMessageResponse("'" + ex.getParameterName()
                + "' parameter is required");
    }

    /**
     * PreconditionFailedException handler.
     *
     * @param ex PreconditionFailedException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    @ExceptionHandler(PreconditionFailedException.class)
    @ResponseBody
    public ApiMessageResponse handlePreconditionFailedException(
            final PreconditionFailedException ex) {
        LOG.log(Level.FINE, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * SaveActionException handler.
     *
     * @param ex SaveActionException
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.PRECONDITION_FAILED)
    @ExceptionHandler(SaveActionException.class)
    @ResponseBody
    public ApiMessageResponse handleSaveActionException(
            final SaveActionException ex) {
        LOG.log(Level.INFO, ex.getMessage(), ex);
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * HttpMediaTypeNotSupportedException handler.
     *
     * @param ex {@link HttpMediaTypeNotSupportedException}
     * @return ApiStringResponse
     */
    @ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseBody
    public ApiMessageResponse httpMediaTypeNotSupportedException(
            final HttpMediaTypeNotSupportedException ex) {
        return new ApiMessageResponse(ex.getMessage());
    }

    /**
     * Exceptions to ignore for sending email.
     * @param ex {@link Throwable}
     * @return boolean
     */
    public boolean isIgnoreException(final Throwable ex) {

        boolean ignore = false;

        if (ex instanceof IOException) {
            IOException e = (IOException) ex;
            ignore = e.getMessage().toLowerCase().contains("broken pipe");
        } else if (ex.getCause() != null) {
            ignore = isIgnoreException(ex.getCause());
        }

        return ignore;
    }
}


text:
/* Generated By:JJTree: Do not edit this line. EnumBodyDeclarations.java Version 4.3 */
/* JavaCCOptions:MULTI=true,NODE_USES_PARSER=false,VISITOR=true,TRACK_TOKENS=true,NODE_PREFIX=,NODE_EXTENDS=,NODE_FACTORY=,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */
package javacc.generated;

public
class EnumBodyDeclarations extends SimpleNode {
  public EnumBodyDeclarations(int id) {
    super(id);
  }

  public EnumBodyDeclarations(JavaParser1_7 p, int id) {
    super(p, id);
  }

  /** Accept the visitor. **/
  public Object jjtAccept(JavaParser1_7Visitor visitor, Object data) {
    return visitor.visit(this, data);
  }
}
/* JavaCC - OriginalChecksum=c625d1cecf0c6147b79930985eac5edf (do not edit this line) */

redpajama_set_name: RedPajamaGithub


text:
/**
 * Dependency of CSS editing plugins like CSS Snippets or CSS Controls
 * @author Lea Verou
 * MIT License
 */

(function(){

var guineaPig = document.createElement('div');

var self = window.CSSEdit = {
	setupSubjects: function(subjects) {
		for (var i=0; i<subjects.length; i++) {
			var subject = subjects[i];

			subject.setAttribute('data-originalstyle', subject.getAttribute('style'));
			subject.setAttribute('data-originalcssText', subject.style.cssText);
		}
	},

	getSubjects: function(element) {
		var selector = element.getAttribute('data-subject'),
			subjects;

		if(selector) {
			subjects = self.util.toArray(document.querySelectorAll(selector)) || [];
		}
		else {
			subjects = element.hasAttribute('data-subject')? [element] : [];
		}

		if(/^(input|textarea)$/i.test(element.nodeName)) {
			// If no subject specified, it will be the slide
			if(!subjects.length) {
				// Find containing slide
				var slide = SlideShow.getSlide(element.parentNode);

				subjects = [slide? slide : element];
			}
		}
		else {
			subjects.unshift(element);
		}

		return subjects;
	},

	updateStyle: function(subjects, code, originalAttribute) {
		code = CSSPrefix.prefixCSS(code.trim());

		if(code && CSSPrefix.isCSSValid(code)) {
			guineaPig.setAttribute('style', code);

			var appliedCode = guineaPig.style.cssText;
			if(appliedCode.match(/\b[a-z-]+(?=:)/gi) === null) console.log('"' + appliedCode + '"');
			var properties = appliedCode.match(/\b[a-z-]+(?=:)/gi), propRegex = [];

			for(var i=0; i<properties.length; i++) {
				properties[i] = self.util.camelCase(properties[i]);
			}

			for (var i=0; i<subjects.length; i++) {
				var element = subjects[i],
					prevStyle = subjects[i].getAttribute('style'),
					style = prevStyle;

				if(prevStyle && prevStyle !== 'null') {
					for(var j=0; j<properties.length; j++) {
						element.style[properties[i]] = null;
					}

					element.setAttribute('style', element.getAttribute(originalAttribute) + '; ' + code);
				}
				else {
					element.setAttribute('style', code);
				}
			}

			return true;
		}
		else {
			return false;
		}
	},

	elastic: function(textarea) {
		if(!/^textarea$/i.test(textarea.nodeName)
			|| !('rows' in textarea)
			|| textarea.classList.contains('dont-resize')) {
			return;
		}

		self.util.adjustHeight(textarea);

		textarea.addEventListener('keyup', function(evt) {
			if(evt.keyCode == 13) {
				self.util.adjustHeight(this);
			}
		}, false);

		textarea.addEventListener('input', function(evt) {
			self.util.adjustHeight(this);
		}, false);
	},

	util: {
		camelCase: function(str) {
			return str.replace(/-(.)/g, function($0, $1) { return $1.toUpperCase() })
		},

		toArray: function(collection) {
			return Array.prototype.slice.apply(collection);
		},

		adjustHeight: function(textarea) {
			textarea.rows = textarea.value.split(/\r\n?|\n/).length;

			textarea.style.fontSize = Math.min(90, 100 - textarea.rows * 5) + '%';
		}
	}
 };

 })()


text:
sudo apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 36A1D7869245C8950F966E92D8576A8BA88D21E9
sudo sh -c "echo deb http://get.docker.io/ubuntu docker main > /etc/apt/sources.list.d/docker.list"
sudo apt-get -q update
sudo apt-get -q -y install lxc-docker


text:
def source
    super + erb(:github_link)
end


text:
<?php
/* Prototype: bool is_file ( string $filename );
   Description: Tells whether the filename is a regular file
     Returns TRUE if the filename exists and is a regular file
*/

/* Passing file names with different notations, using slashes, wild-card chars */

$file_path = dirname(__FILE__);

echo "*** Testing is_file() with different notations of file names ***\n";
$dir_name = $file_path."/is_file_variation4";
mkdir($dir_name);
$file_handle = fopen($dir_name."/is_file_variation4.tmp", "w");
fclose($file_handle);

$files_arr = array(
  "/is_file_variation4/is_file_variation4.tmp",

  /* Testing a file trailing slash */
  "/is_file_variation4/is_file_variation4.tmp/",

  /* Testing file with double slashes */
  "/is_file_variation4//is_file_variation4.tmp",
  "//is_file_variation4//is_file_variation4.tmp",
  "/is_file_variation4/*.tmp",
  "is_file_variation4/is_file*.tmp",

  /* Testing Binary safe */
  "/is_file_variation4/is_file_variation4.tmp".chr(0),
  "/is_file_variation4/is_file_variation4.tmp\0"
);

$count = 1;
/* loop through to test each element in the above array */
foreach($files_arr as $file) {
  echo "- Iteration $count -\n";
  var_dump( is_file( $file_path."/".$file ) );
  clearstatcache();
  $count++;
}

echo "\n*** Done ***";
?>


text:
require 'active_model'

# Require base code
require 'custom_validations/version'
require 'custom_validations/engine'

# Require validators
require 'custom_validations/br_postal_code_validator'
require 'custom_validations/br_cpf_validator'
require 'custom_validations/br_cnpj_validator'
require 'custom_validations/email_validator'
require 'custom_validations/url_validator'

# Require ClientSideValidations midlewares
if defined?(ClientSideValidations)
  require 'custom_validations/client_side_validations_midleware/url'
end

# Load translations
require 'active_support/i18n'
I18n.load_path += Dir[File.dirname(__FILE__) + '/custom_validations/locales/*.{rb,yml}']


text:
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using DigitallyImported.Components.Caching;

#endregion

namespace DigitallyImported.Components
{
    /// <summary>
    /// </summary>
    /// <typeparam name="T"> </typeparam>
    public abstract class ContentSerializer<T> : CacheItem<T>, IXmlSerializable
        where T : IContent
    {
        #region IXmlSerializable Members

        /// <summary>
        /// </summary>
        /// <returns> </returns>
        public XmlSchema GetSchema()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        /// <summary>
        /// </summary>
        /// <param name="reader"> </param>
        public void ReadXml(XmlReader reader)
        {
            if (reader == null) throw new ArgumentNullException("reader");
            throw new Exception("The method or operation is not implemented.");
        }

        /// <summary>
        /// </summary>
        /// <param name="writer"> </param>
        public void WriteXml(XmlWriter writer)
        {
            if (writer == null) throw new ArgumentNullException("writer");
            throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
}


text:
package org.jtwig.render.expression.test.calculator;

import org.jtwig.model.expression.Expression;
import org.jtwig.model.expression.test.NotTestExpression;
import org.jtwig.model.position.Position;
import org.jtwig.render.RenderRequest;
import org.jtwig.render.expression.test.CalculateTestExpressionService;
import org.jtwig.value.convert.Converter;

public class NotTestExpressionCalculator implements TestExpressionCalculator<NotTestExpression> {
    @Override
    public Object calculate(RenderRequest request, Position position, NotTestExpression test, Expression argument) {
        CalculateTestExpressionService calculateTestExpressionService = request.getEnvironment().getRenderEnvironment().getCalculateTestExpressionService();
        Converter<Boolean> booleanConverter = request.getEnvironment().getValueEnvironment().getBooleanConverter();

        Object calculate = calculateTestExpressionService.calculate(request, position, test.getTestExpression(), argument);

        return !booleanConverter.convert(calculate).or(true);
    }
}


text:
package org.apache.felix.ipojo.runtime.core.test.dependencies;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.runtime.core.test.services.CheckService;
import org.apache.felix.ipojo.runtime.core.test.services.Setter;
import org.junit.Test;

import java.util.Dictionary;
import java.util.Hashtable;
import java.util.Properties;

import static org.fest.assertions.Assertions.assertThat;

/**
 * Checks the combination of tracking and ranking interceptors.
 *
 * First, the tracking interceptor selects the references, it also transforms them.
 * Then, the ranking interceptor sorts the remaining references.
 */
public class TestCombinationOfInterceptors extends Common {

    private ComponentInstance provider1;
    private ComponentInstance provider2;
    private ComponentInstance provider3;
    private ComponentInstance provider4;
    private ComponentInstance provider5;
    private ComponentInstance provider6;

    @Test
    public void testCombination() {

        provider1 = provider(0);
        provider2 = provider(1);
        provider3 = provider(2);
        provider4 = provider(3);
        provider5 = provider(4);
        provider6 = provider(5);

        // Create the interceptor
        Properties configuration = new Properties();
        configuration.put("target", "(dependency.id=foo)");
        ipojoHelper.createComponentInstance("org.apache.felix.ipojo.runtime.core.test.interceptors" +
                ".TrackerAndRankerInterceptor", configuration);

        // Create the FooConsumer
        ipojoHelper.createComponentInstance("org.apache.felix.ipojo.runtime.core.test.components.FooConsumer");

        // Check we are using provider 2
        osgiHelper.waitForService(CheckService.class.getName(), null, 1000, true);
        CheckService check = osgiHelper.getServiceObject(CheckService.class);
        assertThat(check.getProps().get("grade")).isEqualTo(5);

        provider6.dispose();

        assertThat(check.getProps().get("grade")).isEqualTo(4);

        // Change range
        Setter setter = osgiHelper.getServiceObject(Setter.class);
        setter.set("LOW REVERSE");
        assertThat(check.getProps().get("grade")).isEqualTo(0);
    }

    @Test
    public void testAdvanced() {

        provider1 = provider(0);
        provider2 = provider(0);
        provider3 = provider(1);
        provider4 = provider(1);
        provider5 = provider(2);
        provider6 = provider(2);

        // Create the interceptor
        Properties configuration = new Properties();
        configuration.put("target", "(dependency.id=foo)");
        ipojoHelper.createComponentInstance("org.apache.felix.ipojo.runtime.core.test.interceptors" +
                ".AdvancedTrackerAndRankerInterceptor", configuration);

        // Create the FooConsumer
        ComponentInstance instance = ipojoHelper.createComponentInstance("org.apache.felix.ipojo.runtime.core.test" +
                ".components.AdvancedFooConsumer");

        // Check we are using provider 0
        osgiHelper.waitForService(CheckService.class.getName(), null, 1000, true);
        CheckService check = osgiHelper.getServiceObject(CheckService.class);
        assertThat(check.getProps().get("grade")).isEqualTo(0);

        Dictionary conf = new Hashtable();
        conf.put("grade", "1");
        instance.reconfigure(conf);

        assertThat(check.getProps().get("grade")).isEqualTo(1);

        conf.put("grade", "2");
        instance.reconfigure(conf);
        assertThat(check.getProps().get("grade")).isEqualTo(2);

        conf.put("grade", "3");
        instance.reconfigure(conf);
        assertThat(check.getProps().get("grade")).isNull();
    }

    private ComponentInstance provider(int i) {
        Dictionary<String, String> configuration = new Hashtable<String, String>();
        configuration.put("grade", Integer.toString(i));
        return ipojoHelper.createComponentInstance("org.apache.felix.ipojo.runtime.core.test.components.FooProvider",
                configuration);
    }
}


text:
from math import sqrt

from numpy.testing import TestCase, assert_almost_equal, assert_warns, \
                            assert_, run_module_suite

from scipy.optimize import zeros as cc

# Import testing parameters
from scipy.optimize._tstutils import functions, fstrings

class TestBasic(TestCase) :
    def run_check(self, method, name):
        a = .5
        b = sqrt(3)
        for function, fname in zip(functions, fstrings):
            zero, r = method(function, a, b, xtol=0.1e-12, full_output=True)
            assert_(r.converged)
            assert_almost_equal(zero, 1.0, decimal=12,
                err_msg='method %s, function %s' % (name, fname))

    def test_bisect(self):
        self.run_check(cc.bisect, 'bisect')
    def test_ridder(self):
        self.run_check(cc.ridder, 'ridder')
    def test_brentq(self):
        self.run_check(cc.brentq, 'brentq')
    def test_brenth(self):
        self.run_check(cc.brenth, 'brenth')

    def test_deriv_zero_warning(self):
        func = lambda x: x**2
        dfunc = lambda x: 2*x
        assert_warns(RuntimeWarning, cc.newton, func, 0.0, dfunc)

if __name__ == '__main__' :
    run_module_suite()


text:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#a2d8fd">

    <ListView
        android:id="@+id/collaboratorListView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >
    </ListView>

</FrameLayout>


text:
require 'spec_helper'

describe Conversation do

  before do
    @entity1 = FactoryGirl.create(:user)
    @entity2 = FactoryGirl.create(:user)
    @receipt1 = @entity1.send_message(@entity2,"Body","Subject")
    @receipt2 = @entity2.reply_to_all(@receipt1,"Reply body 1")
    @receipt3 = @entity1.reply_to_all(@receipt2,"Reply body 2")
    @receipt4 = @entity2.reply_to_all(@receipt3,"Reply body 3")
    @message1 = @receipt1.notification
    @message4 = @receipt4.notification
    @conversation = @message1.conversation
  end

  it "should have proper original message" do
    @conversation.original_message.should==@message1
  end

  it "should have proper originator (first sender)" do
    @conversation.originator.should==@entity1
  end

  it "should have proper last message" do
    @conversation.last_message.should==@message4
  end

  it "should have proper last sender" do
    @conversation.last_sender.should==@entity2
  end

  it "should have all conversation users" do
    @conversation.recipients.count.should==2
    @conversation.recipients.count.should==2
    @conversation.recipients.count(@entity1).should==1
    @conversation.recipients.count(@entity2).should==1
  end

  it "should be able to be marked as read" do
    @conversation.move_to_trash(@entity1)
  end

  it "should be able to be marked as unread" do
    @conversation.move_to_trash(@entity1)
    @conversation.untrash(@entity1)
  end

  describe "scopes" do
    let(:participant) { FactoryGirl.create(:user) }
    let!(:inbox_conversation) { @entity1.send_message(participant, "Body", "Subject").notification.conversation }
    let!(:sentbox_conversation) { participant.send_message(@entity1, "Body", "Subject").notification.conversation }

    describe ".participant" do
      it "finds conversations with receipts for participant" do
        Conversation.participant(participant).should == [sentbox_conversation, inbox_conversation]
      end
    end

    describe ".inbox" do
      it "finds inbox conversations with receipts for participant" do
        Conversation.inbox(participant).should == [inbox_conversation]
      end
    end

    describe ".sentbox" do
      it "finds sentbox conversations with receipts for participant" do
        Conversation.sentbox(participant).should == [sentbox_conversation]
      end
    end

    describe ".trash" do
      it "finds trash conversations with receipts for participant" do
        trashed_conversation = @entity1.send_message(participant, "Body", "Subject").notification.conversation
        trashed_conversation.move_to_trash(participant)

        Conversation.trash(participant).should == [trashed_conversation]
      end
    end

    describe ".unread" do
      it "finds unread conversations with receipts for participant" do
        [sentbox_conversation, inbox_conversation].each {|c| c.mark_as_read(participant) }
        unread_conversation = @entity1.send_message(participant, "Body", "Subject").notification.conversation

        Conversation.unread(participant).should == [unread_conversation]
      end
    end
  end

  describe "#is_completely_trashed?" do
    it "returns true if all receipts in conversation are trashed for participant" do
      @conversation.move_to_trash(@entity1)
      @conversation.is_completely_trashed?(@entity1).should be_true
    end
  end
end


text:
package com.liner.graduationproject.map.fragments;

import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.liner.graduationproject.R;
import com.liner.graduationproject.map.BaseFragment;
import com.liner.graduationproject.map.adapters.RecyclerItemAdapter;
import com.liner.graduationproject.map.beans.PoiBean;
import com.liner.graduationproject.map.utils.PoiSearchUtil;

import java.util.ArrayList;

/**
 *  POI兴趣点搜索
 */

public class MapPoiFragment extends BaseFragment implements View.OnClickListener, PoiSearchUtil.PoiDataCallBack, SwipeRefreshLayout.OnRefreshListener {

    private EditText mTargetName;
    private EditText mCityName;
    private PoiSearchUtil poiSearchUtil;
    private RecyclerView mRecycler;
    private RecyclerItemAdapter adapter;
    private LinearLayoutManager layoutManager;
    private SwipeRefreshLayout mRefreshLayout;

    @Override
    protected int getResLayout() {
        return R.layout.map_poi_view;
    }

    @Override
    protected void initView() {
        mCityName = ((EditText) layout.findViewById(R.id.fragment_poi_city));// 所在城市
        mTargetName = ((EditText) layout.findViewById(R.id.fragment_poi_target));// 搜索目标
        layout.findViewById(R.id.fragment_poi_submit).setOnClickListener(this);// 搜索按钮

        poiSearchUtil = new PoiSearchUtil(getContext(), this);

        mRecycler = ((RecyclerView) layout.findViewById(R.id.fragment_poi_content_recycler));
        layoutManager = new LinearLayoutManager(getContext());
        mRecycler.setLayoutManager(layoutManager);
        adapter = new RecyclerItemAdapter(getContext());
        mRecycler.setAdapter(adapter);
        mRefreshLayout = ((SwipeRefreshLayout) layout.findViewById(R.id.fragment_poi_refresh_layout));
        mRefreshLayout.setOnRefreshListener(this);

        mRecycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                int childCount = recyclerView.getChildCount();
                int itemCount = layoutManager.getItemCount();
                int firstVisibleItemPosition = layoutManager.findFirstVisibleItemPosition();
                if (itemCount - childCount > firstVisibleItemPosition) {
                    if (poiSearchUtil.getItemPosition() > poiSearchUtil.getItemCount()) {
                        String cityName = mCityName.getText().toString();
                        String targetName = mTargetName.getText().toString();
                        poiSearchUtil.setItemCount(poiSearchUtil.getItemCount()+10);
                        poiSearchUtil.startPoiSearch(cityName, targetName);
                    }else {
                        Toast.makeText(getContext(), "已经加载完全部内容了", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_poi_submit:
                // 开始POI搜索
                String cityName = mCityName.getText().toString();
                String targetName = mTargetName.getText().toString();
                poiSearchUtil.startPoiSearch(cityName, targetName);
                break;
        }
    }

    @Override
    public void poiBeanCallBack(ArrayList<PoiBean> data) {
        adapter.updateData(data);
        mRefreshLayout.setRefreshing(false);
    }

    @Override
    public void onRefresh() {
        String cityName = mCityName.getText().toString();
        String targetName = mTargetName.getText().toString();
        poiSearchUtil.startPoiSearch(cityName, targetName);
    }
}


text:
XML = '''<listitem>
  <para>
    <ulink url="http://wiki.semiolabs.org/test/test/MacDonald#">MacDonald</ulink> TM. A European's perspective of COX-2 drug safety. J Cardiovasc Pharmacol. 2006;47 Suppl 1:S92-7. (<ulink url="http://wiki.semiolabs.org/test/test/PubMed#">PubMed</ulink>: <ulink url="http://www.ncbi.nlm.nih.gov/pubmed/16785838">16785838</ulink>)
  </para>
</listitem>
'''

import amara
from amara.xpath.datatypes import nodeset

def test_last_function_low_level():
    '''
    '''
    doc = amara.parse(XML)
    last_url = doc.xml_select(u'/listitem/para/ulink[position() = last()]/@url')
    EXPECTED = nodeset([u'http://www.ncbi.nlm.nih.gov/pubmed/16785838'])
    assert last_url == EXPECTED, (EXPECTED, last_url)


text:
| Since  | Origin / Contributor  | Maintainer  | Source  |
| :----- | :-------------------- | :---------- | :------ |
| 2014-12-12 | [Zeroday](https://github.com/funshine) |              [dnc40085](https://github.com/dnc40085) | [tmr.c](../../../app/modules/tmr.c)|

The tmr module allows access to simple timers, the system counter and uptime.

It is aimed at setting up regularly occurring tasks, timing out operations, and provide low-resolution deltas.

What the tmr module is *not* however, is a time keeping module. While most timeouts are expressed in milliseconds or even microseconds, the accuracy is limited and compounding errors would lead to rather inaccurate time keeping. Consider using the [rtctime](rtctime.md) module for "wall clock" time.

NodeMCU provides 7 timers, numbered 0-6. It is currently up to the user to keep track of which timers are used for what.

## tmr.alarm()

This is a convenience function combining [`tmr.register()`](#tmrregister) and [`tmr.start()`](#tmrstart) into a single call.

To free up the resources with this timer when done using it, call [`tmr.unregister()`](#tmrunregister) on it. For one-shot timers this is not necessary, unless they were stopped before they expired.

#### Parameters
- `id` timer id (0-6)
- `interval_ms` timer interval in milliseconds. Maximum value is 6870947 (1:54:30.947).
- `mode` timer mode:
	- `tmr.ALARM_SINGLE` a one-shot alarm (and no need to call [`tmr.unregister()`](#tmrunregister))
	- `tmr.ALARM_SEMI` manually repeating alarm (call [`tmr.start()`](#tmrstart) to restart)
	- `tmr.ALARM_AUTO` automatically repeating alarm

#### Returns
`true` if the timer was started, `false` on error

#### Example
```lua
if not tmr.alarm(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end) then print("whoopsie") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.start()`](#tmrstart)
- [`tmr.unregister()`](#tmrunregister)

## tmr.delay()

Busyloops the processor for a specified number of microseconds.

This is in general a **bad** idea, because nothing else gets to run, and the networking stack (and other things) can fall over as a result. The only time `tmr.delay()` may be appropriate to use is if dealing with a peripheral device which needs a (very) brief delay between commands, or similar. *Use with caution!*

Also note that the actual amount of time delayed for may be noticeably greater, both as a result of timing inaccuracies as well as interrupts which may run during this time.

#### Syntax
`tmr.delay(us)`

#### Parameters
`us` microseconds to busyloop for

#### Returns
`nil`

#### Example
```lua
tmr.delay(100)
```

## tmr.interval()

Changes a registered timer's expiry interval.

#### Syntax
`tmr.interval(id, interval_ms)`

#### Parameters
- `id` timer id (0-6)
- `interval_ms` new timer interval in milliseconds. Maximum value is 6870947 (1:54:30.947).

#### Returns
`nil`

#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
tmr.interval(0, 3000) -- actually, 3 seconds is better!
```

## tmr.now()

Returns the system counter, which counts in microseconds. Limited to 31 bits, after that it wraps around back to zero. That is essential if you use this function to [debounce or throttle GPIO input](https://github.com/hackhitchin/esp8266-co-uk/issues/2).

#### Syntax
`tmr.now()`

#### Parameters
none

#### Returns
the current value of the system counter

#### Example
```lua
print(tmr.now())
print(tmr.now())
```

## tmr.register()

Configures a timer and registers the callback function to call on expiry.

To free up the resources with this timer when done using it, call [`tmr.unregister()`](#tmrunregister) on it. For one-shot timers this is not necessary, unless they were stopped before they expired.

#### Syntax
`tmr.register(id, interval_ms, mode, func)`

#### Parameters
- `id` timer id (0-6)
- `interval_ms` timer interval in milliseconds. Maximum value is 6870947 (1:54:30.947).
- `mode` timer mode:
	- `tmr.ALARM_SINGLE` a one-shot alarm (and no need to call [`tmr.unregister()`](#tmrunregister))
	- `tmr.ALARM_SEMI` manually repeating alarm (call [`tmr.start()`](#tmrunregister) to restart)
	- `tmr.ALARM_AUTO` automatically repeating alarm

Note that registering does *not* start the alarm.

#### Returns
`nil`

#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
tmr.start(0)
```
#### See also
[`tmr.alarm()`](#tmralarm)

## tmr.softwd()

Provides a simple software watchdog, which needs to be re-armed or disabled before it expires, or the system will be restarted.

#### Syntax
`tmr.softwd(timeout_s)`

#### Parameters
`timeout_s` watchdog timeout, in seconds. To disable the watchdog, use -1 (or any other negative value).

#### Returns
`nil`

#### Example
```lua
function on_success_callback()
  tmr.softwd(-1)
  print("Complex task done, soft watchdog disabled!")
end

tmr.softwd(5)
-- go off and attempt to do whatever might need a restart to recover from
complex_stuff_which_might_never_call_the_callback(on_success_callback)
```

## tmr.start()

Starts or restarts a previously configured timer.

#### Syntax
`tmr.start(id)`

#### Parameters
`id` timer id (0-6)

#### Returns
`true` if the timer was started, `false` on error

#### Example
```lua
tmr.register(0, 5000, tmr.ALARM_SINGLE, function() print("hey there") end)
if not tmr.start(0) then print("uh oh") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.stop()`](#tmrstop)
- [`tmr.unregister()`](#tmrunregister)

## tmr.state()

Checks the state of a timer.

#### Syntax
`tmr.state(id)`

#### Parameters
`id` timer id (0-6)

#### Returns
(bool, int) or `nil`

If the specified timer is registered, returns whether it is currently started and its mode. If the timer is not registered, `nil` is returned.

#### Example
```lua
running, mode = tmr.state(0)
```

## tmr.stop()

Stops a running timer, but does *not* unregister it. A stopped timer can be restarted with [`tmr.start()`](#tmrstart).

#### Syntax
`tmr.stop(id)`

#### Parameters
`id` timer id (0-6)

#### Returns
`true` if the timer was stopped, `false` on error

#### Example
```lua
if not tmr.stop(2) then print("timer 2 not stopped, not registered?") end
```
#### See also
- [`tmr.register()`](#tmrregister)
- [`tmr.stop()`](#tmrstop)
- [`tmr.unregister()`](#tmrunregister)

## tmr.time()

Returns the system uptime, in seconds. Limited to 31 bits, after that it wraps around back to zero.

#### Syntax
`tmr.time()`

#### Parameters
none

#### Returns
the system uptime, in seconds, possibly wrapped around

#### Example
```lua
print("Uptime (probably):", tmr.time())
```

## tmr.unregister()

Stops the timer (if running) and unregisters the associated callback.

This isn't necessary for one-shot timers (`tmr.ALARM_SINGLE`), as those automatically unregister themselves when fired.

#### Syntax
`tmr.unregister(id)`

#### Parameters
`id` timer id (0-6)

#### Returns
`nil`

#### Example
```lua
tmr.unregister(0)
```
#### See also
[`tmr.register()`](#tmrregister)

## tmr.wdclr()

Feed the system watchdog.

*In general, if you ever need to use this function, you are doing it wrong.*

The event-driven model of NodeMCU means that there is no need to be sitting in hard loops waiting for things to occur. Rather, simply use the callbacks to get notified when somethings happens. With this approach, there should never be a need to manually feed the system watchdog.

#### Syntax
`tmr.wdclr()`

#### Parameters
none

#### Returns
`nil`


text:
<?php

use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Routing\RequestContext;

/**
 * appDevUrlMatcher
 *
 * This class has been auto-generated
 * by the Symfony Routing Component.
 */
class appDevUrlMatcher extends Symfony\Bundle\FrameworkBundle\Routing\RedirectableUrlMatcher
{
    /**
     * Constructor.
     */
    public function __construct(RequestContext $context)
    {
        $this->context = $context;
    }

    public function match($pathinfo)
    {
        $allow = array();
        $pathinfo = rawurldecode($pathinfo);
        $context = $this->context;
        $request = $this->request;

        if (0 === strpos($pathinfo, '/_')) {
            // _wdt
            if (0 === strpos($pathinfo, '/_wdt') && preg_match('#^/_wdt/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                return $this->mergeDefaults(array_replace($matches, array('_route' => '_wdt')), array (  '_controller' => 'web_profiler.controller.profiler:toolbarAction',));
            }

            if (0 === strpos($pathinfo, '/_profiler')) {
                // _profiler_home
                if (rtrim($pathinfo, '/') === '/_profiler') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', '_profiler_home');
                    }

                    return array (  '_controller' => 'web_profiler.controller.profiler:homeAction',  '_route' => '_profiler_home',);
                }

                if (0 === strpos($pathinfo, '/_profiler/search')) {
                    // _profiler_search
                    if ($pathinfo === '/_profiler/search') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchAction',  '_route' => '_profiler_search',);
                    }

                    // _profiler_search_bar
                    if ($pathinfo === '/_profiler/search_bar') {
                        return array (  '_controller' => 'web_profiler.controller.profiler:searchBarAction',  '_route' => '_profiler_search_bar',);
                    }

                }

                // _profiler_purge
                if ($pathinfo === '/_profiler/purge') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:purgeAction',  '_route' => '_profiler_purge',);
                }

                // _profiler_info
                if (0 === strpos($pathinfo, '/_profiler/info') && preg_match('#^/_profiler/info/(?P<about>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_info')), array (  '_controller' => 'web_profiler.controller.profiler:infoAction',));
                }

                // _profiler_phpinfo
                if ($pathinfo === '/_profiler/phpinfo') {
                    return array (  '_controller' => 'web_profiler.controller.profiler:phpinfoAction',  '_route' => '_profiler_phpinfo',);
                }

                // _profiler_search_results
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/search/results$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_search_results')), array (  '_controller' => 'web_profiler.controller.profiler:searchResultsAction',));
                }

                // _profiler
                if (preg_match('#^/_profiler/(?P<token>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler')), array (  '_controller' => 'web_profiler.controller.profiler:panelAction',));
                }

                // _profiler_router
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/router$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_router')), array (  '_controller' => 'web_profiler.controller.router:panelAction',));
                }

                // _profiler_exception
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception')), array (  '_controller' => 'web_profiler.controller.exception:showAction',));
                }

                // _profiler_exception_css
                if (preg_match('#^/_profiler/(?P<token>[^/]++)/exception\\.css$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_profiler_exception_css')), array (  '_controller' => 'web_profiler.controller.exception:cssAction',));
                }

            }

            if (0 === strpos($pathinfo, '/_configurator')) {
                // _configurator_home
                if (rtrim($pathinfo, '/') === '/_configurator') {
                    if (substr($pathinfo, -1) !== '/') {
                        return $this->redirect($pathinfo.'/', '_configurator_home');
                    }

                    return array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::checkAction',  '_route' => '_configurator_home',);
                }

                // _configurator_step
                if (0 === strpos($pathinfo, '/_configurator/step') && preg_match('#^/_configurator/step/(?P<index>[^/]++)$#s', $pathinfo, $matches)) {
                    return $this->mergeDefaults(array_replace($matches, array('_route' => '_configurator_step')), array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::stepAction',));
                }

                // _configurator_final
                if ($pathinfo === '/_configurator/final') {
                    return array (  '_controller' => 'Sensio\\Bundle\\DistributionBundle\\Controller\\ConfiguratorController::finalAction',  '_route' => '_configurator_final',);
                }

            }

        }

        if (0 === strpos($pathinfo, '/api')) {
            if (0 === strpos($pathinfo, '/api/users')) {
                // api_get_user
                if (preg_match('#^/api/users/(?P<id>[^/\\.]++)(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_api_get_user;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_get_user')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::getUserAction',  '_format' => 'json',));
                }
                not_api_get_user:

                // api_get_user_profil
                if (preg_match('#^/api/users/(?P<id>[^/]++)/profil(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                        $allow = array_merge($allow, array('GET', 'HEAD'));
                        goto not_api_get_user_profil;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_get_user_profil')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::getUserProfilAction',  '_format' => 'json',));
                }
                not_api_get_user_profil:

                // api_post_user_facebook
                if (0 === strpos($pathinfo, '/api/users/facebooks') && preg_match('#^/api/users/facebooks(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_api_post_user_facebook;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_user_facebook')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::postUserFacebookAction',  '_format' => 'json',));
                }
                not_api_post_user_facebook:

                // api_post_user_inscription
                if (0 === strpos($pathinfo, '/api/users/inscriptions') && preg_match('#^/api/users/inscriptions(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_api_post_user_inscription;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_user_inscription')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::postUserInscriptionAction',  '_format' => 'json',));
                }
                not_api_post_user_inscription:

                // api_post_user_connexion
                if (0 === strpos($pathinfo, '/api/users/connexions') && preg_match('#^/api/users/connexions(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_api_post_user_connexion;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_user_connexion')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::postUserConnexionAction',  '_format' => 'json',));
                }
                not_api_post_user_connexion:

                // api_put_user
                if (preg_match('#^/api/users/(?P<id>[^/\\.]++)(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'PUT') {
                        $allow[] = 'PUT';
                        goto not_api_put_user;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_put_user')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\UserController::putUserAction',  '_format' => 'json',));
                }
                not_api_put_user:

            }

            // api_post_comment
            if (0 === strpos($pathinfo, '/api/comments') && preg_match('#^/api/comments(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                if ($this->context->getMethod() != 'POST') {
                    $allow[] = 'POST';
                    goto not_api_post_comment;
                }

                return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_comment')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RateCommentController::postCommentAction',  '_format' => 'json',));
            }
            not_api_post_comment:

            if (0 === strpos($pathinfo, '/api/r')) {
                // api_post_rate
                if (0 === strpos($pathinfo, '/api/rates') && preg_match('#^/api/rates(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                    if ($this->context->getMethod() != 'POST') {
                        $allow[] = 'POST';
                        goto not_api_post_rate;
                    }

                    return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_rate')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RateCommentController::postRateAction',  '_format' => 'json',));
                }
                not_api_post_rate:

                if (0 === strpos($pathinfo, '/api/restaurants')) {
                    // api_post_restaurant
                    if (preg_match('#^/api/restaurants(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                        if ($this->context->getMethod() != 'POST') {
                            $allow[] = 'POST';
                            goto not_api_post_restaurant;
                        }

                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_restaurant')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RestaurantController::postRestaurantAction',  '_format' => 'json',));
                    }
                    not_api_post_restaurant:

                    // api_post_restaurant_search
                    if (0 === strpos($pathinfo, '/api/restaurants/searches') && preg_match('#^/api/restaurants/searches(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                        if ($this->context->getMethod() != 'POST') {
                            $allow[] = 'POST';
                            goto not_api_post_restaurant_search;
                        }

                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_restaurant_search')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RestaurantController::postRestaurantSearchAction',  '_format' => 'json',));
                    }
                    not_api_post_restaurant_search:

                    // api_post_restaurant_photo
                    if (0 === strpos($pathinfo, '/api/restaurants/photos') && preg_match('#^/api/restaurants/photos(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                        if ($this->context->getMethod() != 'POST') {
                            $allow[] = 'POST';
                            goto not_api_post_restaurant_photo;
                        }

                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_restaurant_photo')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RestaurantController::postRestaurantPhotoAction',  '_format' => 'json',));
                    }
                    not_api_post_restaurant_photo:

                    // api_post_restaurant_nearby
                    if (0 === strpos($pathinfo, '/api/restaurants/nearbies') && preg_match('#^/api/restaurants/nearbies(?:\\.(?P<_format>xml|json|html))?$#s', $pathinfo, $matches)) {
                        if ($this->context->getMethod() != 'POST') {
                            $allow[] = 'POST';
                            goto not_api_post_restaurant_nearby;
                        }

                        return $this->mergeDefaults(array_replace($matches, array('_route' => 'api_post_restaurant_nearby')), array (  '_controller' => 'Foodsquare\\CommonBundle\\Controller\\RestaurantController::postRestaurantNearbyAction',  '_format' => 'json',));
                    }
                    not_api_post_restaurant_nearby:

                }

            }

            // nelmio_api_doc_index
            if (rtrim($pathinfo, '/') === '/api/doc') {
                if (!in_array($this->context->getMethod(), array('GET', 'HEAD'))) {
                    $allow = array_merge($allow, array('GET', 'HEAD'));
                    goto not_nelmio_api_doc_index;
                }

                if (substr($pathinfo, -1) !== '/') {
                    return $this->redirect($pathinfo.'/', 'nelmio_api_doc_index');
                }

                return array (  '_controller' => 'Nelmio\\ApiDocBundle\\Controller\\ApiDocController::indexAction',  '_route' => 'nelmio_api_doc_index',);
            }
            not_nelmio_api_doc_index:

        }

        throw 0 < count($allow) ? new MethodNotAllowedException(array_unique($allow)) : new ResourceNotFoundException();
    }
}


text:
package com.netflix.staash.mesh.db;

public interface TopicFactory {
    Topic create(String name);
}


text:
<form action="/calendar/<?php echo $scheduleData['calendar_id'] ?>/schedule-element/<?php echo $scheduleData['json_data']['schedule_id'];?>/user-update" method="POST" id="schedule-data-form">

	<?php echo Form::token(); ?>

	<input class="form-control" name="schedule_id" type="hidden" id="schedule_id" value="{{$scheduleData['json_data']['schedule_id']}}">

		scheduled_date
		<input class="form-control" name="scheduled_date" type="text" id="scheduled-date-field" class="date-picker" value="{{$scheduleData['json_data']['scheduled_date'] or ''}}">

		worker_id
 		<?php echo Form::select('worker_id',$scheduleData['workerList'] , $scheduleData['json_data']['worker_id'], ['placeholder' => 'pick a worker...', 'class' => 'form-control']); ?>

	<?php foreach (  $scheduleData['displayFields'] as $f ): ?>

	<?php if ( $f == 'schedule_id'  ||  $f == 'scheduled_date'  || $f == 'worker_id') continue; ?>

			{{$f}}
			<input class="form-control" name="{{$f}}" type="text" id="{{$f}}" value="{{$scheduleData['json_data'][$f] or ''}}">

	<?php endforeach; ?>

</form>


text:
import React, { useEffect, useState } from 'react';
import { createStyles, DialogContent, Grid, makeStyles, Theme} from '@material-ui/core';
import Dialog from '../../CustomDialog';
import SimpleAccordion from '../../SimpleAccordion';
import AddTableComponent from './AddTableComponent';
import CustomCodemirror from '../../CustomCodemirror';
import PinotMethodUtils from '../../../utils/PinotMethodUtils';
import { NotificationContext } from '../../Notification/NotificationContext';
import AddTenantComponent from './AddTenantComponent';
import AddIngestionComponent from './AddIngestionComponent';
import AddIndexingComponent from './AddIndexingComponent';
import AddPartionComponent from './AddPartionComponent';
import AddStorageComponent from './AddStorageComponent';
import AddQueryComponent from './AddQueryComponent';
import _ from 'lodash';
import AddOfflineTenantComponent from './AddOfflineTenantComponent';

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    sqlDiv: {
      border: '1px #BDCCD9 solid',
      borderRadius: 4,
      marginBottom: '20px',
    },
    queryOutput: {
      '& .CodeMirror': { height: '532px !important' },
    },
  })
);

type Props = {
  hideModal: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void,
  fetchData: Function,
  tableType: String
};

const defaultTableObj = {
  "tableName": "",
  "tableType": "",
  "tenants": {
    "broker": "DefaultTenant",
    "server": "DefaultTenant"
  },
  "segmentsConfig": {
    "schemaName": "",
    "timeColumnName": null,
    "replication": "1",
    "replicasPerPartition": "1",
    "retentionTimeUnit": null,
    "retentionTimeValue": null,
    "segmentPushType": "APPEND",
    "segmentPushFrequency": "HOURLY",
    "crypterClassName": null,
    "peerSegmentDownloadScheme": null
  },
  "tableIndexConfig": {
    "loadMode": "MMAP",
    "invertedIndexColumns": [],
    "createInvertedIndexDuringSegmentGeneration": false,
    "rangeIndexColumns": [],
    "sortedColumn": [],
    "bloomFilterColumns": [],
    "bloomFilterConfigs": null,
    "noDictionaryColumns": [],
    "onHeapDictionaryColumns": [],
    "varLengthDictionaryColumns": [],
    "enableDefaultStarTree": false,
    "starTreeIndexConfigs": null,
    "enableDynamicStarTreeCreation": false,
    "segmentPartitionConfig": null,
    "columnMinMaxValueGeneratorMode": null,
    "nullHandlingEnabled": false
  },
  "metadata": {},
  "ingestionConfig": {
    "filterConfig": null,
    "transformConfigs": null
  },
  "quota": {
    "storage": null,
    "maxQueriesPerSecond": null
  },
  "task": null,
  "routing": {
    "segmentPrunerTypes": null,
    "instanceSelectorType": null
  },
  "instanceAssignmentConfigMap": null,
  "query": {
    "timeoutMs": null
  },
  "fieldConfigList": null,
  "upsertConfig": null,
  "tierConfigs": null
};

const defaultSchemaObj = {
  schemaName: '',
  dimensionFieldSpecs: [],
  metricFieldSpecs: [],
  dateTimeFieldSpecs: []
};

let timerId = null;

const tableNamekey = ["dimensionFieldSpecs","metricFieldSpecs","dateTimeFieldSpecs"];

export default function AddOfflineTableOp({
  hideModal,
  fetchData,
  tableType
}: Props) {
  const classes = useStyles();
  const [tableObj, setTableObj] = useState(JSON.parse(JSON.stringify(defaultTableObj)));
  const [schemaObj, setSchemaObj] = useState(JSON.parse(JSON.stringify(defaultSchemaObj)));
  const [tableName, setTableName] = useState('');
  const [columnName, setColumnName] = useState([]);
  const {dispatch} = React.useContext(NotificationContext);
  let isError = false;

  useEffect(()=>{
    if(tableName !== tableObj.tableName){
      setTableName(tableObj.tableName);
      clearTimeout(timerId);
      timerId = setTimeout(()=>{
        updateSchemaObj(tableObj.tableName);
      }, 1000);
    }
  }, [tableObj]);

  useEffect(()=>{
    setTableObj({...tableObj,"tableType":tableType})
  },[])

  const updateSchemaObj = async (tableName) => {
    //table name is same as schema name
    const schemaObj = await PinotMethodUtils.getSchemaData(tableName);
    if(schemaObj.error || typeof schemaObj === 'string'){
      dispatch({
        type: 'error',
        message: schemaObj.error || schemaObj,
        show: true
      });
      setSchemaObj(defaultSchemaObj)
    } else {
      setSchemaObj({...defaultSchemaObj, ...schemaObj});
    }
  }

  const returnValue = (data,key) =>{
    Object.keys(data).map(async (o)=>{
    if(!_.isEmpty(data[o]) && typeof data[o] === "object"){
        await returnValue(data[o],key);
      }
      else if(!_.isEmpty(data[o]) && _.isArray(data[o])){
        data[o].map(async (obj)=>{
          await returnValue(obj,key);
        })
     }else{
        if(o === key && (data[key] === null || data[key] === "")){
          dispatch({
            type: 'error',
            message: `${key} cannot be empty`,
            show: true
          });
          isError = true;
        }
      }
    })
  }

const checkFields = (tableObj,fields) => {
    fields.forEach(async (o:any)=>{
        if(tableObj[o.key] === undefined){
          await returnValue(tableObj,o.key);
        }else{
          if((tableObj[o.key] === null || tableObj[o.key] === "")){
            dispatch({
              type: 'error',
              message: `${o.label} cannot be empty`,
              show: true
            });
            isError = true;
          }
        }
    });
  }

  const validateTableConfig = async () => {
    const fields = [{key:"tableName",label:"Table Name"}];
    await checkFields(tableObj,fields);
    if(isError){
      isError = false;
      return false;
    }
    const validTable = await PinotMethodUtils.validateTableAction(tableObj);
    if(validTable.error || typeof validTable === 'string'){
      dispatch({
        type: 'error',
        message: validTable.error || validTable,
        show: true
      });
      return false;
    }
    return true;
  };

  const handleSave = async () => {
    if(await validateTableConfig()){
      const tableCreationResp = await PinotMethodUtils.saveTableAction(tableObj);
      dispatch({
        type: (tableCreationResp.error || typeof tableCreationResp === 'string') ? 'error' : 'success',
        message: tableCreationResp.error || tableCreationResp.status || tableCreationResp,
        show: true
      });
      tableCreationResp.status && fetchData();
      tableCreationResp.status && hideModal(null);
    }
  };

  useEffect(()=>{
    let columnName = [];
    if(!_.isEmpty(schemaObj)){
      tableNamekey.map((o)=>{
        schemaObj[o] && schemaObj[o].map((obj)=>{
          columnName.push(obj.name);
        })
      })
    }
    setColumnName(columnName);
  },[schemaObj])

  return (
    <Dialog
      open={true}
      handleClose={hideModal}
      handleSave={handleSave}
      title={`Add ${tableType} Table`}
      size="xl"
      disableBackdropClick={true}
      disableEscapeKeyDown={true}
    >
      <DialogContent>
        <Grid container spacing={2}>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Add Table"
              showSearchBox={false}
            >
              <AddTableComponent
                tableObj={tableObj}
                setTableObj={setTableObj}
                dateTimeFieldSpecs={schemaObj.dateTimeFieldSpecs}
                disable={tableType !== ""}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Tenants"
              showSearchBox={false}
            >
              <AddOfflineTenantComponent
                tableObj={{...tableObj}}
                setTableObj={setTableObj}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Ingestion"
              showSearchBox={false}
            >
              <AddIngestionComponent
                tableObj={{...tableObj}}
                setTableObj={setTableObj}
                columnName={columnName}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Indexing & encoding"
              tooltipContent={Click here for more details}
              showSearchBox={false}
            >
              <AddIndexingComponent
                tableObj={tableObj}
                setTableObj={setTableObj}
                columnName={columnName}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Partitioning & Routing"
              showSearchBox={false}
            >
              <AddPartionComponent
                tableObj={tableObj}
                setTableObj={setTableObj}
                columnName={columnName}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Storage & Data retention"
              showSearchBox={false}
            >
              <AddStorageComponent
                tableObj={tableObj}
                setTableObj={setTableObj}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={12}>
            <SimpleAccordion
              headerTitle="Query"
              showSearchBox={false}
            >
              <AddQueryComponent
                tableObj={tableObj}
                setTableObj={setTableObj}
              />
            </SimpleAccordion>
          </Grid>
          <Grid item xs={6}>

              <SimpleAccordion
                headerTitle="Table Config"
                showSearchBox={false}
              >
                <CustomCodemirror
                  customClass={classes.queryOutput}
                  data={tableObj}
                  isEditable={true}
                  returnCodemirrorValue={(newValue)=>{
                    try{
                      const jsonObj = JSON.parse(newValue);
                      if(jsonObj){
                        jsonObj.segmentsConfig.replicasPerPartition = jsonObj.segmentsConfig.replication;
                        setTableObj(jsonObj);
                      }
                    }catch(e){}
                  }}
                />
              </SimpleAccordion>

          </Grid>
          <Grid item xs={6}>

              <SimpleAccordion
                headerTitle="Schema Config (Read only)"
                showSearchBox={false}
              >
                <CustomCodemirror
                  customClass={classes.queryOutput}
                  data={schemaObj}
                  isEditable={false}
                />
              </SimpleAccordion>

          </Grid>
        </Grid>
      </DialogContent>
    </Dialog>
  );
}


text:
package org.apache.commons.collections4.queue;

import java.util.Arrays;
import java.util.Collection;
import java.util.LinkedList;
import java.util.Queue;

import org.apache.commons.collections4.Unmodifiable;
import org.apache.commons.collections4.collection.AbstractCollectionTest;

/**
 * Extension of {@link AbstractCollectionTest} for exercising the
 * {@link UnmodifiableQueue} implementation.
 *
 * @since 4.0
 * @version $Id: UnmodifiableQueueTest.java 1686855 2015-06-22 13:00:27Z tn $
 */
public class UnmodifiableQueueTest<E> extends AbstractQueueTest<E> {

    public UnmodifiableQueueTest(final String testName) {
        super(testName);
    }

    //-----------------------------------------------------------------------
    @Override
    public Queue<E> makeObject() {
        return UnmodifiableQueue.unmodifiableQueue(new LinkedList<E>());
    }

    @Override
    public Queue<E> makeFullCollection() {
        final Queue<E> queue = new LinkedList<E>();
        queue.addAll(Arrays.asList(getFullElements()));
        return UnmodifiableQueue.unmodifiableQueue(queue);
    }

    @Override
    public Collection<E> makeConfirmedCollection() {
        return new LinkedList<E>();
    }

    @Override
    public Collection<E> makeConfirmedFullCollection() {
        final LinkedList<E> list = new LinkedList<E>();
        list.addAll(Arrays.asList(getFullElements()));
        return list;
    }

    @Override
    public Queue<E> getCollection() {
        return super.getCollection();
    }

    @Override
    public boolean isAddSupported() {
        return false;
    }

    @Override
    public boolean isRemoveSupported() {
        return false;
    }

    @Override
    public boolean isNullSupported() {
        return false;
    }

    //-----------------------------------------------------------------------
    @Override
    public void testQueueRemove() {
        resetEmpty();
        try {
            getCollection().remove();
            fail();
        } catch (final UnsupportedOperationException ex) {}
    }

    public void testUnmodifiable() {
        assertTrue(makeObject() instanceof Unmodifiable);
        assertTrue(makeFullCollection() instanceof Unmodifiable);
    }

    public void testDecorateFactory() {
        final Queue<E> queue = makeFullCollection();
        assertSame(queue, UnmodifiableQueue.unmodifiableQueue(queue));

        try {
            UnmodifiableQueue.unmodifiableQueue(null);
            fail();
        } catch (final NullPointerException ex) {}
    }

    //-----------------------------------------------------------------------

    @Override
    public String getCompatibilityVersion() {
        return "4";
    }

//    public void testCreate() throws Exception {
//        resetEmpty();
//        writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableQueue.emptyCollection.version4.obj");
//        resetFull();
//        writeExternalFormToDisk((java.io.Serializable) getCollection(), "src/test/resources/data/test/UnmodifiableQueue.fullCollection.version4.obj");
//    }

}


text:
using System.Globalization;
using System.Security.Cryptography;
using System.Text;

namespace MyWpfFramework.Common.Crypto
{
    /// <summary>
    /// جهت هش کردن کلمه عبور اضافه شده است
    /// </summary>
    public static class Hash
    {
        /// <summary>
        /// هش کردن آرایه‌ای از بایت‌ها
        /// </summary>
        /// <param name="inputBytes">آرایه‌ای از بایت‌ها</param>
        /// <returns>رشته حاوی هش ورودی</returns>
        public static string SHA1Hash(this byte[] inputBytes)
        {
            // step 1, calculate sha1 hash from input
            SHA1 sha1 = SHA1.Create();
            byte[] hash = sha1.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            var sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("X2", CultureInfo.InvariantCulture));
            }
            return sb.ToString();
        }

        /// <summary>
        /// هش کردن یک رشته
        /// </summary>
        /// <param name="strPass">رشته ورودی</param>
        /// <returns>رشته حاوی هش ورودی</returns>
        public static string SHA1Hash(this string strPass)
        {
            if (string.IsNullOrWhiteSpace(strPass))
                return string.Empty;

            byte[] data = Encoding.UTF8.GetBytes(strPass);
            return SHA1Hash(data);
        }
    }
}


text:
module Snapcat
  module Crypt
    extend self

    CIPHER = 'AES-128-ECB'
    ENCRYPTION_KEY = 'M02cnQ51Ji97vwT4'

    def decrypt(data)
      cipher = OpenSSL::Cipher.new(CIPHER)
      cipher.decrypt
      cipher.key = ENCRYPTION_KEY
      decrypted_data = ''

      data.bytes.each_slice(16) do |slice|
        decrypted_data += cipher.update(slice.map(&:chr).join)
      end

      decrypted_data += cipher.final
    end

    def encrypt(data)
      cipher = OpenSSL::Cipher.new(CIPHER)
      cipher.encrypt
      cipher.key = ENCRYPTION_KEY
      cipher.update(pkcs5_pad(data)) + cipher.final
    end

    private

    def pkcs5_pad(data, blocksize = 16)
      pad = blocksize - (data.length % blocksize)
      "#{data}#{pad.chr * pad}"
    end
  end
end


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.pgasync.impl.message;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import static com.github.pgasync.impl.io.IO.bytes;
import static javax.xml.bind.DatatypeConverter.printHexBinary;

/**
 * @author  Antti Laisi
 */
public class PasswordMessage implements Message {

    final String password;
    final byte[] passwordHash;

    public PasswordMessage(String username, String password, byte[] md5salt) {
        this.password = password;
        this.passwordHash = md5salt != null ? md5(username, password, md5salt) : null;
    }

    public byte[] getPasswordHash() {
        return passwordHash;
    }

    public String getPassword() {
        return password;
    }

    static byte[] md5(String username, String password, byte[] md5salt) {
        MessageDigest md5 = md5();
        md5.update(bytes(password));
        md5.update(bytes(username));
        byte[] hash = bytes(printHexBinary(md5.digest()).toLowerCase());

        md5.update(hash);
        md5.update(md5salt);
        hash = bytes(printHexBinary(md5.digest()).toLowerCase());

        byte[] prefixed = new byte[hash.length + 3];
        prefixed[0] = (byte) 'm';
        prefixed[1] = (byte) 'd';
        prefixed[2] = (byte) '5';
        System.arraycopy(hash, 0, prefixed, 3, hash.length);
        return prefixed;
    }

    static MessageDigest md5() {
        try {
            return MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
//------------------------------------------------------------------------------
// <auto-generated>
//     This code was generated by a tool.
//     Runtime Version:4.0.30319.18444
//
//     Changes to this file may cause incorrect behavior and will be lost if
//     the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------

namespace Dibware.Template.Presentation.Web.Resources {
    using System;

    /// <summary>
    ///   A strongly-typed resource class, for looking up localized strings, etc.
    /// </summary>
    // This class was auto-generated by the StronglyTypedResourceBuilder
    // class via a tool like ResGen or Visual Studio.
    // To add or remove a member, edit your .ResX file then rerun ResGen
    // with the /str option, or rebuild your VS project.
    [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
    [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
    public class ConfigurationKeys {

        private static global::System.Resources.ResourceManager resourceMan;

        private static global::System.Globalization.CultureInfo resourceCulture;

        [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
        internal ConfigurationKeys() {
        }

        /// <summary>
        ///   Returns the cached ResourceManager instance used by this class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Resources.ResourceManager ResourceManager {
            get {
                if (object.ReferenceEquals(resourceMan, null)) {
                    global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Dibware.Template.Presentation.Web.Resources.ConfigurationKeys", typeof(ConfigurationKeys).Assembly);
                    resourceMan = temp;
                }
                return resourceMan;
            }
        }

        /// <summary>
        ///   Overrides the current thread's CurrentUICulture property for all
        ///   resource lookups using this strongly typed resource class.
        /// </summary>
        [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
        public static global::System.Globalization.CultureInfo Culture {
            get {
                return resourceCulture;
            }
            set {
                resourceCulture = value;
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to AccountLockoutTimeInMinutes.
        /// </summary>
        public static string AccountLockoutTimeInMinutes {
            get {
                return ResourceManager.GetString("AccountLockoutTimeInMinutes", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplicationDomain.
        /// </summary>
        public static string ApplicationDomain {
            get {
                return ResourceManager.GetString("ApplicationDomain", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplicationEnvironment.
        /// </summary>
        public static string ApplicationEnvironment {
            get {
                return ResourceManager.GetString("ApplicationEnvironment", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplicationTitle.
        /// </summary>
        public static string ApplicationTitle {
            get {
                return ResourceManager.GetString("ApplicationTitle", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ApplicationVersion.
        /// </summary>
        public static string ApplicationVersion {
            get {
                return ResourceManager.GetString("ApplicationVersion", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to BrandName.
        /// </summary>
        public static string BrandName {
            get {
                return ResourceManager.GetString("BrandName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ConfirmationTokenLength.
        /// </summary>
        public static string ConfirmationTokenLength {
            get {
                return ResourceManager.GetString("ConfirmationTokenLength", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ContactEmailAddress.
        /// </summary>
        public static string ContactEmailAddress {
            get {
                return ResourceManager.GetString("ContactEmailAddress", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to DefaultApplicationStatusId.
        /// </summary>
        public static string DefaultApplicationStatusId {
            get {
                return ResourceManager.GetString("DefaultApplicationStatusId", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to DefaultThemeName.
        /// </summary>
        public static string DefaultThemeName {
            get {
                return ResourceManager.GetString("DefaultThemeName", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to HashByteSize.
        /// </summary>
        public static string HashByteSize {
            get {
                return ResourceManager.GetString("HashByteSize", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to MaximumPasswordFailuresSinceLastLogin.
        /// </summary>
        public static string MaximumPasswordFailuresSinceLastLogin {
            get {
                return ResourceManager.GetString("MaximumPasswordFailuresSinceLastLogin", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to MinRequiredNonAlphanumericCharacters.
        /// </summary>
        public static string MinRequiredNonAlphanumericCharacters {
            get {
                return ResourceManager.GetString("MinRequiredNonAlphanumericCharacters", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to MinRequiredPasswordLength.
        /// </summary>
        public static string MinRequiredPasswordLength {
            get {
                return ResourceManager.GetString("MinRequiredPasswordLength", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to PasswordStrengthRegularExpression.
        /// </summary>
        public static string PasswordStrengthRegularExpression {
            get {
                return ResourceManager.GetString("PasswordStrengthRegularExpression", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to PBKDF2Iterations.
        /// </summary>
        public static string PBKDF2Iterations {
            get {
                return ResourceManager.GetString("PBKDF2Iterations", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to RequireConfirmationToken.
        /// </summary>
        public static string RequireConfirmationToken {
            get {
                return ResourceManager.GetString("RequireConfirmationToken", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to RoleName_AdministratorUser.
        /// </summary>
        public static string RoleName_AdministratorUser {
            get {
                return ResourceManager.GetString("RoleName_AdministratorUser", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to RoleName_MainUser.
        /// </summary>
        public static string RoleName_MainUser {
            get {
                return ResourceManager.GetString("RoleName_MainUser", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to RoleName_SuperUser.
        /// </summary>
        public static string RoleName_SuperUser {
            get {
                return ResourceManager.GetString("RoleName_SuperUser", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to RoleName_UnknownUser.
        /// </summary>
        public static string RoleName_UnknownUser {
            get {
                return ResourceManager.GetString("RoleName_UnknownUser", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to SaltByteSize.
        /// </summary>
        public static string SaltByteSize {
            get {
                return ResourceManager.GetString("SaltByteSize", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to ShowDetailedErroMessages.
        /// </summary>
        public static string ShowDetailedErroMessages {
            get {
                return ResourceManager.GetString("ShowDetailedErroMessages", resourceCulture);
            }
        }

        /// <summary>
        ///   Looks up a localized string similar to TokenExpirationInMinutesFromNow.
        /// </summary>
        public static string TokenExpirationInMinutesFromNow {
            get {
                return ResourceManager.GetString("TokenExpirationInMinutesFromNow", resourceCulture);
            }
        }
    }
}


text:
//*******************************************************************************************//
//                                                                                //
// Download Free Evaluation Version From: https://bytescout.com/download/web-installer       //
//                                                                                //
// Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup               //
//                                                                                //
// Copyright © 2017-2020 ByteScout, Inc. All rights reserved.                                //
// https://www.bytescout.com                                                                 //
// https://pdf.co                                                                            //
//                                                                                //
//*******************************************************************************************//

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace HL7CreationFromJson
{
    public class JsonHL7Fields
    {
        public JsonHL7Fields()
        {
            Icd10Codes = new List<string>();
            QuestionAnswer = new List<KeyValuePair<string, string>>();
        }

        public string LabName { get; set; }

        public string PatientLastName { get; set; }
        public string PatientFirstName { get; set; }
        public string PatientSSN { get; set; }
        public string PatientDOB { get; set; }
        public string PatientPhoneHome { get; set; }
        public string PatientPhoneWork { get; set; }
        public string PatientChartNo { get; set; }
        public string PatientGender { get; set; }
        public string PatientAddress { get; set; }

        public string PhysicianName { get; set; }
        public string PhysicianAccountNo { get; set; }
        public string PhysicianNpi { get; set; }

        public string InsuranceName { get; set; }
        public string InsurancePolicy { get; set; }
        public string InsuranceGroup { get; set; }
        public string InsuredName { get; set; }
        public string InsuredSSN { get; set; }
        public string InsuredDob { get; set; }
        public string RelationToPatient { get; set; }

        public string CollectionDateTime { get; set; }

        public List<string> Icd10Codes { get; set; }
        public List<KeyValuePair<string, string>> QuestionAnswer { get; set; }

    }
}


text:
module Fog
  module Compute
    class Brkt
      class Real
        def delete_load_balancer_template(id)
          request(
            :expects => [200],
            :method  => "DELETE",
            :path    => "v1/api/config/loadbalancertemplate/#{id}"
          )
        end
      end

      class Mock
        def delete_load_balancer_template(id)
          self.data[:load_balancer_templates].delete(id)
          Excon::Response.new
        end
      end
    end
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- EN-Revision: 20819 -->
<!-- Reviewed: no -->
<sect1 id="zend.mail.multiple-emails">
    <title>Versand von mehreren E-Mails über eine SMTP Verbindung</title>

    <para>
        Standardmäßig erstellt ein einzelner SMTP Transport eine einzelne Verbindung und verwendet
        Sie wieder wärend der Laufzeit der Skriptausführung. Es können mehrere E-Mails über diese
        SMTP Verbindung gesendet werden. Ein RSET Kommando wird vor jeder Ausführung angewendet um
        sicherzustellen das der korrekte SMTP Handschlag folgt.
    </para>

    <para>
        Optional kann auch eine standardmäßige From Emailadresse und Name definiert werden sowie ein
        standardmäßiger reply-to Header. Das kann durch die statischen Methoden
        <methodname>setDefaultFrom()</methodname> und <methodname>setDefaultReplyTo()</methodname>
        getan werden. Diese Standardwerte werden verwendet wenn man keine From oder Reply-to Adresse
        oder -Name angibt bis die Standardwerte zurückgesetzt werden (gelöscht). Das Zurücksetzen
        der Standardwerte kann durch die Verwendung von <methodname>clearDefaultFrom()</methodname>
        und <methodname>clearDefaultReplyTo</methodname> durchgeführt werden.
    </para>

    <example id="zend.mail.multiple-emails.example-1">
        <title>Versand von mehreren E-Mails über eine SMTP Verbindung</title>

        <programlisting language="php"><![CDATA[
// Transport erstellen
$config = array('name' => 'sender.example.com');
$transport = new Zend_Mail_Transport_Smtp('mail.example.com', $config);

// Setzt From & Reply-To Adressen
// und Namen für alle Emails die zu versenden sind
Zend_Mail::setDefaultFrom('sender@example.com', 'John Doe');
Zend_Mail::setDefaultReplyTo('replyto@example.com','Jane Doe');

// Durch die Nachrichten gehen
for ($i = 0; $i < 5; $i++) {
    $mail = new Zend_Mail();
    $mail->addTo('studio@example.com', 'Test');
    $mail->setFrom('studio@example.com', 'Test');
    $mail->setSubject(
        'Demonstration - mit einer SMTP Verbindung mehrfache E-Mails senden'
    );
    $mail->setBodyText('...Hier die Nachricht...');
    $mail->send($transport);
}

// Setzt die Standardwerte zurück
Zend_Mail::clearDefaultFrom();
Zend_Mail::clearDefaultReplyTo();
]]></programlisting>
    </example>

    <para>
        Wenn man eine separate Verbindung für jeden Mailtransport haben will, muß der Transport vor
        und nach jedem Aufruf der <methodname>send()</methodname> Methode erstellt und gelöscht
        werden. Oder alternativ kann die Verbindung zwischen jedem Transport, durch Zugriff auf das
        Protokoll Objekt des Transportes, manipuliert werden.
    </para>

    <example id="zend.mail.multiple-emails.example-2">
        <title>Die Transportverbindung manuell kontrollieren</title>

        <programlisting language="php"><![CDATA[
// Transport erstellen
$transport = new Zend_Mail_Transport_Smtp();

$protocol = new Zend_Mail_Protocol_Smtp('mail.example.com');
$protocol->connect();
$protocol->helo('mail.example.com');

$transport->setConnection($protocol);

// Durch die Nachrichten gehen
for ($i = 0; $i < 5; $i++) {
    $mail = new Zend_Mail();
    $mail->addTo('studio@example.com', 'Test');
    $mail->setFrom('studio@example.com', 'Test');
    $mail->setSubject(
        'Demonstration - mit einer SMTP Verbindung mehrfache E-Mails senden'
    );
    $mail->setBodyText('...Hier die Nachricht...');

    // Die Verbindung manuell kontrollieren
    $protocol->rset();
    $mail->send($transport);
}

$protocol->quit();
$protocol->disconnect();
]]></programlisting>
    </example>
</sect1>


text:
<?php

namespace spec\Codesleeve\AssetPipeline\Filters;

use PhpSpec\ObjectBehavior;
use Prophecy\Argument;

class SassFilterSpec extends ObjectBehavior
{
    function it_is_initializable()
    {
        $this->shouldHaveType('Codesleeve\AssetPipeline\Filters\SassFilter');
    }
}


text:
require 'spec_helper'
require 'collector/enumerable/enumerable_spec_helper'

describe 'Enumerable' do

  subject { EnumerableSpecHelper::TestEnumerable.new(%w{a b c}) }

  describe '#flat_map' do
    it 'maps, then concatenates the results' do
      pending 'implement Enumerable#flat_map'
      subject.flat_map {|s| (1..3).map {|i| "#{s}#{i}" } }.to_a.should ==
        %w{a1 a2 a3 b1 b2 b3 c1 c2 c3}
    end
  end

  describe '#collect_concat' do
    it 'maps, then concatenates the results' do
      pending 'implement Enumerable#collect_concat'
      subject.collect_concat {|s| (1..3).collect {|i| "#{s}#{i}" } }.to_a.should ==
        %w{a1 a2 a3 b1 b2 b3 c1 c2 c3}
    end
  end

end


text:
<?php if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly ?>
<?php if(!$is_compact) echo VP_View::instance()->load('control/template_control_head', $head_info); ?>

<input type="text" name="<?php echo $name ?>" class="vp-input input-large" value="<?php echo esc_attr($value); ?>" />

<?php if(!$is_compact) echo VP_View::instance()->load('control/template_control_foot', $head_info); ?>