text:
import datetime

from rooms.models import Room, Booking
from rooms.room_serializers import RoomSerializer
from rooms.my_fields import DAYS_OF_THE_WEEK

from rest_framework import viewsets, status
from rest_framework.decorators import list_route
from rest_framework.response import Response

class RoomViewSet(viewsets.ModelViewSet):
    """
    API view set for Room model. Contains multiple views.
    Can list all room or room details
    """
    queryset = Room.objects.all().order_by('number')
    serializer_class = RoomSerializer

    @list_route(methods=['get'])
    def filter(self, request):
        """
        Endpoint for filtering rooms by given query params
        """

        ALLOWED_PARAMS = ['is_computer_room', 'capacity', 'min_capacity']
        params = request.query_params.dict()
        filter_params = {}
        for key in params:
            if key in ALLOWED_PARAMS:
                if key == 'is_computer_room':
                    filter_params[key] = params[key] == 'true'
                elif key == 'min_capacity':
                    filter_params['capacity__gte'] = int(params[key])
                else:
                    filter_params[key] = params[key]

        try:
            filtered_set = Room.objects.filter(**filter_params)
        except:
            return Response(
                {'details': 'Invalid query params'},
                status=status.HTTP_400_BAD_REQUEST)

        serializer = RoomSerializer(
            filtered_set, context={'request': request}, many=True)
        return Response(serializer.data)

    @list_route(methods=['get'])
    def find(self, request):
        """
        Endpoint for finding free rooms for given dates and times.
        If no end_date is given, the search is made for the start date only
        Additional parameters:
            * is_computer_room : filter results by is_computer_room property
            * min_capacity : minimum capacity for the room
        """

        params = request.query_params.dict()
        start_date = datetime.datetime.strptime(
            params['start_date'], "%Y-%m-%d").date()
        try:
            end_date = datetime.datetime.strptime(
                params['end_date'], "%Y-%m-%d").date()
        except KeyError:
            end_date = start_date
        start_time = datetime.datetime.strptime(
            params['start'], "%H:%M").time()
        end_time = datetime.datetime.strptime(params['end'], "%H:%M").time()
        filter_params = {}
        try:
            filter_params['is_computer_room'] = (
                params['is_computer_room'] == 'true')
        except KeyError:
            pass
        try:
            filter_params['capacity__gte'] = int(params['min_capacity'])
        except (KeyError, ValueError):
            pass
        rooms = Room.objects.filter(**filter_params)
        result = []
        for room in rooms:
            bookings = Booking.objects.filter(room_number=room.number)
            is_free = True
            for booking in bookings:
                if (booking.start_date <= end_date and
                   booking.end_date >= start_date and
                   booking.day_of_week == DAYS_OF_THE_WEEK[
                        start_date.weekday()][0]):
                    if (booking.end_time > start_time and
                       booking.start_time < end_time):
                        is_free = False
                        break
            if is_free:
                result.append(room.number)

        result_queryset = Room.objects.filter(number__in=result)
        serializer = RoomSerializer(
            result_queryset, context={'request': request}, many=True)
        return Response(serializer.data)


text:
/** @jsx React.DOM */

var React = require('react');

TogetherJS.config('toolName', 'CoBrowse');
TogetherJS.config('hubBase', 'http://127.0.0.1:8080/');

var CoBrowseButton = React.createClass({

  _handleClick: function(e) {
    TogetherJS(this);
    e.stopPropagation();
    //return false;
  },

  render: function() {
    var endSessionText = 'End Co-Browse';
    return (
      <button onClick={this._handleClick} data-end-togetherjs-html={endSessionText}>Start Co-Browse</button>
    );
  }
});

module.exports = CoBrowseButton;

redpajama_set_name: RedPajamaGithub


text:
define([
    'underscore',
    'backbone',
    'app/models/repo'
], function(_, Backbone, Repo) {
    'use strict';

    var GroupRepo = Repo.extend({
        defaults: {
            permission: "r",
        }
    });

    _.extend(GroupRepo.prototype.defaults, Repo.prototype.defaults);

    return GroupRepo;
});


text:
package org.apache.druid.msq.indexing.error;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeName;
import org.apache.druid.msq.guice.MSQDurableStorageModule;
import org.apache.druid.msq.util.MultiStageQueryContext;

import java.util.Objects;

@JsonTypeName(DurableStorageConfigurationFault.CODE)
public class DurableStorageConfigurationFault extends BaseMSQFault
{
  static final String CODE = "DurableStorageConfiguration";

  private final String errorMessage;

  @JsonCreator
  public DurableStorageConfigurationFault(@JsonProperty("message") final String errorMessage)
  {
    super(
        CODE,
        "Durable storage mode can only be enabled when %s is set to true and "
        + "the connector is configured correctly. "
        + "Check the documentation on how to enable durable storage mode. "
        + "If you want to still query without durable storage mode, set %s to false in the query context. Got error %s",
        MSQDurableStorageModule.MSQ_INTERMEDIATE_STORAGE_ENABLED,
        MultiStageQueryContext.CTX_ENABLE_DURABLE_SHUFFLE_STORAGE,
        errorMessage
    );
    this.errorMessage = errorMessage;
  }

  @JsonProperty
  public String getMessage()
  {
    return errorMessage;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }
    if (!super.equals(o)) {
      return false;
    }
    DurableStorageConfigurationFault that = (DurableStorageConfigurationFault) o;
    return Objects.equals(errorMessage, that.errorMessage);
  }

  @Override
  public int hashCode()
  {
    return Objects.hash(super.hashCode(), errorMessage);
  }
}


text:
package TD4;
public class Etudiant
{
	// Champs de Etudiant
	private String nom;
	private String prenom;
	private int age;
	private String niveau;
	private String filiere;
	// Constructeur de Etudiant
	public Etudiant()
	{
		nom = "inconnu";
		prenom = "inconnu";
		age = 0;
		niveau = "inconnu";
		filiere = "inconnu";
	}
	// Getters
	public String getNom()
	{
		return nom;
	}
	public String getPrenom()
	{
		return prenom;
	}
	public int getAge()
	{
		return age;
	}
	public String getNiveau()
	{
		return niveau;
	}
	public String getFiliere()
	{
		return filiere;
	}
	// Méthode pour imprimer sur la console l'identité d'un étudiant
	public String affiche()
	{
		String infos = prenom + " " + nom + " " + age + " " + niveau + " " + filiere;
		return infos;
	}
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <title>module-select | Style guide | echo-css</title>
    <meta property="og:title" content="module-select | Style guide | echo-css">

    <?php include('../doc_include/html_head.inc'); ?>

    <?php include('../doc_include/header.inc'); ?>

module-select

echo-select

echo-select-(size)

echo-select-fixed

echo-select

セレクトボックスを表示する。select要素ではなく、包括している要素にクラスを付与する。

左に 0.75em 、右に 2.5em の余白が確保される。また、右端には展開できることを示す、CSSでスタイルを定義したシェブロンが表示される。

レイアウトは component > .echo-form, layout > .echo-forms を使用することが望ましい。

.is-error を付与するとエラー表示となり、色が $important に変わる。

<?php include('../doc_include/fonttable_select.html'); ?>

    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>

    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>

<div class="echo-select">
    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>
</div>

<div class="echo-select is-error">
    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>
</div>

sub class echo-select-(size)

セレクトボックスの文字サイズ、最低高さを変更する。

(size)は、 sm, lg に対応している。

このサンプルコードでは比較のため、同サイズのボタンを表示している。

echo-select-sm

    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>

<input type="button" class="echo-button echo-button-sm echo-button-style-a" value="ボタン" />

(default)

    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>

<input type="button" class="echo-button echo-button-style-a" value="ボタン" />

echo-select-lg

    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>

<input type="button" class="echo-button echo-button-lg echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md">echo-select-sm</p>

<div class="echo-select echo-select-sm">
    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-sm echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md echo-margin-top-lg">(default)</p>

<div class="echo-select">
    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md echo-margin-top-lg">echo-select-lg</p>

<div class="echo-select echo-select-lg">
    <select>
        <option>年を選択...</option>
        <option value="2021年">2021年</option>
        <option value="2020年">2020年</option>
        <option value="2019年">2019年</option>
        <option value="2018年">2018年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-lg echo-button-style-a" value="ボタン" />

sub class echo-select-fixed

.echo-select-(size) と同時に付与すると、セレクトボックスが (breakpoint) に関わらず常に同じサイズとなる。

幅の変動が少ないグリッド内のコンポーネント等に使用する。

このサンプルコードでは比較のため、同サイズのボタンを表示している。

echo-select-sm

    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>

<input type="button" class="echo-button echo-button-fixed echo-button-sm echo-button-style-a" value="ボタン" />

(default)

    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>

<input type="button" class="echo-button echo-button-fixed echo-button-style-a" value="ボタン" />

echo-select-lg

    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>

<input type="button" class="echo-button echo-button-fixed echo-button-lg echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md">echo-select-sm</p>

<div class="echo-select echo-select-fixed echo-select-sm">
    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-fixed echo-button-sm echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md echo-margin-top-lg">(default)</p>

<div class="echo-select echo-select-fixed">
    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-fixed echo-button-style-a" value="ボタン" />

<p class="echo-title echo-title-style-a echo-title-level-5 echo-margin-bottom-md echo-margin-top-lg">echo-select-lg</p>

<div class="echo-select echo-select-fixed echo-select-lg">
    <select>
        <option>月を選択...</option>
        <option value="">2017年</option>
        <option value="">2016年</option>
        <option value="">2015年</option>
    </select>
</div>
<input type="button" class="echo-button echo-button-fixed echo-button-lg echo-button-style-a" value="ボタン" />

<?php include('../doc_include/footer.inc'); ?>


text:
import enum
import re
from dataclasses import dataclass, field
from typing import Callable, Optional, Union

from PyQt5 import QtWidgets
from PyQt5.QtGui import QTextCursor, QTextDocument

# Flags
_FLAG_BACKWARDS = 'b'
_FLAG_CASE_INSENSITIVE = 'i'
_FLAG_WHOLE_WORDS = 'w'
_FLAG_COUNT = '#'
_FLAG_REPLACE_ALL = 'a'

_SEARCH_FLAGS = ''.join([
    _FLAG_BACKWARDS,
    _FLAG_CASE_INSENSITIVE,
    _FLAG_WHOLE_WORDS,
    _FLAG_COUNT,
])

_REPLACE_FLAGS = ''.join([
    _FLAG_BACKWARDS,
    _FLAG_CASE_INSENSITIVE,
    _FLAG_WHOLE_WORDS,
    _FLAG_REPLACE_ALL,
])

# Regexes
_SEARCH_PAYLOAD = r'(?:\\/|[^/])'
_search_rx = re.compile(fr'{_SEARCH_PAYLOAD}+')
_search_flags_rx = re.compile(fr"""
    (?P<search>{_SEARCH_PAYLOAD}*?[^\\])
    /
    (?P<flags>[{_SEARCH_FLAGS}]*)
""", re.VERBOSE)
_replace_rx = re.compile(fr"""
    (?P<search>{_SEARCH_PAYLOAD}*?[^\\])
    /
    (?P<replace>({_SEARCH_PAYLOAD}*?[^\\])?)
    /
    (?P<flags>[{_REPLACE_FLAGS}]*)
""", re.VERBOSE)

# State
class SearchFlags(enum.Enum):
    backwards = enum.auto()
    case_insensitive = enum.auto()
    whole_words = enum.auto()

@dataclass
class SearchState:
    text: str
    flags: set[SearchFlags] = field(default_factory=set)

    def find(self, editor: Union[QtWidgets.QPlainTextEdit, QtWidgets.QTextEdit],
             override_flags: Optional[set[SearchFlags]] = None) -> bool:
        return editor.find(self.text,
                           _encode_flags(override_flags if override_flags is not None
                                         else self.flags))

def _parse_flags(flag_str: str) -> set[SearchFlags]:
    out = set()
    if _FLAG_BACKWARDS in flag_str:
        out.add(SearchFlags.backwards)
    if _FLAG_CASE_INSENSITIVE in flag_str:
        out.add(SearchFlags.case_insensitive)
    if _FLAG_WHOLE_WORDS in flag_str:
        out.add(SearchFlags.whole_words)
    return out

def _encode_flags(flags: set[SearchFlags]) -> QTextDocument.FindFlags:
    search_flags = QTextDocument.FindFlags()
    if SearchFlags.backwards in flags:
        search_flags |= QTextDocument.FindBackward  # type: ignore
    if SearchFlags.case_insensitive not in flags:
        search_flags |= QTextDocument.FindCaseSensitively  # type: ignore
    if SearchFlags.whole_words in flags:
        search_flags |= QTextDocument.FindWholeWords  # type: ignore
    return QTextDocument.FindFlags(search_flags)

class Searcher:
    def __init__(self, editor: Union[QtWidgets.QPlainTextEdit, QtWidgets.QTextEdit],
                 error: Callable[[str], None],
                 log: Callable[[str], None]) -> None:
        self._editor = editor
        self._search_state: Optional[SearchState] = None
        self.error = error
        self.log = log

    def search_or_replace(self, cmd: str) -> None:
        """
        Search or replace, depending on how the cmd looks.
        """
        if (match := _search_rx.fullmatch(cmd)):
            self._search_state = SearchState(match[0])
            self.search_next()
        elif (match := _search_flags_rx.fullmatch(cmd)):
            search_buffer, flags = match['search'], match['flags']
            if _FLAG_COUNT in flags:
                self._count_hits(search_buffer, _parse_flags(flags))
            else:
                self._search_state = SearchState(search_buffer, _parse_flags(flags))
                self.search_next()
        elif (match := _replace_rx.fullmatch(cmd)):
            self._search_state = SearchState(match['search'], _parse_flags(match['flags']))
            if _FLAG_REPLACE_ALL in match['flags']:
                self._replace_all(match['replace'])
            else:
                self._replace_next(match['replace'])
        else:
            self.error('Malformed search/replace expression')

    @property
    def _is_searching_backwards(self) -> bool:
        return bool(self._search_state and SearchFlags.backwards in self._search_state.flags)

    def _replace_next(self, replace_buffer: str) -> None:
        """
        Go to the next string found and replace it with replace_buffer.
        """
        if self._search_state is None:
            self.error('No previous searches')
            return
        temp_cursor = self._editor.textCursor()
        found = self._search_state.find(self._editor)
        searching_backwards = self._is_searching_backwards
        if not found and \
                (not self._editor.textCursor().atStart()
                 or (searching_backwards and not self._editor.textCursor().atEnd())):
            self._editor.moveCursor(QTextCursor.End if searching_backwards
                                    else QTextCursor.Start)
            found = self._search_state.find(self._editor)
            if not found:
                self._editor.setTextCursor(temp_cursor)
        if found:
            t = self._editor.textCursor()
            t.insertText(replace_buffer)
            replace_len = len(replace_buffer)
            t.setPosition(t.position() - replace_len)
            t.setPosition(t.position() + replace_len, QTextCursor.KeepAnchor)
            self._editor.setTextCursor(t)
            self.log(f'Replaced on line {t.blockNumber()}, pos {t.positionInBlock()}')
        else:
            self.error('Text not found')

    def search_next(self, in_reverse: bool = False) -> None:
        """
        Go to the next string found.
        """
        if self._search_state is None:
            self.error('No previous searches')
            return
        search_flags = self._search_state.flags.copy()
        if in_reverse != self._is_searching_backwards:
            searching_backwards = True
            search_flags.add(SearchFlags.backwards)
        else:
            searching_backwards = False
            search_flags.discard(SearchFlags.backwards)
        temp_cursor = self._editor.textCursor()
        found = self._search_state.find(self._editor, search_flags)
        if not found and \
                (not self._editor.textCursor().atStart()
                 or (searching_backwards and not self._editor.textCursor().atEnd())):
            self._editor.moveCursor(QTextCursor.End if searching_backwards
                                    else QTextCursor.Start)
            found = self._search_state.find(self._editor, search_flags)
        if not found:
            self._editor.setTextCursor(temp_cursor)
            self.error('Text not found')

    def _count_hits(self, target: str, flags: set[SearchFlags]) -> None:
        """
        Count how many times a term (word/sentence, etc.) has been used.
        """
        times = 0
        cursor = QTextCursor(self._editor.document())
        # Don't use the backwards flag
        flags = flags - {SearchFlags.backwards}
        while True:
            cursor = self._editor.document().find(target, cursor, _encode_flags(flags))
            if not cursor.isNull():
                times += 1
            else:
                break
        if times:
            self.log(f'The word "{target}" is used {times} times')
        else:
            self.log(f'The word "{target}" is not used')

    def _replace_all(self, replace_buffer: str) -> None:
        """
        Replace all strings found with the replace_buffer.

        As with replace_next, you probably don't want to call this manually.
        """
        if self._search_state is None:
            return
        temp_cursor = self._editor.textCursor()
        times = 0
        self._editor.moveCursor(QTextCursor.Start)
        while True:
            found = self._search_state.find(self._editor)
            if found:
                self._editor.textCursor().insertText(replace_buffer)
                times += 1
            else:
                break
        if times:
            self.log(f'{times} instance{"" if times == 1 else "s"} replaced')
        else:
            self.error('Text not found')
        self._editor.setTextCursor(temp_cursor)


text:
package com.horsefire.syncaws.tasks;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.horsefire.syncaws.CommandLineArgs;

public class TaskFactory {

	private final CommandLineArgs m_args;
	private final Map<String, Provider<? extends Task>> m_taskMapping = new HashMap<String, Provider<? extends Task>>();

	@Inject
	public TaskFactory(CommandLineArgs args,
			Provider<VersionTask> versionTaskProvider,
			Provider<InitTask> initTaskProvider,
			Provider<ValidateTask> validateTaskProvider,
			Provider<CreateTask> createTaskProvider,
			Provider<StatusTask> statusTaskProvider,
			Provider<UploadTask> uploadTaskProvider,
			Provider<HelpTask> helpTaskProvider,
			Provider<ListTask> listTaskProvider) {
		m_args = args;
		m_taskMapping.put("init", initTaskProvider);
		m_taskMapping.put("validate", validateTaskProvider);
		m_taskMapping.put("create", createTaskProvider);
		m_taskMapping.put("status", statusTaskProvider);
		m_taskMapping.put("upload", uploadTaskProvider);
		m_taskMapping.put("list", listTaskProvider);
		m_taskMapping.put("version", versionTaskProvider);
		m_taskMapping.put("help", helpTaskProvider);
	}

	public Task getTask() {
		String taskName = m_args.getTask();
		if (taskName == null) {
			throw new RuntimeException("Must specify a task: "
					+ StringUtils.join(m_taskMapping.keySet(), ", "));
		}
		Provider<? extends Task> provider = m_taskMapping.get(taskName);
		if (provider == null) {
			throw new RuntimeException("Unknown task: " + taskName);
		}
		Task task = provider.get();
		task.validate();
		return task;
	}
}


text:
module Jekyll
  class Theme
    extend Forwardable
    attr_reader   :name

    def_delegator :gemspec, :version, :version

    def initialize(name)
      @name = name.downcase.strip
      Jekyll.logger.debug "Theme:", name
      Jekyll.logger.debug "Theme source:", root
    end

    def root
      # Must use File.realpath to resolve symlinks created by rbenv
      # Otherwise, Jekyll.sanitized path with prepend the unresolved root
      @root ||= File.realpath(gemspec.full_gem_path)
    rescue Errno::ENOENT, Errno::EACCES, Errno::ELOOP
      raise "Path #{gemspec.full_gem_path} does not exist, is not accessible "\
        "or includes a symbolic link loop"
    end

    # The name of theme directory
    def basename
      @basename ||= File.basename(root)
    end

    def includes_path
      @includes_path ||= path_for "_includes"
    end

    def layouts_path
      @layouts_path ||= path_for "_layouts"
    end

    def sass_path
      @sass_path ||= path_for "_sass"
    end

    def assets_path
      @assets_path ||= path_for "assets"
    end

    def runtime_dependencies
      gemspec.runtime_dependencies
    end

    private

    def path_for(folder)
      path = realpath_for(folder)
      path if path && File.directory?(path)
    end

    def realpath_for(folder)
      # This resolves all symlinks for the theme subfolder and then ensures that the directory
      # remains inside the theme root. This prevents the use of symlinks for theme subfolders to
      # escape the theme root.
      # However, symlinks are allowed to point to other directories within the theme.
      Jekyll.sanitized_path(root, File.realpath(Jekyll.sanitized_path(root, folder.to_s)))
    rescue Errno::ENOENT, Errno::EACCES, Errno::ELOOP => e
      log_realpath_exception(e, folder)
      nil
    end

    def log_realpath_exception(err, folder)
      return if err.is_a?(Errno::ENOENT)

      case err
      when Errno::EACCES
        Jekyll.logger.error "Theme error:", "Directory '#{folder}' is not accessible."
      when Errno::ELOOP
        Jekyll.logger.error "Theme error:", "Directory '#{folder}' includes a symbolic link loop."
      end
    end

    def gemspec
      @gemspec ||= Gem::Specification.find_by_name(name)
    rescue Gem::LoadError
      raise Jekyll::Errors::MissingDependencyException,
            "The #{name} theme could not be found."
    end
  end
end


text:
using UnityEngine;

public class CreateGravityWell : MonoBehaviour
{
    public GameObject gravityWellPrefab;
    public Camera referenceCamera;

    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0)) {
            HandleMouseButtonDown();
        }
    }

    void HandleMouseButtonDown() {
        Vector3 position = new Vector3(Input.mousePosition.x, Input.mousePosition.y, referenceCamera.nearClipPlane);

        Vector3 worldPosition = referenceCamera.ScreenToWorldPoint(position);

        Instantiate(gravityWellPrefab, worldPosition, Quaternion.identity);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    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:orientation="vertical">

    <include layout="@layout/toolbar"/>

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <RelativeLayout
            android:id="@+id/activity_exchanges_table"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingLeft="@dimen/activity_horizontal_margin"
            android:paddingRight="@dimen/activity_horizontal_margin"
            android:paddingTop="@dimen/activity_vertical_margin"
            android:paddingBottom="@dimen/activity_vertical_margin"
            tools:context="ru.adios.budgeter.activities.ExchangesTableActivity"/>
    </ScrollView>
</LinearLayout>


text:
package org.apache.hadoop.hdfs.tools.offlineImageViewer;

import com.google.common.annotations.VisibleForTesting;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.concurrent.GlobalEventExecutor;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.Closeable;
import java.io.IOException;
import java.net.InetSocketAddress;

/**
 * WebImageViewer loads a fsimage and exposes read-only WebHDFS API for its
 * namespace.
 */
public class WebImageViewer implements Closeable {
  public static final Log LOG = LogFactory.getLog(WebImageViewer.class);

  private Channel channel;
  private InetSocketAddress address;

  private final ServerBootstrap bootstrap;
  private final EventLoopGroup bossGroup;
  private final EventLoopGroup workerGroup;
  private final ChannelGroup allChannels;

  public WebImageViewer(InetSocketAddress address) {
    this.address = address;
    this.bossGroup = new NioEventLoopGroup();
    this.workerGroup = new NioEventLoopGroup();
    this.allChannels = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
    this.bootstrap = new ServerBootstrap()
      .group(bossGroup, workerGroup)
      .channel(NioServerSocketChannel.class);
  }

  /**
   * Start WebImageViewer and wait until the thread is interrupted.
   * @param fsimage the fsimage to load.
   * @throws IOException if failed to load the fsimage.
   */
  public void start(String fsimage) throws IOException {
    try {
      initServer(fsimage);
      channel.closeFuture().await();
    } catch (InterruptedException e) {
      LOG.info("Interrupted. Stopping the WebImageViewer.");
      close();
    }
  }

  /**
   * Start WebImageViewer.
   * @param fsimage the fsimage to load.
   * @throws IOException if fail to load the fsimage.
   */
  @VisibleForTesting
  public void initServer(String fsimage)
          throws IOException, InterruptedException {
    final FSImageLoader loader = FSImageLoader.load(fsimage);

    bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
      @Override
      protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline p = ch.pipeline();
        p.addLast(new HttpRequestDecoder(),
          new StringEncoder(),
          new HttpResponseEncoder(),
          new FSImageHandler(loader, allChannels));
      }
    });

    channel = bootstrap.bind(address).sync().channel();
    allChannels.add(channel);

    address = (InetSocketAddress) channel.localAddress();
    LOG.info("WebImageViewer started. Listening on " + address.toString() + ". Press Ctrl+C to stop the viewer.");
  }

  /**
   * Get the listening port.
   * @return the port WebImageViewer is listening on
   */
  @VisibleForTesting
  public int getPort() {
    return address.getPort();
  }

  @Override
  public void close() {
    allChannels.close().awaitUninterruptibly();
    bossGroup.shutdownGracefully();
    workerGroup.shutdownGracefully();
  }
}


text:
function [ss_info,phi_limits] = frame_phases(first,last,freq,frame_rate,nBins)
%
% Create and map phase values to frame numbers. Used by other functions for phase averaging
%
% created by:
% Prabu Sellappan - August 2010
% modified: Prabu Sellappan, 12/9/2014
%
% usage:
% [ss_info,phi_limits] = frame_phases(first,last,freq,frame_rate,nBins)
% creates Nx2 matrix where col1 is frame # and col2 is phase
%
% first - starting index value of frames
% last - last index value of frames
% freq - frequency of forcing, in Hz
% frame_rate - frame rate of data acquisition, in fps
% nBins - # of bins for phase averaging

framenums = first:2:last;
ElapsedTime = (framenums-first)/frame_rate;
phases = ElapsedTime * freq;
phases = (phases - floor(phases))*2*pi();
ss_info(:,1) = framenums;
ss_info(:,2) = phases;
phi_limits = zeros(nBins,2);
phi_width = max(phases)/nBins;
for i=1:nBins
    phi_limits(i,1) = (i*phi_width)-phi_width;
    phi_limits(i,2) = i*phi_width;

end
end


text:
package verify

import (
	"crypto/hmac"
	"fmt"

	"github.com/open-policy-agent/opa/internal/jwx/jwa"
	"github.com/open-policy-agent/opa/internal/jwx/jws/sign"
	"github.com/pkg/errors"
)

func newHMAC(alg jwa.SignatureAlgorithm) (*HMACVerifier, error) {

	s, err := sign.New(alg)
	if err != nil {
		return nil, fmt.Errorf("failed to generate HMAC signer: %w", err)
	}
	return &HMACVerifier{signer: s}, nil
}

// Verify checks whether the signature for a given input and key is correct
func (v HMACVerifier) Verify(signingInput, signature []byte, key interface{}) (err error) {

	expected, err := v.signer.Sign(signingInput, key)
	if err != nil {
		return fmt.Errorf("failed to generated signature: %w", err)
	}

	if !hmac.Equal(signature, expected) {
		return errors.New("failed to match hmac signature")
	}
	return nil
}


text:
<?php
  // Controlador de login hecho por FVieira.
  session_start(); // se inicia el manejo de sesiones

  require_once '../views/templateEngine.php'; // se carga la clase TemplateEngine
  require_once '../cancerbero/php/DBManager.php'; // se carga el driver de cancerbero
  require_once 'modal.php';
  $db = DBManager::getInstance();
  $db->connect();
  $renderMain = new TemplateEngine();
  $renderlogin = new TemplateEngine(); //instancias de TemplateEngine
  $renderlogin->status = null; //por defecto no hay ningun error (en la plantilla login_v la variable $status valdrá <br/>)

  if(isset($_POST['name'])&&isset($_POST['pass'])){ // si ya se hizo algun post
    if($db->tryLogin($_POST['name'],$_POST['pass'])){ //comprueba los datos nombre de Usuario y contrseña
      $_SESSION["name"] = $_POST['name'];
      header("location: home.php");
    }
    $status = "Usuario y/o contraseña invalido";
    $contenido = "Por favor, compruebe sus datos de acceso y compruebe si no tiene la tecla bloq mayus activada";
    $renderlogin->status = renderModalError($status,$contenido);
  }
  $renderMain->title = "Login";
  $renderMain->navbar = null; //el login no tiene navbar

  $renderMain->content = $renderlogin->render('login_v.php'); //que inserte en la variable $content de la plantilla main.php el resultado de renderizar login_v.php
  echo $renderMain->renderMain(); //renderiza main y escribe la pagina

 ?>


text:
Sequel.migration do
  up do
    create_table :assets do
      primary_key :id
      Integer     :user_id, :null => false, :index => true
      String      :public_url, :text => true
    end
  end

  down do
    drop_table :assets
  end
end


text:
require 'minitest/autorun'
require_relative '../lib/key'

class TestKey < Minitest::Test

  def setup
    @minor_key = Key.new("Gmin")
    @major_key = Key.new("Dmaj")
  end

  def test_to_s
    assert_equal "Dmaj", @major_key.to_s
    assert_equal "Gmin", @minor_key.to_s
  end

  def test_quality
    assert_equal @major_key.quality, "major"
    assert_equal @minor_key.quality, "minor"
  end

  def test_up_fifth
    assert_equal Key.new('Amin').up_fifth, 'Emin'
    assert_equal Key.new('Dmin').up_fifth, 'Amin'
    assert_equal Key.new('C#min').up_fifth, 'G#min'
    assert_equal Key.new('G#min').up_fifth, 'D#min'
  end

  def test_down_fifth
    assert_equal Key.new('Dmin').down_fifth, 'Gmin'
    assert_equal Key.new('G#min').down_fifth, 'C#min'
    assert_equal Key.new('A#min').down_fifth, 'D#min'
  end

  def test_relative
    assert_equal Key.new('Dmin').relative, 'Fmaj'
    assert_equal Key.new('Cmaj').relative, 'Amin'
  end

  def test_can_be_followed_with
    k1 =  Key.new('Amin')
    assert k1.can_be_followed_with Key.new('Emin')
    assert k1.can_be_followed_with Key.new('Dmin')
    assert k1.can_be_followed_with Key.new('Cmaj')
    assert k1.can_be_followed_with Key.new('Amin')

    refute k1.can_be_followed_with Key.new('Fmin')
    refute k1.can_be_followed_with Key.new('D#min')
    refute k1.can_be_followed_with Key.new('Cmin')
  end
end


text:
/**
 *
 */
/**
 * @author java
 *
 */
package com.ipartek.formacion.service.interfaces;


text:
namespace blink {

namespace {

// Returns true if there are event listeners of |handler_class| on |touch_node|
// or any of its ancestors inside the document (including DOMWindow).
bool HasEventHandlerInAncestorPath(
    Node* touch_node,
    EventHandlerRegistry::EventHandlerClass handler_class) {
  Document& document = touch_node->GetDocument();
  const EventTargetSet* event_target_set =
      document.GetFrame()->GetEventHandlerRegistry().EventHandlerTargets(
          handler_class);

  if (event_target_set->Contains(document.domWindow()))
    return true;

  for (Node& ancestor : NodeTraversal::InclusiveAncestorsOf(*touch_node)) {
    if (event_target_set->Contains(&ancestor))
      return true;
  }

  return false;
}

bool HasTouchHandlers(const EventHandlerRegistry& registry) {
  return registry.HasEventHandlers(
             EventHandlerRegistry::kTouchStartOrMoveEventBlocking) ||
         registry.HasEventHandlers(
             EventHandlerRegistry::kTouchStartOrMoveEventBlockingLowLatency) ||
         registry.HasEventHandlers(
             EventHandlerRegistry::kTouchStartOrMoveEventPassive) ||
         registry.HasEventHandlers(
             EventHandlerRegistry::kTouchEndOrCancelEventBlocking) ||
         registry.HasEventHandlers(
             EventHandlerRegistry::kTouchEndOrCancelEventPassive);
}

const AtomicString& TouchEventNameForPointerEventType(
    WebInputEvent::Type type) {
  switch (type) {
    case WebInputEvent::Type::kPointerUp:
      return event_type_names::kTouchend;
    case WebInputEvent::Type::kPointerCancel:
      return event_type_names::kTouchcancel;
    case WebInputEvent::Type::kPointerDown:
      return event_type_names::kTouchstart;
    case WebInputEvent::Type::kPointerMove:
      return event_type_names::kTouchmove;
    default:
      NOTREACHED();
      return g_empty_atom;
  }
}

WebTouchPoint::State TouchPointStateFromPointerEventType(
    WebInputEvent::Type type,
    bool stale) {
  if (stale)
    return WebTouchPoint::State::kStateStationary;
  switch (type) {
    case WebInputEvent::Type::kPointerUp:
      return WebTouchPoint::State::kStateReleased;
    case WebInputEvent::Type::kPointerCancel:
      return WebTouchPoint::State::kStateCancelled;
    case WebInputEvent::Type::kPointerDown:
      return WebTouchPoint::State::kStatePressed;
    case WebInputEvent::Type::kPointerMove:
      return WebTouchPoint::State::kStateMoved;
    default:
      NOTREACHED();
      return WebTouchPoint::State::kStateUndefined;
  }
}

WebTouchPoint CreateWebTouchPointFromWebPointerEvent(
    const WebPointerEvent& web_pointer_event,
    bool stale) {
  WebTouchPoint web_touch_point(web_pointer_event);
  web_touch_point.state =
      TouchPointStateFromPointerEventType(web_pointer_event.GetType(), stale);
  web_touch_point.radius_x = web_pointer_event.width / 2.f;
  web_touch_point.radius_y = web_pointer_event.height / 2.f;
  web_touch_point.rotation_angle = web_pointer_event.rotation_angle;
  return web_touch_point;
}

void SetWebTouchEventAttributesFromWebPointerEvent(
    WebTouchEvent* web_touch_event,
    const WebPointerEvent& web_pointer_event) {
  web_touch_event->dispatch_type = web_pointer_event.dispatch_type;
  web_touch_event->touch_start_or_first_touch_move =
      web_pointer_event.touch_start_or_first_touch_move;
  web_touch_event->moved_beyond_slop_region =
      web_pointer_event.moved_beyond_slop_region;
  web_touch_event->SetFrameScale(web_pointer_event.FrameScale());
  web_touch_event->SetFrameTranslate(web_pointer_event.FrameTranslate());
  web_touch_event->SetTimeStamp(web_pointer_event.TimeStamp());
  web_touch_event->SetModifiers(web_pointer_event.GetModifiers());
}

// Defining this class type local to
// DispatchTouchEventFromAccumulatdTouchPoints() and annotating
// it with STACK_ALLOCATED(), runs into MSVC(VS 2013)'s C4822 warning
// that the local class doesn't provide a local definition for 'operator new'.
// Which it intentionally doesn't and shouldn't.
//
// Work around such toolchain bugginess by lifting out the type, thereby
// taking it out of C4822's reach.
class ChangedTouches final {
  STACK_ALLOCATED();

 public:
  // The touches corresponding to the particular change state this struct
  // instance represents.
  TouchList* touches_ = nullptr;

  using EventTargetSet = HeapHashSet<Member<EventTarget>>;
  // Set of targets involved in m_touches.
  EventTargetSet targets_;
};

}  // namespace

TouchEventManager::TouchEventManager(LocalFrame& frame) : frame_(frame) {
  Clear();
}

void TouchEventManager::Clear() {
  touch_sequence_document_.Clear();
  touch_attribute_map_.clear();
  last_coalesced_touch_event_ = WebTouchEvent();
  suppressing_touchmoves_within_slop_ = false;
  current_touch_action_ = TouchAction::kAuto;
}

void TouchEventManager::Trace(Visitor* visitor) {
  visitor->Trace(frame_);
  visitor->Trace(touch_sequence_document_);
  visitor->Trace(touch_attribute_map_);
}

Touch* TouchEventManager::CreateDomTouch(
    const TouchEventManager::TouchPointAttributes* point_attr,
    bool* known_target) {
  Node* touch_node = point_attr->target_;
  String region_id = point_attr->region_;
  *known_target = false;

  LocalFrame* target_frame = nullptr;
  if (touch_node) {
    Document& doc = touch_node->GetDocument();
    // If the target node has moved to a new document while it was being
    // touched, we can't send events to the new document because that could
    // leak nodes from one document to another. See http://crbug.com/394339.
    if (&doc == touch_sequence_document_.Get()) {
      target_frame = doc.GetFrame();
      *known_target = true;
    }
  }
  if (!(*known_target)) {
    // If we don't have a target registered for the point it means we've
    // missed our opportunity to do a hit test for it (due to some
    // optimization that prevented blink from ever seeing the
    // touchstart), or that the touch started outside the active touch
    // sequence document. We should still include the touch in the
    // Touches list reported to the application (eg. so it can
    // differentiate between a one and two finger gesture), but we won't
    // actually dispatch any events for it. Set the target to the
    // Document so that there's some valid node here. Perhaps this
    // should really be LocalDOMWindow, but in all other cases the target of
    // a Touch is a Node so using the window could be a breaking change.
    // Since we know there was no handler invoked, the specific target
    // should be completely irrelevant to the application.
    touch_node = touch_sequence_document_;
    target_frame = touch_sequence_document_->GetFrame();
  }
  DCHECK(target_frame);

  WebPointerEvent transformed_event =
      point_attr->event_.WebPointerEventInRootFrame();
  float scale_factor = 1.0f / target_frame->PageZoomFactor();

  FloatPoint document_point = target_frame->View()
                                  ->RootFrameToDocument(FloatPoint(
                                      transformed_event.PositionInWidget()))
                                  .ScaledBy(scale_factor);
  FloatSize adjusted_radius =
      FloatSize(transformed_event.width / 2.f, transformed_event.height / 2.f)
          .ScaledBy(scale_factor);

  return MakeGarbageCollected<Touch>(
      target_frame, touch_node, point_attr->event_.id,
      FloatPoint(transformed_event.PositionInScreen()), document_point,
      adjusted_radius, transformed_event.rotation_angle,
      transformed_event.force, region_id);
}

WebCoalescedInputEvent TouchEventManager::GenerateWebCoalescedInputEvent() {
  DCHECK(!touch_attribute_map_.IsEmpty());

  WebTouchEvent event;

  const auto& first_touch_pointer_event =
      touch_attribute_map_.begin()->value->event_;

  SetWebTouchEventAttributesFromWebPointerEvent(&event,
                                                first_touch_pointer_event);
  SetWebTouchEventAttributesFromWebPointerEvent(&last_coalesced_touch_event_,
                                                first_touch_pointer_event);
  WebInputEvent::Type touch_event_type = WebInputEvent::Type::kTouchMove;
  Vector<WebPointerEvent> all_coalesced_events;
  Vector<int> available_ids;
  for (const auto& id : touch_attribute_map_.Keys())
    available_ids.push_back(id);
  std::sort(available_ids.begin(), available_ids.end());
  for (const int& touch_point_id : available_ids) {
    auto* const touch_point_attribute = touch_attribute_map_.at(touch_point_id);
    const WebPointerEvent& touch_pointer_event = touch_point_attribute->event_;
    event.touches[event.touches_length++] =
        CreateWebTouchPointFromWebPointerEvent(touch_pointer_event,
                                               touch_point_attribute->stale_);
    if (!touch_point_attribute->stale_) {
      event.SetTimeStamp(std::max(event.TimeStamp(),
                                  touch_point_attribute->event_.TimeStamp()));
    }

    // Only change the touch event type from move. So if we have two pointers
    // in up and down state we just set the touch event type to the first one
    // we see.
    // TODO(crbug.com/732842): Note that event sender API allows sending any
    // mix of input and as long as we don't crash or anything we should be good
    // for now.
    if (touch_event_type == WebInputEvent::Type::kTouchMove) {
      if (touch_pointer_event.GetType() == WebInputEvent::Type::kPointerDown)
        touch_event_type = WebInputEvent::Type::kTouchStart;
      else if (touch_pointer_event.GetType() ==
               WebInputEvent::Type::kPointerCancel)
        touch_event_type = WebInputEvent::Type::kTouchCancel;
      else if (touch_pointer_event.GetType() == WebInputEvent::Type::kPointerUp)
        touch_event_type = WebInputEvent::Type::kTouchEnd;
    }

    for (const WebPointerEvent& coalesced_event :
         touch_point_attribute->coalesced_events_) {
      all_coalesced_events.push_back(coalesced_event);
    }
  }
  event.SetType(touch_event_type);
  last_coalesced_touch_event_.SetType(touch_event_type);

  // Create all coalesced touch events based on pointerevents
  struct {
    bool operator()(const WebPointerEvent& a, const WebPointerEvent& b) {
      return a.TimeStamp() < b.TimeStamp();
    }
  } timestamp_based_event_comparison;
  std::sort(all_coalesced_events.begin(), all_coalesced_events.end(),
            timestamp_based_event_comparison);
  WebCoalescedInputEvent result(event.Clone(), {}, {}, ui::LatencyInfo());
  for (const auto& web_pointer_event : all_coalesced_events) {
    if (web_pointer_event.GetType() == WebInputEvent::Type::kPointerDown) {
      // TODO(crbug.com/732842): Technically we should never receive the
      // pointerdown twice for the same touch point. But event sender API allows
      // that. So we should handle it gracefully.
      WebTouchPoint web_touch_point(web_pointer_event);
      bool found_existing_id = false;
      for (unsigned i = 0; i < last_coalesced_touch_event_.touches_length;
           ++i) {
        if (last_coalesced_touch_event_.touches[i].id == web_pointer_event.id) {
          last_coalesced_touch_event_.touches[i] =
              CreateWebTouchPointFromWebPointerEvent(web_pointer_event, false);
          last_coalesced_touch_event_.SetTimeStamp(
              web_pointer_event.TimeStamp());
          found_existing_id = true;
          break;
        }
      }
      // If the pointerdown point didn't exist add a new point to the array.
      if (!found_existing_id) {
        last_coalesced_touch_event_
            .touches[last_coalesced_touch_event_.touches_length++] =
            CreateWebTouchPointFromWebPointerEvent(web_pointer_event, false);
      }
      struct {
        bool operator()(const WebTouchPoint& a, const WebTouchPoint& b) {
          return a.id < b.id;
        }
      } id_based_event_comparison;
      std::sort(last_coalesced_touch_event_.touches,
                last_coalesced_touch_event_.touches +
                    last_coalesced_touch_event_.touches_length,
                id_based_event_comparison);
      result.AddCoalescedEvent(last_coalesced_touch_event_);
    } else {
      for (unsigned i = 0; i < last_coalesced_touch_event_.touches_length;
           ++i) {
        if (last_coalesced_touch_event_.touches[i].id == web_pointer_event.id) {
          last_coalesced_touch_event_.touches[i] =
              CreateWebTouchPointFromWebPointerEvent(web_pointer_event, false);
          last_coalesced_touch_event_.SetTimeStamp(
              web_pointer_event.TimeStamp());
          result.AddCoalescedEvent(last_coalesced_touch_event_);

          // Remove up and canceled points.
          unsigned result_size = 0;
          for (unsigned j = 0; j < last_coalesced_touch_event_.touches_length;
               j++) {
            if (last_coalesced_touch_event_.touches[j].state !=
                    WebTouchPoint::State::kStateCancelled &&
                last_coalesced_touch_event_.touches[j].state !=
                    WebTouchPoint::State::kStateReleased) {
              last_coalesced_touch_event_.touches[result_size++] =
                  last_coalesced_touch_event_.touches[j];
            }
          }
          last_coalesced_touch_event_.touches_length = result_size;
          break;
        }
      }
    }

    for (unsigned i = 0; i < event.touches_length; ++i) {
      event.touches[i].state = blink::WebTouchPoint::State::kStateStationary;
      event.touches[i].movement_x = 0;
      event.touches[i].movement_y = 0;
    }
  }

  return result;
}

WebInputEventResult
TouchEventManager::DispatchTouchEventFromAccumulatdTouchPoints() {
  // Build up the lists to use for the |touches|, |targetTouches| and
  // |changedTouches| attributes in the JS event. See
  // http://www.w3.org/TR/touch-events/#touchevent-interface for how these
  // lists fit together.

  bool new_touch_point_since_last_dispatch = false;
  bool any_touch_canceled_or_ended = false;
  bool all_touch_points_pressed = true;

  for (const auto& attr : touch_attribute_map_.Values()) {
    if (!attr->stale_)
      new_touch_point_since_last_dispatch = true;
    if (attr->event_.GetType() == WebInputEvent::Type::kPointerUp ||
        attr->event_.GetType() == WebInputEvent::Type::kPointerCancel)
      any_touch_canceled_or_ended = true;
    if (attr->event_.GetType() != WebInputEvent::Type::kPointerDown)
      all_touch_points_pressed = false;
  }

  if (!new_touch_point_since_last_dispatch)
    return WebInputEventResult::kNotHandled;

  if (any_touch_canceled_or_ended || touch_attribute_map_.size() > 1)
    suppressing_touchmoves_within_slop_ = false;

  if (suppressing_touchmoves_within_slop_) {
    // There is exactly one touch point here otherwise
    // |suppressing_touchmoves_within_slop_| would have been false.
    DCHECK_EQ(1U, touch_attribute_map_.size());
    const auto& touch_point_attribute = touch_attribute_map_.begin()->value;
    if (touch_point_attribute->event_.GetType() ==
        WebInputEvent::Type::kPointerMove) {
      if (!touch_point_attribute->event_.moved_beyond_slop_region)
        return WebInputEventResult::kHandledSuppressed;
      suppressing_touchmoves_within_slop_ = false;
    }
  }

  // Holds the complete set of touches on the screen.
  TouchList* touches = TouchList::Create();

  // A different view on the 'touches' list above, filtered and grouped by
  // event target. Used for the |targetTouches| list in the JS event.
  using TargetTouchesHeapMap = HeapHashMap<EventTarget*, Member<TouchList>>;
  TargetTouchesHeapMap touches_by_target;

  // Array of touches per state, used to assemble the |changedTouches| list.
  ChangedTouches
      changed_touches[static_cast<int>(WebInputEvent::Type::kPointerTypeLast) -
                      static_cast<int>(WebInputEvent::Type::kPointerTypeFirst) +
                      1];

  Vector<int> available_ids;
  for (const auto& id : touch_attribute_map_.Keys())
    available_ids.push_back(id);
  std::sort(available_ids.begin(), available_ids.end());
  for (const int& touch_point_id : available_ids) {
    auto* const touch_point_attribute = touch_attribute_map_.at(touch_point_id);
    WebInputEvent::Type event_type = touch_point_attribute->event_.GetType();
    bool known_target;

    Touch* touch = CreateDomTouch(touch_point_attribute, &known_target);
    EventTarget* touch_target = touch->target();

    // Ensure this target's touch list exists, even if it ends up empty, so
    // it can always be passed to TouchEvent::Create below.
    TargetTouchesHeapMap::iterator target_touches_iterator =
        touches_by_target.find(touch_target);
    if (target_touches_iterator == touches_by_target.end()) {
      touches_by_target.Set(touch_target, TouchList::Create());
      target_touches_iterator = touches_by_target.find(touch_target);
    }

    // |touches| and |targetTouches| should only contain information about
    // touches still on the screen, so if this point is released or
    // cancelled it will only appear in the |changedTouches| list.
    if (event_type != WebInputEvent::Type::kPointerUp &&
        event_type != WebInputEvent::Type::kPointerCancel) {
      touches->Append(touch);
      target_touches_iterator->value->Append(touch);
    }

    // Now build up the correct list for |changedTouches|.
    // Note that  any touches that are in the TouchStationary state (e.g. if
    // the user had several points touched but did not move them all) should
    // never be in the |changedTouches| list so we do not handle them
    // explicitly here. See https://bugs.webkit.org/show_bug.cgi?id=37609
    // for further discussion about the TouchStationary state.
    if (!touch_point_attribute->stale_ && known_target) {
      size_t event_type_idx =
          static_cast<int>(event_type) -
          static_cast<int>(WebInputEvent::Type::kPointerTypeFirst);
      if (!changed_touches[event_type_idx].touches_)
        changed_touches[event_type_idx].touches_ = TouchList::Create();
      changed_touches[event_type_idx].touches_->Append(touch);
      changed_touches[event_type_idx].targets_.insert(touch_target);
    }
  }

  WebInputEventResult event_result = WebInputEventResult::kNotHandled;

  // First we construct the webcoalescedinputevent containing all the coalesced
  // touch event.
  WebCoalescedInputEvent coalesced_event = GenerateWebCoalescedInputEvent();

  // Now iterate through the |changedTouches| list and |m_targets| within it,
  // sending TouchEvents to the targets as required.
  for (unsigned action =
           static_cast<int>(WebInputEvent::Type::kPointerTypeFirst);
       action <= static_cast<int>(WebInputEvent::Type::kPointerTypeLast);
       ++action) {
    size_t action_idx =
        action - static_cast<int>(WebInputEvent::Type::kPointerTypeFirst);
    if (!changed_touches[action_idx].touches_)
      continue;

    const AtomicString& event_name(TouchEventNameForPointerEventType(
        static_cast<WebInputEvent::Type>(action)));

    for (const auto& event_target : changed_touches[action_idx].targets_) {
      EventTarget* touch_event_target = event_target;
      TouchEvent* touch_event = TouchEvent::Create(
          coalesced_event, touches, touches_by_target.at(touch_event_target),
          changed_touches[action_idx].touches_, event_name,
          touch_event_target->ToNode()->GetDocument().domWindow(),
          current_touch_action_);

      DispatchEventResult dom_dispatch_result =
          touch_event_target->DispatchEvent(*touch_event);

      event_result = event_handling_util::MergeEventResult(
          event_result,
          event_handling_util::ToWebInputEventResult(dom_dispatch_result));
    }
  }

  if (should_enforce_vertical_scroll_)
    event_result = EnsureVerticalScrollIsPossible(event_result);

  // Suppress following touchmoves within the slop region if the touchstart is
  // not consumed.
  if (all_touch_points_pressed &&
      event_result == WebInputEventResult::kNotHandled) {
    suppressing_touchmoves_within_slop_ = true;
  }

  return event_result;
}

void TouchEventManager::UpdateTouchAttributeMapsForPointerDown(
    const WebPointerEvent& event,
    const event_handling_util::PointerEventTarget& pointer_event_target) {
  // Touch events implicitly capture to the touched node, and don't change
  // active/hover states themselves (Gesture events do). So we only need
  // to hit-test on touchstart and when the target could be different than
  // the corresponding pointer event target.
  DCHECK(event.GetType() == WebInputEvent::Type::kPointerDown);
  // Ideally we'd DCHECK(!touch_attribute_map_.Contains(event.id))
  // since we shouldn't get a touchstart for a touch that's already
  // down. However EventSender allows this to be violated and there's
  // some tests that take advantage of it. There may also be edge
  // cases in the browser where this happens.
  // See http://crbug.com/345372.
  touch_attribute_map_.Set(event.id,
                           MakeGarbageCollected<TouchPointAttributes>(event));

  Node* touch_node = pointer_event_target.target_element;
  String region = pointer_event_target.region;

  HitTestRequest::HitTestRequestType hit_type = HitTestRequest::kTouchEvent |
                                                HitTestRequest::kReadOnly |
                                                HitTestRequest::kActive;
  HitTestResult result;
  // For the touchPressed points hit-testing is done in
  // PointerEventManager. If it was the second touch there is a
  // capturing documents for the touch and |m_touchSequenceDocument|
  // is not null. So if PointerEventManager should hit-test again
  // against |m_touchSequenceDocument| if the target set by
  // PointerEventManager was either null or not in
  // |m_touchSequenceDocument|.
  if (touch_sequence_document_ &&
      (!touch_node || &touch_node->GetDocument() != touch_sequence_document_)) {
    if (touch_sequence_document_->GetFrame()) {
      HitTestLocation location(PhysicalOffset::FromFloatPointRound(
          touch_sequence_document_->GetFrame()->View()->ConvertFromRootFrame(
              FloatPoint(event.PositionInWidget()))));
      result = event_handling_util::HitTestResultInFrame(
          touch_sequence_document_->GetFrame(), location, hit_type);
      Node* node = result.InnerNode();
      if (!node)
        return;
      if (auto* canvas = DynamicTo<HTMLCanvasElement>(node)) {
        HitTestCanvasResult* hit_test_canvas_result =
            canvas->GetControlAndIdIfHitRegionExists(
                result.PointInInnerNodeFrame());
        if (hit_test_canvas_result->GetControl())
          node = hit_test_canvas_result->GetControl();
        region = hit_test_canvas_result->GetId();
      }
      // Touch events should not go to text nodes.
      if (node->IsTextNode())
        node = FlatTreeTraversal::Parent(*node);
      touch_node = node;
    } else {
      return;
    }
  }
  if (!touch_node)
    return;
  if (!touch_sequence_document_) {
    // Keep track of which document should receive all touch events
    // in the active sequence. This must be a single document to
    // ensure we don't leak Nodes between documents.
    touch_sequence_document_ = &(touch_node->GetDocument());
    DCHECK(touch_sequence_document_->GetFrame()->View());
  }

  TouchPointAttributes* attributes = touch_attribute_map_.at(event.id);
  attributes->target_ = touch_node;
  attributes->region_ = region;

  TouchAction effective_touch_action =
      touch_action_util::ComputeEffectiveTouchAction(*touch_node);

  should_enforce_vertical_scroll_ =
      touch_sequence_document_->IsVerticalScrollEnforced();
  if (should_enforce_vertical_scroll_ &&
      HasEventHandlerInAncestorPath(
          touch_node, EventHandlerRegistry::kTouchStartOrMoveEventBlocking)) {
    delayed_effective_touch_action_ =
        delayed_effective_touch_action_.value_or(TouchAction::kAuto) &
        effective_touch_action;
  }
  if (!delayed_effective_touch_action_) {
    frame_->GetPage()->GetChromeClient().SetTouchAction(frame_,
                                                        effective_touch_action);
  }
  // Combine the current touch action sequence with the touch action
  // for the current finger press.
  current_touch_action_ &= effective_touch_action;
}

void TouchEventManager::HandleTouchPoint(
    const WebPointerEvent& event,
    const Vector<WebPointerEvent>& coalesced_events,
    const event_handling_util::PointerEventTarget& pointer_event_target) {
  DCHECK_GE(event.GetType(), WebInputEvent::Type::kPointerTypeFirst);
  DCHECK_LE(event.GetType(), WebInputEvent::Type::kPointerTypeLast);
  DCHECK_NE(event.GetType(), WebInputEvent::Type::kPointerCausedUaAction);

  if (touch_attribute_map_.IsEmpty()) {
    // Ideally we'd DCHECK(!m_touchSequenceDocument) here since we should
    // have cleared the active document when we saw the last release. But we
    // have some tests that violate this, ClusterFuzz could trigger it, and
    // there may be cases where the browser doesn't reliably release all
    // touches. http://crbug.com/345372 tracks this.
    AllTouchesReleasedCleanup();
  }

  DCHECK(frame_->View());
  if (touch_sequence_document_ &&
      (!touch_sequence_document_->GetFrame() ||
       !touch_sequence_document_->GetFrame()->View())) {
    // If the active touch document has no frame or view, it's probably being
    // destroyed so we can't dispatch events.
    // Update the points so they get removed in flush when they are released.
    if (touch_attribute_map_.Contains(event.id)) {
      TouchPointAttributes* attributes = touch_attribute_map_.at(event.id);
      attributes->event_ = event;
    }
    return;
  }

  // In touch event model only touch starts can set the target and after that
  // the touch event always goes to that target.
  if (event.GetType() == WebInputEvent::Type::kPointerDown) {
    UpdateTouchAttributeMapsForPointerDown(event, pointer_event_target);
  }

  // We might not receive the down action for a touch point. In that case we
  // would have never added them to |touch_attribute_map_| or hit-tested
  // them. For those just keep them in the map with a null target. Later they
  // will be targeted at the |touch_sequence_document_|.
  if (!touch_attribute_map_.Contains(event.id)) {
    touch_attribute_map_.insert(
        event.id, MakeGarbageCollected<TouchPointAttributes>(event));
  }

  TouchPointAttributes* attributes = touch_attribute_map_.at(event.id);
  attributes->event_ = event;
  attributes->coalesced_events_ = coalesced_events;
  attributes->stale_ = false;
}

WebInputEventResult TouchEventManager::FlushEvents() {
  WebInputEventResult result = WebInputEventResult::kNotHandled;

  // If there's no document receiving touch events, or no handlers on the
  // document set to receive the events, then we can skip all the rest of
  // sending the event.
  if (touch_sequence_document_ && touch_sequence_document_->GetPage() &&
      HasTouchHandlers(
          touch_sequence_document_->GetFrame()->GetEventHandlerRegistry()) &&
      touch_sequence_document_->GetFrame()->View()) {
    result = DispatchTouchEventFromAccumulatdTouchPoints();
  }

  // Cleanup the |touch_attribute_map_| map from released and canceled
  // touch points.
  Vector<int> released_canceled_points;
  for (auto& attributes : touch_attribute_map_.Values()) {
    if (attributes->event_.GetType() == WebInputEvent::Type::kPointerUp ||
        attributes->event_.GetType() == WebInputEvent::Type::kPointerCancel) {
      released_canceled_points.push_back(attributes->event_.id);
    } else {
      attributes->stale_ = true;
      attributes->event_.movement_x = 0;
      attributes->event_.movement_y = 0;
      attributes->coalesced_events_.clear();
    }
  }
  touch_attribute_map_.RemoveAll(released_canceled_points);

  if (touch_attribute_map_.IsEmpty()) {
    AllTouchesReleasedCleanup();
  }

  return result;
}

void TouchEventManager::AllTouchesReleasedCleanup() {
  touch_sequence_document_.Clear();
  current_touch_action_ = TouchAction::kAuto;
  last_coalesced_touch_event_ = WebTouchEvent();
  // Ideally, we should have DCHECK(!delayed_effective_touch_action_) but we do
  // we do actually get here from HandleTouchPoint(). Supposedly, if there has
  // been a |touch_sequence_document_| and nothing in the |touch_attribute_map_|
  // we still get here and if |touch_sequence_document| was of the type which
  // cannot block scroll, then the flag is certainly set
  // (https://crbug.com/345372).
  delayed_effective_touch_action_ = base::nullopt;
  should_enforce_vertical_scroll_ = false;
}

bool TouchEventManager::IsAnyTouchActive() const {
  return !touch_attribute_map_.IsEmpty();
}

WebInputEventResult TouchEventManager::EnsureVerticalScrollIsPossible(
    WebInputEventResult event_result) {
  bool prevent_defaulted =
      event_result == WebInputEventResult::kHandledApplication;
  if (prevent_defaulted && delayed_effective_touch_action_) {
    // Make sure that only vertical scrolling is permitted.
    *delayed_effective_touch_action_ &= TouchAction::kPanY;
  }

  if (delayed_effective_touch_action_) {
    // If 'touchstart' is preventDefault()-ed then we can proceed with reporting
    // the effective 'touch-action'.
    // TODO(ekaramad): This does not block horizontal scroll after enforcing
    // vertical scrolling. We should ideally send the 'touch-action' to browser
    // after the first 'touchmove' event has been dispatched.
    // (https://crbug.com/844493).
    frame_->GetPage()->GetChromeClient().SetTouchAction(
        frame_, delayed_effective_touch_action_.value());
    delayed_effective_touch_action_ = base::nullopt;
  }

  // If the event was canceled the result is ignored to make sure vertical
  // scrolling is possible.
  return prevent_defaulted ? WebInputEventResult::kNotHandled : event_result;
}

}  // namespace blink


text:
using System.ComponentModel.Composition;
using Microsoft.CodeAnalysis.Shared.TestHooks;

namespace Roslyn.Hosting.Diagnostics.Waiters
{
    [Export(typeof(IAsynchronousOperationListener))]
    [Export(typeof(IAsynchronousOperationWaiter))]
    [Feature(FeatureAttribute.CompletionSet)]
    internal class CompletionSetWaiter : AsynchronousOperationListener { }
}


text:
package com.esri.runtime.android.materialbasemaps.model;

import android.graphics.Bitmap;

import com.esri.arcgisruntime.portal.PortalItem;

public class BasemapItem {

    private final PortalItem item;
    private final Bitmap image;

    public BasemapItem(PortalItem item, Bitmap image){
        this.item = item;
        this.image = image;
    }

    public PortalItem getItem(){ return item; }

    public Bitmap getImage(){ return image; }

}


text:
<form id="email.filters.form">
    <legend>{{'email.logging.filters' | translate}} </legend>
    <fieldset>
        <legend>{{ 'email.logging.search' | translate }}</legend>

            <input id="email.filters.subject" type="text" placeholder="{{'email.logging.search' | translate }}" name="subject" email-auto-complete="subject" data-event-type="keyup" data-search-field="subject" email-jqgrid-search="emailLoggingTable">

    </fieldset>
    <fieldset class="inside">
        <legend>{{ 'email.logging.creationDate' | translate }}</legend>

            <input id="email.filters.date-from" date-picker ng-model="dateTimeFrom" max="dateTimeTo" type="datetime" placeholder="{{msg('email.logging.fromAddress')}}" data-event-type="change" data-search-field="timeFrom" email-jqgrid-search="emailLoggingTable">

            <input id="email.filters.date-to" date-picker ng-model="dateTimeTo" min="dateTimeFrom" type="datetime" placeholder="{{msg('email.logging.toAddress')}}" data-event-type="change" data-search-field="timeTo" email-jqgrid-search="emailLoggingTable">

    </fieldset>
    <fieldset class="inside">
        <legend>{{'email.logging.disposition' | translate }}</legend>

            <button id="email.filters.error" type="button" data-field-type="array" data-search-field="deliveryStatus" data-search-value="ERROR" email-jqgrid-search="emailLoggingTable"> {{msg('email.logging.error')}}</button>
            <button id="email.filters.sent" data-field-type="array" data-search-field="deliveryStatus" data-search-value="SENT" email-jqgrid-search="emailLoggingTable"> {{msg('email.logging.sent')}}</button>
            <button id="email.filters.received" type="button" data-field-type="array" data-search-field="deliveryStatus" data-search-value="RECEIVED" email-jqgrid-search="emailLoggingTable"> {{msg('email.logging.received')}}</button>

    </fieldset>
</form>


text:
import {VisibilityState} from '#core/constants/visibility-state';
import {Observable} from '#core/data-structures/observable';
import {Deferred} from '#core/data-structures/promise';
import {hasNextNodeInDocumentOrder} from '#core/dom';

import {Services} from '#service';
import {Resource, ResourceState} from '#service/resource';
import {READY_SCAN_SIGNAL} from '#service/resources-interface';

import {dev} from '../log';
import {getMode} from '../mode';
import {Pass} from '../pass';
import {registerServiceBuilderForDoc} from '../service-helpers';

const TAG = 'inabox-resources';
const FOUR_FRAME_DELAY = 70;

/**
 * @implements {../service/resources-interface.ResourcesInterface}
 * @implements {../service.Disposable}
 * @visibleForTesting
 */
export class InaboxResources {
  /**
   * @param {!../service/ampdoc-impl.AmpDoc} ampdoc
   */
  constructor(ampdoc) {
    /** @const {!../service/ampdoc-impl.AmpDoc} */
    this.ampdoc_ = ampdoc;

    /** @const {!Window} */
    this.win = ampdoc.win;

    /** @private @const {!Array<!Resource>} */
    this.resources_ = [];

    /** @private {number} */
    this.resourceIdCounter_ = 0;

    /** @const @private {!Pass} */
    this.pass_ = new Pass(this.win, this.doPass_.bind(this), FOUR_FRAME_DELAY);

    /** @private @const {!Observable} */
    this.passObservable_ = new Observable();

    /** @const @private {!Deferred} */
    this.firstPassDone_ = new Deferred();

    /** @private {?IntersectionObserver} */
    this.inViewportObserver_ = null;

    const input = Services.inputFor(this.win);
    input.setupInputModeClasses(ampdoc);

    // TODO(#31246): launch the visibility logic in inabox as well.
    if (getMode(this.win).runtime != 'inabox') {
      ampdoc.onVisibilityChanged(() => {
        switch (ampdoc.getVisibilityState()) {
          case VisibilityState.PAUSED:
            this.resources_.forEach((r) => r.pause());
            break;
          case VisibilityState.VISIBLE:
            this.resources_.forEach((r) => r.resume());
            this./*OK*/ schedulePass();
            break;
        }
      });
    }

    /** @private {!Array<Resource>} */
    this.pendingBuildResources_ = [];

    /** @private {boolean} */
    this.documentReady_ = false;

    this.ampdoc_.whenReady().then(() => {
      this.documentReady_ = true;
      this.buildReadyResources_();
      this./*OK*/ schedulePass(1);
    });
  }

  /** @override */
  dispose() {
    this.resources_.forEach((r) => r.unload());
    this.resources_.length = 0;
    if (this.inViewportObserver_) {
      this.inViewportObserver_.disconnect();
      this.inViewportObserver_ = null;
    }
  }

  /** @override */
  get() {
    return this.resources_.slice(0);
  }

  /** @override */
  getAmpdoc() {
    return this.ampdoc_;
  }

  /** @override */
  getResourceForElement(element) {
    return Resource.forElement(element);
  }

  /** @override */
  getResourceForElementOptional(element) {
    return Resource.forElementOptional(element);
  }

  /** @override */
  getScrollDirection() {
    return 1;
  }

  /** @override */
  add(element) {
    const resource = new Resource(++this.resourceIdCounter_, element, this);
    this.resources_.push(resource);
    dev().fine(TAG, 'resource added:', resource.debugid);
  }

  /** @override */
  upgraded(element) {
    const resource = Resource.forElement(element);
    this.pendingBuildResources_.push(resource);
    this.buildReadyResources_();
  }

  /** @override */
  remove(element) {
    const resource = Resource.forElementOptional(element);
    if (!resource) {
      return;
    }
    if (this.inViewportObserver_) {
      this.inViewportObserver_.unobserve(element);
    }
    const index = this.resources_.indexOf(resource);
    if (index !== -1) {
      this.resources_.splice(index, 1);
    }
    dev().fine(TAG, 'element removed:', resource.debugid);
  }

  /** @override */
  scheduleLayoutOrPreload(unusedResource) {
    this.pass_.schedule();
  }

  /** @override */
  schedulePass(opt_delay) {
    return this.pass_.schedule(opt_delay);
  }

  /** @override */
  updateOrEnqueueMutateTask(unusedResource, unusedNewRequest) {}

  /** @override */
  schedulePassVsync() {}

  /** @override */
  onNextPass(callback) {
    this.passObservable_.add(callback);
  }

  /** @override */
  ampInitComplete() {}

  /** @override */
  updateLayoutPriority(unusedElement, unusedNewLayoutPriority) {
    // concept of element priority does not exist in inabox
  }

  /** @override */
  setRelayoutTop(unusedRelayoutTop) {}

  /** @override */
  maybeHeightChanged() {}

  /**
   * @return {!Promise} when first pass executed.
   */
  whenFirstPass() {
    return this.firstPassDone_.promise;
  }

  /**
   * @private
   */
  doPass_() {
    const now = Date.now();
    dev().fine(TAG, 'doPass');
    // measure in a batch
    this.resources_.forEach((resource) => {
      if (!resource.isLayoutPending() || resource.element.R1()) {
        return;
      }
      resource.measure();
    });
    // mutation in a batch
    this.resources_.forEach((resource) => {
      if (
        !resource.element.R1() &&
        resource.getState() === ResourceState.READY_FOR_LAYOUT &&
        resource.isDisplayed()
      ) {
        resource.layoutScheduled(now);
        resource.startLayout();
      }
    });

    this.ampdoc_.signals().signal(READY_SCAN_SIGNAL);
    this.passObservable_.fire();
    this.firstPassDone_.resolve();
  }

  /**
   * Builds any pending resouces if document is ready, or next element has been
   * added to DOM.
   * @private
   */
  buildReadyResources_() {
    for (let i = this.pendingBuildResources_.length - 1; i >= 0; i--) {
      const resource = this.pendingBuildResources_[i];
      if (
        this.documentReady_ ||
        hasNextNodeInDocumentOrder(resource.element, this.ampdoc_.getRootNode())
      ) {
        this.pendingBuildResources_.splice(i, 1);
        resource.build().then(() => this./*OK*/ schedulePass());
        dev().fine(TAG, 'resource upgraded:', resource.debugid);
      }
    }
  }
}

/**
 * @param {!../service/ampdoc-impl.AmpDoc} ampdoc
 */
export function installInaboxResourcesServiceForDoc(ampdoc) {
  registerServiceBuilderForDoc(ampdoc, 'resources', InaboxResources);
}


text:
const chai = require('chai');
const chaiHttp = require('chai-http');
chai.use(chaiHttp);
const expect = chai.expect;
const dayFilter = require(__dirname + '/../../../lib/day_filter');

describe('twilio router filters', () => {

  it('should bring back current date in abbrev string form', () => {
    var currentDate = new Date();
    var currentDay = currentDate.getDay();
    var dateArray = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
    expect(dateArray[currentDay]).to.eql(dayFilter.getStringDay());
  });

  it('should filter results with the day-matching filter', () => {
    var filteredDay = dayFilter.getStringDay();
    var testArray = [
      { 'day_time': 'Monday - Friday: 6:15 - 7:00 A.M.',
        'location': '2515 Western Ave., Seattle',
        'meal_served': 'Breakfast',
        'name_of_program': 'Millionair Club Charity',
        'people_served': 'OPEN TO ALL ' },
      { 'day_time': 'Sunday - Thursday 5:30 - 8:30 A.M.',
        'location': '8201 10th Ave S.,  Seattle',
        'meal_served': 'Breakfast', 'name_of_program': 'South Park Breakfast Bunch',
        'people_served': 'OPEN TO ALL' },
      { 'day_time': 'Monday - Friday 7:00 - 9:30 A.M.',
        'location': '410 2nd Ave. Extension So.,  Seattle',
        'meal_served': '  ',
        'name_of_program': 'Chief Seattle Club',
        'people_served': 'AMERICAN INDIANS ONLY' }
    ];
    var results1 = dayFilter.matchDay(testArray, 'sat');
    var results2 = dayFilter.matchDay(testArray, 'fri');
    var results3 = dayFilter.matchDay(testArray, 'notaday');
    var results4 = dayFilter.getDaysOpen(testArray);
    expect(Array.isArray(dayFilter.matchDay(testArray, filteredDay))).to.eql(true);
    expect(results1.length).to.eql(0);
    expect(results2.length).to.eql(2);
    expect(results3.length).to.eql(0);
    expect(Array.isArray(dayFilter.getDaysOpen(testArray))).to.eql(true);
    expect(results4[0]).to.have.property('daysOpen');
  });
});


text:
package net.geocentral.geometria.action;

import net.geocentral.geometria.model.GDocument;
import net.geocentral.geometria.model.GSolution;

import org.apache.log4j.Logger;

public class GRedoAction implements GNavigationAction {

    private static Logger logger = Logger.getLogger("net.geocentral.geometria");

    public boolean execute(GDocumentHandler documentHandler, boolean quietMode) {
        logger.info(quietMode);
        GUndoable action = documentHandler.toNextAction();
        action.execute(documentHandler, quietMode);
        GDocument document = documentHandler.getActiveDocument();
        if (document instanceof GSolution && action instanceof GLoggable)
            ((GSolution)document).getLog().add((GLoggable)action);
        documentHandler.setDocumentModified(true);
        logger.info(action);
        return true;
    }
}


text:
package io.rong.messages;

import io.rong.util.GsonUtil;

/**
 *
 * 添加联系人消息。
 *
 */
public class ContactNtfMessage extends BaseMessage {
	private String operation = "";
	private String extra = "";
	private String sourceUserId = "";
	private String targetUserId = "";
	private String message = "";
	private transient static final String TYPE = "RC:ContactNtf";

	public ContactNtfMessage(String operation, String extra, String sourceUserId, String targetUserId, String message) {
		this.operation = operation;
		this.extra = extra;
		this.sourceUserId = sourceUserId;
		this.targetUserId = targetUserId;
		this.message = message;
	}

	public String getType() {
		return TYPE;
	}

	/**
	 * 获取操作名。
	 *
     * @return
     */
    public String getOperation() {
        return operation;
    }

    /**
	 * 设置操作名。
	 *
	 * @return
	 */
	public void setOperation(String operation) {
		this.operation = operation;
	}

	/**
	 * 获取为附加信息(如果开发者自己需要,可以自己在 App 端进行解析)。
	 *
     * @return
     */
    public String getExtra() {
        return extra;
    }

    /**
	 * 设置为附加信息(如果开发者自己需要,可以自己在 App 端进行解析)。
	 *
	 * @return
	 */
	public void setExtra(String extra) {
		this.extra = extra;
	}

	/**
	 * 获取请求者或者响应者的 UserId。
	 *
     * @return
     */
    public String getSourceUserId() {
        return sourceUserId;
    }

    /**
	 * 设置请求者或者响应者的 UserId。
	 *
	 * @return
	 */
	public void setSourceUserId(String sourceUserId) {
		this.sourceUserId = sourceUserId;
	}

	/**
	 * 获取被请求者或者被响应者的 UserId。
	 *
     * @return
     */
    public String getTargetUserId() {
        return targetUserId;
    }

    /**
	 * 设置被请求者或者被响应者的 UserId。
	 *
	 * @return
	 */
	public void setTargetUserId(String targetUserId) {
		this.targetUserId = targetUserId;
	}

	/**
	 * 获取请求或者响应消息。
	 *
     * @return
     */
    public String getMessage() {
        return message;
    }

    /**
	 * 设置请求或者响应消息。
	 *
	 * @return
	 */
	public void setMessage(String message) {
		this.message = message;
	}

	@Override
	public String toString() {
		return GsonUtil.toJson(this, ContactNtfMessage.class);
	}
}


text:
package org.apache.camel.processor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

import org.apache.camel.AsyncCallback;
import org.apache.camel.AsyncProcessor;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.ExtendedCamelContext;
import org.apache.camel.Navigate;
import org.apache.camel.Processor;
import org.apache.camel.Traceable;
import org.apache.camel.spi.IdAware;
import org.apache.camel.spi.ReactiveExecutor;
import org.apache.camel.spi.RouteIdAware;
import org.apache.camel.support.AsyncProcessorConverterHelper;
import org.apache.camel.support.AsyncProcessorSupport;
import org.apache.camel.support.ExchangeHelper;
import org.apache.camel.support.service.ServiceHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.apache.camel.processor.PipelineHelper.continueProcessing;

/**
 * Creates a Pipeline pattern where the output of the previous step is sent as input to the next step, reusing the same
 * message exchanges
 */
public class Pipeline extends AsyncProcessorSupport implements Navigate<Processor>, Traceable, IdAware, RouteIdAware {

    private static final Logger LOG = LoggerFactory.getLogger(Pipeline.class);

    private final CamelContext camelContext;
    private final ReactiveExecutor reactiveExecutor;
    private final List<AsyncProcessor> processors;
    private final int size;
    private String id;
    private String routeId;

    private final class PipelineTask implements Runnable {

        private final Exchange exchange;
        private final AsyncCallback callback;
        private final AtomicInteger index;

        PipelineTask(Exchange exchange, AsyncCallback callback, AtomicInteger index) {
            this.exchange = exchange;
            this.callback = callback;
            this.index = index;
        }

        @Override
        public void run() {
            boolean stop = exchange.isRouteStop();
            int num = index.get();
            boolean more = num < size;
            boolean first = num == 0;

            if (!stop && more && (first || continueProcessing(exchange, "so breaking out of pipeline", LOG))) {

                // prepare for next run
                if (exchange.hasOut()) {
                    exchange.setIn(exchange.getOut());
                    exchange.setOut(null);
                }

                // get the next processor
                AsyncProcessor processor = processors.get(index.getAndIncrement());

                processor.process(exchange, doneSync -> reactiveExecutor.schedule(this));
            } else {
                ExchangeHelper.copyResults(exchange, exchange);

                // logging nextExchange as it contains the exchange that might have altered the payload and since
                // we are logging the completion if will be confusing if we log the original instead
                // we could also consider logging the original and the nextExchange then we have *before* and *after* snapshots
                if (LOG.isTraceEnabled()) {
                    LOG.trace("Processing complete for exchangeId: {} >>> {}", exchange.getExchangeId(), exchange);
                }

                reactiveExecutor.schedule(callback);
            }
        }
    }

    public Pipeline(CamelContext camelContext, Collection<Processor> processors) {
        this.camelContext = camelContext;
        this.reactiveExecutor = camelContext.adapt(ExtendedCamelContext.class).getReactiveExecutor();
        this.processors = processors.stream().map(AsyncProcessorConverterHelper::convert).collect(Collectors.toList());
        this.size = processors.size();
    }

    public static Processor newInstance(CamelContext camelContext, List<Processor> processors) {
        if (processors.isEmpty()) {
            return null;
        } else if (processors.size() == 1) {
            return processors.get(0);
        }
        return new Pipeline(camelContext, processors);
    }

    public static Processor newInstance(final CamelContext camelContext, final Processor... processors) {
        if (processors == null || processors.length == 0) {
            return null;
        } else if (processors.length == 1) {
            return processors[0];
        }

        final List<Processor> toBeProcessed = new ArrayList<>(processors.length);
        for (Processor processor : processors) {
            if (processor != null) {
                toBeProcessed.add(processor);
            }
        }

        return new Pipeline(camelContext, toBeProcessed);
    }

    @Override
    public boolean process(Exchange exchange, AsyncCallback callback) {
        // create task which has state used during routing
        PipelineTask task = new PipelineTask(exchange, callback, new AtomicInteger());

        if (exchange.isTransacted()) {
            reactiveExecutor.scheduleSync(task);
        } else {
            reactiveExecutor.scheduleMain(task);
        }
        return false;
    }

    @Override
    protected void doStart() throws Exception {
        ServiceHelper.startService(processors);
    }

    @Override
    protected void doStop() throws Exception {
        ServiceHelper.stopService(processors);
    }

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

    @Override
    public String getTraceLabel() {
        return "pipeline";
    }

    @Override
    public String getId() {
        return id;
    }

    @Override
    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String getRouteId() {
        return routeId;
    }

    @Override
    public void setRouteId(String routeId) {
        this.routeId = routeId;
    }

    @Override
    public List<Processor> next() {
        if (!hasNext()) {
            return null;
        }
        return new ArrayList<>(processors);
    }

    @Override
    public boolean hasNext() {
        return processors != null && !processors.isEmpty();
    }
}


text:
#include <iostream>
#include <array>
#include <utility>
#include <tuple>
#include <algorithm>

constexpr std::size_t nodes_count = 10 * 10 * 100;

struct node {
    enum struct gate : int { AND=1, OR, NONE };
    bool value, changeable;
    gate g;
};

std::ostream& operator << (std::ostream& oss, const node& v) {
    oss << std::boolalpha << "{value=" << v.value <<
    ", changeable=" << v.changeable <<
    ", gate=";
    switch(v.g) {
        case node::gate::AND:
            return oss << "AND}";
        case node::gate::OR:
            return oss << "OR}";
        default:
            return oss << "NONE}";
    }
}

template <class T>
void logMessage(const T& message, std::ostream& out = std::cerr) {
    #ifdef DEBUG_MODE
    out << message << '\n';
    #endif
}

template <class Iter>
void logRange(Iter begin, Iter end, std::ostream& out = std::cerr) {
    #ifdef DEBUG_MODE
    while (begin != end) {
        logMessage(*begin++, out);
    }
    #endif
}

int post_order_fix(node* tree, int pos, const bool goal);

inline static constexpr int parent(int pos) {
    return pos == 0 ? -1 : (pos - 1) >> 1;
}

int main(int argc, char const *argv[]) {

    // Remove synchronization between cstdio and iostream
    std::ios_base::sync_with_stdio(false);
    // Prevent flushing of output stream before each io operation
    std::cin.tie(nullptr);

    std::array<node, nodes_count> tree;

    int N, M, V, s;
    std::cin >> N;
    for (int c = 1; c <= N; c++) {
        std::cin >> M >> V;

        // Since M will be odd, no need to subtract 1 before dividing
        int interior_nodes = M >> 1;

        std::for_each(tree.begin(), tree.begin() + interior_nodes, [](node& v) {
            std::cin >> v.value;
            v.g = v.value ? node::gate::AND : node::gate::OR;
            std::cin >> v.changeable;
        });

        std::for_each(tree.begin() + interior_nodes, tree.begin() + M, [](node& v) {
            std::cin >> v.value;
            v.g = node::gate::NONE;
        });

        for (int v = M - 1; v > 0; v -= 2) {
            int p = parent(v);
            tree[p].value = tree[p].g == node::gate::AND ?
            tree[v].value && tree[v - 1].value : tree[v].value || tree[v - 1].value;
        }

        logRange(tree.begin(), tree.begin() + M);

        s = post_order_fix(tree.data(), 0, V);

        std::cout << "Case #" << c << ": ";
        if (s != -1) {
            std::cout << s << '\n';
        } else {
            std::cout << "IMPOSSIBLE\n";
        }
    }
    return 0;
}

inline static constexpr std::pair<int, int> left_right(int pos) {
    return {(pos << 1) + 1, (pos << 1) + 2};
}

inline static constexpr bool is_left_sib(int pos) {
    return pos != 0 && (pos & 1);
}

inline static constexpr bool is_right_sib(int pos) {
    return pos != 0 && ((pos & 1) == 0);
}

/**
 *    Fixes the boolean tree to make the value at the root match the goal.
 *    @param  tree A pointer to the array containing the tree values
 *    @param  pos  The current node to consider
 *    @param  goal The value expected for the root node
 *    @return   a non negative value if it is possible for the root node to
 *    have the value specified by goal, otherwise -1 to indicate it is impossible
 *    The algorithm is as follows:
 *    If value != goal
 *        if not changeable
 *            if "AND"
 *                if goal, want both children to be 1
 *                if not goal, want one child to be 0
 *            if "OR"
 *                if goal, want one child to be 1
 *                if not goal, want both to be zero
 *        if changeable
 *            if goal, want one child to be 1
 *            if not goal, want one child to be 0
 *
 */
int post_order_fix(node* tree, int pos, const bool goal) {
    int left, right, count = 0;

    if (tree[pos].g == node::gate::NONE) {
        return -1;
    }

    if (tree[pos].value == goal) {
        return 0;
    }

    std::tie(left, right) = left_right(pos);

    if (tree[pos].changeable) {
        if ((tree[right].value || tree[left].value) &&
        !(tree[right].value && tree[left].value)) {
            return 1;
        }
    }

    int a = post_order_fix(tree, left, goal);
    int b = post_order_fix(tree, right, goal);

    if (a != -1 || b != -1) {
        if (tree[pos].changeable) {
            return (a != -1 && b != -1 ? std::min(a, b) : std::max(a, b)) +
            ((goal && tree[pos].g == node::gate::AND) ||
             (!goal && tree[pos].g == node::gate::OR) ? 1 : 0);
        }
        else {
            switch(tree[pos].g) {
                case node::gate::AND:
                    return goal ? (a != -1 && b != -1 ? a + b : -1) :
                    (a != -1 && b != -1 ? std::min(a, b) : std::max(a, b));
                case node::gate::OR:
                    return goal ? (a != -1 && b != -1 ? std::min(a, b): std::max(a, b)) :
                    (a != -1 && b != -1 ? a + b : -1);
                default:
                    break;
            }
        }
    }
    return -1;
}


text:
<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Twenty Seventeen suport.
 *
 * @class   WC_Twenty_Seventeen
 * @since   2.6.9
 * @version 2.6.9
 * @package WooCommerce/Classes
 */
class WC_Twenty_Seventeen {

	/**
	 * Constructor.
	 */
	public function __construct() {
		remove_action( 'woocommerce_before_main_content', 'woocommerce_output_content_wrapper', 10 );
		remove_action( 'woocommerce_after_main_content', 'woocommerce_output_content_wrapper_end', 10 );

		add_action( 'woocommerce_before_main_content', array( $this, 'output_content_wrapper' ), 10 );
		add_action( 'woocommerce_after_main_content', array( $this, 'output_content_wrapper_end' ), 10 );
		add_filter( 'woocommerce_enqueue_styles', array( $this, 'enqueue_styles' ) );
	}

	/**
	 * Enqueue CSS for this theme.
	 *
	 * @param  array $styles
	 * @return array
	 */
	public function enqueue_styles( $styles ) {
		unset( $styles['woocommerce-general'] );

		$styles['woocommerce-twenty-seventeen'] = array(
			'src'     => str_replace( array( 'http:', 'https:' ), '', WC()->plugin_url() ) . '/assets/css/twenty-seventeen.css',
			'deps'    => '',
			'version' => WC_VERSION,
			'media'   => 'all',
		);

		return apply_filters( 'woocommerce_twenty_seventeen_styles', $styles );
	}

	/**
	 * Open the Twenty Seventeen wrapper.
	 */
	public function output_content_wrapper() { ?>

		<?php
	}

	/**
	 * Close the Twenty Seventeen wrapper.
	 */
	public function output_content_wrapper_end() { ?>

			<?php get_sidebar(); ?>

		<?php
	}
}

new WC_Twenty_Seventeen();