text:
using System;
using System.Collections.Generic;

namespace NArchitecture
{
    public class ServiceBusOptions
    {
        private IDictionary<Type, string> PolicyMap { get; } =
            new Dictionary<Type, string>();

        public EventComposition Events { get; }
        public RequestComposition Requests { get; }
        public AuthorizationComposition Authorization { get; }

        public ServiceBusOptions()
        {
            Events = new EventComposition();
            Requests = new RequestComposition();
            Authorization = new AuthorizationComposition();
        }

        public void AddPolicyFor<TMessage>(string policy)
            where TMessage : IMessage
        {
            Guard.AgainstEmptyString(nameof(policy), policy);

            AddPolicyFor(typeof(TMessage), policy);
        }

        public void AddPolicyFor(Type messageType, string policy)
        {
            Guard.AgainstNull(nameof(messageType), messageType);
            Guard.AgainstEmptyString(nameof(policy), policy);

            PolicyMap[messageType] = policy;
        }

        public string GetPolicyFor(Type messageType)
        {
            Guard.AgainstNull(nameof(messageType), messageType);

            if (!PolicyMap.ContainsKey(messageType))
            {
                return null;
            }

            return PolicyMap[messageType];
        }
    }
}


text:
package com.communote.server.core.vo.query.java.note;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

import com.communote.common.matcher.Matcher;
import com.communote.server.api.core.note.NoteData;
import com.communote.server.api.core.tag.TagData;

/**
 * Matcher for {@link com.communote.server.core.vo.query.TimelineQueryParameters#getTagIds()}.
 *
 * @author Communote GmbH - http://www.communote.com/
 */
public class TagIdsMatcher extends Matcher<NoteData> {

    private final Set<Long> tagIds = new HashSet<Long>();

    /**
     * Constructor.
     *
     * @param tagIds
     *            Id's of the tags, that have to match. Might be null, which means all tags will
     *            match.
     */
    public TagIdsMatcher(Collection<Long> tagIds) {
        if (tagIds != null) {
            this.tagIds.addAll(tagIds);
        }
    }

    /**
     * Constructor.
     *
     * @param tagIds
     *            Id's of the tags, that have to match. Might be null, which means all tags will
     *            match.
     */
    public TagIdsMatcher(Long... tagIds) {
        if (tagIds != null) {
            for (Long tagId : tagIds) {
                this.tagIds.add(tagId);
            }
        }
    }

    /**
     * {@inheritDoc}
     *
     * @return True, if all tags match or if no tags are given to match.
     *
     */
    @Override
    public boolean matches(NoteData entity) {
        if (tagIds.isEmpty()) {
            return true; // all tags are allowed.
        }
        Set<Long> entityTagIds = new HashSet<Long>();
        for (TagData tag : entity.getTags()) {
            entityTagIds.add(tag.getId());
        }
        for (Long tagId : tagIds) {
            if (!entityTagIds.contains(tagId)) {
                return false;
            }
        }
        return true;
    }
}

redpajama_set_name: RedPajamaGithub


text:
module Bodega
  module ApplicationHelper
    def self.included(base)
      base.class_eval do
        alias :method_missing_without_bodega :method_missing
        alias :method_missing :method_missing_with_bodega
      end
    end

    protected
    def method_missing_with_bodega(method_name, *args)
      if method_name.to_s =~ /.+_(url|path)$/ && main_app.respond_to?(method_name)
        return main_app.send(method_name, *args)
      end
      method_missing_without_bodega method_name, *args
    end
  end
end


text: """Couple django-generic-m2m and django-queryset-sequence for DAL."""


text:
<?php

declare(strict_types=1);

namespace Hostnet\Component\AccessorGenerator\Generator;

use Hostnet\Component\AccessorGenerator\Generator\fixtures\Cart;
use Hostnet\Component\AccessorGenerator\Generator\fixtures\Customer;
use PHPUnit\Framework\TestCase;

class CartTest extends TestCase
{
    public function testSetCustomer(): void
    {
        $cart     = new Cart();
        $customer = new Customer();

        $cart->setCustomer($customer);
        self::assertSame($customer, $cart->getCustomer());
    }

    public function testGetCustomerEmpty(): void
    {
        $cart = new Cart();
        self::assertNull($cart->getCustomer());
    }

    public function testGetCustomerTooManyArguments(): void
    {
        $cart = new Cart();

        $this->expectException(\BadMethodCallException::class);

        $cart->getCustomer(1);
    }

    public function testSetCustomerTooManyArguments(): void
    {
        $cart     = new Cart();
        $customer = new Customer();

        $this->expectException(\BadMethodCallException::class);

        $cart->setCustomer($customer, 2);
    }
}


text:
from __future__ import print_function

# __________________________________________________________________||

def profile_func(func, profile_out_path=None):
    import cProfile
    import pstats
    import StringIO
    pr = cProfile.Profile()
    pr.enable()
    func()
    pr.disable()
    s = StringIO.StringIO()
    sortby = 'cumulative'
    ps = pstats.Stats(pr, stream=s).strip_dirs().sort_stats(sortby)
    ps.print_stats()
    if profile_out_path is None:
        print(s.getvalue())
    else:
        with open(profile_out_path, 'w') as f:
            f.write(s.getvalue())
            f.close()

# __________________________________________________________________||


text:
class LookForBall : public State
{
	public:
	LookForBall();
	virtual ~LookForBall();

	virtual void Play() = 0;
};


text:
package com.sdm.facebook.model.type;

public enum TemplateType {
    button, generic, list, open_graph, receipt, airline_boardingpass, airline_checkin, airline_itinerary, airline_update;
}


text:
package hash

import "io"

// Hash is the common interface implemented by all hash functions.
//
// Hash implementations in the standard library (e.g. hash/crc32 and
// crypto/sha256) implement the encoding.BinaryMarshaler and
// encoding.BinaryUnmarshaler interfaces. Marshaling a hash implementation
// allows its internal state to be saved and used for additional processing
// later, without having to re-write the data previously written to the hash.
// The hash state may contain portions of the input in its original form,
// which users are expected to handle for any possible security implications.
//
// Compatibility: Any future changes to hash or crypto packages will endeavor
// to maintain compatibility with state encoded using previous versions.
// That is, any released versions of the packages should be able to
// decode data written with any previously released version,
// subject to issues such as security fixes.
// See the Go compatibility document for background: https://golang.org/doc/go1compat
type Hash interface {
	// Write (via the embedded io.Writer interface) adds more data to the running hash.
	// It never returns an error.
	io.Writer

	// Sum appends the current hash to b and returns the resulting slice.
	// It does not change the underlying hash state.
	Sum(b []byte) []byte

	// Reset resets the Hash to its initial state.
	Reset()

	// Size returns the number of bytes Sum will return.
	Size() int

	// BlockSize returns the hash's underlying block size.
	// The Write method must be able to accept any amount
	// of data, but it may operate more efficiently if all writes
	// are a multiple of the block size.
	BlockSize() int
}

// Hash32 is the common interface implemented by all 32-bit hash functions.
type Hash32 interface {
	Hash
	Sum32() uint32
}

// Hash64 is the common interface implemented by all 64-bit hash functions.
type Hash64 interface {
	Hash
	Sum64() uint64
}


text:
package com.wangwenjun.java8;

import java.util.concurrent.CompletableFuture;

/***************************************
 * @author:Alex Wang
 * @Date:2016/11/13 QQ:532500648
 * QQ交流群:286081824
 ***************************************/
public class CompletableFutureInAction4 {

    public static void main(String[] args) throws InterruptedException {

        /*CompletableFuture.supplyAsync(() -> 1)
                .thenApply(i -> Integer.sum(i, 10))
                .whenComplete((v, t) -> System.out.println(v));*/

/*        CompletableFuture.supplyAsync(() -> 1)
                .handle((v, t) -> Integer.sum(v, 10))
                .whenComplete((v, t) -> System.out.println(v))
                .thenRun(System.out::println);*/
/*
        CompletableFuture.supplyAsync(() -> 1)
                .thenApply(i -> Integer.sum(i, 10))
                .thenAccept(System.out::println);*/
/*
        CompletableFuture.supplyAsync(() -> 1)
                .thenCompose(i -> CompletableFuture.supplyAsync(() -> 10 * i))
                .thenAccept(System.out::println);*/

/*        CompletableFuture.supplyAsync(() -> 1)
                .thenCombine(CompletableFuture.supplyAsync(() -> 2.0d), (r1, r2) -> r1 + r2)
                .thenAccept(System.out::println);*/

        CompletableFuture.supplyAsync(() -> 1)
                .thenAcceptBoth(CompletableFuture.supplyAsync(() -> 2.0d), (r1, r2) -> {
                    System.out.println(r1);
                    System.out.println(r2);
                    System.out.println(r1 + r2);
                });

        Thread.sleep(1000L);
    }
}


text:
#pragma once
#include <aws/iotsitewise/IoTSiteWise_EXPORTS.h>
#include <aws/iotsitewise/model/TumblingWindow.h>
#include <utility>

namespace Aws
{
namespace Utils
{
namespace Json
{
  class JsonValue;
  class JsonView;
} // namespace Json
} // namespace Utils
namespace IoTSiteWise
{
namespace Model
{

  /**
   *
Contains a time interval window used for data aggregate computations (for
   * example, average, sum, count, and so on).

See Also:
   AWS
   * API Reference

   */
  class AWS_IOTSITEWISE_API MetricWindow
  {
  public:
    MetricWindow();
    MetricWindow(Aws::Utils::Json::JsonView jsonValue);
    MetricWindow& operator=(Aws::Utils::Json::JsonView jsonValue);
    Aws::Utils::Json::JsonValue Jsonize() const;

    /**
     *
The tumbling time interval window.

     */
    inline const TumblingWindow& GetTumbling() const{ return m_tumbling; }

    /**
     *
The tumbling time interval window.

     */
    inline bool TumblingHasBeenSet() const { return m_tumblingHasBeenSet; }

    /**
     *
The tumbling time interval window.

     */
    inline void SetTumbling(const TumblingWindow& value) { m_tumblingHasBeenSet = true; m_tumbling = value; }

    /**
     *
The tumbling time interval window.

     */
    inline void SetTumbling(TumblingWindow&& value) { m_tumblingHasBeenSet = true; m_tumbling = std::move(value); }

    /**
     *
The tumbling time interval window.

     */
    inline MetricWindow& WithTumbling(const TumblingWindow& value) { SetTumbling(value); return *this;}

    /**
     *
The tumbling time interval window.

     */
    inline MetricWindow& WithTumbling(TumblingWindow&& value) { SetTumbling(std::move(value)); return *this;}

  private:

    TumblingWindow m_tumbling;
    bool m_tumblingHasBeenSet = false;
  };

} // namespace Model
} // namespace IoTSiteWise
} // namespace Aws


text:
from setuptools import setup
import os
here = os.path.abspath(os.path.dirname(__file__))
try:
    README = open(os.path.join(here, 'README.rst')).read()
except:
    README = ""

setup(name='paytm',
      version='0.1.8',
      description='paytm payment gateway',
      long_description=README,
      url='http://github.com/harishbisht/paytm',
      author='Harish Bisht',
      author_email='harish@pickrr.com',
      license='MIT',
      packages=['paytm'],
      install_requires=[
          'requests','pycrypto'
      ],
      zip_safe=False)


text:
package org.optaplanner.examples.nqueens.domain;

import java.util.List;

import org.optaplanner.core.api.domain.solution.PlanningEntityCollectionProperty;
import org.optaplanner.core.api.domain.solution.PlanningScore;
import org.optaplanner.core.api.domain.solution.PlanningSolution;
import org.optaplanner.core.api.domain.solution.ProblemFactCollectionProperty;
import org.optaplanner.core.api.domain.valuerange.ValueRangeProvider;
import org.optaplanner.core.api.score.buildin.simple.SimpleScore;
import org.optaplanner.examples.common.domain.AbstractPersistable;
import org.optaplanner.persistence.xstream.api.score.buildin.simple.SimpleScoreXStreamConverter;

import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamConverter;

@PlanningSolution
@XStreamAlias("NQueens")
public class NQueens extends AbstractPersistable {

    private int n;

    private List<Column> columnList;
    private List<Row> rowList;

    private List<Queen> queenList;

    @XStreamConverter(SimpleScoreXStreamConverter.class)
    private SimpleScore score;

    public int getN() {
        return n;
    }

    public void setN(int n) {
        this.n = n;
    }

    @ProblemFactCollectionProperty
    public List<Column> getColumnList() {
        return columnList;
    }

    public void setColumnList(List<Column> columnList) {
        this.columnList = columnList;
    }

    @ValueRangeProvider(id = "rowRange")
    @ProblemFactCollectionProperty
    public List<Row> getRowList() {
        return rowList;
    }

    public void setRowList(List<Row> rowList) {
        this.rowList = rowList;
    }

    @PlanningEntityCollectionProperty
    public List<Queen> getQueenList() {
        return queenList;
    }

    public void setQueenList(List<Queen> queenList) {
        this.queenList = queenList;
    }

    @PlanningScore
    public SimpleScore getScore() {
        return score;
    }

    public void setScore(SimpleScore score) {
        this.score = score;
    }

    // ************************************************************************
    // Complex methods
    // ************************************************************************

}


text:
package org.osc.core.broker.service;

import javax.persistence.EntityManager;

import org.osc.core.broker.job.Job;
import org.osc.core.broker.job.JobEngine;
import org.osc.core.broker.job.TaskGraph;
import org.osc.core.broker.service.api.SetNetworkSettingsServiceApi;
import org.osc.core.broker.service.dto.NetworkSettingsDto;
import org.osc.core.broker.service.request.SetNetworkSettingsRequest;
import org.osc.core.broker.service.response.SetNetworkSettingsResponse;
import org.osc.core.broker.service.tasks.network.IpChangePropagateMetaTask;
import org.osc.core.broker.service.validator.NetworkSettingsDtoValidator;
import org.osc.core.broker.util.NetworkUtil;
import org.osc.core.broker.util.ValidateUtil;
import org.slf4j.LoggerFactory;
import org.osc.core.broker.util.network.NetworkSettingsApi;
import org.osc.core.server.Server;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import org.slf4j.Logger;

/**
 * This component exposes both the API and the implementation so that the
 * {@link SetNATSettingsService} can call the {@link #startIpPropagateJob()}
 * method. This could be removed if {@link #startIpPropagateJob()} were made
 * part of the {@link SetNetworkSettingsServiceApi}
 */
@Component(service={SetNetworkSettingsService.class, SetNetworkSettingsServiceApi.class})
public class SetNetworkSettingsService extends ServiceDispatcher<SetNetworkSettingsRequest, SetNetworkSettingsResponse>
        implements SetNetworkSettingsServiceApi {

    private static final Logger log = LoggerFactory.getLogger(SetNetworkSettingsService.class);

    @Reference
    private Server server;

    @Reference
    private IpChangePropagateMetaTask ipChangePropagateMetaTask;

    @Override
    public SetNetworkSettingsResponse exec(SetNetworkSettingsRequest request, EntityManager em) throws Exception {

        NetworkSettingsApi networkSettingsApi = new NetworkSettingsApi();
        NetworkSettingsDto networkSettingsDto = new NetworkSettingsDto();
        networkSettingsDto.setDhcp(request.isDhcp());
        if (!request.isDhcp()) {
            networkSettingsDto.setHostIpAddress(request.getHostIpAddress());
            networkSettingsDto.setHostSubnetMask(request.getHostSubnetMask());
            networkSettingsDto.setHostDefaultGateway(request.getHostDefaultGateway());
            networkSettingsDto.setHostDnsServer1(request.getHostDnsServer1());
            networkSettingsDto.setHostDnsServer2(request.getHostDnsServer2());
            validate(request);
        }
        boolean isIpChanged = !NetworkUtil.getHostIpAddress().equals(request.getHostIpAddress());

        if(isIpChanged) {
            // If IP is changed, these connections are no longer valid, shutdown so they get restarted again.
            this.server.shutdownRabbitMq();
            this.server.shutdownWebsocket();
        }

        networkSettingsApi.setNetworkSettings(networkSettingsDto);
        SetNetworkSettingsResponse response = new SetNetworkSettingsResponse();

        /*
         * IP address change needs to get propagated to security managers
         */
        if (isIpChanged) {
            response.setJobId(startIpPropagateJob());
            this.server.startRabbitMq();
            this.server.startWebsocket();
        }

        return response;
    }

    void validate(SetNetworkSettingsRequest req) throws Exception {
        NetworkSettingsDtoValidator.checkForNullFields(req);
        // check for valid IP address format
        ValidateUtil.checkForValidIpAddressFormat(req.getHostIpAddress());
        ValidateUtil.checkForValidIpAddressFormat(req.getHostSubnetMask());
        ValidateUtil.checkForValidIpAddressFormat(req.getHostDefaultGateway());
        if (!req.getHostDnsServer1().isEmpty()) {
            ValidateUtil.checkForValidIpAddressFormat(req.getHostDnsServer1());
        }
        if (!req.getHostDnsServer2().isEmpty()) {
            ValidateUtil.checkForValidIpAddressFormat(req.getHostDnsServer2());
        }

    }

    public Long startIpPropagateJob() throws Exception {

        log.info("Start propagating new IP(" + NetworkUtil.getHostIpAddress() + ") to all managers");

        TaskGraph tg = new TaskGraph();

        tg.addTask(this.ipChangePropagateMetaTask.create());

        Job job = JobEngine.getEngine().submit(
                "Updating " + Server.SHORT_PRODUCT_NAME
                        + " IP to Security Manager(s)", tg, null);
        log.info("Done submitting with jobId: " + job.getId());
        return job.getId();

    }
}


text:
package com.jim.novel.model;

import java.util.Date;

public class Chapter {
    private Integer chapterId;

    private Integer articleId;

    private String chapterTitle;

    private Integer commentCount;

    private Date createTime;

    private Date modifyTime;

    private String content;

    private Integer sort;

    public Integer getSort() {
        return sort;
    }

    public void setSort(Integer sort) {
        this.sort = sort;
    }

    public Integer getChapterId() {
        return chapterId;
    }

    public void setChapterId(Integer chapterId) {
        this.chapterId = chapterId;
    }

    public Integer getArticleId() {
        return articleId;
    }

    public void setArticleId(Integer articleId) {
        this.articleId = articleId;
    }

    public String getChapterTitle() {
        return chapterTitle;
    }

    public void setChapterTitle(String chapterTitle) {
        this.chapterTitle = chapterTitle == null ? null : chapterTitle.trim();
    }

    public Integer getCommentCount() {
        return commentCount;
    }

    public void setCommentCount(Integer commentCount) {
        this.commentCount = commentCount;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getModifyTime() {
        return modifyTime;
    }

    public void setModifyTime(Date modifyTime) {
        this.modifyTime = modifyTime;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content == null ? null : content.trim();
    }
}


text:
/**
 * Interaction for the pages templates
 */
jsBackend.template =
{
	// default position names
	defaultPositions: new Array('', 'main', 'left', 'right', 'top'),

	/**
	 * Kind of constructor
	 */
	init: function()
	{
		// add first default position
		if($('#position1').length === 0) jsBackend.template.addPosition();

		// first position can't be removed
		$('#position1').closest('.jsPosition').find('.jsDeletePosition').remove();

		// add handlers
		$(document).on('click', '.jsAddPosition', jsBackend.template.addPosition);
		$(document).on('click', '.jsAddBlock', jsBackend.template.addBlock);
		$(document).on('click', '.jsDeletePosition', jsBackend.template.deletePosition);
		$(document).on('click', '.jsDeleteBlock', jsBackend.template.deleteBlock);
	},

	/**
	 * Add a block to a position
	 */
	addBlock: function(e)
	{
		// prevent default event action
		e.preventDefault();

		// clone default extras dropdown
		var blockContainer = $('#type00').closest('.jsBlock').clone();

		// fetch position & block index
		var positionIndex = $(this).closest('.jsPosition').find('input[id^=position]').attr('id').replace('position', '');
		var blockIndex = $(this).closest('.jsBlocks').find('.jsBlock').length;

		// update for id & name
		$('#type00', blockContainer).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex);

		// if there are no blocks yet prepend blocks container
		if (0 == blockIndex) {
			$(this).closest('.jsBlocks').prepend(blockContainer);
			return;
		}

		// add to dom
		blockContainer.insertAfter($(this).closest('.jsBlocks').find('.jsBlock').last());
	},

	/**
	 * Add a position
	 */
	addPosition: function(e)
	{
		// prevent default event action
		if(e) e.preventDefault();

		// clone default position
		var positionContainer = $('#position0').closest('.jsPosition').clone();

		// set new index
		var index = $('#positions .jsPosition').length;

		// update for (label), id & name (input)
		$('input[id^=position]', positionContainer).attr('id', 'position' + index).attr('name', 'position_' + index);
		$('label[for^=position]', positionContainer).attr('for', 'position' + index);

		// remove default blocks
		$('.jsBlocks > .jsBlock', positionContainer).remove();

		// update default name
		$('#position' + index, positionContainer).val(jsBackend.template.defaultPositions[index]);

		// show position
		positionContainer.show();

		// add to dom
		positionContainer.insertAfter($('#positions .jsPosition:last'));
	},

	/**
	 * Delete a block in a position
	 */
	deleteBlock: function(e)
	{
		// prevent default event action
		e.preventDefault();

		// get blocks container
		var blocksContainer = $(this).closest('.jsBlocks');

		// delete container
		$(this).closest('.jsBlock').remove();

		// loop all remaining blocks
		$('.jsBlock', blocksContainer).each(function(i)
		{
			// fetch position & block index
			var positionIndex = $(this).closest('.jsPosition').prevAll('input[id^=position]').attr('id').replace('position', '');
			var blockIndex = $(this).prevAll('.jsBlock').length;

			// update for id & name
			$('select[id^=type]', this).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex);
		});
	},

	/**
	 * Delete a position
	 */
	deletePosition: function(e)
	{
		// prevent default event action
		e.preventDefault();

		// get positions container
		var positionsContainer = $(this).closest('#positions');

		// delete container
		$(this).closest('.jsPosition').remove();

		// loop all remaining positions
		$('.jsPosition', positionsContainer).each(function(i)
		{
			// fetch position index
			var positionIndex = i;

			// update for (label), id & name (input)
			$('input[id^=position]', this).attr('id', 'position' + positionIndex).attr('name', 'position_' + positionIndex);
			$('label[for^=position]', this).attr('for', 'position' + positionIndex);

			// loop all blocks
			$('.jsBlock', this).each(function(i)
			{
				// fetch block index
				var blockIndex = $(this).prevAll('.jsBlock').length;

				// update for id & name
				$('select[id^=type]', this).attr('id', 'type' + positionIndex + blockIndex).attr('name', 'type_' + positionIndex + '_' + blockIndex);
			});
		});
	}
};

$(jsBackend.template.init);


text:
module LanguageFilterable
  extend ActiveSupport::Concern

  included do
    belongs_to :language

    def self.filter_by_language_or_default(language = 'en')
      language = Language.find_with_id_or_iso_code(language)

      if language.nil? || language.default?
        find_default
      else
        find_by(language_id: language.id) || find_default
      end
    end

    def self.find_default
      find_by(language_id: Language.default.id)
    end
  end
end


text:
@org.junit.runner.RunWith(org.junit.runners.Parameterized.class)
public class Wrongsignature {
    @org.junit.runners.Parameterized.Parameters
    java.util.Collection <warning descr="Data provider method 'regExValues()' has an incorrect signature"><caret>regExValues</warning>() {
        return null;
    }
}


text:
namespace EncompassRest.LoanPipeline
{
    /// <summary>
    /// SortTerm
    /// </summary>
    public sealed class SortTerm : ExtensibleObject
    {
        /// <summary>
        /// SortTerm FieldName
        /// </summary>
#pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.
        public string FieldName { get; set; }
#pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable.

        /// <summary>
        /// SortTerm UseNull
        /// </summary>
        public bool UseNull { get; set; }
    }
}


text:
#ifndef UDATEINTERVALFORMAT_H
#define UDATEINTERVALFORMAT_H

#include "unicode/utypes.h"

#if !UCONFIG_NO_FORMATTING

#include "unicode/umisc.h"
#include "unicode/localpointer.h"

/**
 * \file
 * \brief C API: Format a date interval.
 *
 * A UDateIntervalFormat is used to format the range between two UDate values
 * in a locale-sensitive way, using a skeleton that specifies the precision and
 * completeness of the information to show. If the range smaller than the resolution
 * specified by the skeleton, a single date format will be produced. If the range
 * is larger than the format specified by the skeleton, a locale-specific fallback
 * will be used to format the items missing from the skeleton.
 *
 * For example, if the range is 2010-03-04 07:56 - 2010-03-04 19:56 (12 hours)
 * - The skeleton jm will produce
 *   for en_US, "7:56 AM - 7:56 PM"
 *   for en_GB, "7:56 - 19:56"
 * - The skeleton MMMd will produce
 *   for en_US, "Mar 4"
 *   for en_GB, "4 Mar"
 * If the range is 2010-03-04 07:56 - 2010-03-08 16:11 (4 days, 8 hours, 15 minutes)
 * - The skeleton jm will produce
 *   for en_US, "3/4/2010 7:56 AM - 3/8/2010 4:11 PM"
 *   for en_GB, "4/3/2010 7:56 - 8/3/2010 16:11"
 * - The skeleton MMMd will produce
 *   for en_US, "Mar 4-8"
 *   for en_GB, "4-8 Mar"
 *
 * Note:  the "-" characters in the above sample output will actually be
 * Unicode 2013, EN_DASH, in all but the last example.
 *
 * Note, in ICU 4.4 the standard skeletons for which date interval format data
 * is usually available are as follows; best results will be obtained by using
 * skeletons from this set, or those formed by combining these standard skeletons
 * (note that for these skeletons, the length of digit field such as d, y, or
 * M vs MM is irrelevant (but for non-digit fields such as MMM vs MMMM it is
 * relevant). Note that a skeleton involving h or H generally explicitly requests
 * that time style (12- or 24-hour time respectively). For a skeleton that
 * requests the locale's default time style (h or H), use 'j' instead of h or H.
 *   h, H, hm, Hm,
 *   hv, Hv, hmv, Hmv,
 *   d,
 *   M, MMM, MMMM,
 *   Md, MMMd,
 *   MEd, MMMEd,
 *   y,
 *   yM, yMMM, yMMMM,
 *   yMd, yMMMd,
 *   yMEd, yMMMEd
 *
 * Locales for which ICU 4.4 seems to have a reasonable amount of this data
 * include:
 *   af, am, ar, be, bg, bn, ca, cs, da, de (_AT), el, en (_AU,_CA,_GB,_IE,_IN...),
 *   eo, es (_AR,_CL,_CO,...,_US) et, fa, fi, fo, fr (_BE,_CH,_CA), fur, gsw, he,
 *   hr, hu, hy, is, it (_CH), ja, kk, km, ko, lt, lv, mk, ml, mt, nb, nl )_BE),
 *   nn, pl, pt (_PT), rm, ro, ru (_UA), sk, sl, so, sq, sr, sr_Latn, sv, th, to,
 *   tr, uk, ur, vi, zh (_SG), zh_Hant (_HK,_MO)
 */

/**
 * Opaque UDateIntervalFormat object for use in C programs.
 * @stable ICU 4.8
 */
struct UDateIntervalFormat;
typedef struct UDateIntervalFormat UDateIntervalFormat;  /**< C typedef for struct UDateIntervalFormat. @stable ICU 4.8 */

/**
 * Open a new UDateIntervalFormat object using the predefined rules for a
 * given locale plus a specified skeleton.
 * @param locale
 *            The locale for whose rules should be used; may be NULL for
 *            default locale.
 * @param skeleton
 *            A pattern containing only the fields desired for the interval
 *            format, for example "Hm", "yMMMd", or "yMMMEdHm".
 * @param skeletonLength
 *            The length of skeleton; may be -1 if the skeleton is zero-terminated.
 * @param tzID
 *            A timezone ID specifying the timezone to use. If 0, use the default
 *            timezone.
 * @param tzIDLength
 *            The length of tzID, or -1 if null-terminated. If 0, use the default
 *            timezone.
 * @param status
 *            A pointer to a UErrorCode to receive any errors.
 * @return
 *            A pointer to a UDateIntervalFormat object for the specified locale,
 *            or NULL if an error occurred.
 * @stable ICU 4.8
 */
U_STABLE UDateIntervalFormat* U_EXPORT2
udtitvfmt_open(const char*  locale,
              const UChar* skeleton,
              int32_t      skeletonLength,
              const UChar* tzID,
              int32_t      tzIDLength,
              UErrorCode*  status);

/**
 * Close a UDateIntervalFormat object. Once closed it may no longer be used.
 * @param formatter
 *            The UDateIntervalFormat object to close.
 * @stable ICU 4.8
 */
U_STABLE void U_EXPORT2
udtitvfmt_close(UDateIntervalFormat *formatter);

#if U_SHOW_CPLUSPLUS_API

U_NAMESPACE_BEGIN

/**
 * \class LocalUDateIntervalFormatPointer
 * "Smart pointer" class, closes a UDateIntervalFormat via udtitvfmt_close().
 * For most methods see the LocalPointerBase base class.
 *
 * @see LocalPointerBase
 * @see LocalPointer
 * @stable ICU 4.8
 */
U_DEFINE_LOCAL_OPEN_POINTER(LocalUDateIntervalFormatPointer, UDateIntervalFormat, udtitvfmt_close);

U_NAMESPACE_END

#endif

/**
 * Formats a date/time range using the conventions established for the
 * UDateIntervalFormat object.
 * @param formatter
 *            The UDateIntervalFormat object specifying the format conventions.
 * @param fromDate
 *            The starting point of the range.
 * @param toDate
 *            The ending point of the range.
 * @param result
 *            A pointer to a buffer to receive the formatted range.
 * @param resultCapacity
 *            The maximum size of result.
 * @param position
 *            A pointer to a UFieldPosition. On input, position->field is read.
 *            On output, position->beginIndex and position->endIndex indicate
 *            the beginning and ending indices of field number position->field,
 *            if such a field exists. This parameter may be NULL, in which case
 *            no field position data is returned.
 *            There may be multiple instances of a given field type in an
 *            interval format; in this case the position indices refer to the
 *            first instance.
 * @param status
 *            A pointer to a UErrorCode to receive any errors.
 * @return
 *            The total buffer size needed; if greater than resultLength, the
 *            output was truncated.
 * @stable ICU 4.8
 */
U_STABLE int32_t U_EXPORT2
udtitvfmt_format(const UDateIntervalFormat* formatter,
                UDate           fromDate,
                UDate           toDate,
                UChar*          result,
                int32_t         resultCapacity,
                UFieldPosition* position,
                UErrorCode*     status);

#ifndef U_HIDE_DRAFT_API
/**
 * Attributes and values to control the behavior of udtitvfmt_format.
 * @internal
 */
typedef enum UDateIntervalFormatAttribute {
    /**
     * @internal
     */
    UDTITVFMT_MINIMIZE_TYPE
} UDateIntervalFormatAttribute;

typedef enum UDateIntervalFormatAttributeValue {
    /**
     * Standard behavior, no additional minimization.
     * @internal
     */
    UDTITVFMT_MINIMIZE_NONE = 0,
    /**
     * For intervals of less than 1 month that cross month boundaries,
     * only show one month (use format for greatestDifference=d).
     * @internal
     */
    UDTITVFMT_MINIMIZE_ADJACENT_MONTHS,
    /**
     * For intervals of less than 12 hours that cross day boundaries,
     * only show one day (use format for greatestDifference=h).
     * @internal
     */
    UDTITVFMT_MINIMIZE_ADJACENT_DAYS
} UDateIntervalFormatAttributeValue;

/**
 * Change attributes for the UDateIntervalFormat object.
 * @param formatter
 *            The UDateIntervalFormat object whose attributes are to be changed.
 * @param attr
 *            The attribute to change.
 * @param value
 *            The new value for the attribute.
 * @param status
 *            A pointer to a UErrorCode to receive any errors.
 * @internal
 */
U_INTERNAL void U_EXPORT2
udtitvfmt_setAttribute(UDateIntervalFormat*             formatter,
                      UDateIntervalFormatAttribute      attr,
                      UDateIntervalFormatAttributeValue value,
                      UErrorCode*                       status);

#endif  /* U_HIDE_DRAFT_API */
#endif /* #if !UCONFIG_NO_FORMATTING */

#endif


text:
package cz.metacentrum.perun.core.impl.modules.attributes;

import java.util.List;

import cz.metacentrum.perun.core.api.Attribute;
import cz.metacentrum.perun.core.api.AttributeDefinition;
import cz.metacentrum.perun.core.api.Facility;
import cz.metacentrum.perun.core.api.Group;
import cz.metacentrum.perun.core.api.Pair;
import cz.metacentrum.perun.core.api.Resource;
import cz.metacentrum.perun.core.api.AttributesManager;
import cz.metacentrum.perun.core.api.exceptions.AttributeNotExistsException;
import cz.metacentrum.perun.core.api.exceptions.ConsistencyErrorException;
import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeAssignmentException;
import cz.metacentrum.perun.core.api.exceptions.WrongAttributeValueException;
import cz.metacentrum.perun.core.api.exceptions.WrongReferenceAttributeValueException;
import cz.metacentrum.perun.core.impl.PerunSessionImpl;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceGroupAttributesModuleAbstract;
import cz.metacentrum.perun.core.implApi.modules.attributes.ResourceGroupAttributesModuleImplApi;
import java.util.ArrayList;

/**
 *
 * @author Michal Stava email:<stavamichal@gmail.com>
 */
public class urn_perun_group_resource_attribute_def_def_isSystemUnixGroup extends ResourceGroupAttributesModuleAbstract implements ResourceGroupAttributesModuleImplApi {

	private static final String A_GR_systemUnixGroupName = AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF + ":systemUnixGroupName";
	private static final String A_GR_systemUnixGID = AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF + ":systemUnixGID";

	public Attribute fillAttribute(PerunSessionImpl sess, Resource resource, Group group, AttributeDefinition attributeDefinition) throws InternalErrorException, WrongAttributeAssignmentException {
		return new Attribute(attributeDefinition);
	}

	public void checkAttributeValue(PerunSessionImpl sess, Resource resource, Group group, Attribute attribute) throws InternalErrorException, WrongAttributeValueException, WrongReferenceAttributeValueException, WrongAttributeAssignmentException{

		Integer isSystemUnixGroup = (Integer) attribute.getValue();
		if(isSystemUnixGroup == null) return; //isSystemUnixGroup can be null. It is equivalent to 0.

		if(isSystemUnixGroup != 0 && isSystemUnixGroup != 1) throw new WrongAttributeValueException(attribute, "Attribute isSystemUnixGroup should not other number than 0 or 1.");

		Attribute sysUnixGroupName = new Attribute();
		Attribute sysUnixGID = new Attribute();

		if(isSystemUnixGroup == 1) {

			try {
				sysUnixGroupName = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, resource, group, A_GR_systemUnixGroupName);
				sysUnixGID = sess.getPerunBl().getAttributesManagerBl().getAttribute(sess, resource, group, A_GR_systemUnixGID);
			} catch (AttributeNotExistsException ex) {
				//if any of these attributes not exist, its wrong
				throw new ConsistencyErrorException("Attributes sysUnixGroupName or sysUnixGID not exist.",ex);
			}

			try {
				sess.getPerunBl().getAttributesManagerBl().checkAttributeValue(sess, resource, group, sysUnixGroupName);
			} catch(WrongAttributeValueException ex) {
				throw new WrongReferenceAttributeValueException("Bad value in sysUnixGroupName attribute.",ex);
			}

			try {
				sess.getPerunBl().getAttributesManagerBl().checkAttributeValue(sess, resource, group, sysUnixGID);
			} catch(WrongAttributeValueException ex) {
				throw new WrongReferenceAttributeValueException("Bad value in sysUnixGID.",ex);
			}
		}
	}

	@Override
	public List<String> getDependencies() {
		List<String> dependencies = new ArrayList<String>();
		dependencies.add(A_GR_systemUnixGroupName);
		dependencies.add(A_GR_systemUnixGID);
		return dependencies;
	}

	public AttributeDefinition getAttributeDefinition() {
		AttributeDefinition attr = new AttributeDefinition();
		attr.setNamespace(AttributesManager.NS_GROUP_RESOURCE_ATTR_DEF);
		attr.setFriendlyName("isSystemUnixGroup");
		attr.setDisplayName("Is system unix group");
		attr.setType(Integer.class.getName());
		attr.setDescription("The group is system unix group.");
		return attr;
	}
}


text:
<?php

/**
 * (C) equolo.org - Mit Style License
 *
 *  - Database connection
 */

// NOTE: this is an example of the original database file used in equolo.org
function db() {
  static $db;
  // only if never instantiated/assigned
  if (empty($db)) {
    // differnce between localhost and production
    $prod = isset($_ENV['DATABASE_SERVER']);
    if ($prod) {
      $host = $_ENV['DATABASE_SERVER'];
      $dbmane = 'production_database_name';
      $user = 'production_database_user';
      $pass = 'production_database_pass';
      $type = 'production_database_type';
    } else {
      $host = 'local_database_host';
      $dbmane = 'local_database_name';
      $user = 'local_database_user';
      $pass = 'local_database_pass';
      $type = 'local_database_type';
    }
    // http://www.php.net/manual/en/pdo.construct.php
    try {
      $db = new PDO(
        $type.':dbname='.$dbmane.';host='.$host.';charset=utf8',
        $user,
        $pass
      );
      // be extra sure it's handled like that
      // for older PDO configurations
      $db->exec('set names utf8');
    } catch (PDOException $e) {
      exit($prod ?
        'the database, I haz it no more!' :
        $e->getMessage()
      );
    }
  }
  return $db;
}
?>


text:
TEST(FlEngineTest, WindowMetrics) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->SendWindowMetricsEvent = MOCK_ENGINE_PROC(
      SendWindowMetricsEvent,
      ([&called](auto engine, const FlutterWindowMetricsEvent* event) {
        called = true;
        EXPECT_EQ(event->width, static_cast<size_t>(3840));
        EXPECT_EQ(event->height, static_cast<size_t>(2160));
        EXPECT_EQ(event->pixel_ratio, 2.0);

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  fl_engine_send_window_metrics_event(engine, 3840, 2160, 2.0);

  EXPECT_TRUE(called);
}

// Checks sending mouse pointer events works.
TEST(FlEngineTest, MousePointer) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->SendPointerEvent = MOCK_ENGINE_PROC(
      SendPointerEvent,
      ([&called](auto engine, const FlutterPointerEvent* events,
                 size_t events_count) {
        called = true;
        EXPECT_EQ(events_count, static_cast<size_t>(1));
        EXPECT_EQ(events[0].phase, kDown);
        EXPECT_EQ(events[0].timestamp, static_cast<size_t>(1234567890));
        EXPECT_EQ(events[0].x, 800);
        EXPECT_EQ(events[0].y, 600);
        EXPECT_EQ(events[0].device, static_cast<int32_t>(0));
        EXPECT_EQ(events[0].signal_kind, kFlutterPointerSignalKindScroll);
        EXPECT_EQ(events[0].scroll_delta_x, 1.2);
        EXPECT_EQ(events[0].scroll_delta_y, -3.4);
        EXPECT_EQ(events[0].device_kind, kFlutterPointerDeviceKindMouse);
        EXPECT_EQ(events[0].buttons, kFlutterPointerButtonMouseSecondary);

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  fl_engine_send_mouse_pointer_event(engine, kDown, 1234567890, 800, 600, 1.2,
                                     -3.4, kFlutterPointerButtonMouseSecondary);

  EXPECT_TRUE(called);
}

// Checks sending pan/zoom events works.
TEST(FlEngineTest, PointerPanZoom) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->SendPointerEvent = MOCK_ENGINE_PROC(
      SendPointerEvent,
      ([&called](auto engine, const FlutterPointerEvent* events,
                 size_t events_count) {
        called = true;
        EXPECT_EQ(events_count, static_cast<size_t>(1));
        EXPECT_EQ(events[0].phase, kPanZoomUpdate);
        EXPECT_EQ(events[0].timestamp, static_cast<size_t>(1234567890));
        EXPECT_EQ(events[0].x, 800);
        EXPECT_EQ(events[0].y, 600);
        EXPECT_EQ(events[0].device, static_cast<int32_t>(1));
        EXPECT_EQ(events[0].signal_kind, kFlutterPointerSignalKindNone);
        EXPECT_EQ(events[0].pan_x, 1.5);
        EXPECT_EQ(events[0].pan_y, 2.5);
        EXPECT_EQ(events[0].scale, 3.5);
        EXPECT_EQ(events[0].rotation, 4.5);
        EXPECT_EQ(events[0].device_kind, kFlutterPointerDeviceKindTrackpad);
        EXPECT_EQ(events[0].buttons, 0);

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  fl_engine_send_pointer_pan_zoom_event(engine, 1234567890, 800, 600,
                                        kPanZoomUpdate, 1.5, 2.5, 3.5, 4.5);

  EXPECT_TRUE(called);
}

// Checks dispatching a semantics action works.
TEST(FlEngineTest, DispatchSemanticsAction) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->DispatchSemanticsAction = MOCK_ENGINE_PROC(
      DispatchSemanticsAction,
      ([&called](auto engine, uint64_t id, FlutterSemanticsAction action,
                 const uint8_t* data, size_t data_length) {
        EXPECT_EQ(id, static_cast<uint64_t>(42));
        EXPECT_EQ(action, kFlutterSemanticsActionTap);
        EXPECT_EQ(data_length, static_cast<size_t>(4));
        EXPECT_EQ(data[0], 't');
        EXPECT_EQ(data[1], 'e');
        EXPECT_EQ(data[2], 's');
        EXPECT_EQ(data[3], 't');
        called = true;

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  g_autoptr(GBytes) data = g_bytes_new_static("test", 4);
  fl_engine_dispatch_semantics_action(engine, 42, kFlutterSemanticsActionTap,
                                      data);

  EXPECT_TRUE(called);
}

// Checks sending platform messages works.
TEST(FlEngineTest, PlatformMessage) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  FlutterEngineSendPlatformMessageFnPtr old_handler =
      embedder_api->SendPlatformMessage;
  embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC(
      SendPlatformMessage,
      ([&called, old_handler](auto engine,
                              const FlutterPlatformMessage* message) {
        if (strcmp(message->channel, "test") != 0) {
          return old_handler(engine, message);
        }

        called = true;

        EXPECT_EQ(message->message_size, static_cast<size_t>(4));
        EXPECT_EQ(message->message[0], 't');
        EXPECT_EQ(message->message[1], 'e');
        EXPECT_EQ(message->message[2], 's');
        EXPECT_EQ(message->message[3], 't');

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  g_autoptr(GBytes) message = g_bytes_new_static("test", 4);
  fl_engine_send_platform_message(engine, "test", message, nullptr, nullptr,
                                  nullptr);

  EXPECT_TRUE(called);
}

// Checks sending platform message responses works.
TEST(FlEngineTest, PlatformMessageResponse) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->SendPlatformMessageResponse = MOCK_ENGINE_PROC(
      SendPlatformMessageResponse,
      ([&called](auto engine,
                 const FlutterPlatformMessageResponseHandle* handle,
                 const uint8_t* data, size_t data_length) {
        called = true;

        EXPECT_EQ(
            handle,
            reinterpret_cast<const FlutterPlatformMessageResponseHandle*>(42));
        EXPECT_EQ(data_length, static_cast<size_t>(4));
        EXPECT_EQ(data[0], 't');
        EXPECT_EQ(data[1], 'e');
        EXPECT_EQ(data[2], 's');
        EXPECT_EQ(data[3], 't');

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);
  g_autoptr(GBytes) response = g_bytes_new_static("test", 4);
  EXPECT_TRUE(fl_engine_send_platform_message_response(
      engine, reinterpret_cast<const FlutterPlatformMessageResponseHandle*>(42),
      response, &error));
  EXPECT_EQ(error, nullptr);

  EXPECT_TRUE(called);
}

// Checks settings plugin sends settings on startup.
TEST(FlEngineTest, SettingsPlugin) {
  g_autoptr(FlEngine) engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->SendPlatformMessage = MOCK_ENGINE_PROC(
      SendPlatformMessage,
      ([&called](auto engine, const FlutterPlatformMessage* message) {
        called = true;

        EXPECT_STREQ(message->channel, "flutter/settings");

        g_autoptr(FlJsonMessageCodec) codec = fl_json_message_codec_new();
        g_autoptr(GBytes) data =
            g_bytes_new(message->message, message->message_size);
        g_autoptr(GError) error = nullptr;
        g_autoptr(FlValue) settings = fl_message_codec_decode_message(
            FL_MESSAGE_CODEC(codec), data, &error);
        EXPECT_NE(settings, nullptr);
        EXPECT_EQ(error, nullptr);

        FlValue* text_scale_factor =
            fl_value_lookup_string(settings, "textScaleFactor");
        EXPECT_NE(text_scale_factor, nullptr);
        EXPECT_EQ(fl_value_get_type(text_scale_factor), FL_VALUE_TYPE_FLOAT);

        FlValue* always_use_24hr_format =
            fl_value_lookup_string(settings, "alwaysUse24HourFormat");
        EXPECT_NE(always_use_24hr_format, nullptr);
        EXPECT_EQ(fl_value_get_type(always_use_24hr_format),
                  FL_VALUE_TYPE_BOOL);

        FlValue* platform_brightness =
            fl_value_lookup_string(settings, "platformBrightness");
        EXPECT_NE(platform_brightness, nullptr);
        EXPECT_EQ(fl_value_get_type(platform_brightness), FL_VALUE_TYPE_STRING);

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);

  EXPECT_TRUE(called);
}

void on_pre_engine_restart_cb(FlEngine* engine, gpointer user_data) {
  int* count = reinterpret_cast<int*>(user_data);
  *count += 1;
}

void on_pre_engine_restart_destroy_notify(gpointer user_data) {
  int* count = reinterpret_cast<int*>(user_data);
  *count += 10;
}

// Checks restarting the engine invokes the correct callback.
TEST(FlEngineTest, OnPreEngineRestart) {
  FlEngine* engine = make_mock_engine();
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  OnPreEngineRestartCallback callback;
  void* callback_user_data;

  bool called = false;
  embedder_api->Initialize = MOCK_ENGINE_PROC(
      Initialize, ([&callback, &callback_user_data, &called](
                       size_t version, const FlutterRendererConfig* config,
                       const FlutterProjectArgs* args, void* user_data,
                       FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) {
        called = true;
        callback = args->on_pre_engine_restart_callback;
        callback_user_data = user_data;

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);

  EXPECT_TRUE(called);
  EXPECT_NE(callback, nullptr);

  // The following call has no effect but should not crash.
  callback(callback_user_data);

  int count = 0;

  // Set handler so that:
  //
  //  * When the engine restarts, count += 1;
  //  * When the engine is freed, count += 10.
  fl_engine_set_on_pre_engine_restart_handler(
      engine, on_pre_engine_restart_cb, &count,
      on_pre_engine_restart_destroy_notify);

  callback(callback_user_data);
  EXPECT_EQ(count, 1);

  // Disposal should call the destroy notify.
  g_object_unref(engine);
  EXPECT_EQ(count, 11);
}

TEST(FlEngineTest, DartEntrypointArgs) {
  g_autoptr(FlDartProject) project = fl_dart_project_new();

  GPtrArray* args_array = g_ptr_array_new();
  g_ptr_array_add(args_array, const_cast<char*>("arg_one"));
  g_ptr_array_add(args_array, const_cast<char*>("arg_two"));
  g_ptr_array_add(args_array, const_cast<char*>("arg_three"));
  g_ptr_array_add(args_array, nullptr);
  gchar** args = reinterpret_cast<gchar**>(g_ptr_array_free(args_array, false));

  fl_dart_project_set_dart_entrypoint_arguments(project, args);

  g_autoptr(FlEngine) engine = make_mock_engine_with_project(project);
  FlutterEngineProcTable* embedder_api = fl_engine_get_embedder_api(engine);

  bool called = false;
  embedder_api->Initialize = MOCK_ENGINE_PROC(
      Initialize, ([&called, &set_args = args](
                       size_t version, const FlutterRendererConfig* config,
                       const FlutterProjectArgs* args, void* user_data,
                       FLUTTER_API_SYMBOL(FlutterEngine) * engine_out) {
        called = true;
        EXPECT_NE(set_args, args->dart_entrypoint_argv);
        EXPECT_EQ(args->dart_entrypoint_argc, 3);

        return kSuccess;
      }));

  g_autoptr(GError) error = nullptr;
  EXPECT_TRUE(fl_engine_start(engine, &error));
  EXPECT_EQ(error, nullptr);

  EXPECT_TRUE(called);
}

// NOLINTEND(clang-analyzer-core.StackAddressEscape)


text:
Arduino control over http

## Getting Started
Install the module with: `npm install webduino`

```javascript
var webduino = require('webduino');
webduino.awesome(); // "awesome"
```

## Documentation
_(Coming soon)_

## Examples
_(Coming soon)_

## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).

## Release History
_(Nothing yet)_

## License
Copyright (c) 2014 Ernesto Laval
Licensed under the MIT license.

webduino
========

RESTful API for controlling and reading devices sensors and actuators connected to an Arduino Borad through an HTTP Connection.

It is buit on top of a great set of modules:

**Nodejs** - Javascript on the server!!

**johnny-five** - Communication to Arduino boards in node

**express** - Web server (API & local web pages)

**socket.io** - Get events from sensors of change in state through an http connection

Created by TIDE SA for the support of Makers Movement in Schools.

## Quick start

### Arduino
Get an Arduino (tested on Arduino UNO) and connect to your computer through USB

### NODE JS
If you don't have it already ... install node on your computer.
- http://nodejs.org
- http://howtonode.org/how-to-install-nodejs

### webduino
Create a new directory and install webduino module with nmp
```
$ mkdir myfirstwebduino
$ cd myfirstwebduino
$ npm install webduino
```
Make sure your Arduino is connected to a USB port and run a webduino server
```
$ mkdir myfirstwebduino
$ cd myfirstwebduino
$ npm install webduino
```
Create your server program - server.js
```javascript
var webduino = require('webduino');
var webduinoApp = webduino();

var server = webduinoApp.server();
var PORT = 8000;

webduinoApp.on("ready", function() {
  // On board ready, start listening for http requests
  server.listen(PORT, function() {
    // Notify local IP Addrsss & PORT
    var IP = webduinoApp.localIPs()[0];
    console.log("Listening on "+IP+":"+PORT)
  });
})
```
And run it
```
$ node server
1388687348931 Board Connecting...
1388687348939 Serial Found possible serial port /dev/cu.usbmodemfa131
1388687348941 Board -> Serialport connected /dev/cu.usbmodemfa131
1388687352124 Board <- Serialport connected /dev/cu.usbmodemfa131
1388687352124 Repl Initialized
>> Listening on 192.168.1.123:8000

```

### Try it
In a Web Browser (on any computer from your local network) try the following urls to get the state of Pins, Leds or Sensors
- http://{server address}/api/leds
- http://{server address}/api/leds/13
- http://{server address}/api/sensors
- http://{server address}/api/sensors/A1
- http://{server address}/api/pins
- http://{server address}/api/pins/7

## Complete API Docs
The complete API docs can be found [here](http://htmlpreview.github.io/?https://raw.github.com/elaval/webduino/master/doc/api/index.html)


text:
package handlers

import (
	"encoding/json"
	"net/http"

	"time"

	"github.com/jadiego/bloom/apiserver/models/users"
	"github.com/jadiego/bloom/apiserver/sessions"
)

//UsersHandler allows new users to sign up (POST) or returns all users
func (ctx *Context) UsersHandler(w http.ResponseWriter, r *http.Request) {
	switch r.Method {
	case "POST":
		if r.Body == nil {
			http.Error(w, "Please send a request body", http.StatusBadRequest)
			return
		}

		//Decode the request body into a models.NewUser struct
		d := json.NewDecoder(r.Body)
		nu := &users.NewUser{}
		if err := d.Decode(nu); err != nil {
			http.Error(w, "invalid JSON", http.StatusBadRequest)
			return
		}

		//Validate the models.NewUser
		if err := nu.Validate(); err != nil {
			http.Error(w, "error validating user:"+err.Error(), http.StatusBadRequest)
			return
		}

		//Ensure there isn't already a user in the UserStore with the same email address
		if _, err := ctx.UserStore.GetByEmail(nu.Email); err != users.ErrUserNotFound {
			http.Error(w, "email address is already used:"+nu.Email, http.StatusBadRequest)
			return
		}

		//Ensure there isn't already a user in the UserStore with the same user name
		if _, err := ctx.UserStore.GetByUserName(nu.UserName); err != users.ErrUserNotFound {
			http.Error(w, "username is already used:"+nu.UserName, http.StatusBadRequest)
			return
		}

		//Insert the new user into the UserStore
		u, err := ctx.UserStore.Insert(nu)
		if err != nil {
			http.Error(w, "error inserting user into DB:"+err.Error(), http.StatusBadRequest)
			return
		}

		//Begin a new session
		ss := &SessionState{
			BeganAt:    time.Now(),
			ClientAddr: r.RemoteAddr,
			User:       u,
		}

		_, err = sessions.BeginSession(ctx.SessionKey, ctx.SessionStore, ss, w)
		if err != nil {
			http.Error(w, "error beginning session:"+err.Error(), http.StatusInternalServerError)
			return
		}

		//Respond to the client with the models.User struct encoded as a JSON object
		w.Header().Add(headerContentType, contentTypeJSONUTF8)
		encoder := json.NewEncoder(w)
		encoder.Encode(u)

	case "GET":
		//Get all users from the UserStore and write them
		//to the response as a JSON-encoded array
		us, err := ctx.UserStore.GetAll()
		if err != nil {
			http.Error(w, "error getting users: "+err.Error(), http.StatusInternalServerError)
			return
		}

		w.Header().Add(headerContentType, contentTypeJSONUTF8)
		encoder := json.NewEncoder(w)
		encoder.Encode(us)
	}
}

//SessionsHandler allows existing users to sign-in
func (ctx *Context) SessionsHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "POST" {

		//Decode the request body into a models.Credentials struct
		d := json.NewDecoder(r.Body)
		c := &users.Credentials{}
		if err := d.Decode(c); err != nil {
			http.Error(w, "invalid JSON", http.StatusBadRequest)
			return
		}

		overLoginAttemptThreshold, err := ctx.SessionStore.CheckLoginAttempt(c.UserName)
		if err != nil {
			http.Error(w, err.Error(), http.StatusUnauthorized)
			return
		}
		if overLoginAttemptThreshold {
			http.Error(w, "Too many login attempts! Please try again later.", http.StatusUnauthorized)
			return
		}

		//Get the user with the provided username from the UserStore; if not found,
		//respond with an http.StatusUnauthorized
		u, err := ctx.UserStore.GetByUserName(c.UserName)
		if err != nil {
			http.Error(w, "Incorrect username or password ", http.StatusUnauthorized)
			return
		}

		//Authenticate the user using the provided password; if that fails,
		//respond with an http.StatusUnauthorized
		if err := u.Authenticate(c.Password); err != nil {
			if err := ctx.SessionStore.LogFailedAttempt(u.UserName); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			http.Error(w, "Incorrect username or password ", http.StatusUnauthorized)
			return
		}

		//Begin a new session
		s := &SessionState{
			BeganAt:    time.Now(),
			ClientAddr: r.RemoteAddr,
			User:       u,
		}
		_, err = sessions.BeginSession(ctx.SessionKey, ctx.SessionStore, s, w)
		if err != nil {
			http.Error(w, "error beginning session:"+err.Error(), http.StatusInternalServerError)
			return
		}

		//Respond to the client with the models.User struct encoded as a JSON object
		w.Header().Add(headerContentType, contentTypeJSONUTF8)
		encoder := json.NewEncoder(w)
		encoder.Encode(u)
	}
}

//SessionsMineHandler allows authenticated users to sign-out
func (ctx *Context) SessionsMineHandler(w http.ResponseWriter, r *http.Request) {
	if r.Method == "DELETE" {
		//end the sessions
		_, err := sessions.EndSession(r, ctx.SessionKey, ctx.SessionStore)
		if err != nil {
			http.Error(w, "error deleting session id:"+err.Error(), http.StatusInternalServerError)
			return
		}

		//Respond to the client with a simple message saying
		//that the user has been signed out
		w.Header().Add(headerContentType, contentTypeText)
		w.Write([]byte("User has signed out"))
	}
}

//UsersMeHanlder gets the session state
func (ctx *Context) UsersMeHanlder(w http.ResponseWriter, r *http.Request) {
	//get the session state
	ss := &SessionState{}
	_, err := sessions.GetState(r, ctx.SessionKey, ctx.SessionStore, ss)
	if err != nil {
		http.Error(w, "error getting session: "+err.Error(), http.StatusUnauthorized)
		return
	}

	//Respond to the client with the session
	//state's User field, encoded as a JSON object
	w.Header().Add(headerContentType, contentTypeJSONUTF8)
	encoder := json.NewEncoder(w)
	encoder.Encode(ss.User)
}


text:
package org.hibernate.service;
import org.hibernate.HibernateException;

/**
 * Indicates that an unkown service was requested from the registry.
 *
 * @author Steve Ebersole
 */
public class UnknownServiceException extends HibernateException {
	public final Class serviceRole;

	public UnknownServiceException(Class serviceRole) {
		super( "Unknown service requested [" + serviceRole.getName() + "]" );
		this.serviceRole = serviceRole;
	}

	public Class getServiceRole() {
		return serviceRole;
	}
}


text:
package io.seldon.recommendation.model;

import io.seldon.clustering.recommender.RecommendationContext;
import io.seldon.mf.PerClientExternalLocationListener;
import io.seldon.recommendation.ClientStrategy;
import io.seldon.resources.external.NewResourceNotifier;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

/**
 * @author firemanphil
 *         Date: 28/04/15
 *         Time: 12:16
 */
public abstract class ModelManager<T> implements PerClientExternalLocationListener {
    private static final String MODEL_PROPERTY_NAME = "io.seldon.algorithm.model.name";
    private static Logger logger = Logger.getLogger(ModelManager.class.getName());

    private final ConcurrentMap<String, ConcurrentMap<String,T>> clientStores
            = new ConcurrentHashMap<>();

    private final Executor executor;
    private final Set<String> nodeBases;

    public ModelManager(NewResourceNotifier notifier, Set<String> nodePatterns) {
        this(notifier, nodePatterns, Executors.newFixedThreadPool(2));
    }
    public ModelManager(NewResourceNotifier notifier, Set<String> nodePatterns, Executor executor) {
        this.nodeBases = nodePatterns;
        for (String pattern : nodePatterns) {
            notifier.addListener(pattern, this);
        }
        this.executor = executor;
    }

    @Override
    public void newClientLocation(final String client, final String location, final String nodePattern) {
    	logger.info("New location "+client+" : "+location+ " : "+nodePattern);
        String rightBase = null;
        Iterator<String> iter = nodeBases.iterator();
        while(rightBase==null && iter.hasNext()) {
            String base = iter.next();
            if (nodePattern.contains(base))
                rightBase = base;
        }

        final String finalPartOfNode = nodePattern.replace(rightBase,"").replaceFirst("/", "");

        executor.execute(new Runnable() {
            @Override
            public void run() {
                String key = getKey(client,nodePattern);
                logger.info("Loading with client:"+client+" location:"+location+" key:"+key+" finalPartOfNode:"+finalPartOfNode);
                T result = loadModel(location, client);
                logger.info("Loaded with client:"+client+" location:"+location+" key:"+key+"finalPartOfNodeL"+finalPartOfNode+" result:"+result);
                clientStores.putIfAbsent(key, new ConcurrentHashMap<String, T>());
                clientStores.get(key).put(finalPartOfNode, result);
                for (Map<String, T> store : clientStores.values()) {
                    for (String t : store.keySet()) {
                        logger.info(t + " " + store.get(t));
                    }
                }
            }
        });

    }

    public T getClientStore(String client, RecommendationContext.OptionsHolder options){
        String type = nodeBases.iterator().next();
        return getClientStore(client, type, options);
    }

    public T getClientStore(String client, String type, RecommendationContext.OptionsHolder options){
        String modelName = options.getStringOption(MODEL_PROPERTY_NAME);
        String key = getKey(client, type);
        if (logger.isDebugEnabled())
        	logger.debug("Get client store for client "+client+" type "+type+" modelName "+modelName+" key:"+key);
        if (!clientStores.containsKey(key))
        {
        	if (logger.isDebugEnabled())
        		logger.debug("Failed to find store with key:"+key+" for client "+client);
        	return null;
        }
        // check whether we are testing or not and get relevant model.
        switch (modelName) {
            case ClientStrategy.DEFAULT_NAME:
            	logger.debug("Returning default store for client "+modelName);
                return clientStores.get(key).get("");

            default:
                T store = clientStores.get(key).get(modelName);
                if (store == null) {
                    logger.warn("Couldn't find model under name " + modelName + " for client " + client);
                    return clientStores.get(key).get("");
                } else {
                    return store;
                }
        }

    }

    @Override
    public void clientLocationDeleted(String client, String nodePattern) {
        String rightBase = null;
        Iterator<String> iter = nodeBases.iterator();
        while(rightBase==null && iter.hasNext()) {
            String base = iter.next();
            if (nodePattern.contains(base))
                rightBase = base;
        }
        String key = getKey(client, rightBase);
        final String finalPartOfNode = nodePattern.replace(rightBase, "").replaceFirst("/", "");
        if(clientStores.get(key)!=null){
            clientStores.get(key).remove(finalPartOfNode);
        }
    }

    protected abstract T loadModel(String location,String client);

    private String getKey(String client,String key)
    {
        return client + ":" + key;
    }
}


text:
"""
Run unit tests for the ZPar tagger.

:author: Nitin Madnani (nmadnani@ets.org)
"""

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import glob
import os

from io import open
from os.path import abspath, dirname, join

from nose.tools import assert_equal
from zpar import ZPar

_my_dir = abspath(dirname(__file__))

z = None
tagger = None

def setUp():
    """
    set up things we need for the tests
    """
    global z, tagger

    assert 'ZPAR_MODEL_DIR' in os.environ

    model_dir = os.environ['ZPAR_MODEL_DIR']

    z = ZPar(model_dir)
    tagger = z.get_tagger()

def tearDown():
    """
    Clean up after the tests
    """
    global z, tagger

    if z:
        z.close()
        del tagger
        del z

    # delete all the files we may have created
    data_dir = abspath(join(_my_dir, '..', 'examples'))
    for f in glob.glob(join(data_dir, 'test*.tag')):
        os.unlink(f)

def check_tag_sentence(tokenize=False):
    """
    Check tag_sentence method with and without tokenization
    """
    global tagger

    sentence = "I'm going to the market." if tokenize else "I 'm going to the market ."
    correct_output = "I/PRP 'm/VBP going/VBG to/TO the/DT market/NN ./."
    tagged_sentence = tagger.tag_sentence(sentence, tokenize=tokenize)

    assert_equal(tagged_sentence, correct_output)

def test_tag_sentence():
    yield check_tag_sentence, False
    yield check_tag_sentence, True

def check_tag_file(tokenize=False):
    """
    Check tag_file method with and without tokenization
    """

    global tagger

    prefix = 'test' if tokenize else 'test_tokenized'

    correct_output = ['I/PRP am/VBP going/VBG to/TO the/DT market/NN ./.',
                      'Are/VBP you/PRP going/VBG to/TO come/VB with/IN me/PRP ?/.']

    input_file = abspath(join(_my_dir, '..', 'examples', '{}.txt'.format(prefix)))
    output_file = abspath(join(_my_dir, '..', 'examples', '{}.tag'.format(prefix)))

    # tag the file
    tagger.tag_file(input_file, output_file, tokenize=tokenize)

    # read the output file and make sure we have the expected output
    with open(output_file, 'r') as outf:
        output = [l.strip() for l in outf.readlines()]

    assert_equal(output, correct_output)

def test_tag_file():
    yield check_tag_file, False
    yield check_tag_file, True


text:
<?php
namespace zip\ziparchive_002;

function print_ret($ret) {
  if (is_bool($ret)) {
    echo $ret ? "true\n" : "false\n";
  } else {
    echo $ret ."\n";
  }
}

function print_props($zip) {
  echo $zip->status ."|". $zip->statusSys ."|". $zip->numFiles ."|". strtolower($zip->filename) ."|". $zip->comment ."|". @$zip->getStatusString() ."\n";
}

function test($filename) {
  // Delete the archive file possibly hanging there from previous test
  if (file_exists($filename)) {
    unlink($filename);
  }

  $zip = new \ZipArchive();
  print_props($zip);

  // Error - not existing file
  print_ret($zip->open($filename));
  print_props($zip);

  // Creating a new file
  print_ret($zip->open($filename, \ZipArchive::CREATE));
  print_props($zip);

  print_ret($zip->addEmptyDir("foo"));
  print_props($zip);

  // Add an existing entry
  print_ret($zip->addEmptyDir("foo"));
  print_props($zip);

  $zip->close();
  print_props($zip);

  // Overwriting an existing archive with exclusive mode
  $zip2 = new \ZipArchive();
  print_ret($zip2->open($filename, \ZipArchive::EXCL));
  print_props($zip2);

  // Clean up the created archive
  unlink($filename);
}

test("ziparchive_002.zip");


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
  ~
  ~ WSO2 Inc. licenses this file to you 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.
  -->

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <parent>
        <groupId>org.wso2.carbon.devicemgt</groupId>
        <artifactId>identity-extensions</artifactId>
        <version>1.2.6-SNAPSHOT</version>
        <relativePath>../pom.xml</relativePath>
    </parent>

    <modelVersion>4.0.0</modelVersion>
    <artifactId>org.wso2.carbon.identity.jwt.client.extension</artifactId>
    <packaging>bundle</packaging>
    <name>WSO2 Carbon - Device Management JWT Client Extensions</name>
    <description>WSO2 Carbon - Device Management JWT Client Extensions</description>
    <url>http://wso2.org</url>

    <dependencies>
        <dependency>
            <groupId>org.wso2.carbon.governance</groupId>
            <artifactId>org.wso2.carbon.governance.api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.registry.api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.registry.core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.devicemgt</groupId>
            <artifactId>org.wso2.carbon.device.mgt.common</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.ws.commons.axiom.wso2</groupId>
            <artifactId>axiom</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon</groupId>
            <artifactId>org.wso2.carbon.utils</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.orbit.org.scannotation</groupId>
            <artifactId>scannotation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi</artifactId>
        </dependency>
        <dependency>
            <groupId>org.eclipse.osgi</groupId>
            <artifactId>org.eclipse.osgi.services</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.tomcat</groupId>
            <artifactId>tomcat</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.tomcat</groupId>
            <artifactId>tomcat-servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.ws.rs</groupId>
            <artifactId>jsr311-api</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.axis2.wso2</groupId>
            <artifactId>axis2</artifactId>
        </dependency>
        <dependency>
            <groupId>commons-lang.wso2</groupId>
            <artifactId>commons-lang</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.carbon.registry</groupId>
            <artifactId>org.wso2.carbon.registry.indexing</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.orbit.com.nimbusds</groupId>
            <artifactId>nimbus-jose-jwt</artifactId>
        </dependency>
        <dependency>
            <groupId>com.googlecode.json-simple.wso2</groupId>
            <artifactId>json-simple</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents.wso2</groupId>
            <artifactId>httpcore</artifactId>
        </dependency>
        <dependency>
            <groupId>org.wso2.orbit.org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-scr-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.felix</groupId>
                <artifactId>maven-bundle-plugin</artifactId>
                <version>1.4.0</version>
                <extensions>true</extensions>
                <configuration>
                    <instructions>
                        <Bundle-SymbolicName>${project.artifactId}</Bundle-SymbolicName>
                        <Bundle-Name>${project.artifactId}</Bundle-Name>
                        <Bundle-Version>${carbon.device.mgt.version}</Bundle-Version>
                        <Bundle-Description>Device Management JWT Client Bundle</Bundle-Description>
                        <Private-Package>org.wso2.carbon.identity.jwt.client.extension.internal</Private-Package>
                        <Export-Package>
                            !org.wso2.carbon.identity.jwt.client.extension.internal,
                            org.wso2.carbon.identity.jwt.client.extension.*
                        </Export-Package>
                        <Import-Package>
                            org.osgi.framework,
                            org.osgi.service.component,
                            org.wso2.carbon.governance.api.*,
                            org.wso2.carbon.context,
                            org.wso2.carbon.registry.core,
                            org.wso2.carbon.registry.core.exceptions,
                            org.wso2.carbon.registry.core.session,
                            org.wso2.carbon.utils,
                            org.apache.commons.logging,
                            org.wso2.carbon.registry.core.*;resolution:=optional,
                            org.wso2.carbon.registry.common.*;version="${carbon.registry.imp.pkg.version.range}",
                            org.wso2.carbon.registry.indexing.*; version="${carbon.registry.imp.pkg.version.range}",
                            com.nimbusds.jwt.*;version="${nimbus.orbit.version.range}",
                            com.nimbusds.jose.*;version="${nimbus.orbit.version.range}",
                            javax.net.ssl,
                            org.apache.commons.codec.binary,
                            org.apache.commons.io,
                            org.apache.http;version="${httpclient.version.range}",
                            org.apache.http.client;version="${httpclient.version.range}",
                            org.apache.http.message;version="${httpclient.version.range}",
                            org.apache.http.client;version="${httpclient.version.range}",
                            org.apache.http.impl;version="${httpclient.version.range}",
                            org.apache.http.conn.*;version="${httpclient.version.range}",
                            org.apache.http.util;version="${httpclient.version.range}",
                            org.apache.http.client.entity;version="${httpclient.version.range}",
                            org.apache.http.client.methods;version="${httpclient.version.range}",
                            org.apache.http.impl.client;version="${httpclient.version.range}",
                            org.json.simple.*,
                            org.wso2.carbon.core.util,
                            javax.net.ssl,
                            org.wso2.carbon.user.core.service,
                            org.wso2.carbon.user.core.tenant,
                            org.wso2.carbon.base
                        </Import-Package>
                    </instructions>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>


text:
// https://leetcode.com/problems/first-bad-version/

/*
  You are a product manager and currently leading a team to develop a new product.
  Unfortunately, the latest version of your product fails the quality check. Since
  each version is developed based on the previous version, all the versions after a bad version are also bad.

  Suppose you have n versions [1, 2, ..., n] and you want to find out the first bad one,
  which causes all the following ones to be bad.

  You are given an API bool isBadVersion(version) which will return whether version is bad.
  Implement a function to find the first bad version. You should minimize the number of calls to the API.
*/

bool isBadVersion(int version);

class Solution {
public:
  int firstBadVersion(int n) {
    int l = 0, h = n;

    while (h > l) {
      int m = l + (h - l) / 2;
      if (isBadVersion(m)) h = m;
      else l = m + 1;
    }

    return h;
  }
};


text:
<?php

namespace Symfony\Component\Notifier\Bridge\FakeChat;

use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
use Symfony\Component\Mailer\MailerInterface;
use Symfony\Component\Mime\Email;
use Symfony\Component\Notifier\Exception\UnsupportedMessageTypeException;
use Symfony\Component\Notifier\Message\ChatMessage;
use Symfony\Component\Notifier\Message\MessageInterface;
use Symfony\Component\Notifier\Message\SentMessage;
use Symfony\Component\Notifier\Transport\AbstractTransport;
use Symfony\Contracts\HttpClient\HttpClientInterface;

/**
 * @author Oskar Stark <oskarstark@googlemail.com>
 */
final class FakeChatEmailTransport extends AbstractTransport
{
    protected const HOST = 'default';

    private $mailer;
    private $to;
    private $from;

    public function __construct(MailerInterface $mailer, string $to, string $from, HttpClientInterface $client = null, EventDispatcherInterface $dispatcher = null)
    {
        $this->mailer = $mailer;
        $this->to = $to;
        $this->from = $from;

        parent::__construct($client, $dispatcher);
    }

    public function __toString(): string
    {
        return sprintf('fakechat+email://%s?to=%s&from=%s', $this->getEndpoint(), $this->to, $this->from);
    }

    public function supports(MessageInterface $message): bool
    {
        return $message instanceof ChatMessage;
    }

    /**
     * @param MessageInterface|ChatMessage $message
     *
     * @throws TransportExceptionInterface
     */
    protected function doSend(MessageInterface $message): SentMessage
    {
        if (!$this->supports($message)) {
            throw new UnsupportedMessageTypeException(__CLASS__, ChatMessage::class, $message);
        }

        $subject = 'New Chat message without specified recipient!';
        if (null !== $message->getRecipientId()) {
            $subject = sprintf('New Chat message for recipient: %s', $message->getRecipientId());
        }

        $email = (new Email())
            ->from($this->from)
            ->to($this->to)
            ->subject($subject)
            ->html($message->getSubject())
            ->text($message->getSubject());

        if ('default' !== $transportName = $this->getEndpoint()) {
            $email->getHeaders()->addTextHeader('X-Transport', $transportName);
        }

        $this->mailer->send($email);

        return new SentMessage($message, (string) $this);
    }
}


text:
package com.intellij.refactoring.actions;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.lookup.Lookup;
import com.intellij.codeInsight.lookup.LookupEx;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.ide.IdeEventQueue;
import com.intellij.internal.statistic.eventLog.FeatureUsageData;
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger;
import com.intellij.lang.ContextAwareActionHandler;
import com.intellij.lang.Language;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.application.ApplicationBundle;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.UndoConfirmationPolicy;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.actionSystem.DocCommandGroupId;
import com.intellij.openapi.progress.ProcessCanceledException;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.NlsActions;
import com.intellij.psi.*;
import com.intellij.psi.util.PsiUtilCore;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.rename.inplace.InplaceRefactoring;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.util.SlowOperations;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.ApiStatus;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.function.Predicate;

public abstract class BaseRefactoringAction extends AnAction implements UpdateInBackground {

  protected abstract boolean isAvailableInEditorOnly();

  protected abstract boolean isEnabledOnElements(PsiElement @NotNull [] elements);

  protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element,
                                                        @NotNull Editor editor,
                                                        @NotNull PsiFile file,
                                                        @NotNull DataContext context,
                                                        @NotNull String place) {
    if (ActionPlaces.isPopupPlace(place)) {
      final RefactoringActionHandler handler = getHandler(context);
      if (handler instanceof ContextAwareActionHandler) {
        ContextAwareActionHandler contextAwareActionHandler = (ContextAwareActionHandler)handler;
        if (!contextAwareActionHandler.isAvailableForQuickList(editor, file, context)) {
          return false;
        }
      }
    }

    return isAvailableOnElementInEditorAndFile(element, editor, file, context);
  }

  protected boolean isAvailableOnElementInEditorAndFile(@NotNull PsiElement element,
                                                        @NotNull Editor editor,
                                                        @NotNull PsiFile file,
                                                        @NotNull DataContext context) {
    return true;
  }

  protected boolean hasAvailableHandler(@NotNull DataContext dataContext) {
    final RefactoringActionHandler handler = getHandler(dataContext);
    if (handler != null) {
      if (handler instanceof ContextAwareActionHandler) {
        final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
        final PsiFile file = CommonDataKeys.PSI_FILE.getData(dataContext);
        if (editor != null && file != null && !((ContextAwareActionHandler)handler).isAvailableForQuickList(editor, file, dataContext)) {
          return false;
        }
      }
      return true;
    }
    return false;
  }

  @Nullable
  protected abstract RefactoringActionHandler getHandler(@NotNull DataContext dataContext);

  @Override
  public final void actionPerformed(@NotNull AnActionEvent e) {
    DataContext dataContext = e.getDataContext();
    Project project = e.getProject();
    if (project == null) return;
    int eventCount = IdeEventQueue.getInstance().getEventCount();
    if (!PsiDocumentManager.getInstance(project).commitAllDocumentsUnderProgress()) {
      return;
    }

    RefactoringActionHandler handler;
    try {
      handler = getHandler(dataContext);
    }
    catch (ProcessCanceledException ignored) {
      return;
    }
    IdeEventQueue.getInstance().setEventCount(eventCount);

    SlowOperations.allowSlowOperations(() -> performRefactoringAction(project, dataContext, handler));
  }

  @ApiStatus.Internal
  public static void performRefactoringAction(@NotNull Project project,
                                              @NotNull DataContext dataContext,
                                              @Nullable RefactoringActionHandler handler) {
    final Editor editor = dataContext.getData(CommonDataKeys.EDITOR);

    if (handler == null) {
      String message = RefactoringBundle.getCannotRefactorMessage(RefactoringBundle.message("error.wrong.caret.position.symbol.to.refactor"));
      CommonRefactoringUtil.showErrorHint(project, editor, message, RefactoringBundle.getCannotRefactorMessage(null), null);
      return;
    }

    final PsiElement[] elements = getPsiElementArray(dataContext);
    InplaceRefactoring activeInplaceRenamer = InplaceRefactoring.getActiveInplaceRenamer(editor);
    if (activeInplaceRenamer != null && !InplaceRefactoring.canStartAnotherRefactoring(editor, handler, elements)) {
      InplaceRefactoring.unableToStartWarning(project, editor);
      return;
    }

    if (activeInplaceRenamer == null) {
      final LookupEx lookup = LookupManager.getActiveLookup(editor);
      if (lookup instanceof LookupImpl) {
        Runnable command = () -> ((LookupImpl)lookup).finishLookup(Lookup.NORMAL_SELECT_CHAR);
        Document doc = editor.getDocument();
        DocCommandGroupId group = DocCommandGroupId.noneGroupId(doc);
        CommandProcessor.getInstance().executeCommand(editor.getProject(), command, ApplicationBundle.message("title.code.completion"), group, UndoConfirmationPolicy.DEFAULT, doc);
      }
    }

    final PsiFile file = editor != null ? PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) : null;
    final Language language = file != null
                              ? file.getLanguage()
                              : (elements.length > 0 ? elements[0].getLanguage() : null);
    FeatureUsageData data = new FeatureUsageData()
      .addData("handler", handler.getClass().getName())
      .addLanguage(language);
    if (elements.length > 0) {
      data.addData("element", elements[0].getClass().getName());
    }

    FUCounterUsageLogger.getInstance().logEvent(project, "refactoring", "handler.invoked", data);

    if (editor != null) {
      if (file == null) return;
      DaemonCodeAnalyzer.getInstance(project).autoImportReferenceAtCursor(editor, file);
      handler.invoke(project, editor, file, dataContext);
    }
    else {
      handler.invoke(project, elements, dataContext);
    }
  }

  protected boolean isEnabledOnDataContext(@NotNull DataContext dataContext) {
    return false;
  }

  @Override
  public void update(@NotNull AnActionEvent e) {
    Presentation presentation = e.getPresentation();
    presentation.setEnabledAndVisible(true);
    DataContext dataContext = e.getDataContext();
    Project project = e.getData(CommonDataKeys.PROJECT);
    if (project == null || isHidden()) {
      hideAction(e);
      return;
    }

    Editor editor = e.getData(CommonDataKeys.EDITOR);
    PsiFile file = e.getData(CommonDataKeys.PSI_FILE);
    if (file != null) {
      if (file instanceof PsiCompiledElement && disableOnCompiledElement() || !isAvailableForFile(file)) {
        hideAction(e);
        return;
      }
    }

    if (editor == null) {
      if (isAvailableInEditorOnly()) {
        hideAction(e);
        return;
      }
      final PsiElement[] elements = getPsiElementArray(dataContext);
      final boolean isEnabled = isEnabledOnDataContext(dataContext) || elements.length != 0 && isEnabledOnElements(elements);
      if (!isEnabled) {
        disableAction(e);
      }
      else {
        updateActionText(e);
      }
    }
    else {
      PsiElement element = findRefactoringTargetInEditor(dataContext, this::isAvailableForLanguage);
      if (element != null) {
        boolean isEnabled = file != null && isAvailableOnElementInEditorAndFile(element, editor, file, dataContext, e.getPlace());
        if (!isEnabled) {
          disableAction(e);
        }
        else {
          updateActionText(e);
        }
      }
      else {
        hideAction(e);
      }
    }
  }

  @ApiStatus.Internal
  public static PsiElement findRefactoringTargetInEditor(@NotNull DataContext dataContext,
                                                         @NotNull Predicate<? super Language> elementLanguagePredicate) {
    Editor editor = dataContext.getData(CommonDataKeys.EDITOR);
    PsiFile file = dataContext.getData(CommonDataKeys.PSI_FILE);
    PsiElement element = dataContext.getData(CommonDataKeys.PSI_ELEMENT);
    Language[] languages = dataContext.getData(LangDataKeys.CONTEXT_LANGUAGES);
    if (element == null || element instanceof SyntheticElement || !elementLanguagePredicate.test(element.getLanguage())) {
      if (file == null || editor == null) {
        return null;
      }
      element = getElementAtCaret(editor, file);
    }

    if (element == null || element instanceof SyntheticElement || languages == null) {
      return null;
    }

    if (ContainerUtil.find(languages, elementLanguagePredicate::test) == null) {
      return null;
    }
    return element;
  }

  private void updateActionText(AnActionEvent e) {
    String actionText = getActionName(e.getDataContext());
    if (actionText != null) {
      e.getPresentation().setText(actionText);
    }
  }

  @NlsActions.ActionText
  @Nullable
  protected String getActionName(@NotNull DataContext dataContext) {
    return null;
  }

  protected boolean disableOnCompiledElement() {
    return true;
  }

  private static void hideAction(@NotNull AnActionEvent e) {
    e.getPresentation().setVisible(false);
    disableAction(e);
  }

  protected boolean isHidden() {
    return false;
  }

  public static PsiElement getElementAtCaret(@NotNull final Editor editor, final PsiFile file) {
    final int offset = fixCaretOffset(editor);
    PsiElement element = file.findElementAt(offset);
    if (element == null && offset == file.getTextLength()) {
      element = file.findElementAt(offset - 1);
    }

    if (element instanceof PsiWhiteSpace) {
      element = file.findElementAt(element.getTextRange().getStartOffset() - 1);
    }
    return element;
  }

  private static int fixCaretOffset(@NotNull final Editor editor) {
    final int caret = editor.getCaretModel().getOffset();
    if (editor.getSelectionModel().hasSelection()) {
      if (caret == editor.getSelectionModel().getSelectionEnd()) {
        return Math.max(editor.getSelectionModel().getSelectionStart(), editor.getSelectionModel().getSelectionEnd() - 1);
      }
    }

    return caret;
  }

  private static void disableAction(@NotNull AnActionEvent e) {
    e.getPresentation().setEnabled(false);
  }

  protected boolean isAvailableForLanguage(Language language) {
    return true;
  }

  protected boolean isAvailableForFile(PsiFile file) {
    return true;
  }

  public static PsiElement @NotNull [] getPsiElementArray(@NotNull DataContext dataContext) {
    PsiElement[] psiElements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
    if (psiElements == null || psiElements.length == 0) {
      PsiElement element = CommonDataKeys.PSI_ELEMENT.getData(dataContext);
      if (element != null) {
        psiElements = new PsiElement[]{element};
      }
    }

    if (psiElements == null) return PsiElement.EMPTY_ARRAY;

    List<PsiElement> filtered = null;
    for (PsiElement element : psiElements) {
      if (element instanceof SyntheticElement) {
        if (filtered == null) filtered = new ArrayList<>(Collections.singletonList(element));
        filtered.remove(element);
      }
    }
    return filtered == null ? psiElements : PsiUtilCore.toPsiElementArray(filtered);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="io.github.kmanikumarreddy.myappportifolio.MainActivity">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:orientation="vertical">

            <TextView
                android:id="@+id/Heading"
                style="@style/WrapCenter"
                android:layout_marginTop="5dp"
                android:text="@string/my_nanodegree_apss"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <Button
                android:id="@+id/popularMoviesButton"
                style="@style/WrapCenter"
                android:layout_marginTop="5dp"
                android:onClick="displayInfo"
                android:text="@string/popular_movies" />

            <Button
                android:id="@+id/stockHawkButton"
                style="@style/WrapCenter"
                android:onClick="displayInfo"
                android:text="@string/stock_hawk" />

            <Button
                android:id="@+id/buildItBiggerButton"
                style="@style/WrapCenter"
                android:onClick="displayInfo"
                android:text="@string/build_it_bigger" />

            <Button
                android:id="@+id/makeYourAppMaterialButton"
                style="@style/WrapCenter"
                android:onClick="displayInfo"
                android:text="@string/make_your_app_material" />

            <Button
                android:id="@+id/goUbiquitousButton"
                style="@style/WrapCenter"
                android:onClick="displayInfo"
                android:text="@string/go_ubiquitous" />

            <Button
                android:id="@+id/capstoneButton"
                style="@style/WrapCenter"
                android:onClick="displayInfo"
                android:text="@string/capstone" />
        </LinearLayout>
    </ScrollView>
</RelativeLayout>


text:
/*
* header
* author: ruleechen
* contact: rulee@live.cn
* create date: 2014.7.11
*/

'use strict';

module.exports = function() {
    //
    return function(req, res, next, err) {
        //
        var enabled = req._app.get('x-headers-enabled');
        if (enabled) {
            //
            res.setHeader('X-Nodejs-Version', process.version);
            //
            var version = req._app.get('version');
            if (version) { res.setHeader('X-CatMVC-Version', version); }
        }
        //
        next(err);
    };
};


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Calonge, Donadini, Torre, Rocabruna & Tabaré, Boln Soc. Micol. Madrid 12: 28 (1988)

#### Original name
Trichophaea paraphysincrustata Donadini, M. Torre & Calonge

### Remarks
null


text:
package com.twitter.uncleandr.championship.DAO;

import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;

/**
 * Created by Heisenberg on 03.05.2015.
 */
@DatabaseTable( tableName = "match" )
public class Match
{
    @DatabaseField( generatedId = true )
    private int id;

    @DatabaseField( foreign = true )
    private Gamer gamer1;

    @DatabaseField( foreign = true )
    private Gamer gamer2;

    @DatabaseField
    private int score1;

    @DatabaseField
    private int score2;

    @DatabaseField
    private MatchStatus status;

    @DatabaseField( foreign = true )
    private Game game;

    @DatabaseField
    private String name;

    public int getId()
    {
        return id;
    }

    public void setId( int id )
    {
        this.id = id;
    }

    public Gamer getGamer1()
    {
        return gamer1;
    }

    public void setGamer1( Gamer gamer1 )
    {
        this.gamer1 = gamer1;
        updateName();
    }

    public Gamer getGamer2()
    {
        return gamer2;
    }

    public void setGamer2( Gamer gamer2 )
    {
        this.gamer2 = gamer2;
        updateName();
    }

    public int getScore1()
    {
        return score1;
    }

    public void setScore1( int score1 )
    {
        this.score1 = score1;
    }

    public int getScore2()
    {
        return score2;
    }

    public void setScore2( int score2 )
    {
        this.score2 = score2;
    }

    public MatchStatus getStatus()
    {
        return status;
    }

    public void setStatus( MatchStatus status )
    {
        this.status = status;
    }

    private void updateName()
    {
        name = String.format( "%1$s versus %2$s", gamer1 == null ? "Gamer 1" : gamer1.toString(), gamer2 == null ? "Gamer 2" : gamer2.toString() );
    }

    @Override
    public String toString()
    {
        return name;
    }
}