text:
"""----------------------------------------------------------------------------
Author:
    Huang Quanyong (wo1fSea)
    quanyongh@foxmail.com
Date:
    2016/10/19
Description:
    MaxRects.py
----------------------------------------------------------------------------"""

from ..Rect import Rect

MAX_RANK = 2 ** 32
MAX_WIDTH = 1024 * 16
MAX_HEIGHT = 1024 * 16

class MaxRects(object):
    """
    the max rects data structure used in max rects bin pack algorithm
    """

    # EXPAND STRATEGY
    EXPAND_BOTH = 0
    EXPAND_WIDTH = 1
    EXPAND_HEIGHT = 2
    EXPAND_SHORT_SIDE = 3
    EXPAND_LONG_SIDE = 4

    # RANK STRATEGY
    RANK_BSSF = 0
    RANK_BLSF = 1
    RANK_BAF = 3

    def __init__(self, width=1, height=1, max_width=MAX_WIDTH, max_height=MAX_HEIGHT,
                 force_square=False, border_padding=0, shape_padding=0, inner_padding=0):
        super(MaxRects, self).__init__()

        if force_square:
            width = height = max(width, height)
            max_width = max_height = max(max_width, max_height)

        self.size = (width, height)
        self.max_size = (max_width, max_height)

        self.border_padding = border_padding
        self.shape_padding = shape_padding
        self.inner_padding = inner_padding

        self.force_square = force_square

        self.max_rect_list = [Rect(0 + self.border_padding,
                                   0 + self.border_padding,
                                   width - 2 * self.border_padding,
                                   height - 2 * self.border_padding)]
        self.image_rect_list = []

    def _is_in_max_size(self, size):
        return size[0] <= self.max_size[0] and size[1] <= self.max_size[1]

    def expand(self, method=EXPAND_SHORT_SIDE):
        if self.force_square:
            method = self.EXPAND_BOTH

        if method == MaxRects.EXPAND_BOTH:
            new_size = (self.size[0] * 2, self.size[1] * 2)
        elif method == MaxRects.EXPAND_WIDTH:
            new_size = (self.size[0] * 2, self.size[1])
        elif method == MaxRects.EXPAND_HEIGHT:
            new_size = (self.size[0], self.size[1] * 2)
        elif method == MaxRects.EXPAND_SHORT_SIDE:
            if self.size[0] <= self.size[1]:
                new_size = (self.size[0] * 2, self.size[1])
            else:
                new_size = (self.size[0], self.size[1] * 2)
        elif method == MaxRects.EXPAND_LONG_SIDE:
            if self.size[0] >= self.size[1]:
                new_size = (self.size[0] * 2, self.size[1])
            else:
                new_size = (self.size[0], self.size[1] * 2)
        else:
            raise ValueError("Unexpected Method")

        if not self._is_in_max_size(new_size):
            return False

        old_size = self.size
        self.size = new_size

        for max_rect in self.max_rect_list:
            if max_rect.right == old_size[0] - self.border_padding:
                max_rect.right = self.size[0] - self.border_padding
            if max_rect.bottom == old_size[1] - self.border_padding:
                max_rect.bottom = self.size[1] - self.border_padding

        if old_size[0] != self.size[0]:
            new_rect = Rect(old_size[0] - self.border_padding,
                            0 + self.border_padding,
                            self.size[0] - old_size[0],
                            self.size[1] - 2 * self.border_padding)
            self.max_rect_list.append(new_rect)

        if old_size[1] != self.size[1]:
            new_rect = Rect(0 + self.border_padding,
                            old_size[1] - self.border_padding,
                            self.size[0] - 2 * self.border_padding,
                            self.size[1] - old_size[1])
            self.max_rect_list.append(new_rect)

        self.max_rect_list = list(filter(self._max_rect_list_pruning, self.max_rect_list))

        return True

    def cut(self, main_rect, sub_rect):
        sub_rect = sub_rect.clone()
        sub_rect.left -= self.inner_padding
        sub_rect.right += self.inner_padding + self.shape_padding
        sub_rect.top -= self.inner_padding
        sub_rect.bottom += self.inner_padding + self.shape_padding

        if not main_rect.is_overlaped(sub_rect):
            return [main_rect, ]

        result = []
        if main_rect.left < sub_rect.left:
            tmp = main_rect.clone()
            tmp.right = sub_rect.left
            if tmp.area > 0:
                result.append(tmp)
        if main_rect.top < sub_rect.top:
            tmp = main_rect.clone()
            tmp.bottom = sub_rect.top
            if tmp.area > 0:
                result.append(tmp)
        if main_rect.right > sub_rect.right:
            tmp = main_rect.clone()
            tmp.left = sub_rect.right
            if tmp.area > 0:
                result.append(tmp)
        if main_rect.bottom > sub_rect.bottom:
            tmp = main_rect.clone()
            tmp.top = sub_rect.bottom
            if tmp.area > 0:
                result.append(tmp)

        return result

    def rank(self, main_rect, sub_rect, method=RANK_BSSF):
        """
        rank
        :param main_rect:
        :param sub_rect:
        :param method:
        :return:
        """
        if method == self.RANK_BSSF:
            tmp = main_rect.width - sub_rect.width if main_rect.width < main_rect.height \
                else main_rect.height - sub_rect.height
        elif method == self.RANK_BLSF:
            tmp = main_rect.width - sub_rect.width if main_rect.width > main_rect.height \
                else main_rect.height - sub_rect.height
        elif method == self.RANK_BAF:
            tmp = main_rect.area - sub_rect.area

        assert tmp < MAX_RANK
        if tmp < 0 \
                or main_rect.width - sub_rect.width < 2 * self.inner_padding + self.shape_padding \
                or main_rect.height - sub_rect.height < 2 * self.inner_padding + self.shape_padding:
            return MAX_RANK
        else:
            return tmp

    def find_best_rank(self, image_rect, enable_rotated=False):
        if enable_rotated:
            return self.find_best_rank_with_rotate(image_rect)
        else:
            return self.find_best_rank_without_rotate(image_rect)

    def find_best_rank_without_rotate(self, image_rect):
        best_rank = MAX_RANK
        best_index = -1
        for i, rect in enumerate(self.max_rect_list):
            rank = self.rank(rect, image_rect)
            if rank < best_rank:
                best_rank = rank
                best_index = i
        return best_index, best_rank, False

    def find_best_rank_with_rotate(self, image_rect):
        image_rect_r = image_rect.clone()
        image_rect_r.rotate()

        index, rank, _ = self.find_best_rank_without_rotate(image_rect)
        index_r, rank_r, _ = self.find_best_rank_without_rotate(image_rect_r)

        if rank < rank_r:
            return index, rank, False
        else:
            return index_r, rank, True

    def place_image_rect(self, rect_index, image_rect):
        rect = self.max_rect_list[rect_index]
        image_rect.x, image_rect.y = rect.x + self.inner_padding, rect.y + self.inner_padding

        _max_rect_list = []
        for i, rect in enumerate(self.max_rect_list):
            _max_rect_list.extend(self.cut(rect, image_rect))

        self.max_rect_list = _max_rect_list
        self.max_rect_list = list(filter(self._max_rect_list_pruning, _max_rect_list))
        self.image_rect_list.append(image_rect)

    def _max_rect_list_pruning(self, rect):
        for max_rect in self.max_rect_list:
            if rect != max_rect and rect in max_rect:
                return False

        return True

    def dump_plist(self, file_name, duplicates = None, prefix = ""):
        import os

        plist_data = {}

        frames = {}
        for image_rect in self.image_rect_list:
            width, height = (image_rect.width, image_rect.height) if not image_rect.rotated \
                else (image_rect.height, image_rect.width)

            center_offset = (0, 0)
            if image_rect.trimmed:
                center_offset = (image_rect.source_box[0] + width / 2. - image_rect.source_size[0] / 2.,
                                 - (image_rect.source_box[1] + height / 2. - image_rect.source_size[1] / 2.))

            paths = []

            if image_rect.short_path:
                paths.append(image_rect.short_path.replace("\\", "/"))
            else:
                paths.append(os.path.split(image_rect.path)[1])

            if duplicates and image_rect.image_path in duplicates:
                for duplicate in duplicates[image_rect.image_path]:
                    if duplicate.short_path:
                        paths.append(duplicate.short_path.replace("\\", "/"))
                    else:
                        paths.append(os.path.split(duplicate.path)[1])

            for path in paths:
                frames[prefix + path] = dict(
                    frame="{{%d,%d},{%d,%d}}" % (image_rect.x, image_rect.y, width, height),
                    offset="{%d,%d}" % center_offset,
                    rotated=bool(image_rect.rotated),
                    sourceColorRect="{{%d,%d},{%d,%d}}" % (
                        image_rect.source_box[0], image_rect.source_box[1], width, height),
                    sourceSize="{%d,%d}" % image_rect.source_size,
                )

        plist_data["frames"] = frames
        plist_data["metadata"] = dict(
            format=int(2),
            textureFileName=file_name,
            realTextureFileName=file_name,
            size="{%d,%d}" % self.size,
        )

        return plist_data

    def dump_image(self, bg_color=0xffffffff):
        from PIL import Image
        packed_image = Image.new('RGBA', self.size, bg_color)

        for image_rect in self.image_rect_list:
            image = image_rect.image.crop()
            if image_rect.rotated:
                image = image.transpose(Image.ROTATE_270)
            packed_image.paste(image, (image_rect.left, image_rect.top, image_rect.right, image_rect.bottom))

        return packed_image


text:
require 'test_helper'

class Test::Unit::TestCase
  def self.should_have_9953_gitrepos
    should "have 9953 gitrepos in database" do
      Gear.delete_all
      Gear.update_from_gitalt("test/data/people-packages-list")
      assert_equal(Gear.count(:all), 9953)
    end
  end

  def self.should_have_440_gitrepos_for_builder
    should "have 440 gitrepos in database for ldv@" do
      Gear.delete_all
      Gear.update_from_gitalt("test/data/people-packages-list")
      assert_equal(Gear.count(:all, :conditions => { :login => 'ldv' }), 440)
    end
  end

  def self.should_have_0_gitrepos_for_builder
    should "have 0 gitrepos in database for aaaaa@" do
      Gear.delete_all
      Gear.update_from_gitalt("test/data/people-packages-list")
      assert_equal(Gear.count(:all, :conditions => { :login => 'aaaaa' }), 0)
    end
  end

  def self.should_have_5_gitrepos_for_package
    should "have 5 gitrepos in database for package 'glibc'" do
      Gear.delete_all
      Gear.update_from_gitalt("test/data/people-packages-list")
      assert_equal(Gear.count(:all, :conditions => { :package => 'glibc' }), 5)
    end
  end

  def self.should_not_update_if_url_to_gitrepos_is_empty
    should "not update if url to gitrepos is empty" do
      Gear.delete_all
      Gear.create(:package => 'glibc', :login => 'ldv', :lastchange => Time.now())
      Gear.update_from_gitalt("")
      assert_equal(Gear.count(:all), 1)
    end
  end

  def self.should_not_update_if_gitrepos_file_size_is_zero
    should "not update if gitrepos file size is zero" do
      Gear.delete_all
      Gear.create(:package => 'glibc', :login => 'ldv', :lastchange => Time.now())
      Gear.update_from_gitalt("test/data/people-packages-list1")
      assert_equal(Gear.count(:all), 1)
    end
  end

  def self.should_not_add_twice
    should "not add twice data to database" do
      Gear.delete_all
      Gear.update_from_gitalt("test/data/people-packages-list")
      Gear.update_from_gitalt("test/data/people-packages-list")
      assert_equal(Gear.count(:all), 9953)
    end
  end

  def self.should_fail_on_int
    should "fail on int" do
      Gear.delete_all
      Gear.create(:package => 'glibc', :login => 'ldv', :lastchange => Time.now())
      Gear.update_from_gitalt(1)
      assert_equal(Gear.count(:all), 1)
    end
  end

  def self.should_check_gear_for_exists_and_not_add_twice
    should "check gear for exists and not add twice" do
      Gear.delete_all
      Gear.create(:package => 'glibc', :login => 'ldv', :lastchange => Time.now())
      Gear.create(:package => 'glibc', :login => 'ldv', :lastchange => Time.now())
      assert_equal(Gear.count(:all), 1)
    end
  end
end

class GearTest < ActiveSupport::TestCase
  should_validate_presence_of :package, :login, :lastchange
  should_have_9953_gitrepos
  should_have_440_gitrepos_for_builder
  should_have_0_gitrepos_for_builder
  should_have_5_gitrepos_for_package
  should_not_update_if_url_to_gitrepos_is_empty
  should_not_update_if_gitrepos_file_size_is_zero
  should_not_add_twice
  should_fail_on_int
  should_check_gear_for_exists_and_not_add_twice
end

redpajama_set_name: RedPajamaGithub


text:
#ifndef FORMAT_UNPACK_H
#define FORMAT_UNPACK_H

extern GLfloat
_mesa_nonlinear_to_linear(GLubyte cs8);

extern void
_mesa_unpack_rgba_row(gl_format format, GLuint n,
                      const void *src, GLfloat dst[][4]);

extern void
_mesa_unpack_ubyte_rgba_row(gl_format format, GLuint n,
                            const void *src, GLubyte dst[][4]);

void
_mesa_unpack_uint_rgba_row(gl_format format, GLuint n,
                           const void *src, GLuint dst[][4]);

extern void
_mesa_unpack_rgba_block(gl_format format,
                        const void *src, GLint srcRowStride,
                        GLfloat dst[][4], GLint dstRowStride,
                        GLuint x, GLuint y, GLuint width, GLuint height);

extern void
_mesa_unpack_float_z_row(gl_format format, GLuint n,
                         const void *src, GLfloat *dst);

void
_mesa_unpack_uint_z_row(gl_format format, GLuint n,
                        const void *src, GLuint *dst);

void
_mesa_unpack_ubyte_stencil_row(gl_format format, GLuint n,
			       const void *src, GLubyte *dst);

void
_mesa_unpack_uint_24_8_depth_stencil_row(gl_format format, GLuint n,
					 const void *src, GLuint *dst);

#endif /* FORMAT_UNPACK_H */


text:
from lib.utils.util import shell_command

class CollectinfoReader:
    cinfo_log_file_identifier_key = "=ASCOLLECTINFO"
    cinfo_log_file_identifiers = [
        "Configuration~~~\|Configuration (.*)~",
        "Statistics~\|Statistics (.*)~",
    ]
    system_log_file_identifier_key = "=ASCOLLECTINFO"
    system_log_file_identifiers = [
        "hostname -I",
        "uname -a",
        "ip addr",
        "Data collection for get_awsdata in progress",
        "top -n",
        "cat /var/log/syslog",
    ]

    def is_cinfo_log_file(self, log_file=""):
        if not log_file:
            return False

        try:
            out, err = shell_command(['head -n 30 "%s"' % (log_file)])
        except Exception:
            return False

        if err or not out:
            return False

        lines = out.strip().split("\n")
        found = False
        for line in lines:
            try:
                if self.cinfo_log_file_identifier_key in line:
                    found = True
                    break
            except Exception:
                pass

        if not found:
            return False

        for search_string in self.cinfo_log_file_identifiers:
            try:
                out, err = shell_command(
                    ['grep -m 1 "%s" "%s"' % (search_string, log_file)]
                )
            except Exception:
                return False
            if err or not out:
                return False
        return True

    def is_system_log_file(self, log_file=""):
        if not log_file:
            return False
        try:
            out, err = shell_command(['head -n 30 "%s"' % (log_file)])
        except Exception:
            return False
        if err or not out:
            return False
        lines = out.strip().split("\n")
        found = False
        for line in lines:
            try:
                if self.system_log_file_identifier_key in line:
                    found = True
                    break
            except Exception:
                pass
        if not found:
            return False
        for search_string in self.system_log_file_identifiers:
            try:
                out, err = shell_command(
                    ['grep -m 1 "%s" "%s"' % (search_string, log_file)]
                )
            except Exception:
                continue
            if err or not out:
                continue
            else:
                return True
        return False


text:
namespace <%= appNamespace %>.Services {

    <% if(type === "Sample Data") { %>export class MovieService {
        private MovieResource;

        public listMovies() {
            return this.MovieResource.query();
        }

        constructor($resource: ng.resource.IResourceService) {
            this.MovieResource = $resource('/api/movies');
        }
    }
    angular.module('<%= appNamespace %>').service('movieService', MovieService);
    <% } %><% if(type === "Sample Data") { %>export class MyService {

    }
    angular.module('<%= appNamespace %>').service('myService', MyService);
    <% } %>}


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>gmp_float</title>
<link rel="stylesheet" href="../../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.77.1">
<link rel="home" href="../../../index.html" title="Chapter 1. Boost.Multiprecision">
<link rel="up" href="../floats.html" title="Floating Point Numbers">
<link rel="prev" href="cpp_dec_float.html" title="cpp_dec_float">
<link rel="next" href="mpfr_float.html" title="mpfr_float">

Home
Libraries
People
FAQ
More

gmp_float

          #include <boost/multiprecision/gmp.hpp>

namespace boost{ namespace multiprecision{

template <unsigned Digits10>
class gmp_float;

typedef number<gmp_float<50> >    mpf_float_50;
typedef number<gmp_float<100> >   mpf_float_100;
typedef number<gmp_float<500> >   mpf_float_500;
typedef number<gmp_float<1000> >  mpf_float_1000;
typedef number<gmp_float<0> >     mpf_float;

}} // namespaces

          The gmp_float back-end
          is used in conjunction with number
          : it acts as a thin wrapper around the GMP
          mpf_t to provide an real-number
          type that is a drop-in replacement for the native C++ floating-point types,
          but with much greater precision.

          Type gmp_float can be used
          at fixed precision by specifying a non-zero Digits10
          template parameter, or at variable precision by setting the template argument
          to zero. The typedefs mpf_float_50, mpf_float_100, mpf_float_500, mpf_float_1000
          provide arithmetic types at 50, 100, 500 and 1000 decimal digits precision
          respectively. The typedef mpf_float provides a variable precision type
          whose precision can be controlled via the numbers
          member functions.

Note

            This type only provides standard library and numeric_limits
            support when the precision is fixed at compile time.

          As well as the usual conversions from arithmetic and string types, instances
          of number<mpf_float<N> > are copy constructible and assignable
          from:

              The GMP native types mpf_t, mpz_t,
              mpq_t.

              The number wrappers
              around those types: number<mpf_float<M> >,
              number<gmp_int>,
              number<gmp_rational>.

          It's also possible to access the underlying mpf_t
          via the data()
          member function of gmp_float.

          Things you should know when using this type:

              Default constructed gmp_floats
              have the value zero (this is the GMP
              library's default behavior).

              No changes are made to the GMP
              library's global settings, so this type can be safely mixed with existing
              GMP code.

              This backend supports rvalue-references and is move-aware, making instantiations
              of number on this backend
              move aware.

              It is not possible to round-trip objects of this type to and from a
              string and get back exactly the same value. This appears to be a limitation
              of GMP.

              Since the underlying GMP types
              have no notion of infinities or NaN's, care should be taken to avoid
              numeric overflow or division by zero. That latter will result in a
              std::overflow_error being thrown, while generating excessively large
              exponents may result in instability of the underlying GMP
              library (in testing, converting a number with an excessively large
              or small exponent to a string caused GMP
              to segfault).

              This type can equally be used with MPIR
              as the underlying implementation - indeed that is the recommended option
              on Win32.

              Conversion from a string results in a std::runtime_error
              being thrown if the string can not be interpreted as a valid floating
              point number.

              Division by zero results in a std::overflow_error
              being thrown.

          GMP example:

#include <boost/multiprecision/gmp.hpp>

using namespace boost::multiprecision;

// Operations at variable precision and limited standard library support:
mpf_float a = 2;
mpf_float::default_precision(1000);
std::cout << mpf_float::default_precision() << std::endl;
std::cout << sqrt(a) << std::endl; // print root-2

// Operations at fixed precision and full standard library support:
mpf_float_100 b = 2;
std::cout << std::numeric_limits<mpf_float_100>::digits << std::endl;
// We can use any C++ std lib function:
std::cout << log(b) << std::endl; // print log(2)
// We can also use any function from Boost.Math:
std::cout << boost::math::tgamma(b) << std::endl;
// These even work when the argument is an expression template:
std::cout << boost::math::tgamma(b * b) << std::endl;

// Access the underlying representation:
mpf_t f;
mpf_init(f);
mpf_set(f, a.backend().data());

Copyright © 2002-2012 John Maddock and Christopher Kormanyos

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)


text:
package org.apache.wicket.core.request.handler.logger;

import org.apache.wicket.Page;
import org.apache.wicket.core.request.handler.IPageClassRequestHandler;
import org.apache.wicket.core.request.handler.IPageProvider;
import org.apache.wicket.core.request.handler.IPageRequestHandler;
import org.apache.wicket.request.ILogData;
import org.apache.wicket.request.component.IRequestablePage;
import org.apache.wicket.request.mapper.parameter.PageParameters;

/**
 * Contains logging data for request handlers that are related to pages; most likely
 * {@link IPageRequestHandler} or {@link IPageClassRequestHandler}.
 *
 * @author Emond Papegaaij
 */
public class PageLogData implements ILogData
{
	private static final long serialVersionUID = 1L;

	private final Class<? extends IRequestablePage> pageClass;
	private final Integer pageId;
	private final PageParameters pageParameters;
	private final Integer renderCount;

	/**
	 * Construct.
	 *
	 * @param pageProvider
	 */
	public PageLogData(IPageProvider pageProvider)
	{
		pageClass = tryToGetPageClass(pageProvider);
		pageId = pageProvider.getPageId();
		pageParameters = pageProvider.getPageParameters();
		renderCount = pageProvider.getRenderCount();
	}

	private static Class<? extends IRequestablePage> tryToGetPageClass(IPageProvider pageProvider)
	{
		try
		{
			return pageProvider.getPageClass();
		}
		catch (Exception e)
		{
			// getPageClass might fail if the page does not exist (ie session timeout)
			return null;
		}
	}

	/**
	 * Construct.
	 *
	 * @param page
	 */
	public PageLogData(Page page)
	{
		pageClass = page.getPageClass();
		pageId = page.getPageId();
		pageParameters = page.getPageParameters();
		renderCount = page.getRenderCount();
	}

	/**
	 * @return pageClass
	 */
	public final Class<? extends IRequestablePage> getPageClass()
	{
		return pageClass;
	}

	/**
	 * @return pageId
	 */
	public final Integer getPageId()
	{
		return pageId;
	}

	/**
	 * @return pageParameters
	 */
	public final PageParameters getPageParameters()
	{
		return pageParameters;
	}

	/**
	 * @return renderCount
	 */
	public final Integer getRenderCount()
	{
		return renderCount;
	}

	@Override
	public String toString()
	{
		StringBuilder sb = new StringBuilder("{");
		if (pageClass != null)
		{
			sb.append("pageClass=");
			sb.append(getPageClass().getName());
			sb.append(',');
		}
		sb.append("pageId=");
		sb.append(getPageId());
		sb.append(",pageParameters={");
		sb.append(getPageParameters());
		sb.append("},renderCount=");
		sb.append(getRenderCount());
		sb.append("}");
		return sb.toString();
	}
}


text:
package org.artifactory.rest.services.replication;

import java.util.List;

import org.artifactory.descriptor.config.CentralConfigDescriptor;
import org.artifactory.descriptor.config.MutableCentralConfigDescriptor;
import org.artifactory.descriptor.replication.LocalReplicationDescriptor;
import org.artifactory.descriptor.replication.RemoteReplicationDescriptor;
import org.artifactory.rest.common.exception.BadRequestException;
import org.artifactory.rest.common.util.RestUtils;
import org.artifactory.rest.http.request.ArtifactoryRestRequest;
import org.artifactory.rest.http.response.IResponse;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

/**
 * @author Chen Keinan
 */
@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class DeleteReplicationsService extends BaseReplicationService {
    @Override
    public void execute(ArtifactoryRestRequest artifactoryRequest, IResponse artifactoryResponse) {
        String repoKey = artifactoryRequest.getPathParamByKey("repoKey");
        String url = artifactoryRequest.getQueryParamByKey("url");
        verifyArtifactoryPro();
        verifyRepositoryExists(repoKey);
        MutableCentralConfigDescriptor descriptor = centralConfigService.getMutableDescriptor();
        switch (RestUtils.repoType(repoKey)) {
            case LOCAL:
                // delete local replications
                deleteLocalReplications(repoKey, url, descriptor);
                break;
            case REMOTE:
                // delete remote replications
                deleteRemoteReplication(repoKey, descriptor);
                break;
            default:
                throw new BadRequestException("Invalid repository");
        }
    }

    /**
     * delete local replications
     *
     * @param repoKey    - repo key
     * @param url        - url
     * @param descriptor - config descriptor
     */
    private void deleteLocalReplications(String repoKey, String url, MutableCentralConfigDescriptor descriptor) {
        if (url.length() == 0) {
            deleteAllReplication(repoKey, descriptor);
        } else {
            deleteSpecificReplication(repoKey, url, descriptor);
        }
        centralConfigService.saveEditedDescriptorAndReload(descriptor);
    }

    /**
     * iterate repo replication and delete replication with same kkey and url
     *
     * @param repoKey    - repo key
     * @param url        - url
     * @param descriptor - config descriptor
     */
    private void deleteSpecificReplication(String repoKey, String url, MutableCentralConfigDescriptor descriptor) {
        List<LocalReplicationDescriptor> localReplications = descriptor.getMultiLocalReplications(repoKey);
        if (localReplications == null || localReplications.isEmpty()) {
            throw new BadRequestException("Could not find existing replication for delete");
        }
        int replicationIndex = 0;
        for (LocalReplicationDescriptor localReplicationDescriptor : localReplications) {
            if (localReplicationDescriptor.getRepoKey().equals(repoKey) && localReplicationDescriptor.getUrl().equals(
                    url)) {
                break;
            }
            replicationIndex = replicationIndex + 1;
        }
        if (localReplications.size() == replicationIndex) {
            throw new BadRequestException("Invalid replication url");
        } else {
            localReplications.remove(replicationIndex);
            descriptor.setLocalReplications(localReplications);
        }
    }

    /**
     * replication and delete all replication for repo key
     *
     * @param repoKey    - repo key
     * @param descriptor - config descriptor
     */
    private void deleteAllReplication(String repoKey, CentralConfigDescriptor descriptor) {
        List<LocalReplicationDescriptor> localReplications = descriptor.getMultiLocalReplications(repoKey);
        if (localReplications == null || localReplications.isEmpty()) {
            throw new BadRequestException("Could not find existing replication for update");
        }
        descriptor.getLocalReplications().removeAll(localReplications);
    }

    /**
     * delete remote replications
     *
     * @param repoKey    - repo key
     * @param descriptor - config descriptor
     */
    private void deleteRemoteReplication(String repoKey, CentralConfigDescriptor descriptor) {
        RemoteReplicationDescriptor remoteReplication = descriptor.getRemoteReplication(repoKey);
        if (remoteReplication == null) {
            throw new BadRequestException("Could not find existing replication for update");
        }
        descriptor.getRemoteReplications().remove(remoteReplication);
        centralConfigService.saveEditedDescriptorAndReload(descriptor);
    }
}


text:
package swaggering

import (
	"encoding/json"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
)

type ServiceJSON struct {
	Apis []*ServiceApiJSON
}

type ServiceApiJSON struct {
	Path, Desc string
}

func ProcessService(dir string, ingester *Context) {
	ingester.ProcessServiceDir(dir)
}

func (ingester *Context) ProcessServiceDir(dir string) {
	fullpath := filepath.Join(dir, "service.json")

	apis := &ServiceJSON{}

	loadJSONfromPath(fullpath, apis)

	fileRE := regexp.MustCompile(`^/(\w+).{format}$`)

	for _, api := range apis.Apis {
		smi := fileRE.FindStringSubmatchIndex(api.Path)
		file := []byte("")
		file = fileRE.ExpandString(file, "$1.json", api.Path, smi)

		ingester.ingestApifromPath(filepath.Join(dir, string(file)))
	}
}

func loadJSONfromPath(fullpath string, into interface{}) {
	data, err := os.Open(fullpath)
	if err != nil {
		log.Print("Trouble with", fullpath, ":", err)
		return
	}

	loadJSON(fullpath, data, into)
}

func loadJSON(fullpath string, data io.Reader, into interface{}) {
	dec := json.NewDecoder(data)

	if err := dec.Decode(into); err == io.EOF {
		log.Fatal("Trouble with empty", fullpath, ":", err)
		return
	} else if err != nil {
		log.Print("Trouble parsing", fullpath, ":", err)
		return
	}
}

func (ctx *Context) ingestApifromPath(fullpath string) {
	log.Print("Processing:", fullpath)

	data, err := os.Open(fullpath)
	if err != nil {
		log.Print("Trouble with", fullpath, ":", err)
		return
	}
	ctx.IngestApi(fullpath, data)
}

func (ctx *Context) IngestApi(aspath string, data io.Reader) {
	ctx.swaggers = append(ctx.swaggers, &Swagger{})
	swagger := ctx.swaggers[len(ctx.swaggers)-1]

	loadJSON(aspath, data, swagger)
}


text:
package net.gmx.dercd.bukkit.cdapi.tools.minecraft;

import com.google.common.collect.ImmutableMap;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonPrimitive;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import org.bukkit.entity.Player;

import net.gmx.dercd.bukkit.cdapi.CDAPI;
import net.gmx.dercd.bukkit.cdapi.exceptions.CDPlayerNameNotFoundException;
import net.gmx.dercd.bukkit.cdapi.exceptions.CDPlayerResolveException;
import net.gmx.dercd.bukkit.cdapi.tools.Log;
import net.gmx.dercd.bukkit.cdapi.tools.Tools.Minecraft;

public class UUIDFetcher
{
	private Log clog = Log.getInstance();
	private static final double PROFILES_PER_REQUEST = 100;
	private static final String PROFILE_URL = "https://api.mojang.com/profiles/minecraft";
	private JsonParser jsonParser = new JsonParser();
	protected Map<String, UUID> fetched = new HashMap<String, UUID>();
	private NameFetcher nameFetcher;

	public UUIDFetcher()
	{
		init();
	}

	public void init()
	{
		for(Player p : Minecraft.getOnlinePlayers())
			this.fetched.put(p.getName(), p.getUniqueId());
	}

	public void setNameFetcher(NameFetcher f)
	{
		this.nameFetcher = f;
	}

	public Map<String, UUID> fetch(List<String> input) throws CDPlayerResolveException
	{
		return fetch(input, 0);
	}

	public Map<String, UUID> fetch(List<String> input, int attempt) throws CDPlayerResolveException
	{
		List<String> names = new ArrayList<String>(input);
		for (String s : input)
			if (this.fetched.containsKey(s) && this.fetched.get(s) != null) names.remove(s);
		int requests = (int) Math.ceil(names.size() / PROFILES_PER_REQUEST);
		for (int i = 0; i < requests; i++)
		{
			try
			{
				HttpURLConnection connection = createConnection();
				JsonArray ja = new JsonArray();
				for (String str : names.subList(i * 100, Math.min((i + 1) * 100, names.size())))
					ja.add(new JsonPrimitive(str));
				String body = ja.toString();
				writeBody(connection, body);
				JsonArray array = (JsonArray) this.jsonParser.parse(new InputStreamReader(connection.getInputStream()));
				JsonObject jsonProfile;
				Iterator<JsonElement> it = array.iterator();
				while (it.hasNext())
				{
					jsonProfile = (JsonObject) it.next();
					String id = jsonProfile.get("id").getAsString();
					String name = jsonProfile.get("name").getAsString();
					UUID uuid = UUIDFetcher.getUUID(id);
					this.fetched.put(name, uuid);
					this.nameFetcher.fetched.put(uuid, name);
				}
				attempt = 0;
			}
			catch (Exception x)
			{
				attempt++;
				this.clog.log("Error while fetching UUIDs; " + attempt + " attempt", this);
				if (attempt >= 5)
				{
					this.clog.log("Do not try to fetch UUIDs anymore", this);
					CDPlayerResolveException toThrow = new CDPlayerResolveException();
					toThrow.initCause(x);
					throw toThrow;
				}
				return fetch(input, attempt);
			}
		}
		return ImmutableMap.copyOf(this.fetched);
	}

	private static void writeBody(HttpURLConnection connection, String body) throws Exception
	{
		OutputStream stream = connection.getOutputStream();
		stream.write(body.getBytes());
		stream.flush();
		stream.close();
	}

	private static HttpURLConnection createConnection() throws IOException
	{
		URL url = new URL(PROFILE_URL);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/json");
		connection.setUseCaches(false);
		connection.setDoInput(true);
		connection.setDoOutput(true);
		connection.setReadTimeout(5000);
		connection.setConnectTimeout(5000);
		return connection;
	}

	private static UUID getUUID(String id)
	{
		return UUID.fromString(id.substring(0, 8) + "-" + id.substring(8, 12) + "-" + id.substring(12, 16) + "-" + id.substring(16, 20) + "-" + id.substring(20, 32));
	}

	public UUID fetch(String name) throws CDPlayerResolveException
	{
		try
		{
			UUID uuid = fetch(new ArrayList<String>(Arrays.asList(name))).get(name);
			if(uuid != null) return uuid;
			throw new CDPlayerNameNotFoundException(name);
		}
		catch (Exception x)
		{
			if (x instanceof CDPlayerResolveException) throw (CDPlayerResolveException) x;
			this.clog.printException(x);
			CDPlayerResolveException toThrow = new CDPlayerResolveException(name);
			toThrow.initCause(x);
			throw toThrow;
		}
	}

	public void put(String name, UUID u)
	{
		this.fetched.put(name, u);
		this.nameFetcher.fetched.put(u, name);
	}

	public static UUIDFetcher getInstance()
	{
		return CDAPI.getInstance().getHandler().getUUIDFetcher();
	}
}


text:
<?php

namespace tests\Dudulina\Testing\EventStore\InMemory\RawEventStreamTest;

use Dudulina\Event;
use Dudulina\Event\EventWithMetaData;
use Dudulina\Event\MetaData;
use Dudulina\Testing\EventStore\InMemory\InMemoryEventSequence;
use Dudulina\Testing\EventStore\InMemory\FilteredRawEventStreamGroupedByCommit;
use Dudulina\Testing\EventStore\InMemory\InMemoryEventsCommit;

class RawEventStreamTest extends \PHPUnit_Framework_TestCase
{

    public function test()
    {
        $eventCommits = [
            new InMemoryEventsCommit(
                100,
                1,
                [1, 2]
            ),
            new InMemoryEventsCommit(
                200,
                2,
                [3, 4])
            , new InMemoryEventsCommit(
                300,
                3,
                [5, 6]),
        ];

        $sut = new FilteredRawEventStreamGroupedByCommit($eventCommits);

        $this->assertEquals([1, 2, 3, 4, 5, 6], iterator_to_array($sut->getIterator()));

        $sut = new FilteredRawEventStreamGroupedByCommit($eventCommits);
        $sut->limitCommits(2);
        $this->assertEquals([1, 2, 3, 4], iterator_to_array($sut->getIterator()));
        $this->assertEquals(4, $sut->count());
    }

    public function testWithEventClasses()
    {
        $event1 = new MyEvent();
        $event1->prop = '1';
        $event2 = new MyEvent();
        $event2->prop = '2';

        $event3 = new MyEvent2();
        $event3->prop = '3';
        $event4 = new MyEvent2();
        $event4->prop = '4';

        $eventCommits = [
            new InMemoryEventsCommit(
                100,
                1,
                [
                    $this->wrapEventInMetadata($event1),
                    $this->wrapEventInMetadata($event2),
                ]
            ),
            new InMemoryEventsCommit(
                200,
                2,
                [
                    $this->wrapEventInMetadata($event3),
                    $this->wrapEventInMetadata($event4),
                ]
            ),
        ];

        $sut = new FilteredRawEventStreamGroupedByCommit($eventCommits, [MyEvent::class]);

        $commits = $sut->fetchCommits();

        $this->assertCount(1, $commits);
        $this->assertEquals(1, $sut->countCommits());

        $this->assertEquals(100, $commits[0]->getCommitSequence());

        //$sut->afterSequence()
    }

    public function testWithSeek()
    {
        $event1 = new MyEvent();
        $event1->prop = '1';
        $event2 = new MyEvent();
        $event2->prop = '2';
        $event3 = new MyEvent2();
        $event3->prop = '3';
        $event4 = new MyEvent2();
        $event4->prop = '4';

        $eventCommits = [
            new InMemoryEventsCommit(
                100,
                1,
                [
                    $this->wrapEventInMetadata($event1, new InMemoryEventSequence(100, 0)),
                    $this->wrapEventInMetadata($event2, new InMemoryEventSequence(100, 1))
                ]
            ),
            new InMemoryEventsCommit(
                200,
                2,
                [
                    $this->wrapEventInMetadata($event3, new InMemoryEventSequence(200, 0)),
                    $this->wrapEventInMetadata($event4, new InMemoryEventSequence(200, 1))
                ]
            ),
        ];

        $sut = new FilteredRawEventStreamGroupedByCommit($eventCommits, []);
        $sut->afterSequence(new InMemoryEventSequence(200, 0));//after the first event from the second commit
        $this->assertEquals(1, $sut->count());
        /** @var EventWithMetaData[] $events */
        $events = iterator_to_array($sut, false);
        $this->assertCount(1, $events);
        $this->assertSame($event4, $events[0]->getEvent());

        $sut = new FilteredRawEventStreamGroupedByCommit($eventCommits, []);
        $sut->beforeSequence(new InMemoryEventSequence(100, 1));//after the first event from the second commit
        $this->assertEquals(1, $sut->count());
        /** @var EventWithMetaData[] $events */
        $events = iterator_to_array($sut, false);
        $this->assertCount(1, $events);
        $this->assertSame($event1, $events[0]->getEvent());
    }

    private function wrapEventInMetadata($event, InMemoryEventSequence $eventSequence = null): EventWithMetaData
    {
        /** @var MetaData $metaData */
        $metaData = new MetaData(
            'someId',
            'someClass',
            new \DateTimeImmutable(),
            null,
            null
        );
        if ($eventSequence) {
            $metaData = $metaData->withSequence($eventSequence);
        }
        return new EventWithMetaData(
            $event,
            $metaData
        );
    }
}

class MyEvent implements Event
{

}

class MyEvent2 implements Event
{

}


text:
package gov.nij.camel.xpath;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import org.w3c.dom.NodeList;

import org.apache.camel.component.bean.XPathAnnotationExpressionFactory;
import org.apache.camel.language.LanguageAnnotation;
import org.apache.camel.language.NamespacePrefix;

/**
 * This class allows Camel to use parameter binding with namespace support
 * in message processors.  See this link for more information:
 *
 * http://camel.apache.org/parameter-binding-annotations.html
 *
 *
 */

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
@LanguageAnnotation(language = "xpath", factory = XPathAnnotationExpressionFactory.class)
public @interface CamelXpathAnnotations {
    String value();

    // You can add the namespaces as the default value of the annotation
    NamespacePrefix[] namespaces() default {
    @NamespacePrefix(prefix = "merge", uri = "http://nij.gov/IEPD/Exchange/EntityMergeRequestMessage/1.0"),
    @NamespacePrefix(prefix = "er-ext", uri = "http://nij.gov/IEPD/Extensions/EntityResolutionExtensions/1.0")
    };

    Class<?> resultType() default NodeList.class;
}


text:
package org.hisp.dhis.dxf2.dataset;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import com.google.common.base.MoreObjects;
import org.apache.commons.lang3.StringUtils;
import org.hisp.dhis.common.DxfNamespaces;

/**
 * @author Halvdan Hoem Grelland
 */
@JacksonXmlRootElement( localName = "completeDataSetRegistration", namespace = DxfNamespaces.DXF_2_0 )
public class CompleteDataSetRegistration
{
    //--------------------------------------------------------------------------
    // Field names
    //--------------------------------------------------------------------------

    protected static final String FIELD_COMPLETE_DATA_SET_REGISTRATION = "completeDataSetRegistration";

    protected static final String FIELD_DATASET = "dataSet";

    protected static final String FIELD_PERIOD = "period";

    protected static final String FIELD_ORGUNIT = "organisationUnit";

    protected static final String FIELD_ATTR_OPTION_COMBO = "attributeOptionCombo";

    protected static final String FIELD_DATE = "date";

    protected static final String FIELD_STORED_BY = "storedBy";

    //--------------------------------------------------------------------------
    // Properties
    //--------------------------------------------------------------------------

    protected String dataSet;

    protected String period;

    protected String organisationUnit; // 'source'

    protected String attributeOptionCombo;

    protected String date;

    protected String storedBy;

    protected String cc;

    protected String cp;

    //--------------------------------------------------------------------------
    // Constructors
    //--------------------------------------------------------------------------

    public CompleteDataSetRegistration()
    {
    }

    //--------------------------------------------------------------------------
    // Logic
    //--------------------------------------------------------------------------

    public boolean hasDate()
    {
        return StringUtils.isNotBlank( getDate() );
    }

    @Override
    public String toString()
    {
        return MoreObjects.toStringHelper( this )
            .add( FIELD_DATASET, dataSet )
            .add( FIELD_PERIOD, period )
            .add( FIELD_ORGUNIT, organisationUnit )
            .add( FIELD_ATTR_OPTION_COMBO, attributeOptionCombo )
            .add( FIELD_DATE, date )
            .add( FIELD_STORED_BY, storedBy )
            .toString();
    }

    //--------------------------------------------------------------------------
    // Streaming logic stubs
    //--------------------------------------------------------------------------

    protected void open()
    {
    }

    protected void close()
    {
    }

    protected void writeField( String fieldName, String value )
    {
    }

    //--------------------------------------------------------------------------
    // Getters and setters
    //--------------------------------------------------------------------------

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getDataSet()
    {
        return dataSet;
    }

    public void setDataSet( String dataSet )
    {
        this.dataSet = dataSet;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getPeriod()
    {
        return period;
    }

    public void setPeriod( String period )
    {
        this.period = period;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getOrganisationUnit()
    {
        return organisationUnit;
    }

    public void setOrganisationUnit( String organisationUnit )
    {
        this.organisationUnit = organisationUnit;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getAttributeOptionCombo()
    {
        return attributeOptionCombo;
    }

    public void setAttributeOptionCombo( String attributeOptionCombo )
    {
        this.attributeOptionCombo = attributeOptionCombo;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getDate()
    {
        return date;
    }

    public void setDate( String date )
    {
        this.date = date;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getStoredBy()
    {
        return storedBy;
    }

    public void setStoredBy( String storedBy )
    {
        this.storedBy = storedBy;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getCc()
    {
        return cc;
    }

    public void setCc( String cc )
    {
        this.cc = cc;
    }

    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    public String getCp()
    {
        return cp;
    }

    public void setCp( String cp )
    {
        this.cp = cp;
    }

}


text:
@interface FMEleNagationController : UINavigationController

@end


text:
from cloudify import ctx

def check_if_configuration_changed(ctx, update_payload, current_vm):
    for prop in ['location', 'tags', 'plan', 'availability_set',
                 'eviction_policy', 'billing_profile', 'priority',
                 'hardware_profile']:
        update_property_value = update_payload.get(prop)
        current_vm_property_value = current_vm.get(prop)
        if update_property_value and ordered(
                update_property_value) != ordered(current_vm_property_value):
            ctx.logger.info("{prop} changed.".format(prop=prop))
            ctx.logger.info("update payload: {content}.".format(
                content=update_property_value))
            ctx.logger.info("current configuration: {content}.".format(
                content=current_vm_property_value))
            return True

    for prop in ['os_profile', 'storage_profile', 'network_profile']:
        if prop == 'network_profile' and update_payload.get(prop):
            update_property_value = update_payload.get(prop).as_dict()
        else:
            update_property_value = update_payload.get(prop, {})

        current_vm_property_value = current_vm.get(prop, {})
        if diff_dictionaries(update_property_value, current_vm_property_value):
            ctx.logger.info("{prop} changed.".format(prop=prop))
            return True

    return False

def diff_dictionaries(update_dict, current_conf_dict):
    """
    Returns True if update_dict has changes in a key that doesn't appear in
    current_conf_dict.
    current_conf_dict can have additional keys and its not considered as a
    diff.
    """
    for key in update_dict:
        if isinstance(update_dict.get(key), dict):
            res = diff_dictionaries(update_dict.get(key),
                                    current_conf_dict.get(key, {}))
            if res:
                return True
        elif ordered(update_dict.get(key)) != ordered(
                current_conf_dict.get(key)):
            ctx.logger.info(
                'Changes found in diff_dictionaries: key={key}\n'.format(
                    key=key))
            ctx.logger.info(
                'update_dict: {}'.format(ordered(update_dict.get(key))))
            ctx.logger.info(
                'current_conf_dict: {}'.format(ordered(
                    current_conf_dict.get(key))))
            return True
    return False

def ordered(obj):
    """
    This function will recursively sort any lists it finds
    (and convert dictionaries to lists of (key, value) pairs so that they're
    orderable)
    """
    if isinstance(obj, dict):
        return sorted((k, ordered(v)) for k, v in obj.items())
    if isinstance(obj, list):
        return sorted(ordered(x) for x in obj)
    if isinstance(obj, str):
        return obj.lower()
    if isinstance(obj, (int, float)):
        return str(obj)
    else:
        return obj


text:
package cocos2d.actions.action_intervals;

import cocos2d.actions.action.CCFiniteTimeAction;
import cocos2d.base_nodes.CCNode;
import cocos2d.cocoa.ICCCopyable;

public class CCBlink extends CCActionInterval
{
	//Êý¾ÝÀàÐÍÓдýÈ·¶¨
	//protected uint m_nTimes;
    protected int m_nTimes;
    protected boolean m_bOriginalState;

    public CCBlink(float duration, int uBlinks)
    {
        initWithDuration(duration, uBlinks);
    }

    protected CCBlink(CCBlink blink)
    {
    	super(blink);
        initWithDuration(m_fDuration, m_nTimes);
    }

    protected boolean initWithDuration(float duration, int uBlinks)
    {
        if (super.initWithDuration(duration))
        {
            m_nTimes = uBlinks;
            return true;
        }

        return false;
    }

    @Override
    public Object copy(ICCCopyable pZone)
    {
        if (pZone != null)
        {
            //in case of being called at sub class
        	CCBlink pCopy = (CCBlink) (pZone);
            super.copy(pZone);

            pCopy.initWithDuration(m_fDuration, m_nTimes);
            return pCopy;
        }
        else
        {
            return new CCBlink(this);
        }
    }

    @Override
    public void stop()
    {
        m_pTarget.setVisible(m_bOriginalState);
        super.stop();
    }

    @Override
    public void startWithTarget(CCNode target)
    {
        super.startWithTarget(target);
        m_bOriginalState = target.getVisible();
    }

    @Override
    public void update(float time)
    {
        if (m_pTarget != null && ! isDone())
        {
            float slice = 1.0f / m_nTimes;
            // float m = fmodf(time, slice);
            float m = time % slice;
            m_pTarget.setVisible(m > (slice / 2));
        }
    }

    @Override
    public CCFiniteTimeAction reverse()
    {
        return new CCBlink(m_fDuration, m_nTimes);
    }
}


text:
using PetCenter.Referencias.Dominio.Logica.Base;
using PetCenter.Referencias.Dominio.Logica.VOBs.Maestros.Mascota;
using PetCenter.Referencias.Transversal.Enumeraciones;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace PetCenter.Referencias.Dominio.Logica.Criterios.Maestros.Mascota
{
    public class MascotaBuscadorCriterio : Criterio<MascotaVob>
    {
        #region VARIABLES

        /// <summary>
        /// _area
        /// </summary>
        private readonly MascotaVob _mascota;

        #endregion

        #region CONSTRUCTORES

        /// <summary>
        /// Constructor por defecto
        /// </summary>
        /// <param name="solicitud">AreaVob</param>
        public MascotaBuscadorCriterio(MascotaVob mascota)
        {
            _mascota = mascota;
        }

        #endregion

        #region MÉTODOS REEMPLAZADOS

        /// <summary>
        /// SatisfacePara
        /// </summary>
        /// <returns>TupaVob</returns>
        public override Expression<Func<MascotaVob, bool>> SatisfacePara()
        {
            string todos = ((int)PrimerValorEnum.Seleccione).ToString();
            Criterio<MascotaVob> criterio = new CriterioTrue<MascotaVob>();

            #region Filtro

            //Nro de Ruc
            if (!string.IsNullOrEmpty(_mascota.NombreMascota))
                criterio &= new CriterioDirect<MascotaVob>(p => p.NombreMascota.Contains(_mascota.NombreMascota));

            //idcliente
            criterio &= new CriterioDirect<MascotaVob>(p => p.IdCliente == _mascota.IdCliente);

            #endregion

            return criterio.SatisfacePara();
        }

        #endregion
    }
}


text:
KAFKA_CONNECTOR_VERSION="$1"
KAFKA_VERSION="$2"
CONFLUENT_VERSION="$3"
CONFLUENT_MAJOR_VERSION="$4"
KAFKA_SQL_VERSION="$5"

source "$(dirname "$0")"/kafka-common.sh $2 $3 $4

function create_kafka_json_source {
    topicName="$1"
    create_kafka_topic 1 1 $topicName

    # put JSON data into Kafka
    echo "Sending messages to Kafka..."

    send_messages_to_kafka '{"timestamp": "2018-03-12 08:00:00", "user": "Alice", "event": { "type": "WARNING", "message": "This is a warning."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 08:10:00", "user": "Alice", "event": { "type": "WARNING", "message": "This is a warning."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 09:00:00", "user": "Bob", "event": { "type": "WARNING", "message": "This is another warning."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 09:10:00", "user": "Alice", "event": { "type": "INFO", "message": "This is a info."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 09:20:00", "user": "Steve", "event": { "type": "INFO", "message": "This is another info."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 09:30:00", "user": "Steve", "event": { "type": "INFO", "message": "This is another info."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 09:30:00", "user": null, "event": { "type": "WARNING", "message": "This is a bad message because the user is missing."}}' $topicName
    send_messages_to_kafka '{"timestamp": "2018-03-12 10:40:00", "user": "Bob", "event": { "type": "ERROR", "message": "This is an error."}}' $topicName
}

function get_kafka_json_source_schema {
    topicName="$1"
    tableName="$2"
    cat << EOF
  - name: $tableName
    type: source-table
    update-mode: append
    schema:
      - name: rowtime
        type: TIMESTAMP
        rowtime:
          timestamps:
            type: from-field
            from: timestamp
          watermarks:
            type: periodic-bounded
            delay: 2000
      - name: user
        type: VARCHAR
      - name: event
        type: ROW<type VARCHAR, message VARCHAR>
    connector:
      type: kafka
      version: "$KAFKA_SQL_VERSION"
      topic: $topicName
      startup-mode: earliest-offset
      properties:
        - key: zookeeper.connect
          value: localhost:2181
        - key: bootstrap.servers
          value: localhost:9092
    format:
      type: json
      json-schema: >
        {
          "type": "object",
          "properties": {
            "timestamp": {
              "type": "string"
            },
            "user": {
              "type": ["string", "null"]
            },
            "event": {
              "type": "object",
              "properties": {
                "type": {
                  "type": "string"
                },
                "message": {
                  "type": "string"
                }
              }
            }
          }
        }
EOF
}


text:
package com.google.javascript.jscomp;

import static com.google.javascript.jscomp.CheckRequiresForConstructors.MISSING_REQUIRE_WARNING;

import com.google.common.collect.ImmutableList;
<<<<<<< HEAD
import com.google.javascript.jscomp.CheckLevel;
import com.google.javascript.jscomp.Result;
=======
>>>>>>> 5c522db6e745151faa1d8dc310d145e94f78ac77

/**
 * Tests for {@link CheckRequiresForConstructors}.
 *
 */
public class CheckRequiresForConstructorsTest extends CompilerTestCase {
  @Override
  protected CompilerPass getProcessor(Compiler compiler) {
    return new CheckRequiresForConstructors(compiler, CheckLevel.WARNING);
  }

  public void testPassWithNoNewNodes() {
    String js = "var str = 'g4'; /* does not use new */";
    testSame(js);
  }

  public void testPassWithOneNew() {
    String js =
        "var goog = {};" +
        "goog.require('foo.bar.goo'); var bar = new foo.bar.goo();";
    testSame(js);
  }

  public void testPassWithOneNewOuterClass() {
    String js =
        "var goog = {};" +
        "goog.require('goog.foo.Bar'); var bar = new goog.foo.Bar.Baz();";
    testSame(js);
  }

  public void testPassWithOneNewOuterClassWithUpperPrefix() {
    String js =
        "var goog = {};" +
        "goog.require('goog.foo.IDBar'); var bar = new goog.foo.IDBar.Baz();";
    testSame(js);
  }

  public void testFailWithOneNew() {
    String[] js = new String[] {"var foo = {}; var bar = new foo.bar();"};
    String warning = "'foo.bar' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testPassWithTwoNewNodes() {
    String js =
        "var goog = {};" +
        "goog.require('goog.foo.Bar');goog.require('goog.foo.Baz');" +
        "var str = new goog.foo.Bar('g4'), num = new goog.foo.Baz(5); ";
    testSame(js);
  }

  public void testPassWithNestedNewNodes() {
    String js =
        "var goog = {}; goog.require('goog.foo.Bar'); " +
        "var str = new goog.foo.Bar(new goog.foo.Bar('5')); ";
    testSame(js);
  }

  public void testFailWithNestedNewNodes() {
    String[] js =
        new String[] {"var goog = {}; goog.require('goog.foo.Bar'); "
            + "var str = new goog.foo.Bar(new goog.foo.Baz('5')); "};
    String warning = "'goog.foo.Baz' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testPassWithLocalFunctions() {
    String js =
        "/** @constructor */ function tempCtor() {}; var foo = new tempCtor();";
    testSame(js);
  }

  public void testPassWithLocalVariables() {
    String js =
        "/** @constructor */ var nodeCreator = function() {};"
            + "var newNode = new nodeCreator();";
    testSame(js);
  }

  public void testFailWithLocalVariableInMoreThanOneFile() {
    // there should be a warning for the 2nd script because it is only declared
    // in the 1st script
    String localVar =
        "/** @constructor */ function tempCtor() {}" +
        "function baz(){" + " /** @constructor */ function tempCtor() {}; "
            + "var foo = new tempCtor();}";
    String[] js = new String[] {localVar, " var foo = new tempCtor();"};
    String warning = "'tempCtor' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testNewNodesMetaTraditionalFunctionForm() {
    // the class in this script creates an instance of itself
    // there should be no warning because the class should not have to
    // goog.require itself .
    String js =
        "/** @constructor */ function Bar(){}; "
            + "Bar.prototype.bar = function(){ return new Bar();};";
    testSame(js);
  }

  public void testNewNodesMeta() {
    String js =
        "var goog = {};" +
        "/** @constructor */goog.ui.Option = function(){};"
            + "goog.ui.Option.optionDecorator = function(){"
            + "  return new goog.ui.Option(); };";
    testSame(js);
  }

  public void testShouldWarnWhenInstantiatingObjectsDefinedInGlobalScope() {
    // there should be a warning for the 2nd script because
    // Bar was declared in the 1st file, not the 2nd
    String good =
        "/** @constructor */ function Bar(){}; "
            + "Bar.prototype.bar = function(){return new Bar();};";
    String bad = "/** @constructor */ function Foo(){ var bar = new Bar();}";
    String[] js = new String[] {good, bad};
    String warning = "'Bar' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testShouldWarnWhenInstantiatingGlobalClassesFromGlobalScope() {
    // there should be a warning for the 2nd script because Baz
    // was declared in the first file, not the 2nd
    String good =
      "/** @constructor */ function Baz(){}; "
          + "Baz.prototype.bar = function(){return new Baz();};";
    String bad = "var baz = new Baz()";
    String[] js = new String[] {good, bad};
    String warning = "'Baz' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testIgnoresNativeObject() {
    String externs = "/** @constructor */ function String(val) {}";
    String js = "var str = new String('4');";
    test(externs, js, js, null, null);
  }

  public void testNewNodesWithMoreThanOneFile() {
    // Bar is created, and goog.require()ed, but in different files.
    String[] js = new String[] {
        "var goog = {};" +
        "/** @constructor */ function Bar() {}" +
        "goog.require('Bar');",
        "var bar = new Bar();"};
    String warning = "'Bar' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testPassWithoutWarningsAndMultipleFiles() {
    String[] js = new String[] {
        "var goog = {};" +
        "goog.require('Foo'); var foo = new Foo();",
        "goog.require('Bar'); var bar = new Bar();"};
    testSame(js);
  }

  public void testFailWithWarningsAndMultipleFiles() {
    /* goog.require is in the code base, but not in the correct file */
    String[] js = new String[] {
        "var goog = {};" +
        "/** @constructor */ function Bar() {}" +
        "goog.require('Bar');",
        "var bar = new Bar();"};
    String warning = "'Bar' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }

  public void testCanStillCallNumberWithoutNewOperator() {
    String externs = "/** @constructor */ function Number(opt_value) {}";
    String js = "var n = Number('42');";
    test(externs, js, js, null, null);
    js = "var n = Number();";
    test(externs, js, js, null, null);
  }

  public void testRequiresAreCaughtBeforeProcessed() {
    String js = "var foo = {}; var bar = new foo.bar.goo();";
    SourceFile input = SourceFile.fromCode("foo.js", js);
    Compiler compiler = new Compiler();
    CompilerOptions opts = new CompilerOptions();
    opts.checkRequires = CheckLevel.WARNING;
    opts.closurePass = true;

    Result result = compiler.compile(ImmutableList.<SourceFile>of(),
        ImmutableList.of(input), opts);
    JSError[] warnings = result.warnings;
    assertNotNull(warnings);
    assertTrue(warnings.length > 0);

    String expectation = "'foo.bar.goo' used but not goog.require'd";

    for (JSError warning : warnings) {
      if (expectation.equals(warning.description)) {
        return;
      }
    }

    fail("Could not find the following warning:" + expectation);
  }

  public void testNoWarningsForThisConstructor() {
    String js =
      "var goog = {};" +
      "/** @constructor */goog.Foo = function() {};" +
      "goog.Foo.bar = function() {" +
      "  return new this.constructor; " +
      "};";
    testSame(js);
  }

  public void testBug2062487() {
    testSame(
      "var goog = {};" +
      "/** @constructor */goog.Foo = function() {" +
      "  /** @constructor */ this.x_ = function() {};" +
      "  this.y_ = new this.x_();" +
      "};");
  }

  public void testIgnoreDuplicateWarningsForSingleClasses(){
    // no use telling them the same thing twice
    String[] js = new String[]{
      "var goog = {};" +
      "/** @constructor */goog.Foo = function() {};" +
      "goog.Foo.bar = function(){" +
      "  var first = new goog.Forgot();" +
      "  var second = new goog.Forgot();" +
      "};"};
    String warning = "'goog.Forgot' used but not goog.require'd";
    test(js, js, null, MISSING_REQUIRE_WARNING, warning);
  }
<<<<<<< HEAD
=======

  public void testVarConstructorName() {
    String js = "/** @type {function(new:Date)} */var bar = Date;" +
        "new bar();";
    testSame(js);
  }

  public void testVarConstructorFunction() {
    String js = "/** @type {function(new:Date)} */var bar = function() {};" +
        "new bar();";
    testSame(js);
  }

  public void testAssignConstructorName() {
    String js = "var foo = {};" +
        "/** @type {function(new:Date)} */foo.bar = Date;" +
        "new foo.bar();";
    testSame(js);
  }

  public void testAssignConstructorFunction() {
    String js = "var foo = {};" +
        "/** @type {function(new:Date)} */foo.bar = function() {};" +
        "new foo.bar();";
    testSame(js);
  }

  public void testConstructorFunctionReference() {
    String js = "/** @type {function(new:Date)} */function bar() {}" +
        "new bar();";
    testSame(js);
  }
>>>>>>> 5c522db6e745151faa1d8dc310d145e94f78ac77
}


text:
namespace espv2 {
namespace envoy {
namespace http_filters {
namespace service_control {

using Envoy::Http::CustomHeaders;
using Envoy::Http::CustomInlineHeaderRegistry;
using Envoy::Http::RegisterCustomInlineHeader;
using ::Envoy::StreamInfo::FilterState;
using ::espv2::api_proxy::service_control::CheckResponseInfo;
using ::espv2::api_proxy::service_control::OperationInfo;
using ::espv2::api_proxy::service_control::QuotaResponseInfo;
using ::espv2::api_proxy::service_control::ScResponseError;
using ::espv2::api_proxy::service_control::ScResponseErrorType;
using ::google::protobuf::util::OkStatus;
using ::google::protobuf::util::Status;
using ::google::protobuf::util::StatusCode;

namespace {
RegisterCustomInlineHeader<CustomInlineHeaderRegistry::Type::RequestHeaders>
    referer_handle(CustomHeaders::get().Referer);

// The HTTP header suffix to send consumer info to backend.
constexpr char kConsumerTypeHeaderSuffix[] = "api-consumer-type";
constexpr char kConsumerNumberHeaderSuffix[] = "api-consumer-number";

// CheckRequest headers
const Envoy::Http::LowerCaseString kIosBundleIdHeader{
    "x-ios-bundle-identifier"};
const Envoy::Http::LowerCaseString kAndroidPackageHeader{"x-android-package"};
const Envoy::Http::LowerCaseString kAndroidCertHeader{"x-android-cert"};

constexpr char JwtPayloadIssuerPath[] = "iss";
constexpr char JwtPayloadAudiencePath[] = "aud";
}  // namespace

ServiceControlHandlerImpl::ServiceControlHandlerImpl(
    const Envoy::Http::RequestHeaderMap& headers,
    Envoy::Http::StreamDecoderFilterCallbacks* decoder_callbacks,
    const std::string& uuid, const FilterConfigParser& cfg_parser,
    Envoy::TimeSource& time_source, ServiceControlFilterStats& filter_stats)
    : cfg_parser_(cfg_parser),
      stream_info_(decoder_callbacks->streamInfo()),
      decoder_callbacks_(decoder_callbacks),
      time_source_(time_source),
      uuid_(uuid),
      request_header_size_(headers.byteSize()),
      consumer_type_header_(cfg_parser_.config().generated_header_prefix() +
                            kConsumerTypeHeaderSuffix),
      consumer_number_header_(cfg_parser_.config().generated_header_prefix() +
                              kConsumerNumberHeaderSuffix),
      is_grpc_(false),
      filter_stats_(filter_stats) {
  is_grpc_ = Envoy::Grpc::Common::hasGrpcContentType(headers);

  http_method_ = std::string(utils::readHeaderEntry(headers.Method()));
  path_ = std::string(utils::readHeaderEntry(headers.Path()));

  const auto operation = getOperationFromPerRoute();
  if (!operation.empty()) {
    require_ctx_ = cfg_parser_.find_requirement(operation);
    if (!require_ctx_) {
      ENVOY_LOG(debug, "No requirement matched!");
    }
  } else {
    ENVOY_LOG(debug, "No operation found");
  }
  if (require_ctx_ == nullptr) {
    ENVOY_LOG(debug, "Use non matched requirement.");
    require_ctx_ = cfg_parser_.non_match_rqm_ctx();
  }

  if (require_ctx_->config().api_key().locations_size() > 0) {
    extractAPIKey(headers, require_ctx_->config().api_key().locations(),
                  api_key_);
  } else {
    extractAPIKey(headers, cfg_parser_.default_api_keys().locations(),
                  api_key_);
  }
}

ServiceControlHandlerImpl::~ServiceControlHandlerImpl() {}

absl::string_view ServiceControlHandlerImpl::getOperationFromPerRoute() {
  const auto* per_route =
      ::Envoy::Http::Utility::resolveMostSpecificPerFilterConfig<
          PerRouteFilterConfig>(decoder_callbacks_);
  if (per_route == nullptr) {
    ENVOY_LOG(debug, "no per-route config");
    return Envoy::EMPTY_STRING;
  }
  ENVOY_LOG(debug, "get operation_name: {}", per_route->operation_name());
  return per_route->operation_name();
}

void ServiceControlHandlerImpl::fillFilterState(FilterState& filter_state) {
  utils::setStringFilterState(filter_state, utils::kFilterStateApiKey,
                              api_key_);

  utils::setStringFilterState(filter_state, utils::kFilterStateApiMethod,
                              require_ctx_->config().operation_name());
}

void ServiceControlHandlerImpl::onDestroy() {
  if (cancel_fn_) {
    cancel_fn_();
    cancel_fn_ = nullptr;
  }
}

void ServiceControlHandlerImpl::fillOperationInfo(
    ::espv2::api_proxy::service_control::OperationInfo& info) {
  info.operation_id = uuid_;
  info.operation_name = require_ctx_->config().operation_name();
  info.producer_project_id =
      require_ctx_->service_ctx().config().producer_project_id();
  info.current_time = time_source_.systemTime();

  if (stream_info_.downstreamAddressProvider().remoteAddress()->type() ==
      Envoy::Network::Address::Type::Ip) {
    info.client_ip = stream_info_.downstreamAddressProvider()
                         .remoteAddress()
                         ->ip()
                         ->addressAsString();
  }

  info.api_key = api_key_;
}

void ServiceControlHandlerImpl::prepareReportRequest(
    ::espv2::api_proxy::service_control::ReportRequestInfo& info) {
  fillOperationInfo(info);

  info.url = path_;
  info.method = http_method_;
  info.api_method = require_ctx_->config().operation_name();
  info.api_name = require_ctx_->config().api_name();
  info.api_version = require_ctx_->config().api_version();
  info.log_message = info.api_method + " is called";

  info.check_response_info = check_response_info_;
  info.status = check_status_;

  fillGCPInfo(cfg_parser_.config(), info);
}

void ServiceControlHandlerImpl::callCheck(
    Envoy::Http::RequestHeaderMap& headers, Envoy::Tracing::Span& parent_span,
    CheckDoneCallback& callback) {
  // Don't have per-route config so pass through the request, regarded as the
  // unknown method.
  if (!isConfigured()) {
    callback.onCheckDone(OkStatus(), "");
    return;
  }
  check_callback_ = &callback;

  if (!isCheckRequired()) {
    callQuota();
    return;
  }

  if (!hasApiKey()) {
    filter_stats_.filter_.denied_consumer_error_.inc();
    check_status_ =
        Status(StatusCode::kUnauthenticated,
               "Method doesn't allow unregistered callers (callers without "
               "established identity). Please use API Key or other form of "
               "API consumer identity to call this API.");
    callback.onCheckDone(
        check_status_,
        utils::generateRcDetails(utils::kRcDetailFilterServiceControl,
                                 utils::kRcDetailErrorTypeBadRequest,
                                 utils::kRcDetailErrorMissingApiKey));
    return;
  }

  // Make a check call
  ::espv2::api_proxy::service_control::CheckRequestInfo info;
  fillOperationInfo(info);

  info.referer = std::string(
      utils::readHeaderEntry(headers.getInline(referer_handle.handle())));
  info.ios_bundle_id =
      std::string(utils::extractHeader(headers, kIosBundleIdHeader));
  info.android_package_name =
      std::string(utils::extractHeader(headers, kAndroidPackageHeader));
  info.android_cert_fingerprint =
      std::string(utils::extractHeader(headers, kAndroidCertHeader));

  on_check_done_called_ = false;
  cancel_fn_ = require_ctx_->service_ctx().call().callCheck(
      info, parent_span,
      [this, &headers](const Status& status,
                       const CheckResponseInfo& response_info) {
        cancel_fn_ = nullptr;
        on_check_done_called_ = true;
        onCheckResponse(headers, status, response_info);
      });
  if (on_check_done_called_) {
    cancel_fn_ = nullptr;
  }
}

// TODO(taoxuy): add unit test
void ServiceControlHandlerImpl::callQuota() {
  if (!isQuotaRequired()) {
    check_callback_->onCheckDone(check_status_, rc_detail_);
    return;
  }

  ::espv2::api_proxy::service_control::QuotaRequestInfo info{
      require_ctx_->metric_costs()};
  info.method_name = require_ctx_->config().operation_name();
  fillOperationInfo(info);

  // TODO: if quota cache is disabled, need to use in-flight
  // transport, need to save its cancel function.
  // For now, quota cache is always enabled, in-flight transport
  // is not called.
  require_ctx_->service_ctx().call().callQuota(
      info,
      [this](const Status& status, const QuotaResponseInfo& response_info) {
        if (!response_info.error.name.empty()) {
          rc_detail_ = utils::generateRcDetails(
              utils::kRcDetailFilterServiceControl,
              response_info.error.is_network_error
                  ? utils::kRcDetailErrorTypeScQuotaNetwork
                  : utils::kRcDetailErrorTypeScQuota,
              response_info.error.name);
        }
        check_status_ = status;
        check_callback_->onCheckDone(status, rc_detail_);
      });
}

void ServiceControlHandlerImpl::onCheckResponse(
    Envoy::Http::RequestHeaderMap& headers, const Status& status,
    const CheckResponseInfo& response_info) {
  check_response_info_ = response_info;

  if (!response_info.error.name.empty()) {
    rc_detail_ =
        utils::generateRcDetails(utils::kRcDetailFilterServiceControl,
                                 response_info.error.is_network_error
                                     ? utils::kRcDetailErrorTypeScCheckNetwork
                                     : utils::kRcDetailErrorTypeScCheck,
                                 response_info.error.name);
  }
  check_status_ = status;

  // Set consumer info to backend. Since consumer_project_id is deprecated and
  // replaced by consumer_number so don't set it here.
  if (!response_info.consumer_type.empty()) {
    headers.setReferenceKey(consumer_type_header_, response_info.consumer_type);
  }

  if (!response_info.consumer_number.empty()) {
    headers.setReferenceKey(consumer_number_header_,
                            response_info.consumer_number);
  }

  if (!check_status_.ok()) {
    check_callback_->onCheckDone(check_status_, rc_detail_);
    return;
  }

  callQuota();
}

void ServiceControlHandlerImpl::callReport(
    const Envoy::Http::RequestHeaderMap* request_headers,
    const Envoy::Http::ResponseHeaderMap* response_headers,
    const Envoy::Http::ResponseTrailerMap* response_trailers,
    const Envoy::Tracing::Span& parent_span) {
  if (!isReportRequired()) {
    return;
  }

  ::espv2::api_proxy::service_control::ReportRequestInfo info;
  prepareReportRequest(info);
  fillLoggedHeader(request_headers,
                   require_ctx_->service_ctx().config().log_request_headers(),
                   info.request_headers);
  fillLoggedHeader(response_headers,
                   require_ctx_->service_ctx().config().log_response_headers(),
                   info.response_headers);
  fillJwtPayloads(
      stream_info_.dynamicMetadata(),
      require_ctx_->service_ctx().config().jwt_payload_metadata_name(),
      require_ctx_->service_ctx().config().log_jwt_payloads(),
      info.jwt_payloads);

  fillJwtPayload(
      stream_info_.dynamicMetadata(),
      require_ctx_->service_ctx().config().jwt_payload_metadata_name(),
      JwtPayloadIssuerPath, info.auth_issuer);

  fillJwtPayload(
      stream_info_.dynamicMetadata(),
      require_ctx_->service_ctx().config().jwt_payload_metadata_name(),
      JwtPayloadAudiencePath, info.auth_audience);

  info.frontend_protocol = getFrontendProtocol(response_headers, stream_info_);
  info.backend_protocol =
      getBackendProtocol(require_ctx_->service_ctx().config());

  if (request_headers) {
    info.referer = std::string(utils::readHeaderEntry(
        request_headers->getInline(referer_handle.handle())));
  }

  fillLatency(stream_info_, info.latency, filter_stats_);
  fillStatus(response_headers, response_trailers, stream_info_, info);

  info.request_size = stream_info_.bytesReceived() + request_header_size_;

  uint64_t response_header_size = 0;
  if (response_headers) {
    response_header_size += response_headers->byteSize();
  }
  if (response_trailers) {
    response_header_size += response_trailers->byteSize();
  }
  info.response_size = stream_info_.bytesSent() + response_header_size;

  info.response_code_detail = stream_info_.responseCodeDetails().value_or("");

  info.trace_id = parent_span.getTraceIdAsHex();

  require_ctx_->service_ctx().call().callReport(info);
}

}  // namespace service_control
}  // namespace http_filters
}  // namespace envoy
}  // namespace espv2


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using DotSpatial.Modeling.Forms.Parameters;

namespace DotSpatial.Modeling.Forms.Elements
{
    /// <summary>
    /// Open File Element.
    /// </summary>
    public partial class OpenFileElement : DialogElement
    {
        #region Fields

        private readonly List<DataSetArray> _dataSets;
        private DataSetArray _addedTextFile;
        private bool _refreshCombo = true;

        #endregion

        #region  Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="OpenFileElement"/> class.
        /// </summary>
        /// <param name="param">The parameter this element represents.</param>
        /// <param name="text">Not used.</param>
        public OpenFileElement(FileParam param, string text)
        {
            InitializeComponent();
            Param = param;

            GroupBox.Text = param.Name;
            DoRefresh();

            // Populates the dialog with the default parameter value
            if (param.Value != null && param.DefaultSpecified)
            {
                Status = ToolStatus.Ok;
                LightTipText = ModelingMessageStrings.FeaturesetValid;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="OpenFileElement"/> class.
        /// </summary>
        /// <param name="inputParam">The parameter this element represents.</param>
        /// <param name="dataSets">An array of available data.</param>
        public OpenFileElement(FileParam inputParam, List<DataSetArray> dataSets)
        {
            // Needed by the designer
            InitializeComponent();

            // We save the parameters passed in
            Param = inputParam;

            _dataSets = dataSets;

            // Saves the label
            GroupBox.Text = Param.Name;

            DoRefresh();
        }

        #endregion

        #region Methods

        /// <summary>
        /// updates the param if something's been changed.
        /// </summary>
        public override void Refresh()
        {
            DoRefresh();
        }

        private void BtnAddDataClick(object sender, EventArgs e)
        {
            using OpenFileDialog dialog = new();
            dialog.Title = ModelingMessageStrings.OpenFileElement_btnAddDataClick_SelectFileName;
            if (Param == null) Param = new FileParam("open filename");
            if (Param is FileParam p) dialog.Filter = p.DialogFilter;

            if (dialog.ShowDialog() == DialogResult.OK)
            {
                TextFile tmpTextFile = new(dialog.FileName);
                _addedTextFile = new DataSetArray(Path.GetFileNameWithoutExtension(dialog.FileName), tmpTextFile);

                Param.ModelName = _addedTextFile.Name;
                Param.Value = _addedTextFile.DataSet;
                Refresh();
                Status = ToolStatus.Ok;
            }
        }

        private void ComboFileSelectedValueChanged(object sender, EventArgs e)
        {
            if (_refreshCombo)
            {
                if (_comboFile.SelectedItem is DataSetArray dsa)
                {
                    Param.ModelName = dsa.Name;
                    Param.Value = dsa.DataSet;
                }
            }
        }

        private void DoRefresh()
        {
            // Disable the combo box temporarily
            _refreshCombo = false;

            // We set the combo boxes status to empty to start
            Status = ToolStatus.Empty;
            LightTipText = ModelingMessageStrings.FeaturesetMissing;
            _comboFile.Items.Clear();

            // If the user added a text file
            if (_addedTextFile != null)
            {
                _comboFile.Items.Add(_addedTextFile);
                if (Param.Value != null && Param.DefaultSpecified && _addedTextFile.DataSet == Param.Value)
                {
                    _comboFile.SelectedItem = _addedTextFile;
                    Status = ToolStatus.Ok;
                    LightTipText = ModelingMessageStrings.FeaturesetValid;
                }
            }

            // Add all the dataSets back to the combo box
            if (_dataSets != null)
            {
                foreach (DataSetArray dsa in _dataSets)
                {
                    if (dsa.DataSet is TextFile aTextFile && !_comboFile.Items.Contains(dsa))
                    {
                        // If the featureset is the correct type and isn't already in the combo box we add it
                        _comboFile.Items.Add(dsa);
                        if (Param.Value != null && Param.DefaultSpecified && dsa.DataSet == Param.Value)
                        {
                            _comboFile.SelectedItem = dsa;
                            Status = ToolStatus.Ok;
                            LightTipText = ModelingMessageStrings.FeaturesetValid;
                        }
                    }
                }
            }

            _refreshCombo = true;
        }

        #endregion
    }
}


text:
package org.usfirst.frc.team166.robot.commands.lifts;

import edu.wpi.first.wpilibj.command.Command;

import org.usfirst.frc.team166.robot.Robot;

/**
 *
 */
public class RaiseToteLift extends Command {

	public RaiseToteLift() {
		requires(Robot.toteLift);
	}

	// Called just before this Command runs the first time
	@Override
	protected void initialize() {
		Robot.toteLift.moveUp();
	}

	// Called repeatedly when this Command is scheduled to run
	@Override
	protected void execute() {
		Robot.toteLift.updatePIDSetpoint(1);
		Robot.toteLift.printEncoderValues();
	}

	// Make this return true when this Command no longer needs to run execute()
	@Override
	protected boolean isFinished() {
		return Robot.rcLift.isBoundaryHit() && Robot.rcLift.areLiftsInContact();
	}

	// Called once after isFinished returns true
	@Override
	protected void end() {
		Robot.toteLift.stop();
		Robot.toteLift.resetEncoder();
	}

	// Called when another command which requires one or more of the same
	// subsystems is scheduled to run
	@Override
	protected void interrupted() {
		Robot.toteLift.stop();
		Robot.rcLift.resetEncoder();
	}
}


text:
<?php

namespace App\Middlewares;

class LogMiddleware
{
    public function handle($request, $next)
    {
        return $next($request);
    }
}


text:
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V12.Errors {

  /// Holder for reflection information generated from google/ads/googleads/v12/errors/null_error.proto
  public static partial class NullErrorReflection {

    #region Descriptor
    /// File descriptor for google/ads/googleads/v12/errors/null_error.proto
    public static pbr::FileDescriptor Descriptor {
      get { return descriptor; }
    }
    private static pbr::FileDescriptor descriptor;

    static NullErrorReflection() {
      byte[] descriptorData = global::System.Convert.FromBase64String(
          string.Concat(
            "CjBnb29nbGUvYWRzL2dvb2dsZWFkcy92MTIvZXJyb3JzL251bGxfZXJyb3Iu",
            "cHJvdG8SH2dvb2dsZS5hZHMuZ29vZ2xlYWRzLnYxMi5lcnJvcnMiTAoNTnVs",
            "bEVycm9yRW51bSI7CglOdWxsRXJyb3ISDwoLVU5TUEVDSUZJRUQQABILCgdV",
            "TktOT1dOEAESEAoMTlVMTF9DT05URU5UEAJC7gEKI2NvbS5nb29nbGUuYWRz",
            "Lmdvb2dsZWFkcy52MTIuZXJyb3JzQg5OdWxsRXJyb3JQcm90b1ABWkVnb29n",
            "bGUuZ29sYW5nLm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVh",
            "ZHMvdjEyL2Vycm9ycztlcnJvcnOiAgNHQUGqAh9Hb29nbGUuQWRzLkdvb2ds",
            "ZUFkcy5WMTIuRXJyb3JzygIfR29vZ2xlXEFkc1xHb29nbGVBZHNcVjEyXEVy",
            "cm9yc+oCI0dvb2dsZTo6QWRzOjpHb29nbGVBZHM6OlYxMjo6RXJyb3JzYgZw",
            "cm90bzM="));
      descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
          new pbr::FileDescriptor[] { },
          new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
            new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V12.Errors.NullErrorEnum), global::Google.Ads.GoogleAds.V12.Errors.NullErrorEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V12.Errors.NullErrorEnum.Types.NullError) }, null, null)
          }));
    }
    #endregion

  }
  #region Messages
  ///
  /// Container for enum describing possible null errors.
  ///
  public sealed partial class NullErrorEnum : pb::IMessage<NullErrorEnum>
  #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      , pb::IBufferMessage
  #endif
  {
    private static readonly pb::MessageParser<NullErrorEnum> _parser = new pb::MessageParser<NullErrorEnum>(() => new NullErrorEnum());
    private pb::UnknownFieldSet _unknownFields;
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pb::MessageParser<NullErrorEnum> Parser { get { return _parser; } }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static pbr::MessageDescriptor Descriptor {
      get { return global::Google.Ads.GoogleAds.V12.Errors.NullErrorReflection.Descriptor.MessageTypes[0]; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    pbr::MessageDescriptor pb::IMessage.Descriptor {
      get { return Descriptor; }
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public NullErrorEnum() {
      OnConstruction();
    }

    partial void OnConstruction();

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public NullErrorEnum(NullErrorEnum other) : this() {
      _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public NullErrorEnum Clone() {
      return new NullErrorEnum(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override bool Equals(object other) {
      return Equals(other as NullErrorEnum);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public bool Equals(NullErrorEnum other) {
      if (ReferenceEquals(other, null)) {
        return false;
      }
      if (ReferenceEquals(other, this)) {
        return true;
      }
      return Equals(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override int GetHashCode() {
      int hash = 1;
      if (_unknownFields != null) {
        hash ^= _unknownFields.GetHashCode();
      }
      return hash;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public override string ToString() {
      return pb::JsonFormatter.ToDiagnosticString(this);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void WriteTo(pb::CodedOutputStream output) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      output.WriteRawMessage(this);
    #else
      if (_unknownFields != null) {
        _unknownFields.WriteTo(output);
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
      if (_unknownFields != null) {
        _unknownFields.WriteTo(ref output);
      }
    }
    #endif

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public int CalculateSize() {
      int size = 0;
      if (_unknownFields != null) {
        size += _unknownFields.CalculateSize();
      }
      return size;
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(NullErrorEnum other) {
      if (other == null) {
        return;
      }
      _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
    }

    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public void MergeFrom(pb::CodedInputStream input) {
    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
      input.ReadRawMessage(this);
    #else
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
            break;
        }
      }
    #endif
    }

    #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
      uint tag;
      while ((tag = input.ReadTag()) != 0) {
        switch(tag) {
          default:
            _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
            break;
        }
      }
    }
    #endif

    #region Nested types
    /// Container for nested types declared in the NullErrorEnum message type.
    [global::System.Diagnostics.DebuggerNonUserCodeAttribute]
    [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)]
    public static partial class Types {
      ///
      /// Enum describing possible null errors.
      ///
      public enum NullError {
        ///
        /// Enum unspecified.
        ///
        [pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
        ///
        /// The received error code is not known in this version.
        ///
        [pbr::OriginalName("UNKNOWN")] Unknown = 1,
        ///
        /// Specified list/container must not contain any null elements
        ///
        [pbr::OriginalName("NULL_CONTENT")] NullContent = 2,
      }

    }
    #endregion

  }

  #endregion

}

#endregion Designer generated code


text:
module.exports = {
    //where the cloned repos are put
    SESSION_DIR           : './session-data',
    //maximum time spent on clone before cancelling (in milliseconds)
    MAX_CLONE_DURATION_MS : 30 * 1000,
    //maximum number of POST requests allowed to be sent per IP during window
    MAX_CLONES_PER_IP     : 10,
    //duration after which to clear countng of MAX_CLONES_PER_IP (in milliseconds)
    MAX_CLONES_WINDOW_MS  : 60 * 60 * 1000,
    //trust x-forward headers for IP limiting above (set to true when behind
    //a trusted proxy, e.g. Heroku or own Nginx setup)
    TRUST_PROXY           : true,
    //maximum time session is kept after last request (in milliseconds)
    SESSION_MAX_AGE_MS    : 60 * 60 * 1000,
    //domains allowed to make requests (other than the domain this is served on)
    ALLOWED_CORS_DOMAINS  : [/* 'https://example.com' */],
    //salt used for cookie-session hashing
    SESSION_SECRETS       : ['secret squirrel'],
}


text:
name "knife-ec-backup"
default_version "2.0.6"

license "Apache-2.0"
license_file "https://github.com/chef/knife-ec-backup/blob/master/LICENSE"
# No need to collect license information for dependencies since
# --ignore-dependencies flag is passed in during gem install.
skip_transitive_dependency_licensing true

dependency "pg-gem"
dependency "sequel-gem"

build do
  env = with_standard_compiler_flags(with_embedded_path)

  # Ignore dependencies, since they are already installed on the system by
  # omnibus from one of the dependencies. This ensures we can properly link the
  # pg to the needed headers without needing to pass options through
  # knife-ec-backup.
  gem "install knife-ec-backup" \
      " --version '#{version}'" \
      " --bindir '#{install_dir}/embedded/bin'" \
      " --ignore-dependencies" \
      " --no-ri --no-rdoc", env: env
end


text:
<?php

class Login_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    function validate($username, $password) {

        if ($username == 'test' && $password == 'test'){
		return TRUE;
        }
        return FALSE;
    }

}

?>


text:
using System;

class Program
{
    static void Main(string[] args)
    {
        int a = -123;
        Console.WriteLine(-a);
    }
}


text:
from enum import IntEnum, unique

class BoardFieldType(IntEnum):
    HOME = 0
    FIELD = 1
    FINISH = 2

# Players
@unique
class Players(IntEnum):
    black = 0
    yellow = 1
    green = 2
    red = 3

    @staticmethod
    def next(current):
        if current == Players.red:
            return Players.black
        return Players(current + 1)

PAWN_COUNT = 4
BOARD_FIELD_COUNT = 40

MAX_DICE_NUMBER_OF_POINTS = 6


text:
using System;
using UnityEngine;
using System.Collections;

public class GroundCheck : MonoBehaviour
{
    public bool IsOnGround { get; private set; }

    public void OnTriggerStay(Collider other)
    {
        var geometry = other.gameObject.GetComponent<LevelGeometry>();
        if (geometry != null)
        {
            IsOnGround = true;
        }
    }

    public void OnTriggerExit(Collider other)
    {
        var geometry = other.gameObject.GetComponent<LevelGeometry>();
        if (geometry != null)
        {
            IsOnGround = false;
        }
    }
}


text:
.. rapidsms-celery-router documentation master file, created by
   sphinx-quickstart on Thu Sep 20 12:05:59 2012.
   You can adapt this file completely to your liking, but it should at least
   contain the root `toctree` directive.

Welcome to rapidsms-celery-router!
==================================

rapidsms-celery-router is a custom RapidSMS_ router implementation that uses
Celery_ to queue incoming and outgoing messages.

.. warning::
    rapidsms-celery-router is only compatible with the `feature/new-routing`_
    branch of RapidSMS.

.. _RapidSMS: http://www.rapidsms.org/
.. _Celery: http://www.celeryproject.org/
.. _feature/new-routing: https://github.com/rapidsms/rapidsms/tree/feature/new-routing

Motivation
----------

RapidSMS ships with a router, ``BlockingRouter``, that processes messages
synchronously in the main HTTP thread. This is fine for most scenarios, but in
some cases you may wish to process messages outside of the HTTP
request/response cycle to be more efficient. rapidsms-celery-router is a custom
router that allows you queue messages for background processing. It's designed
for projects that require high messages volumes and greater concurrency.

Contents
--------

.. toctree::
   :maxdepth: 2

   installation
   configuration
   tests
   releases