text:
module Virtus
  # Abstract class implementing base API for attribute types
  #
  # @abstract
  class Attribute
    # Implements a Union attribute type, covering multiple EmbeddedValues
    #
    # @see Virtus::Union
    # @api private
    class Union < EmbeddedValue
      primitive Virtus::Union

      # Init an instance of Virtus::Attribute::Union
      #
      # @api private
      def initialize(*)
        super
        @union_attributes = AttributeSet.new
        options[:types].each do |tag, type|
          @union_attributes << Attribute.build(tag, type)
        end
        @discriminator = Attribute.build(:discriminator, Symbol)
      end

      # Reads types and discriminator values from the configuration
      # type.
      #
      # @param [Virtus::Union]
      #
      # @param [Hash]
      #
      # @return [Hash]
      #
      # @api private
      def self.merge_options(type, options)
        options.merge type.options
        super
      end

      # Coerce a given value to the correct type given in the
      # Union configuration. Return `nil` if unknown.
      #
      # @param [Object] value
      #
      # @return [Virtus] The coerced value.
      def coerce(value)
        return value if union_type?(value)
        coerce_using_attribute(value)
      end

      private
        # Get the union attribute matching by discriminator.
        #
        # @param [Object] value
        #
        # @return [Virtus::Attribute]
        def fetch_union_attribute(value)
          @union_attributes[fetch_discriminator_value(value)]
        end

        # Fetch the value of the discriminator field for a given value.
        #
        # @param [Object] value
        #
        # @return [Object] discriminator value
        def fetch_discriminator_value(value)
          discriminator_value = value[options[:discriminator]]
          @discriminator.coerce(discriminator_value)
        end

        # Predicate to check whether the value is already one of
        # the types allowed in this union.
        #
        # @param [Object] value
        #
        # @return [true|false]
        def union_type?(value)
          @union_attributes.any? do |attribute|
            value.class <= attribute.options[:primitive]
          end
        end

        # Coerce the value using one of the internal type attributes.
        #
        # @param [Object] value The value to coerce.
        #
        # @return [Object] The coerced value
        def coerce_using_attribute(value)
          attribute = fetch_union_attribute(value)

          if attribute
            attribute.coerce(value)
          end
        end
    end
  end
end


text:
package com.facebook.buck.rules;

import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.rules.coercer.TypeCoercerFactory;
import com.facebook.buck.util.ProjectFilesystem;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;

/**
 * Used to derive information from the constructor args returned by {@link Description} instances.
 * There are two major uses this information is put to: populating the DTO object from the
 * {@link BuildRuleFactoryParams}, which is populated by the functions added to Buck's core build
 * file parsing script. The second function of this class is to generate those functions.
 *
 * @see ConstructorArg
 */
public class ConstructorArgMarshaller {

  private final Path basePath;
  private final TypeCoercerFactory typeCoercerFactory;

  /**
   * Constructor. {@code pathFromProjectRootToBuildFile} is the path relative to the project root to
   * the build file that has called the build rule's function in buck.py. This is used for resolving
   * additional paths to ones relative to the project root, and to allow {@link BuildTarget}
   * instances to be fully qualified.
   *
   * @param pathFromProjectRootToBuildFile The path from the root of the project to the directory of
   *     the build file that this function is being created from.
   */
  public ConstructorArgMarshaller(Path pathFromProjectRootToBuildFile) {
    Preconditions.checkNotNull(pathFromProjectRootToBuildFile);

    // Without this check an IndexOutOfBounds exception is thrown by normalize.
    if (pathFromProjectRootToBuildFile.toString().isEmpty()) {
      this.basePath = pathFromProjectRootToBuildFile;
    } else {
      this.basePath = pathFromProjectRootToBuildFile.normalize();
    }

    this.typeCoercerFactory = new TypeCoercerFactory();
  }

  /**
   * Use the information contained in the {@code params} to fill in the public fields and settable
   * properties of {@code dto}. The following rules are used:
   *

   *
Boolean values are set to true or false.

   *
{@link BuildRule}s will be resovled.

   *
{@link BuildTarget}s are resolved and will be fully qualified.

   *
Numeric values are handled as if being cast from Long.

   *
{@link SourcePath} instances will be set to the appropriate implementation.

   *
{@link Path} declarations will be set to be relative to the project root.

   *
Strings will be set "as is".

   *
{@link List}s and {@link Set}s will be populated with the expected generic type,
   *   provided the wildcarding allows an upperbound to be determined to be one of the above.

   *

   *
   * Any property that is marked as being an {@link Optional} field will be set to a default value
   * if none is set. This is typically {@link Optional#absent()}, but in the case of collections is
   * an empty collection.
   *
   * @param ruleResolver The resolver to use when looking up {@link BuildRule}s.
   * @param params The parameters to be used to populate the {@code dto} instance.
   * @param dto The constructor dto to be populated.
   */
  public void populate(
      BuildRuleResolver ruleResolver,
      ProjectFilesystem filesystem,
      BuildRuleFactoryParams params,
      ConstructorArg dto) throws ConstructorArgMarshalException {
    populate(
        ruleResolver,
        filesystem,
        params,
        dto,
        /* populate all fields, optional and required */ false);
  }

  public void populate(
      BuildRuleResolver ruleResolver,
      ProjectFilesystem filesystem,
      BuildRuleFactoryParams params,
      ConstructorArg dto,
      boolean onlyOptional) throws ConstructorArgMarshalException {
    Set<ParamInfo> allInfo = getAllParamInfo(dto);

    for (ParamInfo info : allInfo) {
      if (onlyOptional && !info.isOptional()) {
        continue;
      }
      try {
        info.setFromParams(ruleResolver, filesystem, dto, params);
      } catch (ParamInfoException e) {
        throw new ConstructorArgMarshalException(e.getMessage(), e);
      }
    }
  }

  ImmutableSet<ParamInfo> getAllParamInfo(ConstructorArg dto) {
    Class<?> argClass = dto.getClass();

    ImmutableSet.Builder<ParamInfo> allInfo = ImmutableSet.builder();

    for (Field field : argClass.getFields()) {
      if (Modifier.isFinal(field.getModifiers())) {
        continue;
      }
      allInfo.add(new ParamInfo(typeCoercerFactory, basePath, field));
    }

    return allInfo.build();
  }
}

redpajama_set_name: RedPajamaGithub


text:
    module BlogHelperPlugin
        def add_patch_before_post_content
            @user.patch_before_post_content.to_s
        end
        def add_patch_after_post_content
            @user.patch_after_post_content.to_s
        end
        def add_patch_after_post_brief
            @user.patch_after_post_brief.to_s
        end
    end


text:
/**
 * tests/db/helpers/common.js
 */
'use strict';
const expect = require('chai').expect;
const tu = require('../../testUtils');
const u = require('../model/subject/utils');
const Subject = tu.db.Subject;
const common = require('../../../db/helpers/common');

describe('tests/db/helpers/common.js >', () => {
  after(u.forceDelete);

  describe('checkDuplicatesInStringArray >', () => {
    it('empty input returns false', () => {
      expect(common.checkDuplicatesInStringArray()).to.be.false;
    });

    it('empty array input returns false', () => {
      expect(common.checkDuplicatesInStringArray([])).to.be.false;
    });

    it('all identical elements returns true', () => {
      expect(common.checkDuplicatesInStringArray(['a', 'a', 'a'])).to.be.true;
    });

    it('no duplicates return false', () => {
      expect(common.checkDuplicatesInStringArray(['a', 'b', 'c'])).to.be.false;
    });

    it('multiple duplicates return true', () => {
      const uniqueArray = ['a', 'b', 'c'];
      const dupesArr = [];
      dupesArr.push(...uniqueArray);
      dupesArr.push(...uniqueArray);
      dupesArr.push(...uniqueArray);
      expect(dupesArr.length).to.equal(9);
      expect(common.checkDuplicatesInStringArray(dupesArr)).to.be.true;
    });
  });

  describe('tagsChanged', () => {
    let sub;

    beforeEach(() => {
      const s = u.getSubjectPrototype(`${tu.namePrefix}1`, null);
      s.tags = ['tag1', 'tag2'];
      return Subject.create(s)
      .then((s) => sub = s);
    });

    afterEach(u.forceDelete);

    it('not updated', () => {
      sub.set({ description: '...' });
      expect(common.tagsChanged(sub)).to.be.false;
    });

    it('exactly the same', () => {
      sub.set({ tags: ['tag1', 'tag2'] });
      expect(common.tagsChanged(sub)).to.be.false;
    });

    it('different order', () => {
      sub.set({ tags: ['tag2', 'tag1'] });
      expect(common.tagsChanged(sub)).to.be.false;
    });

    it('different capitalization', () => {
      sub.set({ tags: ['Tag1', 'Tag2'] });
      expect(common.tagsChanged(sub)).to.be.false;
    });

    it('changed', () => {
      sub.set({ tags: ['tag1', 'tag3'] });
      expect(common.tagsChanged(sub)).to.be.true;
    });

    it('appended', () => {
      sub.set({ tags: ['tag1', 'tag2', 'tag3'] });
      expect(common.tagsChanged(sub)).to.be.true;
    });

    it('set to empty', () => {
      sub.set({ tags: [] });
      expect(common.tagsChanged(sub)).to.be.true;
    });

    it('no previous tags', () => {
      const s = u.getSubjectPrototype(`${tu.namePrefix}2`, null);
      return Subject.create(s)
      .then((sub) => {
        sub.set({ tags: ['tag1', 'tag2'] });
        expect(common.tagsChanged(sub)).to.be.true;
      });
    });

    it('no previous tags, not updated', () => {
      const s = u.getSubjectPrototype(`${tu.namePrefix}2`, null);
      return Subject.create(s)
      .then((sub) => {
        sub.set({ description: '...' });
        expect(common.tagsChanged(sub)).to.be.false;
      });
    });
  });
});


text:
package net.sourceforge.plantuml.cucadiagram;

import java.util.EnumSet;

import net.sourceforge.plantuml.awt.geom.XDimension2D;
import net.sourceforge.plantuml.awt.geom.XPoint2D;
import net.sourceforge.plantuml.svek.ShapeType;
import net.sourceforge.plantuml.ugraphic.Shadowable;
import net.sourceforge.plantuml.ugraphic.UEllipse;
import net.sourceforge.plantuml.ugraphic.UGraphic;
import net.sourceforge.plantuml.ugraphic.ULine;
import net.sourceforge.plantuml.ugraphic.URectangle;
import net.sourceforge.plantuml.ugraphic.UTranslate;

public enum EntityPosition {

	NORMAL, ENTRY_POINT, EXIT_POINT, INPUT_PIN, OUTPUT_PIN, EXPANSION_INPUT, EXPANSION_OUTPUT, PORTIN, PORTOUT;

	public static final double RADIUS = 6;

	public static EnumSet<EntityPosition> getInputs() {
		return EnumSet.of(ENTRY_POINT, INPUT_PIN, EXPANSION_INPUT, PORTIN);
	}

	public static EnumSet<EntityPosition> getOutputs() {
		return EnumSet.of(EXIT_POINT, OUTPUT_PIN, EXPANSION_OUTPUT, PORTOUT);
	}

	public static EnumSet<EntityPosition> getNormals() {
		return EnumSet.of(NORMAL);
	}

	public boolean isNormal() {
		return this == NORMAL;
	}

	public boolean isInput() {
		return getInputs().contains(this);
	}

	public boolean isOutput() {
		return getOutputs().contains(this);
	}

	public void drawSymbol(UGraphic ug, Rankdir rankdir) {
		if (this == NORMAL) {
			throw new IllegalStateException();
		} else if (this == ENTRY_POINT || this == EXIT_POINT) {
			final Shadowable circle = new UEllipse(RADIUS * 2, RADIUS * 2);
			ug.draw(circle);
			if (this == EntityPosition.EXIT_POINT) {
				final double xc = 0 + RADIUS + .5;
				final double yc = 0 + RADIUS + .5;
				final double radius = RADIUS - .5;
				drawLine(ug, getPointOnCircle(xc, yc, Math.PI / 4, radius),
						getPointOnCircle(xc, yc, Math.PI + Math.PI / 4, radius));
				drawLine(ug, getPointOnCircle(xc, yc, -Math.PI / 4, radius),
						getPointOnCircle(xc, yc, Math.PI - Math.PI / 4, radius));
			}
		} else if (this == INPUT_PIN || this == OUTPUT_PIN /* || this == PORT */) {
			final Shadowable rectangle = new URectangle(RADIUS * 2, RADIUS * 2);
			ug.draw(rectangle);
		} else if (this == EXPANSION_INPUT || this == EXPANSION_OUTPUT) {
			if (rankdir == Rankdir.TOP_TO_BOTTOM) {
				final Shadowable rectangle = new URectangle(RADIUS * 2 * 4, RADIUS * 2);
				ug.draw(rectangle);
				final ULine vline = ULine.vline(RADIUS * 2);
				ug.apply(UTranslate.dx(RADIUS * 2)).draw(vline);
				ug.apply(UTranslate.dx(RADIUS * 2 * 2)).draw(vline);
				ug.apply(UTranslate.dx(RADIUS * 2 * 3)).draw(vline);
			} else {
				final Shadowable rectangle = new URectangle(RADIUS * 2, RADIUS * 2 * 4);
				ug.apply(UTranslate.dy(0)).draw(rectangle);
				final ULine hline = ULine.hline(RADIUS * 2);
				ug.apply(UTranslate.dy(RADIUS * 2)).draw(hline);
				ug.apply(UTranslate.dy(RADIUS * 2 * 2)).draw(hline);
				ug.apply(UTranslate.dy(RADIUS * 2 * 3)).draw(hline);
			}
		}

	}

	public XDimension2D getDimension(Rankdir rankdir) {
		if (this == EXPANSION_INPUT || this == EXPANSION_OUTPUT) {
			if (rankdir == Rankdir.TOP_TO_BOTTOM)
				return new XDimension2D(EntityPosition.RADIUS * 2 * 4, EntityPosition.RADIUS * 2);

			return new XDimension2D(EntityPosition.RADIUS * 2, EntityPosition.RADIUS * 2 * 4);
		}
		return new XDimension2D(EntityPosition.RADIUS * 2, EntityPosition.RADIUS * 2);
	}

	private XPoint2D getPointOnCircle(double xc, double yc, double angle, double radius) {
		final double x = xc + radius * Math.cos(angle);
		final double y = yc + radius * Math.sin(angle);
		return new XPoint2D(x, y);
	}

	static private void drawLine(UGraphic ug, XPoint2D p1, XPoint2D p2) {
		final double dx = p2.getX() - p1.getX();
		final double dy = p2.getY() - p1.getY();
		ug.apply(new UTranslate(p1.getX(), p1.getY())).draw(new ULine(dx, dy));

	}

	public ShapeType getShapeType() {
		if (this == NORMAL)
			throw new IllegalStateException();

		if (this == ENTRY_POINT || this == EXIT_POINT)
			return ShapeType.RECTANGLE_PORT;

		return ShapeType.RECTANGLE;
	}

	public static EntityPosition fromStereotype(String label) {
		if ("<<port>>".equalsIgnoreCase(label))
			throw new UnsupportedOperationException();

		if ("<<entrypoint>>".equalsIgnoreCase(label))
			return ENTRY_POINT;

		if ("<<exitpoint>>".equalsIgnoreCase(label))
			return EXIT_POINT;

		if ("<<inputpin>>".equalsIgnoreCase(label))
			return INPUT_PIN;

		if ("<<outputpin>>".equalsIgnoreCase(label))
			return OUTPUT_PIN;

		if ("<<expansioninput>>".equalsIgnoreCase(label))
			return EXPANSION_INPUT;

		if ("<<expansionoutput>>".equalsIgnoreCase(label))
			return EXPANSION_OUTPUT;

		return EntityPosition.NORMAL;
	}

//	public static EnumSet<EntityPosition> getSame() {
//		return EnumSet.of(PORT);
//	}
//
	public boolean isPort() {
		return /* this == PORT || */ this == PORTIN || this == PORTOUT;
	}

	public boolean usePortP() {
		return isPort() || this == EXIT_POINT || this == ENTRY_POINT;
	}

}


text:
=head1 LICENSE

Copyright [1999-2015] Wellcome Trust Sanger Institute and the EMBL-European Bioinformatics Institute
Copyright [2016-2022] EMBL-European Bioinformatics Institute

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

=cut

package EnsEMBL::Web::Document::Element::BodyJavascript;

use strict;
use warnings;

use parent qw(EnsEMBL::Web::Document::Element);

sub init {
  my $self          = shift;
  my $hub           = $self->hub;
  my $species_defs  = $hub->species_defs;
  my $js_groups     = $species_defs->get_config('ENSEMBL_JSCSS_FILES')->{'js'};

  for (@$js_groups) {
    next unless $_->condition($hub);

    if (($hub->param('debug') || '') eq 'js' || $species_defs->ENSEMBL_DEBUG_JS) {
      $self->add_script($_->url_path) for @{$_->files};
    } else {
      $self->add_script($_->minified_url_path);
    }
  }
}

sub content {
  my $self = shift;

  return '' if $self->shared->{'sent_js'};
  return join '',
    map(sprintf(qq(<script type="text/javascript" src="%s%s"></script>\n), $self->static_server, $_), @{$self->{'_sources'} || []}),
    map(sprintf(qq(<script type="text/javascript">%s</script>), $_), @{$self->{'_inline'} || []});
}

sub add_script {
  my ($self, $src) = @_;

  push @{$self->{'_sources'}}, $src unless grep { $src eq $_ } @{$self->{'_sources'}};
}

sub add_inlinejs {
  my ($self, $code) = @_;

  push @{$self->{'_inline'}}, $code;
}

1;


text:
package net.kwaz.chicago.hbase.table;

import net.kwaz.chicago.hbase.ChicagoTableColumns;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.conf.Configured;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.io.compress.Compression;
import org.apache.hadoop.hbase.util.RegionSplitter;
import org.apache.hadoop.util.Tool;
import org.apache.hadoop.util.ToolRunner;

public class ChicagoTableCreator extends Configured implements Tool {

	public static void main(String[] args) throws Exception {
		ToolRunner.run(new ChicagoTableCreator(), args);
	}

	@Override
	public int run(String[] args) throws Exception {
		String stringTableName = args[0];

		Configuration config = getConf();
		config.addResource("hbase-site.xml");

		HBaseAdmin admin = new HBaseAdmin(config);

		TableName tableName = TableName.valueOf(stringTableName);

		HColumnDescriptor columnDescriptor = new HColumnDescriptor(ChicagoTableColumns.CF);
		columnDescriptor.setCompressionType(Compression.Algorithm.GZ);
		columnDescriptor.setCompactionCompressionType(Compression.Algorithm.GZ);

		HTableDescriptor tableDescriptor = new HTableDescriptor(tableName);
		tableDescriptor.addFamily(columnDescriptor);
		tableDescriptor.setMaxFileSize(1000 * 1000 * 1024);
		tableDescriptor.setConfiguration(HTableDescriptor.SPLIT_POLICY, "org.apache.hadoop.hbase.regionserver.ConstantSizeRegionSplitPolicy");

		RegionSplitter.UniformSplit split = new RegionSplitter.UniformSplit();
		admin.createTable(tableDescriptor, split.split(4));

		admin.close();

		return 0;
	}

}


text:
class Jedzenie;
class Pelzacz;
class Pelzaczofag;
class Plansza;
class Potwor;
class StrukturyPomocnicze;
class Teleporter;

using namespace std;

int nrTury = 1;

int main(int argc, const char * argv[]) {
    // insert code here...
    Plansza plansza(14, 7);
    cout << "Legenda: " << endl;
    cout << ". - pelzacz" << endl << "* - pelzaczofag" << endl << "T - teleporter" << endl;

    while (plansza.getAktualnaIloscPelzaczy()>0 || plansza.getAktualnaIloscPelzaczofagow()>0) {
        cout << "Nr tury: " << to_string(nrTury) << endl;
        cout << "Ilosc pelzaczy: " << to_string( plansza.getAktualnaIloscPelzaczy() ) << endl;
        cout << "Ilosc pelzaczofagow: " << to_string( plansza.getAktualnaIloscPelzaczofagow() ) << endl;
        cout << "Ile razy zadzialal teleporter: " << to_string( plansza.ileRazyZadzialalTeleporter ) << endl;
        Ascii::wyswietlPlansze(plansza);
        plansza.tura(plansza, nrTury);
        nrTury++;
    }
    return 0;
}


text:
namespace GeekyTool.Messaging
{
    /// <summary>
    /// Defines an interface for classes that create objects whose types <see
    /// cref="IMessageBus" />-Implement Interface.
    /// </summary>
    public interface IMessageBusFactory
    {
        /// <summary>
        /// provides a <see cref="IMessageBus" />.
        /// </summary>
        /// <returns>
        /// An object whose type is the <see cref="IMessageBus" />-Implement Interface.
        /// </returns>
        IMessageBus CreateBus();
    }

    /// <summary>
    /// Returns objects of type <see cref="WeakMessageBus" />.
    /// </summary>
    public class WeakMessageBusFactory : IMessageBusFactory
    {
        /// <summary>
        /// provides a <see cref="IMessageBus" />.
        /// </summary>
        /// <returns>
        /// An object whose type is the <see cref="IMessageBus" />-Implement Interface.
        /// </returns>
        public IMessageBus CreateBus()
        {
            return new WeakMessageBus();
        }
    }
}


text:
package org.apache.camel.component.elasticsearch;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.camel.CamelContext;
import org.apache.camel.Endpoint;
import org.apache.camel.spi.Metadata;
import org.apache.camel.spi.annotations.Component;
import org.apache.camel.support.DefaultComponent;
import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;

/**
 * Represents the component that manages {@link ElasticsearchEndpoint}.
 */
@Component("elasticsearch-rest")
public class ElasticsearchComponent extends DefaultComponent {

    @Metadata(label = "advanced")
    private RestClient client;
    @Metadata(label = "advanced")
    private String hostAddresses;
    @Metadata(label = "advanced", defaultValue = "" + ElasticsearchConstants.DEFAULT_SOCKET_TIMEOUT)
    private int socketTimeout = ElasticsearchConstants.DEFAULT_SOCKET_TIMEOUT;
    @Metadata(label = "advanced", defaultValue = "" + ElasticsearchConstants.MAX_RETRY_TIMEOUT)
    private int maxRetryTimeout = ElasticsearchConstants.MAX_RETRY_TIMEOUT;
    @Metadata(label = "advanced", defaultValue = "" + ElasticsearchConstants.DEFAULT_CONNECTION_TIMEOUT)
    private int connectionTimeout = ElasticsearchConstants.DEFAULT_CONNECTION_TIMEOUT;

    @Metadata(label = "security")
    private String user;
    @Metadata(label = "security", secret = true)
    private String password;
    @Metadata(label = "security", defaultValue = "false")
    private boolean enableSSL;
    @Metadata(label = "advanced", defaultValue = "false")
    private boolean enableSniffer;
    @Metadata(label = "advanced", defaultValue = "" + ElasticsearchConstants.DEFAULT_SNIFFER_INTERVAL)
    private int snifferInterval = ElasticsearchConstants.DEFAULT_SNIFFER_INTERVAL;
    @Metadata(label = "advanced", defaultValue = "" + ElasticsearchConstants.DEFAULT_AFTER_FAILURE_DELAY)
    private int sniffAfterFailureDelay = ElasticsearchConstants.DEFAULT_AFTER_FAILURE_DELAY;

    public ElasticsearchComponent() {
        this(null);
    }

    public ElasticsearchComponent(CamelContext context) {
        super(context);
        registerExtension(new ElasticsearchRestComponentVerifierExtension());
    }

    @Override
    protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception {
        ElasticsearchConfiguration config = new ElasticsearchConfiguration();
        config.setHostAddresses(this.getHostAddresses());
        config.setSocketTimeout(this.getSocketTimeout());
        config.setMaxRetryTimeout(this.getMaxRetryTimeout());
        config.setConnectionTimeout(this.getConnectionTimeout());
        config.setUser(this.getUser());
        config.setEnableSSL(this.getEnableSSL());
        config.setPassword(this.getPassword());
        config.setEnableSniffer(this.getEnableSniffer());
        config.setSnifferInterval(this.getSnifferInterval());
        config.setSniffAfterFailureDelay(this.getSniffAfterFailureDelay());
        config.setClusterName(remaining);

        Endpoint endpoint = new ElasticsearchEndpoint(uri, this, config, client);
        setProperties(endpoint, parameters);
        config.setHostAddressesList(parseHostAddresses(config.getHostAddresses(), config));

        return endpoint;
    }

    private List<HttpHost> parseHostAddresses(String ipsString, ElasticsearchConfiguration config) throws UnknownHostException {
        if (ipsString == null || ipsString.isEmpty()) {
            return null;
        }
        List<String> addressesStr = Arrays.asList(ipsString.split(","));
        List<HttpHost> addressesTrAd = new ArrayList<>(addressesStr.size());
        for (String address : addressesStr) {
            String[] split = address.split(":");
            String hostname;
            if (split.length > 0) {
                hostname = split[0];
            } else {
                throw new IllegalArgumentException();
            }
            int port = split.length > 1 ? Integer.parseInt(split[1]) : ElasticsearchConstants.DEFAULT_PORT;
            addressesTrAd.add(new HttpHost(hostname, port, config.isEnableSSL() ? "HTTPS" : "HTTP"));
        }
        return addressesTrAd;
    }

    public RestClient getClient() {
        return client;
    }

    /**
     * To use an existing configured Elasticsearch client, instead of creating a client per endpoint. This allow to
     * customize the client with specific settings.
     */
    public void setClient(RestClient client) {
        this.client = client;
    }

    /**
     * Comma separated list with ip:port formatted remote transport addresses to use. The ip and port options must be
     * left blank for hostAddresses to be considered instead.
     */
    public String getHostAddresses() {
        return hostAddresses;
    }

    public void setHostAddresses(String hostAddresses) {
        this.hostAddresses = hostAddresses;
    }

    /**
     * The timeout in ms to wait before the socket will timeout.
     */
    public int getSocketTimeout() {
        return socketTimeout;
    }

    public void setSocketTimeout(int socketTimeout) {
        this.socketTimeout = socketTimeout;
    }

    /**
     * The time in ms to wait before connection will timeout.
     */
    public int getConnectionTimeout() {
        return connectionTimeout;
    }

    public void setConnectionTimeout(int connectionTimeout) {
        this.connectionTimeout = connectionTimeout;
    }

    /**
     * Basic authenticate user
     */
    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    /**
     * Password for authenticate
     */
    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    /**
     * Enable SSL
     */
    public Boolean getEnableSSL() {
        return enableSSL;
    }

    public void setEnableSSL(Boolean enableSSL) {
        this.enableSSL = enableSSL;
    }

    /**
     * The time in ms before retry
     */
    public int getMaxRetryTimeout() {
        return maxRetryTimeout;
    }

    public void setMaxRetryTimeout(int maxRetryTimeout) {
        this.maxRetryTimeout = maxRetryTimeout;
    }

    /**
     * Enable automatically discover nodes from a running Elasticsearch cluster
     */
    public Boolean getEnableSniffer() {
        return enableSniffer;
    }

    public void setEnableSniffer(Boolean enableSniffer) {
        this.enableSniffer = enableSniffer;
    }

    /**
     * The interval between consecutive ordinary sniff executions in milliseconds. Will be honoured when sniffOnFailure
     * is disabled or when there are no failures between consecutive sniff executions
     */
    public int getSnifferInterval() {
        return snifferInterval;
    }

    public void setSnifferInterval(int snifferInterval) {
        this.snifferInterval = snifferInterval;
    }

    /**
     * The delay of a sniff execution scheduled after a failure (in milliseconds)
     */
    public int getSniffAfterFailureDelay() {
        return sniffAfterFailureDelay;
    }

    public void setSniffAfterFailureDelay(int sniffAfterFailureDelay) {
        this.sniffAfterFailureDelay = sniffAfterFailureDelay;
    }

}


text:
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
        <title>Livia</title>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link href="static/lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen">
        <link rel="stylesheet" href="static/css/style.css" />

                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>
                    Livia

Home

Loggers

Data


text:
package org.apache.flink.table.client.gateway.local.result;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.table.client.gateway.TypedResult;
import org.apache.flink.types.Row;

import java.net.InetAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * Collects results and returns them as a changelog.
 *
 * @param <C> cluster id to which this result belongs to
 */
public class ChangelogCollectStreamResult<C> extends CollectStreamResult<C> implements ChangelogResult<C> {

	private List<Tuple2<Boolean, Row>> changeRecordBuffer;
	private static final int CHANGE_RECORD_BUFFER_SIZE = 5_000;

	public ChangelogCollectStreamResult(TypeInformation<Row> outputType, ExecutionConfig config,
			InetAddress gatewayAddress, int gatewayPort) {
		super(outputType, config, gatewayAddress, gatewayPort);

		// prepare for changelog
		changeRecordBuffer = new ArrayList<>();
	}

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

	@Override
	public TypedResult<List<Tuple2<Boolean, Row>>> retrieveChanges() {
		synchronized (resultLock) {
			// retrieval thread is alive return a record if available
			// but the program must not have failed
			if (isRetrieving() && executionException == null) {
				if (changeRecordBuffer.isEmpty()) {
					return TypedResult.empty();
				} else {
					final List<Tuple2<Boolean, Row>> change = new ArrayList<>(changeRecordBuffer);
					changeRecordBuffer.clear();
					resultLock.notify();
					return TypedResult.payload(change);
				}
			}
			// retrieval thread is dead but there is still a record to be delivered
			else if (!isRetrieving() && !changeRecordBuffer.isEmpty()) {
				final List<Tuple2<Boolean, Row>> change = new ArrayList<>(changeRecordBuffer);
				changeRecordBuffer.clear();
				return TypedResult.payload(change);
			}
			// no results can be returned anymore
			else {
				return handleMissingResult();
			}
		}
	}

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

	@Override
	protected void processRecord(Tuple2<Boolean, Row> change) {
		synchronized (resultLock) {
			// wait if the buffer is full
			if (changeRecordBuffer.size() >= CHANGE_RECORD_BUFFER_SIZE) {
				try {
					resultLock.wait();
				} catch (InterruptedException e) {
					// ignore
				}
			} else {
				changeRecordBuffer.add(change);
			}
		}
	}
}


text:
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
// THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
//*********************************************************

using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.Text;
using Microsoft.Graphics.Canvas.UI.Composition;
using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.DirectX;
using Windows.UI;
using Windows.UI.Composition;

namespace News.Helpers.Composition
{
    public delegate CompositionDrawingSurface LoadTimeEffectHandler(CanvasBitmap bitmap, CompositionGraphicsDevice device, Size sizeTarget);

    public class SurfaceLoader
    {
        private static bool                         _intialized;
        private static Compositor                   _compositor;
        private static CanvasDevice                 _canvasDevice;
        private static CompositionGraphicsDevice    _compositionDevice;

        static public void Initialize(Compositor compositor)
        {
            Debug.Assert(!_intialized || compositor == _compositor);

            if (!_intialized)
            {
                _compositor = compositor;
                _canvasDevice = new CanvasDevice();
                _compositionDevice = CanvasComposition.CreateCompositionGraphicsDevice(_compositor, _canvasDevice);

                _intialized = true;
            }
        }

        static public void Uninitialize()
        {
            _compositor = null;

            if (_compositionDevice != null)
            {
                _compositionDevice.Dispose();
                _compositionDevice = null;
            }

            if(_canvasDevice != null)
            {
                _canvasDevice.Dispose();
                _canvasDevice = null;
            }

            _intialized = false;
        }

        static public bool IsInitialized
        {
            get
            {
                return _intialized;
            }
        }

        static public async Task<CompositionDrawingSurface> LoadFromUri(Uri uri)
        {
            return await LoadFromUri(uri, Size.Empty);
        }

        static public async Task<CompositionDrawingSurface> LoadFromUri(Uri uri, Size sizeTarget)
        {
            Debug.Assert(_intialized);

            CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(_canvasDevice, uri);
            Size sizeSource = bitmap.Size;

            if (sizeTarget.IsEmpty)
            {
                sizeTarget = sizeSource;
            }

            CompositionDrawingSurface surface = _compositionDevice.CreateDrawingSurface(sizeTarget,
                                                            DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            using (var ds = CanvasComposition.CreateDrawingSession(surface))
            {
                ds.Clear(Color.FromArgb(0, 0, 0, 0));
                ds.DrawImage(bitmap, new Rect(0, 0, sizeTarget.Width, sizeTarget.Height), new Rect(0, 0, sizeSource.Width, sizeSource.Height));
            }

            return surface;
        }

        static public CompositionDrawingSurface LoadText(string text, Size sizeTarget, CanvasTextFormat textFormat, Color textColor, Color bgColor)
        {
            Debug.Assert(_intialized);

            CompositionDrawingSurface surface = _compositionDevice.CreateDrawingSurface(sizeTarget,
                                                            DirectXPixelFormat.B8G8R8A8UIntNormalized, DirectXAlphaMode.Premultiplied);
            using (var ds = CanvasComposition.CreateDrawingSession(surface))
            {
                ds.Clear(bgColor);
                ds.DrawText(text, new Rect(0, 0, sizeTarget.Width, sizeTarget.Height), textColor, textFormat);
            }

            return surface;
        }

        static public async Task<CompositionDrawingSurface> LoadFromUri(Uri uri, Size sizeTarget, LoadTimeEffectHandler loadEffectHandler)
        {
            Debug.Assert(_intialized);

            if (loadEffectHandler != null)
            {
                CanvasBitmap bitmap = await CanvasBitmap.LoadAsync(_canvasDevice, uri);
                return loadEffectHandler(bitmap, _compositionDevice, sizeTarget);
            }
            else
            {
                return await LoadFromUri(uri, sizeTarget);
            }
        }
    }
}


text:
<?php

/**
 * Bootstrap
 *
 * File boot and application initialization
 *
 * @uses    Zend_Application_Bootstrap_Bootstrap
 * @package Bootstrap
 * @author   Sergii Beskorovainyi <bsa2657@yandex.ru>
 * @license  MIT <http://www.opensource.org/licenses/mit-license.php>
 * @link     https://github.com/bsa-git/zf-myblog/
 */
class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {

    /**
     * Initialization Autoloader, Session, Auth, Locale,
     *
     * @return void
     */
    protected function _initAutoload() {

        $_startTime = microtime(1);

        //------- Define the autoloader parameters ------------
        // Define basic prefix and the base path to the resources for the default module
        $autoloader = new Zend_Application_Module_Autoloader(
                array('namespace' => 'Default', 'basePath' => dirname(__FILE__)));

        // Add resource loader for admin module
        $resourceLoader = new Zend_Loader_Autoloader_Resource(array(
            'basePath' => APPLICATION_PATH . '/modules/admin',
            'namespace' => 'Admin',
            'resourceTypes' => array(
                'form' => array(
                    'path' => 'forms/',
                    'namespace' => 'Form',
                )
            ),
        ));

        //------- Create an application directory ------------
        Default_Plugin_SysBox::createAppPaths();

        //--------- Remember the configuration to register ---------
        $config = $this->_options;
        Zend_Registry::set('config', $config);

        //------- Copy users upload dir ------------
        Default_Plugin_SysBox::copyUsersUploadDir();

        //----------------- Set session ---------------
        // Start session
        Zend_Session::start();
        // Install option in order to prevent re-execution
        // Zend_Session::start() when calling (new Zend_Session_Namespace)
        Zend_Session::setOptions(array('strict' => true));

        // Obtain an instance session object for the appropriate namespace
        $Zend_Auth = new Zend_Session_Namespace('Zend_Auth');

        // Save to Registry
        Zend_Registry::set("Zend_Auth", $Zend_Auth);

        // Add a new type of resource controllers for plug-ins
        //$autoloader->addResourceType('cplugins', 'controllers/plugins', 'Controller_Plugins');
        //---- Configuring user authentication -----
        $auth = Zend_Auth::getInstance();
        $auth->setStorage(new Zend_Auth_Storage_Session());

        //------ Registering plugins ---------
        // Start 'FrontController'
        $this->bootstrap('FrontController');

        $front = Zend_Controller_Front::getInstance();

        // The plugin checks the user's access to resources
        $front->registerPlugin(
                new Default_Plugin_AclManager($auth));

        //------------ Configure language translation -------------

        $translate = new Zend_Translate('array', APPLICATION_PATH . '/languages/ru/My_Messages.php', 'ru');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/ru/Zend_Validate.php', 'ru');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/ru/My_Validate.php', 'ru');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/uk/My_Messages.php', 'uk');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/uk/Zend_Validate.php', 'uk');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/uk/My_Validate.php', 'uk');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/en/My_Messages.php', 'en');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/en/Zend_Validate.php', 'en');
        $translate->addTranslation(
                APPLICATION_PATH . '/languages/en/My_Validate.php', 'en');

        //------------ Configure language translation modules -------------
        $translate->addTranslation(
                APPLICATION_PATH . '/modules/hr/languages/ru/My_Messages.php', 'ru');
        $translate->addTranslation(
                APPLICATION_PATH . '/modules/hr/languages/uk/My_Messages.php', 'uk');
        $translate->addTranslation(
                APPLICATION_PATH . '/modules/hr/languages/en/My_Messages.php', 'en');

        // Set the default translation language
        if (!isset($Zend_Auth->translate_locale)) {
            $Zend_Auth->translate_locale = $config['user']['locale'];
        } else {
            $locale = $Zend_Auth->translate_locale;
            $newLocal = Default_Plugin_SysBox::isUpdateTranslateLocale($locale);
            if (!$newLocal === FALSE) {
                $Zend_Auth->translate_locale = $newLocal;
            }
        }
        $translate->setLocale($Zend_Auth->translate_locale);

        // Save to Registry
        Zend_Registry::set('Zend_Translate', $translate);

        //------------ Configure site localization -------------

        // Get type localization
        $paramLocal = Default_Plugin_SysBox::getLocalParam(
                        $Zend_Auth->translate_locale);
        // Set localization
        $locale = new Zend_Locale($paramLocal);
        // Set timezone
        date_default_timezone_set($config['user']['timezone']);
        // Save to Registry
        Zend_Registry::set('Zend_Locale', $locale);

        //------------ Set the color scheme of the site -------------
        if (!isset($Zend_Auth->user_scheme)) {
            $Zend_Auth->user_scheme = $config['user']['scheme'];
        } else {
            $scheme = $Zend_Auth->user_scheme;
            $newScheme = Default_Plugin_SysBox::getUserScheme($scheme);
            if ($newScheme !== $scheme) {
                $Zend_Auth->user_scheme = $newScheme;
            }
        }

        //---- Defining script execution time ----
        $infoProfiler = Default_Plugin_SysBox::Translate("Время выполнения") . " Bootstrap_initAutoload(): ";
        Default_Plugin_SysBox::profilerTime2Registry($_startTime, $infoProfiler);

        return $autoloader;
    }

    /**
     * Initialization routes
     *
     * @return void
     */
    protected function _initRouter() {

        $_startTime = microtime(1);

        $front = Zend_Controller_Front::getInstance();

        // setup the route for user home pages
        $route = new Zend_Controller_Router_Route('user/:username/:action/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'index'));

        $front->getRouter()->addRoute('user', $route);

        // set up the route for viewing blog posts
        $route = new Zend_Controller_Router_Route(
                'user/:username/view/:url/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'view')
        );

        $front->getRouter()->addRoute('post', $route);

        // set up the route for viewing monthly archives
        $route = new Zend_Controller_Router_Route(
                'user/:username/archive/:year/:month/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'archive')
        );

        $front->getRouter()->addRoute('archive', $route);

        // set up the route for tag blog posts
        $route = new Zend_Controller_Router_Route(
                'user/:username/tag/:tag/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'tag')
        );

        $front->getRouter()->addRoute('tagspace', $route);

        // set up the route for feed tag blog posts
        $route = new Zend_Controller_Router_Route(
                'user/:username/feed/:tag/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'feed')
        );

        $front->getRouter()->addRoute('feed_tag', $route);

        // set up the route for images blog post
        $route = new Zend_Controller_Router_Route(
                'user/:username/post/:post_id/images/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'images')
        );

        $front->getRouter()->addRoute('get_images', $route);

        // set up the route for audios blog post
        $route = new Zend_Controller_Router_Route(
                'user/:username/post/:post_id/audios/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'audios')
        );

        $front->getRouter()->addRoute('get_audios', $route);

        // set up the route for videos blog post
        $route = new Zend_Controller_Router_Route(
                'user/:username/post/:post_id/videos/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'videos')
        );

        $front->getRouter()->addRoute('get_videos', $route);

        // set up the route for comments blog post
        $route = new Zend_Controller_Router_Route(
                'user/:username/post/:post_id/comments/*', array(
            'module' => 'default',
            'controller' => 'user',
            'action' => 'comments')
        );

        $front->getRouter()->addRoute('get_comments', $route);

        // set up the route for all users tag blog posts
        $route = new Zend_Controller_Router_Route(
                'user/all/tag/:tag/*', array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'tag')
        );

        $front->getRouter()->addRoute('tags_all', $route);

        // set up the route for  all users  tag blog posts
        $route = new Zend_Controller_Router_Route(
                'user/all/feed/:tag/*', array(
            'module' => 'default',
            'controller' => 'index',
            'action' => 'feed')
        );

        $front->getRouter()->addRoute('feed_tag_all', $route);

        //---- Defining script execution time ----
        $infoProfiler = Default_Plugin_SysBox::Translate("Время выполнения") . " Bootstrap_initRouter(): ";
        Default_Plugin_SysBox::profilerTime2Registry($_startTime, $infoProfiler);
    }

    /**
     * Initialization View
     *
     * @return void
     */
    protected function _initViews() {
        //-------------

        $_startTime = microtime(1);

        $this->bootstrap('view');
        //!!!! Initialization Smarty. It is performed in the class - Default_Plugin_AclManager
        //---- Defining script execution time ----
        $infoProfiler = Default_Plugin_SysBox::Translate("Время выполнения") . " Bootstrap_initViews(): ";
        Default_Plugin_SysBox::profilerTime2Registry($_startTime, $infoProfiler);
    }

    /**
     * Initialization DB
     *
     * @return void
     */
    protected function _initDb() {

        $_startTime = microtime(1);

        $arrParam = array();
        //--------------------
        try {

            //------- Copy the database, if needed ------------
            Default_Plugin_SysBox::copyDataBase();

            // Get parameters for the database connection
            $arrParam = $this->_options['resources']['db']['params'];

            // Connection to DB
            $db = Zend_Db::factory(
                            "PDO_SQLITE", $arrParam);
            $db->getConnection();
            // Setting the default adapter class heirs Zend_Db_Table_Abstract
            Zend_Db_Table_Abstract::setDefaultAdapter($db);
            // Save to Registry
            Zend_Registry::set('db', $db);

            //---- Defining script execution time ----
            $infoProfiler = Default_Plugin_SysBox::Translate("Время выполнения") . " Bootstrap_initDb(): ";
            Default_Plugin_SysBox::profilerTime2Registry($_startTime, $infoProfiler);

        } catch (Zend_Db_Adapter_Exception $e) {
            throw $e;
        } catch (Zend_Exception $e) {
            throw $e;
        }
    }

    /**
     * Initialization Log, Search, KCFinder
     *
     * @return void
     */
    protected function _initLog() {
        $params = array();
        //------------------
        $_startTime = microtime(1);

        //Получим конфигурацию
        $config = $this->_options;

        //----- Create Zend_Log object -----
        $columnMapping = array(
            'ts' => 'timestamp',
            'msg' => 'message',
            'pr' => 'priority',
            'pr_name' => 'priorityName');

        $countMsg = $config['logging']['log']['max_rows'];
        $countEx = $config['logging']['exeption']['max_rows'];
        $countStat = $config['logging']['statistics']['max_rows'];

        // Get DB
        $db = Zend_Registry::get('db');
        // Set params
        $params['db'] = $db;
        $params['columnMap'] = $columnMapping;

        // Create writer for DB
        $params['table'] = 'log_msg';
        $params['max_rows'] = $countMsg;
        $writerMsg = new Default_Model_Log($params);
        $params['table'] = 'log_error';
        $params['max_rows'] = $countEx;
        $writerEx = new Default_Model_Log($params);
        $params['table'] = 'log_stat';
        $params['max_rows'] = $countStat;
        $writerStat = new Default_Model_Log($params);

        // Create logers
        $logMsg = new Zend_Log($writerMsg);
        $logEx = new Zend_Log($writerEx);
        $logStat = new Zend_Log($writerStat);

        // Adding new priorities for the $logMsg
        $logMsg->addPriority('LOGIN_OK', 8);
        $logMsg->addPriority('LOGIN_ERR', 9);
        $logMsg->addPriority('LOGOUT', 10);
        $logMsg->addPriority('REG_OK', 11);
        $logMsg->addPriority('REG_ERR', 12);
        $logMsg->addPriority('DETAILS_OK', 13);
        $logMsg->addPriority('FETCHPASS_COMPLETE_OK', 14);
        $logMsg->addPriority('FETCHPASS_COMPLETE_ERR', 15);
        $logMsg->addPriority('FETCHPASS_CONFIRM_OK', 16);
        $logMsg->addPriority('FETCHPASS_CONFIRM_ERR', 17);
        $logMsg->addPriority('MAIL_OK', 18);
        $logMsg->addPriority('MAIL_ERR', 19);
        $logMsg->addPriority('DB_SAVE_ERR', 20);
        $logMsg->addPriority('DB_DELETE_ERR', 21);
        $logMsg->addPriority('POST_EDIT', 22);
        $logMsg->addPriority('POST_SET_STATUS', 23);
        $logMsg->addPriority('ADMIN_POST_EDIT', 24);
        $logMsg->addPriority('ADMIN_ROW_UPDATE', 25);
        $logMsg->addPriority('ADMIN_ROW_INSERT', 26);
        $logMsg->addPriority('ADMIN_ROW_DELETE', 27);
        $logMsg->addPriority('MY_MSG', 28);

        // Adding new priorities for the $logStat
        $logStat->addPriority('LOGIN_OK', 8);
        $logStat->addPriority('LOGIN_ERR', 9);
        $logStat->addPriority('MAIL_OK', 10);
        $logStat->addPriority('FETCHPASS_COMPLETE_OK', 11);
        $logStat->addPriority('FETCHPASS_COMPLETE_ERR', 12);
        $logStat->addPriority('FETCHPASS_CONFIRM_OK', 13);
        $logStat->addPriority('FETCHPASS_CONFIRM_ERR', 14);
        $logStat->addPriority('POST_OPEN', 15);
        $logStat->addPriority('VIDEO_PLAY', 16);
        $logStat->addPriority('AUDIO_PLAY', 17);

        $emailParams = $config['logging']['email'];
        if ($emailParams['send']) {

            $mail = Default_Plugin_SysBox::createMail($emailParams);

            $writer = new Zend_Log_Writer_Mail($mail);

            $my_request = Default_Plugin_SysBox::getUrlRequest();
            if (!$emailParams['subject'])
                $writer->setSubjectPrependText('Errors request - ' . $my_request);

            $writer->addFilter(Zend_Log::EMERG);
            $writer->addFilter(Zend_Log::ALERT);
            $writer->addFilter(Zend_Log::CRIT);
            $writer->addFilter(Zend_Log::ERR);

            $logger->addWriter($writer);
        }

        // Save to Registry
        Zend_Registry::set("Zend_Log", $logMsg);
        Zend_Registry::set("Zend_LogEx", $logEx);
        Zend_Registry::set("Zend_LogStat", $logStat);

        // Remember in the session array of search results
        $Zend_Auth = Zend_Registry::get("Zend_Auth");
        if (!$Zend_Auth->search) {
            $Zend_Auth->search = array();
        }

        //------------ Configure default search -------------

        // Establish a query analyzer in the coding Utf8
        Zend_Search_Lucene_Analysis_Analyzer::setDefault(
                new Zend_Search_Lucene_Analysis_Analyzer_Common_Utf8_CaseInsensitive());

        //------ Initialization file manager -------------
        Default_Plugin_SysBox::iniKCFinder();

        //---- Defining script execution time ----
        $infoProfiler = Default_Plugin_SysBox::Translate("Время выполнения") . " Bootstrap_initLog(): ";
        Default_Plugin_SysBox::profilerTime2Registry($_startTime, $infoProfiler);
    }

    /**
     * Initialization test
     *
     * @return void
     */
    protected function _initTest() {

    }
}


text:
<?php

namespace JoiPolloi\Bundle\JsonValidationBundle\Annotation;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\ConfigurationAnnotation;

/**
 * Validate JSON annotation @ValidateJson()
 *
 * @Annotation
 * @Target({"METHOD"})
 * @author John Noel <john.noel@joipolloi.com>
 * @package JsonValidationBundle
 */
class ValidateJson extends ConfigurationAnnotation
{
    /**
     * The path to the JSON schema
     *
     * @var string
     */
    private $path;
    /**
     * Whether an empty JSON request value is valid
     *
     * @var bool
     */
    private $emptyIsValid = false;
    /**
     * Only validate on certain HTTP method(s)
     *
     * @var array
     */
    private $methods = [];

    /**
     * @param array $data An array of key/value parameters
     * @throws BadMethodCallException
     * @see Symfony\Component\Routing\Annotation\Route
     */
    public function __construct(array $data)
    {
        if (isset($data['value'])) {
            $data['path'] = $data['value'];
            unset($data['value']);
        }

        parent::__construct($data);
    }

    public function setPath(string $path)
    {
        $this->path = $path;
    }

    public function getPath() : string
    {
        return $this->path;
    }

    public function setEmptyIsValid(bool $emptyIsValid)
    {
        $this->emptyIsValid = $emptyIsValid;
    }

    public function getEmptyIsValid() : bool
    {
        return $this->emptyIsValid;
    }

    public function setMethods($methods)
    {
        if (is_string($methods)) {
            $methods = [ $methods ];
        }

        $this->methods = $methods;
    }

    public function getMethods() : array
    {
        return $this->methods;
    }

    /**
     * {@inheritDoc}
     */
    public function getAliasName()
    {
        return 'validate_json';
    }

    /**
     * {@inheritDoc}
     */
    public function allowArray()
    {
        return false;
    }
}


text:
![Travis CI](https://travis-ci.org/ShezHsky/Countdown.svg?branch=master)

Countdown application for iOS.


text:
package skiplist

import (
	"math"
	"math/rand"
	"time"
)

const (
	// Suitable for math.Floor(math.Pow(math.E, 18)) == 65659969 elements in list
	DefaultMaxLevel    int     = 18
	DefaultProbability float64 = 1 / math.E
)

// Front returns the head node of the list.
func (list *SkipList) Front() *Element {
	return list.next[0]
}

// Set inserts a value in the list with the specified key, ordered by the key.
// If the key exists, it updates the value in the existing node.
// Returns a pointer to the new element.
// Locking is optimistic and happens only after searching.
func (list *SkipList) Set(key float64, value interface{}) *Element {
	list.mutex.Lock()
	defer list.mutex.Unlock()

	var element *Element
	prevs := list.getPrevElementNodes(key)

	if element = prevs[0].next[0]; element != nil && element.key <= key {
		element.value = value
		return element
	}

	element = &Element{
		elementNode: elementNode{
			next: make([]*Element, list.randLevel()),
		},
		key:   key,
		value: value,
	}

	for i := range element.next {
		element.next[i] = prevs[i].next[i]
		prevs[i].next[i] = element
	}

	list.Length++
	return element
}

// Get finds an element by key. It returns element pointer if found, nil if not found.
// Locking is optimistic and happens only after searching with a fast check for deletion after locking.
func (list *SkipList) Get(key float64) *Element {
	list.mutex.Lock()
	defer list.mutex.Unlock()

	var prev *elementNode = &list.elementNode
	var next *Element

	for i := list.maxLevel - 1; i >= 0; i-- {
		next = prev.next[i]

		for next != nil && key > next.key {
			prev = &next.elementNode
			next = next.next[i]
		}
	}

	if next != nil && next.key <= key {
		return next
	}

	return nil
}

// Remove deletes an element from the list.
// Returns removed element pointer if found, nil if not found.
// Locking is optimistic and happens only after searching with a fast check on adjacent nodes after locking.
func (list *SkipList) Remove(key float64) *Element {
	list.mutex.Lock()
	defer list.mutex.Unlock()
	prevs := list.getPrevElementNodes(key)

	// found the element, remove it
	if element := prevs[0].next[0]; element != nil && element.key <= key {
		for k, v := range element.next {
			prevs[k].next[k] = v
		}

		list.Length--
		return element
	}

	return nil
}

// getPrevElementNodes is the private search mechanism that other functions use.
// Finds the previous nodes on each level relative to the current Element and
// caches them. This approach is similar to a "search finger" as described by Pugh:
// http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.524
func (list *SkipList) getPrevElementNodes(key float64) []*elementNode {
	var prev *elementNode = &list.elementNode
	var next *Element

	prevs := list.prevNodesCache

	for i := list.maxLevel - 1; i >= 0; i-- {
		next = prev.next[i]

		for next != nil && key > next.key {
			prev = &next.elementNode
			next = next.next[i]
		}

		prevs[i] = prev
	}

	return prevs
}

// SetProbability changes the current P value of the list.
// It doesn't alter any existing data, only changes how future insert heights are calculated.
func (list *SkipList) SetProbability(newProbability float64) {
	list.probability = newProbability
	list.probTable = probabilityTable(list.probability, list.maxLevel)
}

func (list *SkipList) randLevel() (level int) {
	// Our random number source only has Int63(), so we have to produce a float64 from it
	// Reference: https://golang.org/src/math/rand/rand.go#L150
	r := float64(list.randSource.Int63()) / (1 << 63)

	level = 1
	for level < list.maxLevel && r < list.probTable[level] {
		level++
	}
	return
}

// probabilityTable calculates in advance the probability of a new node having a given level.
// probability is in [0, 1], MaxLevel is (0, 64]
// Returns a table of floating point probabilities that each level should be included during an insert.
func probabilityTable(probability float64, MaxLevel int) (table []float64) {
	for i := 1; i <= MaxLevel; i++ {
		prob := math.Pow(probability, float64(i-1))
		table = append(table, prob)
	}
	return table
}

// NewWithMaxLevel creates a new skip list with MaxLevel set to the provided number.
// maxLevel has to be int(math.Ceil(math.Log(N))) for DefaultProbability (where N is an upper bound on the
// number of elements in a skip list). See http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.17.524
// Returns a pointer to the new list.
func NewWithMaxLevel(maxLevel int) *SkipList {
	if maxLevel < 1 || maxLevel > 64 {
		panic("maxLevel for a SkipList must be a positive integer <= 64")
	}

	return &SkipList{
		elementNode:    elementNode{next: make([]*Element, maxLevel)},
		prevNodesCache: make([]*elementNode, maxLevel),
		maxLevel:       maxLevel,
		randSource:     rand.New(rand.NewSource(time.Now().UnixNano())),
		probability:    DefaultProbability,
		probTable:      probabilityTable(DefaultProbability, maxLevel),
	}
}

// New creates a new skip list with default parameters. Returns a pointer to the new list.
func New() *SkipList {
	return NewWithMaxLevel(DefaultMaxLevel)
}


text:
import {Component, Input, OnInit} from 'angular2/core';
import {RouteParams} from 'angular2/router';
import {Stck} from './stck';
import {StcksService} from './stcks.service';

@Component({
	selector: 'stck-editor',
	template: `
		Acquiring data...

{{stck.sid}} on {{stck.date}}

profile

			age: <input [(ngModel)]=stck.age type=number placeholder=0.0 />

			weight: <input [(ngModel)]=stck.weight type=number placeholder=0.0 />k/lb

			height: <input [(ngModel)]=stck.height type=number placeholder=0.0 />in/cm

spec

			exercise: <input type=text placeholder=Barbell />

			mass: <input type=number placeholder=0.0 />

			reps: <input type=number placeholder=0 />

			duration: <input type=number placeholder=0.0 />seconds

			set: <input type=number placeholder=0 />

meta

			circuit: <input type=number placeholder=0 />

			tags: <input type=text placeholder=Blue />

	`
})

export class StckEditorComponent implements OnInit {

	@Input() stck: Stck;

	constructor(
		private _stcksService: StcksService,
		private _routeParams: RouteParams
	) {

	}

	ngOnInit() {
		let sid = +this._routeParams.get('sid');
		this._stcksService.getStck(sid)
			.then(stck => this.stck = stck);
	}

}