text:
package org.ovirt.engine.ui.common.widget.editor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.ovirt.engine.core.common.utils.ListUtils;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.safehtml.shared.SafeHtmlUtils;
import com.google.gwt.text.shared.Renderer;
import com.google.gwt.user.client.TakesValue;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HasConstrainedValue;

/**
 * The CheckboxGroup Widget is used to group together a set of Checkbox buttons. Any number of checkboxes can be
 * checked/set at any point in time. Pushing/Clicking any checkbox in the group toggles its state.
 */

public class CheckBoxGroup<T> extends Composite implements TakesValue<List<T>>, HasConstrainedValue<List<T>> {

    private final Map<T, CheckBox> checkBoxes = new LinkedHashMap<>();

    private static Resources RESOURCES = GWT.create(Resources.class);
    private final FlowPanel wrapperPanel = new FlowPanel();

    private final CheckBoxGroupCss style;

    private boolean enabled = true;

    Renderer<T> renderer;

    int tabIndex;

    public interface Resources extends ClientBundle {
        @Source("org/ovirt/engine/ui/common/css/CheckBoxGroup.css")
        CheckBoxGroupCss checkBoxGroupCss();
    }

    /**
     * CheckBoxGroup construcor.
     * @param renderer
     *            to render the values passed to ListModel's setItems and hence setAcceptableValues
     */
    public CheckBoxGroup(Renderer<T> renderer) {
        this.renderer = renderer;
        style = RESOURCES.checkBoxGroupCss();
        style.ensureInjected();
        initWidget(wrapperPanel);
    }

    private void addCheckBox(T checkBoxValue) {
        String checkBoxLabel = renderer.render(checkBoxValue);
        if (checkBoxLabel == null) {
            throw new IllegalArgumentException("null value is not permited"); //$NON-NLS-1$
        }
        final CheckBox newCheckBox = buildCheckbox(checkBoxValue);
        checkBoxes.put(checkBoxValue, newCheckBox);
    }

    private CheckBox buildCheckbox(final T checkBoxValue) {
        final CheckBox newCheckBox = new CheckBox(SafeHtmlUtils.fromString(renderer.render(checkBoxValue)));
        newCheckBox.setValue(false);
        newCheckBox.setStyleName(style.checkBox());
        newCheckBox.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                // ValueChangeEvent fired to notify the mapped ListModel about the new Selection/deselection.
                ValueChangeEvent.fire(CheckBoxGroup.this, getValue());
            }
        });
        return newCheckBox;
    }

    /**
     * Clear All checkBoxes' selection in the group
     */
    public void clearAllSelections() {
        for (Entry<T, CheckBox> currentcheckBoxValue : checkBoxes.entrySet()) {
            currentcheckBoxValue.getValue().setValue(false);
        }
    }

    public HandlerRegistration addKeyUpHandler(KeyUpHandler handler) {
        return addDomHandler(handler, KeyUpEvent.getType());
    }

    public HandlerRegistration addKeyDownHandler(KeyDownHandler handler) {
        return addDomHandler(handler, KeyDownEvent.getType());
    }

    public HandlerRegistration addKeyPressHandler(KeyPressHandler handler) {
        return addDomHandler(handler, KeyPressEvent.getType());
    }

    public boolean isEnabled() {
        return enabled;
    }

    /**
     * Enable/disable all checkboxes
     * @param enabled
     *            boolean whether to enable/disable all checkboxes
     * @return void
     */
    public void setEnabled(boolean enabled) {
        for(Entry<T, CheckBox> currentValue : checkBoxes.entrySet()) {
            currentValue.getValue().setEnabled(enabled);
        }
    }

    public int getTabIndex() {
        return tabIndex;
    }

    public void setTabIndex(int index) {
        tabIndex = index;
    }

    /**
     * When the mapped ListModel does a setSelectedItem, this is invoked. This method sets checked, the checkboxes
     * corresponding to the list passed to it.
     * @param value
     *            list of checkboxes to set checked.
     * @param fireEvents
     *            whether to fire ValueChangeEvent
     * @return void
     */
    @Override
    public void setValue(List<T> value, boolean fireEvents) {
        List<T> selectedItems = getValue();
        if (value == selectedItems
                || (selectedItems != null && value != null && ListUtils.listsEqual(selectedItems, value))) {
            return;
        }
        clearAllSelections();
        if(value == null){
            return;
        }
        for (T currentvalue : value) {
            if (checkBoxes.containsKey(currentvalue)) {
                checkBoxes.get(currentvalue).setValue(true);
            }
        }
        if (fireEvents) {
            ValueChangeEvent.fire(this, value);
        }
    }

    @Override
    public HandlerRegistration addValueChangeHandler(ValueChangeHandler<List<T>> handler) {
        return addHandler(handler, ValueChangeEvent.getType());
    }

    /**
     * Api to add list of CheckBoxes to the CheckBoxGroup. This is invoked by the mapped ListModel's setItems.
     * @param values
     *            list of values for which checkboxes are to be created in the group.
     * @return void
     */
    @Override
    public void setAcceptableValues(Collection<List<T>> values) {
        List<T> seletedItems = getValue();
        wrapperPanel.clear();
        checkBoxes.clear();
        if (values.isEmpty()) {
            throw new IllegalArgumentException("Widget has nothing to do");//$NON-NLS-1$
        }
        List<T> acceptableValues = (List<T>) values.toArray()[0];
        for(T currentValue : acceptableValues) {
            if(!checkBoxes.containsKey(currentValue)) {
                addCheckBox(currentValue);
            }
        }
        showCheckBoxes(seletedItems);
    }

    private void showCheckBoxes(List<T> seletedItems) {
        for (Entry<T, CheckBox> currentEntry : checkBoxes.entrySet()) {
            wrapperPanel.add(currentEntry.getValue());
            if (seletedItems.contains(currentEntry.getKey())) {
                currentEntry.getValue().setValue(true);
            }
        }
    }

    /**
     * When the mapped ListModel does a setSelectedItem, this is invoked. This method sets checked, the checkboxes
     * corresponding to the list passed to it.
     * @param value
     *            list of checkboxes to set checked.
     * @return void
     */
    @Override
    public void setValue(List<T> value) {
        setValue(value, false);
    }

    /**
     * Calculate and obtain the list of checkboxes checked
     * @return List of checkboxes checked
     */
    @Override
    public List<T> getValue() {
        List<T> selectedItems = new ArrayList<>();
        for (Entry<T, CheckBox> currentEntry : checkBoxes.entrySet()) {
            if (currentEntry.getValue().getValue()) {
                selectedItems.add(currentEntry.getKey());
            }
        }
        return selectedItems;
    }

}


text:
Decision StrategyRecomendations::make_decision() {
    std::string decision;
    auto guy_decision = guy.make_decision();
    while (decision != "c" && decision != "d" && decision != "C" && decision != "D") {
        std::cout << "It's better to ";
        if (guy_decision == COOPERATE) {
            std::cout << "cooperate." << std::endl;
        } else {
            std::cout << "defect." << std::endl;
        }
        std::cout << "What is your decision? (C/D): ";
        std::cin >> decision;
    }
    if (decision == "c" || decision == "C") {
        return COOPERATE;
    } else {
        return DEFECT;
    }
}

void StrategyRecomendations::remember_decision(std::string name, Decision decision) {
    guy.remember_decision(name, decision);
}

void StrategyRecomendations::notify_start(std::string name) {
    guy.notify_start(name);
}

void StrategyRecomendations::notify_end() {
    guy.Strategy::notify_end();
}

namespace {
    bool b = Factory<std::string, Strategy>::init()->add<StrategyRecomendations>("recomendations");
}

redpajama_set_name: RedPajamaGithub


text:
name: "\U0001F41BBug report"
about: Create a report to help us improve.
---

[//]: # NOTE: This repository only maintains packages that are listed in the [Readme](https://github.com/webdriverio/webdriverio/blob/master/README.md#packages). Please make sure that your issue is directly caused by one of these packages and if not file an issue in the correct 3rd party package repository.

**Environment (please complete the following information):**
 - **WebdriverIO version:** [e.g. 4.13.2]
 - **Mode:** [Standalone mode or WDIO Testrunner]
 - **If WDIO Testrunner, running sync/async:** [e.g. sync/async]
 - **Node.js version:** [e.g. 8.11.2]
 - **NPM version:** [e.g. 5.8.0]
 - **Browser name and version:** [e.g. Chrome 68]
 - **Platform name and version:** [e.g. Windows 10]
 - **Additional wdio packages used (if applicable):** [e.g. @wdio/spec reporter, @wdio/selenium-standalone service]

**Config of WebdriverIO**
An example of how you configured WebdriverIO config

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:

[Include code or an example repository that can easily be set up]

**Expected behavior**
A clear and concise description of what you expected to happen.

**Log**
If applicable, add logs to help explain your problem.
Create a [gist](https://gist.github.com) which is a paste of your _full_ Selenium/WebdriverIO logs, and link them here. Do _not_ paste your full Appium logs here, as it will make this issue very long and hard to read! If you are reporting a bug, _always_ include Selenium/WebdriverIO logs!

**Additional context**
Add any other context about the problem here.

> Please use the correct markdown


text:
<?php

namespace Chrisguitarguy\Plot\Core;

use Chrisguitarguy\Plot\Environment;

class PrintLine
{
    public function __invoke(array $nodes, Environment $env)
    {
        $values = array();
        foreach ($nodes as $node) {
            $values[] = $node->evaluate($env);
        }

        echo implode(' ', $values), PHP_EOL;
    }
}


text:
@class XStepper;

extern const double kXStepperDefaultMinValue;
extern const double kXStepperDefaultMaxValue;
extern const double kXStepperDefaultValue;

@protocol XStepperDelegate <NSObject>

- (void)xStepper:(XStepper *)xStepper valueChanged:(double)value;

@end

@interface XStepper : UIStepper

- (XStepper *)initWithFrame:(CGRect)frame minValue:(double)minValue maxValue:(double)maxValue value:(double)value;

- (XStepper *)initWithSuperView:(UIView *)superView minValue:(double)minValue maxValue:(double)maxValue value:(double)value;

@property(nonatomic, assign) id<XStepperDelegate> delegate;

@end


text:
title: Header Image With Pattern
date: 2014-10-08 00:00:00 Z
categories:
- design
tags:
- design
- pattern
- header
layout: page
subheadline: Headers With Style
teaser: Feeling Responsive allows you to use all kinds of headers. This example shows
  a header image in front of a pattern.
header:
  image: header_unsplash_2-970x.jpg
  pattern: pattern_concrete.jpg
  caption: This is a caption for the header image with link
  caption_url: https://unsplash.com/
---

It's so easy to do. Just define in front matter an image and a pattern image. Instead of a pattern you can also use a color. Have a look at the [example with a background color]({{ site.url }}{{ site.baseurl }}/design/header-image-color/).
<!--more-->

## Front Matter Code

~~~
header:
    image:  "header_unsplash_2-970x.jpg"
    pattern:  "pattern_concrete.jpg"
    caption: This is a caption for the header image with link
    caption_url: https://unsplash.com/
~~~

### All Header-Styles
{: .t60 }

{% include list-posts tag='header' %}


text:
var isElevated, stdin;

stdin = require('get-stdin');

isElevated = require('is-elevated');

exports.getStdin = stdin;

exports.isElevated = isElevated;


text:
'use strict'

exports.getCallback = function (options, callback) {
  return typeof options === 'function' ? options : callback
}

exports.getOptions = function (options) {
  return typeof options === 'object' && options !== null ? options : {}
}


text:
/*
 * Generated by the Jasper component of Apache Tomcat
 * Version: Apache Tomcat/8.5.11
 * Generated at: 2017-04-26 14:33:30 UTC
 * Note: The last modified time of this file was set to
 *       the last modified time of the source file after
 *       generation to assist with modification tracking.
 */
package org.apache.jsp.jsp.jsp2.el;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;

public final class basic_002darithmetic_jsp extends org.apache.jasper.runtime.HttpJspBase
    implements org.apache.jasper.runtime.JspSourceDependent,
                 org.apache.jasper.runtime.JspSourceImports {

  private static final javax.servlet.jsp.JspFactory _jspxFactory =
          javax.servlet.jsp.JspFactory.getDefaultFactory();

  private static java.util.Map<java.lang.String,java.lang.Long> _jspx_dependants;

  private static final java.util.Set<java.lang.String> _jspx_imports_packages;

  private static final java.util.Set<java.lang.String> _jspx_imports_classes;

  static {
    _jspx_imports_packages = new java.util.HashSet<>();
    _jspx_imports_packages.add("javax.servlet");
    _jspx_imports_packages.add("javax.servlet.http");
    _jspx_imports_packages.add("javax.servlet.jsp");
    _jspx_imports_classes = null;
  }

  private volatile javax.el.ExpressionFactory _el_expressionfactory;
  private volatile org.apache.tomcat.InstanceManager _jsp_instancemanager;

  public java.util.Map<java.lang.String,java.lang.Long> getDependants() {
    return _jspx_dependants;
  }

  public java.util.Set<java.lang.String> getPackageImports() {
    return _jspx_imports_packages;
  }

  public java.util.Set<java.lang.String> getClassImports() {
    return _jspx_imports_classes;
  }

  public javax.el.ExpressionFactory _jsp_getExpressionFactory() {
    if (_el_expressionfactory == null) {
      synchronized (this) {
        if (_el_expressionfactory == null) {
          _el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
        }
      }
    }
    return _el_expressionfactory;
  }

  public org.apache.tomcat.InstanceManager _jsp_getInstanceManager() {
    if (_jsp_instancemanager == null) {
      synchronized (this) {
        if (_jsp_instancemanager == null) {
          _jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
        }
      }
    }
    return _jsp_instancemanager;
  }

  public void _jspInit() {
  }

  public void _jspDestroy() {
  }

  public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
      throws java.io.IOException, javax.servlet.ServletException {

    final java.lang.String _jspx_method = request.getMethod();
    if (!"GET".equals(_jspx_method) && !"POST".equals(_jspx_method) && !"HEAD".equals(_jspx_method) && !javax.servlet.DispatcherType.ERROR.equals(request.getDispatcherType())) {
      response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "JSPs only permit GET POST or HEAD");
      return;
    }

    final javax.servlet.jsp.PageContext pageContext;
    javax.servlet.http.HttpSession session = null;
    final javax.servlet.ServletContext application;
    final javax.servlet.ServletConfig config;
    javax.servlet.jsp.JspWriter out = null;
    final java.lang.Object page = this;
    javax.servlet.jsp.JspWriter _jspx_out = null;
    javax.servlet.jsp.PageContext _jspx_page_context = null;

    try {
      response.setContentType("text/html");
      pageContext = _jspxFactory.getPageContext(this, request, response,
      			null, true, 8192, true);
      _jspx_page_context = pageContext;
      application = pageContext.getServletContext();
      config = pageContext.getServletConfig();
      session = pageContext.getSession();
      out = pageContext.getOut();
      _jspx_out = out;

      out.write("\n");
      out.write("\n");
      out.write("  \n");
      out.write("    <title>JSP 2.0 Expression Language - Basic Arithmetic</title>\n");
      out.write("  \n");
      out.write("  \n");
      out.write("
JSP 2.0 Expression Language - Basic Arithmetic
\n");
      out.write("
\n");
      out.write("    This example illustrates basic Expression Language arithmetic.\n");
      out.write("    Addition (+), subtraction (-), multiplication (*), division (/ or div),\n");
      out.write("    and modulus (% or mod) are all supported.  Error conditions, like\n");
      out.write("    division by zero, are handled gracefully.\n");
      out.write("
\n");
      out.write("
\n");
      out.write("      \n");
      out.write("
\n");
      out.write("
\n");
      out.write("        EL Expression	\n");
      out.write("        Result	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${1}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${1}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${1 + 2}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${1 + 2}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${1.2 + 2.3}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${1.2 + 2.3}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${1.2E4 + 1.4}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${1.2E4 + 1.4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${-4 - 2}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${-4 - 2}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${21 * 2}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${21 * 2}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${3/4}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${3/4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${3 div 4}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${3 div 4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${3/0}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${3/0}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${10%4}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${10%4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("        ${10 mod 4}	\n");
      out.write("        ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${10 mod 4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("      ${(1==2) ? 3 : 4}	\n");
      out.write("      ");
      out.write((java.lang.String) org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate("${(1==2) ? 3 : 4}", java.lang.String.class, (javax.servlet.jsp.PageContext)_jspx_page_context, null));
      out.write("	\n");
      out.write("
\n");
      out.write("
\n");
      out.write("      \n");
      out.write("
\n");
      out.write("  \n");
      out.write("\n");
    } catch (java.lang.Throwable t) {
      if (!(t instanceof javax.servlet.jsp.SkipPageException)){
        out = _jspx_out;
        if (out != null && out.getBufferSize() != 0)
          try {
            if (response.isCommitted()) {
              out.flush();
            } else {
              out.clearBuffer();
            }
          } catch (java.io.IOException e) {}
        if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
        else throw new ServletException(t);
      }
    } finally {
      _jspxFactory.releasePageContext(_jspx_page_context);
    }
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="300dp"
    android:layout_centerInParent="true"
    app:cardCornerRadius="5dp"
    app:cardBackgroundColor="#fff"
    app:cardElevation="5dp"
    android:layout_height="wrap_content">
    <RelativeLayout
        android:padding="10dp"
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content">
        <ImageView
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:layout_centerHorizontal="true"
            android:id="@+id/appIcon"
            android:scaleType="centerCrop"
            android:src="@mipmap/help_setting"/>
        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/appIcon"
            android:textSize="50sp"
            android:text="0%"
            android:textColor="#fa6832"
            android:id="@+id/progress"
            android:layout_marginTop="20dp"
            android:gravity="center"/>
        <TextView
            android:layout_marginTop="20dp"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/progress"
            android:textSize="18sp"
            android:id="@+id/downloadInfo"
            android:textColor="@color/fontsColor"
            android:gravity="center"
            android:layout_marginBottom="10dp"
            android:text="系统更新中,请稍后..."/>
    </RelativeLayout>

</android.support.v7.widget.CardView>


text:
Public Class GoLabs

End Class


text:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Reflection;

namespace Sdl.Community.GroupShareKit.Clients
{
    /// <summary>
    /// Base class for classes which represent query string parameters to certain API endpoints.
    /// </summary>
    public abstract class RequestParameters
    {
        private static readonly ConcurrentDictionary<Type, List<PropertyParameter>> PropertiesMap =
            new ConcurrentDictionary<Type, List<PropertyParameter>>();

        /// <summary>
        /// Converts the derived object into a dictionary that can be used to supply query string parameters.
        /// </summary>
        /// <returns></returns>
        public virtual IDictionary<string, string> ToParametersDictionary()
        {
            var map = PropertiesMap.GetOrAdd(GetType(), GetPropertyParametersForType);
            return (from property in map
                let value = property.GetValue(this)
                let key = property.Key
                where value != null
                select new {key, value}).ToDictionary(kvp => kvp.key, kvp => kvp.value);
        }

        private static List<PropertyParameter> GetPropertyParametersForType(Type type)
        {
            return GetAllProperties(type)
                .Where(p => p.Name != "DebuggerDisplay")
                .Select(p => new PropertyParameter(p))
                .ToList();
        }

        private static IEnumerable<PropertyInfo> GetAllProperties(Type type)
        {
            var typeInfo = type.GetTypeInfo();
            var properties = typeInfo.DeclaredProperties;

            var baseType = typeInfo.BaseType;

            return baseType == null ? properties : properties.Concat(GetAllProperties(baseType));
        }

        static Func<PropertyInfo, object, string> GetValueFunc(Type propertyType)
        {
            if (typeof(IEnumerable<string>).IsAssignableFrom(propertyType))
            {
                return (prop, value) =>
                {
                    var list = ((IEnumerable<string>)value).ToArray();
                    return !list.Any() ? null : string.Join(",", list);
                };
            }

            if (propertyType == typeof(DateTimeOffset) ||
                propertyType == typeof(DateTimeOffset?))
            {
                return (prop, value) => ((DateTimeOffset?) value)?.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ",
                    CultureInfo.InvariantCulture);
            }

            if (typeof(bool).IsAssignableFrom(propertyType))
            {
                return (prop, value) => value?.ToString().ToLowerInvariant();
            }
            if (typeof (IJsonRequest).IsAssignableFrom(propertyType))
            {

                return (prop, value) =>
                {
                    var name = prop.Name;
                    var json = string.Empty;
                    if (name.Equals("Filter", StringComparison.OrdinalIgnoreCase))
                    {
                        if ((FilterOptions) value != null)
                        {
                            json = ((FilterOptions)value).Stringify();
                        }

                    }
                    if (name.Equals("Sort", StringComparison.OrdinalIgnoreCase))
                    {
                        var sortParameters = (SortParameters)value;
                        if (sortParameters != null) json = sortParameters.Stringify();
                    }
                    return json;

                };
            }

            return (prop, value) => value?.ToString();
        }

        private class PropertyParameter
        {
            readonly Func<PropertyInfo, object, string> _valueFunc;
            readonly PropertyInfo _property;
            public PropertyParameter(PropertyInfo property)
            {
                _property = property;
                Key = property.Name.ToLowerInvariant();
                _valueFunc = GetValueFunc(property.PropertyType);
            }

            public string Key { get; }

            public string GetValue(object instance)
            {
                return _valueFunc(_property, _property.GetValue(instance, null));
            }

        }
    }

}


text:
"""Support for Blinkstick lights."""
import logging

import voluptuous as vol

from homeassistant.components.light import (
    ATTR_BRIGHTNESS, ATTR_HS_COLOR, SUPPORT_BRIGHTNESS, SUPPORT_COLOR, Light,
    PLATFORM_SCHEMA)
from homeassistant.const import CONF_NAME
import homeassistant.helpers.config_validation as cv
import homeassistant.util.color as color_util

_LOGGER = logging.getLogger(__name__)

CONF_SERIAL = 'serial'

DEFAULT_NAME = 'Blinkstick'

SUPPORT_BLINKSTICK = SUPPORT_BRIGHTNESS | SUPPORT_COLOR

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
    vol.Required(CONF_SERIAL): cv.string,
    vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
})

def setup_platform(hass, config, add_entities, discovery_info=None):
    """Set up Blinkstick device specified by serial number."""
    from blinkstick import blinkstick

    name = config.get(CONF_NAME)
    serial = config.get(CONF_SERIAL)

    stick = blinkstick.find_by_serial(serial)

    add_entities([BlinkStickLight(stick, name)], True)

class BlinkStickLight(Light):
    """Representation of a BlinkStick light."""

    def __init__(self, stick, name):
        """Initialize the light."""
        self._stick = stick
        self._name = name
        self._serial = stick.get_serial()
        self._hs_color = None
        self._brightness = None

    @property
    def should_poll(self):
        """Set up polling."""
        return True

    @property
    def name(self):
        """Return the name of the light."""
        return self._name

    @property
    def brightness(self):
        """Read back the brightness of the light."""
        return self._brightness

    @property
    def hs_color(self):
        """Read back the color of the light."""
        return self._hs_color

    @property
    def is_on(self):
        """Return True if entity is on."""
        return self._brightness > 0

    @property
    def supported_features(self):
        """Flag supported features."""
        return SUPPORT_BLINKSTICK

    def update(self):
        """Read back the device state."""
        rgb_color = self._stick.get_color()
        hsv = color_util.color_RGB_to_hsv(*rgb_color)
        self._hs_color = hsv[:2]
        self._brightness = hsv[2]

    def turn_on(self, **kwargs):
        """Turn the device on."""
        if ATTR_HS_COLOR in kwargs:
            self._hs_color = kwargs[ATTR_HS_COLOR]
        if ATTR_BRIGHTNESS in kwargs:
            self._brightness = kwargs[ATTR_BRIGHTNESS]
        else:
            self._brightness = 255

        rgb_color = color_util.color_hsv_to_RGB(
            self._hs_color[0], self._hs_color[1], self._brightness / 255 * 100)
        self._stick.set_color(
            red=rgb_color[0], green=rgb_color[1], blue=rgb_color[2])

    def turn_off(self, **kwargs):
        """Turn the device off."""
        self._stick.turn_off()


text:
require File.expand_path('../../spec_helper', __FILE__)

module Xcodeproj
  describe XCScheme::MacroExpansion do
    describe 'Created from scratch' do
      before do
        @macro_exp = Xcodeproj::XCScheme::MacroExpansion.new(nil)
      end

      it 'Creates an initial, empty XML node' do
        @macro_exp.xml_element.name.should == 'MacroExpansion'
        @macro_exp.xml_element.attributes.count.should == 0
        @macro_exp.xml_element.elements.count.should == 0
      end
    end

    describe 'Created from a XML node' do
      before do
        node = REXML::Element.new('MacroExpansion')
        ref = REXML::Element.new('BuildableReference')
        node.add_element(ref)
        @macro_exp = Xcodeproj::XCScheme::MacroExpansion.new(node)
      end

      it 'raises if invalid XML node' do
        node = REXML::Element.new('Foo')
        should.raise(Informative) do
          Xcodeproj::XCScheme::MacroExpansion.new(node)
        end.message.should.match /Wrong XML tag name/
      end

      it '#buildable_reference' do
        @macro_exp.buildable_reference.xml_element.should == @macro_exp.xml_element.elements['BuildableReference']
      end

      it '#buildable_reference=' do
        other_ref = Xcodeproj::XCScheme::BuildableReference.new(nil)
        @macro_exp.buildable_reference = other_ref
        @macro_exp.xml_element.elements.count.should == 1
        @macro_exp.xml_element.elements['BuildableReference'].should == other_ref.xml_element
      end
    end

    describe 'Created from a target' do
      before do
        @project = Xcodeproj::Project.new('/foo/bar/baz.xcodeproj')
        @target = @project.new_target(:application, 'FooApp', :ios)
        @macro_exp = Xcodeproj::XCScheme::MacroExpansion.new(@target)
      end

      it 'Uses the proper XML node' do
        @macro_exp.xml_element.name.should == 'MacroExpansion'
      end

      it '#buildable_reference' do
        @macro_exp.buildable_reference.xml_element.should == @macro_exp.xml_element.elements['BuildableReference']
      end

      it '#buildable_name=' do
        other_ref = Xcodeproj::XCScheme::BuildableReference.new(nil)
        @macro_exp.buildable_reference = other_ref
        @macro_exp.xml_element.elements.count.should == 1
        @macro_exp.xml_element.elements['BuildableReference'].should == other_ref.xml_element
      end
    end
  end
end


text:
import io
import json
import os
import unittest

from . import processresponse
from .fhirdate import FHIRDate

class ProcessResponseTests(unittest.TestCase):
    def instantiate_from(self, filename):
        datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
        with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
            js = json.load(handle)
            self.assertEqual("ProcessResponse", js["resourceType"])
        return processresponse.ProcessResponse(js)

    def testProcessResponse1(self):
        inst = self.instantiate_from("processresponse-example-error.json")
        self.assertIsNotNone(inst, "Must have instantiated a ProcessResponse instance")
        self.implProcessResponse1(inst)

        js = inst.as_json()
        self.assertEqual("ProcessResponse", js["resourceType"])
        inst2 = processresponse.ProcessResponse(js)
        self.implProcessResponse1(inst2)

    def implProcessResponse1(self, inst):
        self.assertEqual(inst.created.date, FHIRDate("2014-07-14").date)
        self.assertEqual(inst.created.as_json(), "2014-07-14")
        self.assertEqual(inst.disposition, "Referred to claim not found on system.")
        self.assertEqual(inst.error[0].coding[0].code, "a001")
        self.assertEqual(inst.error[0].coding[0].system, "http://hl7.org/fhir/adjudication-error")
        self.assertEqual(inst.form.coding[0].code, "PRRESP/2016/01")
        self.assertEqual(inst.form.coding[0].system, "http://ncforms.org/formid")
        self.assertEqual(inst.id, "SR2349")
        self.assertEqual(inst.identifier[0].system, "http://www.BenefitsInc.com/fhir/processresponse")
        self.assertEqual(inst.identifier[0].value, "ER987634")
        self.assertEqual(inst.outcome.coding[0].code, "error")
        self.assertEqual(inst.outcome.coding[0].system, "http://hl7.org/fhir/processoutcomecodes")
        self.assertEqual(inst.processNote[0].text, "Please check the submitted payor identification and local claim number.")
        self.assertEqual(inst.processNote[0].type.coding[0].code, "print")
        self.assertEqual(inst.processNote[0].type.coding[0].system, "http://hl7.org/fhir/note-type")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.div, "
A human-readable rendering of the ProcessResponse
")
        self.assertEqual(inst.text.status, "generated")

    def testProcessResponse2(self):
        inst = self.instantiate_from("processresponse-example-pended.json")
        self.assertIsNotNone(inst, "Must have instantiated a ProcessResponse instance")
        self.implProcessResponse2(inst)

        js = inst.as_json()
        self.assertEqual("ProcessResponse", js["resourceType"])
        inst2 = processresponse.ProcessResponse(js)
        self.implProcessResponse2(inst2)

    def implProcessResponse2(self, inst):
        self.assertEqual(inst.contained[0].id, "comreq-1")
        self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date)
        self.assertEqual(inst.created.as_json(), "2014-08-16")
        self.assertEqual(inst.disposition, "Additional information required.")
        self.assertEqual(inst.id, "SR2499")
        self.assertEqual(inst.identifier[0].system, "http://www.BenefitsInc.com/fhir/processresponse")
        self.assertEqual(inst.identifier[0].value, "881222")
        self.assertEqual(inst.outcome.coding[0].code, "pended")
        self.assertEqual(inst.outcome.coding[0].system, "http://hl7.org/fhir/processoutcomecodes")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.div, "
A ProcessResponse indicating pended status with a request for additional information.
")
        self.assertEqual(inst.text.status, "generated")

    def testProcessResponse3(self):
        inst = self.instantiate_from("processresponse-example.json")
        self.assertIsNotNone(inst, "Must have instantiated a ProcessResponse instance")
        self.implProcessResponse3(inst)

        js = inst.as_json()
        self.assertEqual("ProcessResponse", js["resourceType"])
        inst2 = processresponse.ProcessResponse(js)
        self.implProcessResponse3(inst2)

    def implProcessResponse3(self, inst):
        self.assertEqual(inst.created.date, FHIRDate("2014-08-16").date)
        self.assertEqual(inst.created.as_json(), "2014-08-16")
        self.assertEqual(inst.disposition, "Adjudication processing completed, ClaimResponse and EOB ready for retrieval.")
        self.assertEqual(inst.id, "SR2500")
        self.assertEqual(inst.identifier[0].system, "http://www.BenefitsInc.com/fhir/processresponse")
        self.assertEqual(inst.identifier[0].value, "881234")
        self.assertEqual(inst.outcome.coding[0].code, "complete")
        self.assertEqual(inst.outcome.coding[0].system, "http://hl7.org/fhir/processoutcomecodes")
        self.assertEqual(inst.status, "active")
        self.assertEqual(inst.text.div, "
A human-readable rendering of the ProcessResponse
")
        self.assertEqual(inst.text.status, "generated")


text:
namespace MatchingParenFinder
{
    using NUnit.Framework;
    using System;

    [TestFixture]
    public class MatchingParenFinderTests
    {
        [TestCase("Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing.", 10, Result = 79)]
        public int CheckOutcome(string code, int startPosition)
        {
            MatchingParenFinder finder = new MatchingParenFinder();
            return finder.FindMatchingParenPosition(code, startPosition);
        }

        [Test]
        public void StartPositionNegative()
        {
            string code = "some";
            MatchingParenFinder finder = new MatchingParenFinder();
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => finder.FindMatchingParenPosition(code, -5));
        }

        [Test]
        public void StartPositionAboveCodeLength()
        {
            string code = "some";
            MatchingParenFinder finder = new MatchingParenFinder();
            Assert.Throws(typeof(ArgumentOutOfRangeException), () => finder.FindMatchingParenPosition(code, 1000));
        }

        [Test]
        public void CodeIsNullOrEmptyThrowsArgumentException()
        {
            string code = null;
            MatchingParenFinder finder = new MatchingParenFinder();
            Assert.Throws(typeof(ArgumentException), () => finder.FindMatchingParenPosition(code, 1000));
        }
    }
}


text:
package net.tomp2p.peers;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;

import org.junit.Assert;
import org.junit.Test;

/**
 * Test the serialization and deserialization of PeerAddress.
 *
 * @author Thomas Bocek
 *
 */
public class TestPeerAddress {
    private static final int SEED = 1;
    private static final int BIT_16 = 256 * 256;
    private static final Random RND = new Random(SEED);

    /**
     * Test serialization and deserialization of PeerAddress.
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress() throws UnknownHostException {
        Number160 id = new Number160(RND.nextInt());
        InetAddress address = InetAddress.getByName("127.0.0.1");
        int portTCP = RND.nextInt(BIT_16);
        int portUDP = RND.nextInt(BIT_16);
        PeerAddress pa = new PeerAddress(id, address, portTCP, portUDP);
        byte[] me = pa.toByteArray();
        PeerAddress pa2 = new PeerAddress(me);
        compare(pa, pa2);
    }

    /**
     * Test serialization and deserialization of PeerAddress.
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress2() throws UnknownHostException {
        Number160 id = new Number160("0x657435a424444522456");
        InetAddress address = InetAddress.getByName("192.168.240.230");
        int portTCP = RND.nextInt(BIT_16);
        int portUDP = RND.nextInt(BIT_16);
        PeerAddress pa = new PeerAddress(id, address, portTCP, portUDP);
        byte[] me = pa.toByteArray();
        PeerAddress pa2 = new PeerAddress(me);
        compare(pa, pa2);
    }

    /**
     * Test serialization and deserialization of PeerAddress.
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress3() throws UnknownHostException {
        PeerAddress pa1 = new PeerAddress(new Number160("0x857e35a42e444522456"),
                InetAddress.getByName("192.168.230.230"), RND.nextInt(BIT_16), RND.nextInt(BIT_16));
        PeerAddress pa2 = new PeerAddress(new Number160("0x657435a424444522456"),
                InetAddress.getByName("192.168.240.230"), RND.nextInt(BIT_16), RND.nextInt(BIT_16));
        final int length = 200;
        byte[] me = new byte[length];
        final int offset = 50;
        int offset2 = pa1.toByteArray(me, offset);
        pa2.toByteArray(me, offset2);
        //
        PeerAddress pa3 = new PeerAddress(me, offset);
        int offset4 = pa3.offset();
        PeerAddress pa4 = new PeerAddress(me, offset4);
        compare(pa1, pa3);
        compare(pa2, pa4);
    }

    /**
     * Test serialization and deserialization of PeerAddress. Test also IPv6
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress4() throws UnknownHostException {
        PeerAddress pa1 = new PeerAddress(new Number160("0x857e35a42e444522456"),
                InetAddress.getByName("0123:4567:89ab:cdef:0123:4567:89ab:cdef"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16));
        PeerAddress pa2 = new PeerAddress(new Number160("0x657435a424444522456"),
                InetAddress.getByName("0123:4567:89ab:cdef:0123:4567:89ab:cdef"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16));

        final int length = 200;
        byte[] me = new byte[length];
        final int offset = 50;
        int offset2 = pa1.toByteArray(me, offset);
        pa2.toByteArray(me, offset2);
        //
        PeerAddress pa3 = new PeerAddress(me, offset);
        int offset4 = pa3.offset();
        PeerAddress pa4 = new PeerAddress(me, offset4);
        compare(pa1, pa3);
        compare(pa2, pa4);
    }

    /**
     * Test serialization and deserialization of PeerAddress. Test maximum size.
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress5() throws UnknownHostException {

        Collection<PeerSocketAddress> psa = new ArrayList<PeerSocketAddress>();
        psa.add(new PeerSocketAddress(InetAddress.getByName("192.168.230.230"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("2123:4567:89ab:cdef:0123:4567:89ab:cde2"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("192.168.230.231"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("4123:4567:89ab:cdef:0123:4567:89ab:cde4"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("192.168.230.232"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16)));
        PeerAddress pa3 = new PeerAddress(new Number160("0x657435a424444522456"), new PeerSocketAddress(
                InetAddress.getByName("192.168.230.236"), RND.nextInt(BIT_16), RND.nextInt(BIT_16)), true, true, true, true,
                true, psa);

        final int length = 200;
        byte[] me = new byte[length];
        final int offset = 50;
        pa3.toByteArray(me, offset);
        PeerAddress pa4 = new PeerAddress(me, offset);

        compare(pa3, pa4);
    }

    /**
     * Test serialization and deserialization of PeerAddress. Test mix of IPv4 and IPv6.
     *
     * @throws UnknownHostException .
     */
    @Test
    public void testPeerAddress6() throws UnknownHostException {

        Collection<PeerSocketAddress> psa = new ArrayList<PeerSocketAddress>();
        psa.add(new PeerSocketAddress(InetAddress.getByName("1123:4567:89ab:cdef:0123:4567:89ab:cde1"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("2123:4567:89ab:cdef:0123:4567:89ab:cde2"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("3123:4567:89ab:cdef:0123:4567:89ab:cde3"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("4123:4567:89ab:cdef:0123:4567:89ab:cde4"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("5123:4567:89ab:cdef:0123:4567:89ab:cde5"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        PeerAddress pa3 = new PeerAddress(new Number160("0x657435a424444522456"), new PeerSocketAddress(
                InetAddress.getByName("1123:4567:89ab:cdef:0123:4567:89ab:cde0"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16)), true, true, true, true, true, psa);

        final int length = 200;
        byte[] me = new byte[length];
        final int offset = 50;
        int offset2 = pa3.toByteArray(me, offset);
        int len = offset2 - offset;
        // 142 is the
        Assert.assertEquals(PeerAddress.MAX_SIZE, PeerAddress.size(pa3.options(), pa3.relays()));
        Assert.assertEquals(PeerAddress.MAX_SIZE, len);
        //
        PeerAddress pa4 = new PeerAddress(me, offset);

        compare(pa3, pa4);
    }

    @Test
    public void testPeerAddress7() throws UnknownHostException {

        Collection<PeerSocketAddress> psa = new ArrayList<PeerSocketAddress>();
        psa.add(new PeerSocketAddress(InetAddress.getByName("1123:4567:89ab:cdef:0123:4567:89ab:cde1"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("2123:4567:89ab:cdef:0123:4567:89ab:cde2"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("3123:4567:89ab:cdef:0123:4567:89ab:cde3"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("4123:4567:89ab:cdef:0123:4567:89ab:cde4"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        psa.add(new PeerSocketAddress(InetAddress.getByName("5123:4567:89ab:cdef:0123:4567:89ab:cde5"),
                RND.nextInt(BIT_16), RND.nextInt(BIT_16)));
        PeerAddress pa3 = new PeerAddress(new Number160("0x657435a424444522456"), new PeerSocketAddress(
                InetAddress.getByName("1123:4567:89ab:cdef:0123:4567:89ab:cde0"), RND.nextInt(BIT_16),
                RND.nextInt(BIT_16)), true, true, true, true, true, psa);

        Assert.assertEquals(142, pa3.toByteArray().length);

    }

    /**
     * Compare two PeerAddress.
     *
     * @param pa1
     *            The first PeerAddress
     * @param pa2
     *            The second PeerAddress
     */
    private void compare(final PeerAddress pa1, final PeerAddress pa2) {
        Assert.assertEquals(pa1.peerId(), pa2.peerId());
        Assert.assertEquals(pa1.createSocketTCP().getPort(), pa2.createSocketTCP().getPort());
        Assert.assertEquals(pa1.createSocketTCP(), pa2.createSocketTCP());
        Assert.assertEquals(pa1.createSocketUDP().getPort(), pa2.createSocketUDP().getPort());
        Assert.assertEquals(pa1.createSocketUDP(), pa2.createSocketUDP());
        Assert.assertEquals(pa1.isFirewalledTCP(), pa2.isFirewalledTCP());
        Assert.assertEquals(pa1.isFirewalledUDP(), pa2.isFirewalledUDP());
        Assert.assertEquals(pa1.isIPv6(), pa2.isIPv6());
        Assert.assertEquals(pa1.isRelayed(), pa2.isRelayed());
        Assert.assertEquals(pa1.options(), pa2.options());
        Assert.assertEquals(pa1.relays(), pa2.relays());
        List<PeerSocketAddress> psa1 = new ArrayList<PeerSocketAddress>(pa1.peerSocketAddresses());
        List<PeerSocketAddress> psa2 = new ArrayList<PeerSocketAddress>(pa2.peerSocketAddresses());
        Assert.assertEquals(psa1.size(), psa2.size());
        for (int i = 0; i < psa1.size(); i++) {
            Assert.assertEquals(psa1.get(i), psa2.get(i));
        }

    }
}


text:
package com.amazonaws.services.apigateway.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.apigateway.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * DeleteUsagePlanResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class DeleteUsagePlanResultJsonUnmarshaller implements Unmarshaller<DeleteUsagePlanResult, JsonUnmarshallerContext> {

    public DeleteUsagePlanResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        DeleteUsagePlanResult deleteUsagePlanResult = new DeleteUsagePlanResult();

        return deleteUsagePlanResult;
    }

    private static DeleteUsagePlanResultJsonUnmarshaller instance;

    public static DeleteUsagePlanResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new DeleteUsagePlanResultJsonUnmarshaller();
        return instance;
    }
}


text:
package com.orientechnologies.orient.test.internal;

import java.io.IOException;
import java.util.List;

import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx;
import com.orientechnologies.orient.core.metadata.schema.OClass;
import com.orientechnologies.orient.core.metadata.schema.OClass.INDEX_TYPE;
import com.orientechnologies.orient.core.metadata.schema.OSchema;
import com.orientechnologies.orient.core.metadata.schema.OType;
import com.orientechnologies.orient.core.record.impl.ODocument;
import com.orientechnologies.orient.core.sql.query.OSQLSynchQuery;

public class TestOrientPagination {
  public static final String         dbName   = "memory:/testDB";
  public static final String         dbUser   = "admin";
  public static final String         dbPwd    = "admin";

  private static ODatabaseDocumentTx database = null;

  @BeforeClass
  static public void init() throws IOException {
    // database = new ODatabaseDocumentTx(dbName);
    // ODatabaseHelper.createDatabase(database, dbName);

    database = new ODatabaseDocumentTx(dbName);
    database.open(dbUser, dbPwd);

    OSchema schema = database.getMetadata().getSchema();

    schema.createClass("test_class");
    OClass oclass = schema.getClass("test_class");
    oclass.createProperty("testp", OType.LONG);
    oclass.createIndex("testp_idx", INDEX_TYPE.NOTUNIQUE, "testp");

    ODocument doc = new ODocument(oclass);
    doc.field("testp", 1);

    ODocument doc1 = new ODocument(oclass);
    doc1.field("testp", 2);

    ODocument doc2 = new ODocument(oclass);
    doc2.field("testp", 3);

    ODocument doc3 = new ODocument(oclass);
    doc3.field("testp", 4);

    ODocument doc4 = new ODocument(oclass);
    doc4.field("testp", 5);

    ODocument doc5 = new ODocument(oclass);
    doc5.field("testp", 6);

    ODocument doc6 = new ODocument(oclass);
    doc6.field("testp", 7);

    database.save(doc);
    database.save(doc1);
    database.save(doc2);
    database.save(doc3);
    database.save(doc4);
    database.save(doc5);
    database.save(doc6);
  }

  @Test
  public void testOrderBySkip() {
    String query = "select from test_class order by testp limit 3 skip ";
    List<ODocument> docs = database.query(new OSQLSynchQuery<ODocument>(query + "0"));
    List<ODocument> docs2 = database.query(new OSQLSynchQuery<ODocument>(query + "3"));

    // Assert.assertFalse(docs.equals(docs2));
  }

  @Test
  public void testOrderByDescSkip() {
    String query = "select from test_class order by testp desc limit 3 skip ";
    // List<ODocument> docs = database.query(new
    // OSQLSynchQuery<ODocument>(query + "0"));
    List<ODocument> docs2 = database.query(new OSQLSynchQuery<ODocument>(query + "3"));
    // Assert.assertFalse(docs.equals(docs2));
  }
}


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

    <ImageSwitcher
        android:id="@+id/animationTests_isWeatherLogo"
        android:layout_width="175dp"
        android:layout_height="175dp"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true" />

    <TextView
        android:id="@+id/animationTests_tvAppName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/animationTests_isWeatherLogo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:text="@string/app_name"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/white"
        android:textSize="65dp" />
</RelativeLayout>


text:
package com.intellij.refactoring.encapsulateFields;

import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
* @author Max Medvedev
*/
public interface FieldDescriptor {
  @NotNull
  PsiField getField();

  @NotNull
  String getGetterName();

  @NotNull
  String getSetterName();

  @Nullable
  PsiMethod getGetterPrototype();

  @Nullable
  PsiMethod getSetterPrototype();

  void refreshField(@NotNull PsiField newField);
}


text:
package org.appcelerator.kroll;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.HashMap;

import org.appcelerator.kroll.KrollExceptionHandler.ExceptionMessage;
import org.appcelerator.kroll.common.Log;
import org.appcelerator.kroll.common.TiMessenger;
import org.appcelerator.kroll.util.KrollAssetHelper;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

/**
 * The common Javascript runtime instance that Titanium interacts with.
 *
 * The runtime instance itself is static and lives with the Android process.
 * KrollRuntime use activity reference counting to tear down the runtime state
 * when all of the application's Titanium activities have been destroyed.
 *
 * Even after all of the activities have been destroyed, Android can (and usually does)
 * keep the application process running. When the application is re-entered from
 * this "torn down" state, we simply re-initialize again, this time from the first
 * activity ref increment (TiBaseActivity.onCreate), instead of TiApplication.onCreate
 */
public abstract class KrollRuntime implements Handler.Callback
{
	private static final String TAG = "KrollRuntime";
	private static final int MSG_INIT = 100;
	private static final int MSG_DISPOSE = 101;
	private static final int MSG_RUN_MODULE = 102;
	private static final int MSG_EVAL_STRING = 103;
	private static final String PROPERTY_FILENAME = "filename";
	private static final String PROPERTY_SOURCE = "source";

	public interface OnDisposingListener {
		void onDisposing(KrollRuntime runtime);
	}

	private static KrollRuntime instance;
	private static ArrayList<OnDisposingListener> disposingListeners = new ArrayList<>();
	private static int activityRefCount = 0;
	private static int serviceReceiverRefCount = 0;

	private WeakReference<KrollApplication> krollApplication;
	private long threadId;
	private KrollEvaluator evaluator;
	private KrollExceptionHandler primaryExceptionHandler;
	private HashMap<String, KrollExceptionHandler> exceptionHandlers;

	public enum State { INITIALIZED, RELEASED, DISPOSED }
	private static State runtimeState = State.DISPOSED;
	private static boolean isDisposing;

	protected Handler handler;

	public static final int MSG_LAST_ID = MSG_RUN_MODULE + 100;

	public static final Object UNDEFINED = new Object() {
		public String toString()
		{
			return "undefined";
		}
	};

	public static final int DONT_INTERCEPT = Integer.MIN_VALUE + 1;
	public static final int DEFAULT_THREAD_STACK_SIZE = 16 * 1024;
	public static final String SOURCE_ANONYMOUS = "<anonymous>";

	public static void init(Context context, KrollRuntime runtime)
	{
		// Initialize asset helper, if not done already.
		KrollAssetHelper.init(context);

		// Do not continue if already initialized.
		if (runtimeState == State.INITIALIZED) {
			return;
		}

		// Keep a reference to the given runtime.
		// Must be done before calling doInit() below.
		instance = runtime;

		// Load all application properties.
		((KrollApplication) context).loadAppProperties();

		// Set up runtime member variables.
		Looper looper = Looper.getMainLooper();
		runtime.krollApplication = new WeakReference<KrollApplication>((KrollApplication) context);
		runtime.exceptionHandlers = new HashMap<String, KrollExceptionHandler>();
		runtime.threadId = looper.getThread().getId();
		runtime.handler = new Handler(looper, runtime);

		// Initialize the TiMessenger instance for the current thread.
		// NOTE: This must occur after "threadId" is set and before doInit() is called.
		TiMessenger.getMessenger();

		// Initialize the given runtime.
		runtime.doInit();
	}

	public static KrollRuntime getInstance()
	{
		return instance;
	}

	public static void suggestGC()
	{
		if (instance != null) {
			instance.setGCFlag();
		}
	}

	public static boolean isInitialized()
	{
		if (instance != null) {
			synchronized (runtimeState)
			{
				return runtimeState == State.INITIALIZED;
			}
		}
		return false;
	}

	public static boolean isDisposed()
	{
		if (instance != null) {
			synchronized (runtimeState)
			{
				return runtimeState == State.DISPOSED;
			}
		}
		return true;
	}

	public KrollApplication getKrollApplication()
	{
		if (krollApplication != null) {
			return krollApplication.get();
		}
		return null;
	}

	public boolean isRuntimeThread()
	{
		return Thread.currentThread().getId() == threadId;
	}

	public long getThreadId()
	{
		return threadId;
	}

	private void doInit()
	{
		// Do not continue if already initialized.
		if (runtimeState == State.INITIALIZED) {
			return;
		}

		// Make sure this method is being called on the runtime's thread.
		if (!isRuntimeThread()) {
			instance.handler.sendEmptyMessage(MSG_INIT);
			return;
		}

		// If currently scheduled to be disposed, then do so now.
		if (runtimeState == State.RELEASED) {
			internalDispose();
			if (runtimeState != State.DISPOSED) {
				instance.handler.sendEmptyMessage(MSG_INIT);
				return;
			}
		}

		// Initialize the JavaScript runtime.
		initRuntime();
		runtimeState = State.INITIALIZED;
	}

	public void dispose()
	{
		// Flag the runtime as "released" to indicate that it's about to be disposed.
		synchronized (runtimeState)
		{
			switch (runtimeState) {
				case RELEASED:
				case DISPOSED:
					return;
			}
			runtimeState = State.RELEASED;
		}

		// Dispose the runtime on the thread it was created on.
		Log.d(TAG, "Disposing runtime.", Log.DEBUG_MODE);
		internalDispose();
	}

	public void runModule(String source, String filename, KrollProxySupport activityProxy)
	{
		if (isRuntimeThread()) {
			doRunModule(source, filename, activityProxy);

		} else {
			Message message = handler.obtainMessage(MSG_RUN_MODULE, activityProxy);
			message.getData().putString(PROPERTY_SOURCE, source);
			message.getData().putString(PROPERTY_FILENAME, filename);
			message.sendToTarget();
		}
	}

	/**
	 * Equivalent to
evalString(source, SOURCE_ANONYMOUS)

	 * @see #evalString(String, String)
	 * @param source A string containing Javascript source
	 * @return The Java representation of the return value of {@link source}, as long as Kroll supports the return value
	 */
	public Object evalString(String source)
	{
		return evalString(source, SOURCE_ANONYMOUS);
	}

	/**
	 * Evaluates a String of Javascript code, returning the result of the execution
	 * when this method is called on the KrollRuntime thread. If this method is called
	 * ony any other thread, then the code is executed asynchronous, and this method returns null.
	 *
	 * Currently, Kroll supports converting the following Javascript return types:
	 *

	 *
Primitives (String, Number, Boolean, etc)

	 *
Javascript object literals as {@link org.appcelerator.kroll.KrollDict}

	 *
Arrays

	 *
Any Proxy type that extends {@link org.appcelerator.kroll.KrollProxy}

	 *

	 * @param source A string containing Javascript source
	 * @param filename The name of the filename represented by {@link source}
	 * @return The Java representation of the return value of {@link source}, as long as Kroll supports the return value
	 */
	public Object evalString(String source, String filename)
	{
		if (isRuntimeThread()) {
			return doEvalString(source, filename);

		} else {
			Message message = handler.obtainMessage(MSG_EVAL_STRING);
			message.getData().putString(PROPERTY_SOURCE, source);
			message.getData().putString(PROPERTY_FILENAME, filename);
			message.sendToTarget();
			return null;
		}
	}

	public int getThreadStackSize(Context context)
	{
		if (context instanceof KrollApplication) {
			KrollApplication app = (KrollApplication) context;
			return app.getThreadStackSize();
		}
		return DEFAULT_THREAD_STACK_SIZE;
	}

	public boolean handleMessage(Message msg)
	{
		switch (msg.what) {
			case MSG_INIT: {
				doInit();
				return true;
			}

			case MSG_DISPOSE: {
				internalDispose();
				return true;
			}

			case MSG_RUN_MODULE: {
				String source = msg.getData().getString(PROPERTY_SOURCE);
				String filename = msg.getData().getString(PROPERTY_FILENAME);
				KrollProxySupport activityProxy = (KrollProxySupport) msg.obj;

				doRunModule(source, filename, activityProxy);
				return true;
			}

			case MSG_EVAL_STRING: {
				String source = msg.getData().getString(PROPERTY_SOURCE);
				String filename = msg.getData().getString(PROPERTY_FILENAME);

				doEvalString(source, filename);
				return true;
			}
		}

		return false;
	}

	/**
	 * This method is expected to be called for every Titanium activity that has been created.
	 * This will startup the JavaScript runtime when the activity count is 1 (the first activity created).
	 *

	 * You must call the decrementActivityRefCount() when the Titanium activity is being destroyed.
	 */
	public static void incrementActivityRefCount()
	{
		// Increment the activity count.
		activityRefCount++;

		// If this is the 1st activity, then start up the runtime, if not done already.
		if ((activityRefCount == 1) && (instance != null)) {
			instance.doInit();
		}
	}

	public static void decrementActivityRefCount(boolean willDisposeRuntime)
	{
		// Validate.
		if (activityRefCount <= 0) {
			Log.e(TAG, "The decrementActivityRefCount() method was called while count is zero.");
			return;
		}

		// Decrement the activity count.
		activityRefCount--;

		// Terminate the runtime if activity count is zero.
		if (!willDisposeRuntime) {
			return;
		}
		if ((activityRefCount > 0) || (instance == null)) {
			return;
		}
		instance.dispose();
	}

	public static int getActivityRefCount()
	{
		return activityRefCount;
	}

	// Similar to {@link #incrementActivityRefCount} but for a Titanium Service.
	public static void incrementServiceReceiverRefCount()
	{
		serviceReceiverRefCount++;
	}

	public static void decrementServiceReceiverRefCount()
	{
		if (serviceReceiverRefCount > 0) {
			serviceReceiverRefCount--;
		} else {
			Log.e(TAG, "The decrementServiceReceiverRefCount() method was called while count is zero.");
		}
	}

	public static int getServiceReceiverRefCount()
	{
		return serviceReceiverRefCount;
	}

	private void internalDispose()
	{
		// Make sure this method is called on the runtime's thread.
		if (!isRuntimeThread()) {
			handler.sendEmptyMessage(MSG_DISPOSE);
			return;
		}

		// Do not continue if already disposed/disposing.
		synchronized (runtimeState)
		{
			if (runtimeState != State.RELEASED) {
				return;
			}
			if (isDisposing) {
				return;
			}
			isDisposing = true;
		}

		// Invoke all OnDisposingListener objects before disposing this runtime.
		onDisposing(this);

		// Dispose/terminate the runtime.
		doDispose();
		synchronized (runtimeState)
		{
			runtimeState = State.DISPOSED;
			isDisposing = false;
		}

		// Request the application to dispose its native resources.
		KrollApplication app = krollApplication.get();
		if (app != null) {
			app.dispose();
		}
	}

	public KrollEvaluator getEvaluator()
	{
		return evaluator;
	}

	public void setEvaluator(KrollEvaluator eval)
	{
		evaluator = eval;
	}

	public void setGCFlag()
	{
		// No-op V8 should override.
	}

	public State getRuntimeState()
	{
		return runtimeState;
	}

	/**
	 * Sets the default exception handler for the runtime. There can only be one default exception handler set at a
	 * time.
	 *
	 * @param handler The exception handler to set
	 * @module.api
	 */
	public static void setPrimaryExceptionHandler(KrollExceptionHandler handler)
	{
		if (instance != null) {
			instance.primaryExceptionHandler = handler;
		}
	}

	/**
	 * Adds an exception handler to a list of handlers that will be called in addition to the default one. To replace the
	 * default exception, use {@link #setPrimaryExceptionHandler(KrollExceptionHandler)}.
	 *
	 * @param handler The exception handler to set
	 * @param key The key for the exception handler
	 * @module.api
	 */
	public static void addAdditionalExceptionHandler(KrollExceptionHandler handler, String key)
	{
		if (instance != null && key != null) {
			instance.exceptionHandlers.put(key, handler);
		}
	}

	/**
	 * Removes the exception handler from the list of additional handlers. This will not affect the default handler.
	 * @param key The key for the exception handler
	 * @module.api
	 */
	public static void removeExceptionHandler(String key)
	{
		if (instance != null && key != null) {
			instance.exceptionHandlers.remove(key);
		}
	}

	public static void dispatchException(final String title, final String message, final String sourceName,
										 final int line, final String lineSource, final int lineOffset,
										 final String jsStack, final String javaStack)
	{
		if (instance != null) {
			HashMap<String, KrollExceptionHandler> handlers = instance.exceptionHandlers;
			ExceptionMessage exceptionMessage =
				new ExceptionMessage(title, message, sourceName, line, lineSource, lineOffset, jsStack, javaStack);

			if (!handlers.isEmpty()) {
				for (KrollExceptionHandler handler : handlers.values()) {
					if (handler != null) {
						handler.handleException(exceptionMessage);
					}
				}
				return;
			}

			// Handle exception with defaultExceptionHandler
			instance.primaryExceptionHandler.handleException(exceptionMessage);
		}
	}

	/**
	 * Adds a listener to be invoked just before a Titanium JavaScript runtime instance has been terminated.
	 *

	 * You cannot add the same listener instance twice. Duplicate listener instances will be ignored.
	 * @param listener The listener to be added. Null references will be ignored.
	 */
	public static void addOnDisposingListener(KrollRuntime.OnDisposingListener listener)
	{
		if ((listener != null) && (disposingListeners.contains(listener) == false)) {
			disposingListeners.add(listener);
		}
	}

	/**
	 * Removes the given listener by reference that was added via the addOnDisposingListener() method.
	 * @param listener The listener to be removed by reference. Can be null.
	 */
	public static void removeOnDisposingListener(KrollRuntime.OnDisposingListener listener)
	{
		if (listener != null) {
			disposingListeners.remove(listener);
		}
	}

	/**
	 * This method is intended to be called just before the given runtime's doDispose() method has been called.
	 * Invokes all "OnDisposingListener" objects, allowing them to perform final cleanup operations.
	 * @param runtime The runtime instance that is about to be disposed of. Can be null.
	 */
	private static void onDisposing(KrollRuntime runtime)
	{
		// Validate.
		if (runtime == null) {
			return;
		}

		// Create a shallow copy of all listeners to be iterated down below.
		// We do this because an invoked listener can add/remove listeners in main collection.
		ArrayList<OnDisposingListener> clonedListeners =
			(ArrayList<OnDisposingListener>) KrollRuntime.disposingListeners.clone();
		if (clonedListeners == null) {
			return;
		}

		// Notify all listeners.
		for (OnDisposingListener listener : clonedListeners) {
			if (KrollRuntime.disposingListeners.contains(listener)) {
				// Previous listener did not remove this listener. Invoke it.
				try {
					listener.onDisposing(runtime);
				} catch (Exception ex) {
					Log.e(TAG, "OnDisposingListener threw an exception.", ex);
				}
			}
		}
	}

	public abstract void doDispose();
	public abstract void doRunModule(String source, String filename, KrollProxySupport activityProxy);
	public abstract Object doEvalString(String source, String filename);

	public abstract String getRuntimeName();
	public abstract void initRuntime();
	public abstract void initObject(KrollProxySupport proxy);
}


text:
package com.what2p.repositorys;

import com.what2p.domains.RateTable;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * RateTable的Repository类
 */
public interface RateTableRepository extends JpaRepository<RateTable, Long> {
}


text:
module Route53Aliaser
  class Aliaser
    attr_reader :config

    def initialize(config = Configuration.new)
      @config = config
    end

    def stale?
      config.cache.fetch(config.source_key).nil?
    end

    def call
      unless stale?
        # NOOP if we haven't expired
        config.logger.info "Route53Aliaser: NOOP because cache is fresh"
        return
      end

      target_ips = get_ips(config.target_record, config.target_key)
      source_ips = get_ips(config.source_record, config.source_key)

      if target_ips == source_ips
        config.logger.info "Route53Aliaser: No Route 53 Update required (Target IPs match the Source IPs)"
      else
        config.logger.info "Route53Aliaser: IPs for #{config.target_record} #{target_ips} differ from #{config.source_record} #{source_ips}; will attempt to update"
        rt53 = Route53Updater.new(config)
        rt53.update_target(config.target_record, config.source_record, source_ips, config.zone_id)
      end
    end

    private
    def get_ips(zone, key)
      ips = retrieve_ips_from_cache(key)
      if ips.empty?
        ips, ttl = get_ips_and_ttl_from_dns(zone)
        cache_results(key, zone, ips, ttl)
      end
      ips
    end

    def retrieve_ips_from_cache(key)
      cached_value = config.cache.fetch(key)
      if cached_value
        cached_value.split(',')
      else
        []
      end
    end

    def get_ips_and_ttl_from_dns(zone)
      ips, ttl = [], 0
      resources = Resolv::DNS.new.getresources(zone, Resolv::DNS::Resource::IN::A)
      if resources && resources.size > 0
        ips = resources.collect{|res| res.address.to_s}.sort
        ttl = resources.first.ttl
      end
      return ips, ttl
    rescue ResolvError => e
      config.logger.error e
      return ips, ttl
    end

    def cache_results(key, zone, ips, ttl)
      unless ips.empty?
        config.cache.write(key,
                           ips.join(','),
                           expires_in: ttl.seconds,
                           race_condition_ttl: 10
                          )
        config.logger.debug "Route53Aliaser: Caching #{key}: #{ips} for #{ttl} seconds (ttl)"
      else
        config.logger.error "Route53Aliaser: NOT Caching #{key} because no IPs were found."
      end
    end
  end
end


text:
This boilerplate contains base LESS files and site-specific LESS files. The base LESS files exist in the `base/` directory and define the default bootstrap appearance; DO NOT edit the base files. The site-specific LESS files exist in the `site/` directory; create custom LESS files in the `site/` directory to customize the bootstrap for your website design.

The base and site-specific LESS files are controlled with LESS variables. Find the default
variables in `base/variables.less`; DO NOT edit this file. If you need to change a variable, override the base variable with a site-specific variable in `site/variables.less`.

## Getting Started

1. Copy the contents of this directory into your HiFi template's `styles/` directory.
2. Create site-specific `.less` files inside the `site/` directory.
3. `@import` site-specific `.less` files into `all.less`.
4. Compile and minify `all.less` before site launch.

## Upgrading Bootstrap Files

This bootstrap is designed so that you may update the base LESS files without affecting site-specific LESS files.

1. Replace the `base/` directory with the updated `base/` directory.

## Coding Style

* Indent with 4 spaces (do not use tabs)
* Variable, mixin, operator, and function names should:
    * Use lower-case characters
    * Use dashes to separate words


text:
module.exports = function(graphics, shapeObject, AppState) {
  var selected = false;
  var original;
  var movingSelf = false;
  var Shapes = AppState.Canvas.Shapes;
  //var graphics = shapeObject.graphics;
  var socket = AppState.Socket;

  graphics.interactive = true;
  console.log('setting move listeners');
  graphics.mousedown = function(data) {
    //console.log('mouseDownRecieved on shape', data);
    data.originalEvent.preventDefault();
    if(AppState.Tools.selected === 'select') {

      this.data = data;
      original = data.getLocalPosition(this);
      this.alpha = 0.9;
      selected = true;
      //graphics.selected = true;
      //console.log(AppState);
      AppState.Tools.select.selectedObject = shapeObject;

    }
    else if(AppState.Tools.selected === 'fill') {

      this.clear();
      console.log('fill Color: ' + AppState.Tools.fill.fillColor);
      this.endFill(AppState.Tools.fill.fillColor);
      AppState.Canvas.stage.addChild(this);
    }
  };

  graphics.mousemove = function(data)
  {
    if(selected) {
      var newPosition = this.data.getLocalPosition(this.parent);
      movingSelf = true;

      this.position.x = newPosition.x - original.x;
      this.position.y = newPosition.y - original.y;

      var newPos = {
        x: this.position.x,
        y: this.position.y
      };
    }
  };

  graphics.mouseup = graphics.mouseupoutside = function(data) {
    selected = false;
    this.alpha = 1;
    //shapeObject.selected = false;
    // set the interaction data to null
    this.data = null;
    movingSelf = false;
    //SocketObject.emitObjectMoveDone(stage.getChildIndex(this));
  };
};


text:
package com.haulmont.cuba.web.widgets.client.optiongroup;

import java.io.Serializable;

public enum OptionGroupOrientation implements Serializable {
    HORIZONTAL,
    VERTICAL
}


text:
define([
    'ko',
    'mageUtils',
    'underscore',
    'uiLayout',
    'uiCollection',
    'uiRegistry',
    'mage/translate'
], function (ko, utils, _, layout, uiCollection, registry, $t) {
    'use strict';

    return uiCollection.extend({
        defaults: {
            defaultRecord: false,
            columnsHeader: true,
            columnsHeaderAfterRender: false,
            columnsHeaderClasses: '',
            labels: [],
            recordTemplate: 'record',
            collapsibleHeader: false,
            additionalClasses: {},
            visible: true,
            disabled: false,
            fit: false,
            addButton: true,
            addButtonLabel: $t('Add'),
            recordData: [],
            maxPosition: 0,
            deleteProperty: 'delete',
            identificationProperty: 'record_id',
            deleteValue: true,
            showSpinner: true,
            isDifferedFromDefault: false,
            fallbackResetTpl: 'ui/form/element/helper/fallback-reset-link',
            dndConfig: {
                name: '${ $.name }_dnd',
                component: 'Magento_Ui/js/dynamic-rows/dnd',
                template: 'ui/dynamic-rows/cells/dnd',
                recordsProvider: '${ $.name }',
                enabled: true
            },
            templates: {
                record: {
                    parent: '${ $.$data.collection.name }',
                    name: '${ $.$data.index }',
                    dataScope: '${ $.$data.collection.index }.${ $.name }',
                    nodeTemplate: '${ $.parent }.${ $.$data.collection.recordTemplate }'
                }
            },
            links: {
                recordData: '${ $.provider }:${ $.dataScope }.${ $.index }'
            },
            listens: {
                visible: 'setVisible',
                disabled: 'setDisabled',
                childTemplate: 'initHeader',
                recordTemplate: 'onUpdateRecordTemplate',
                recordData: 'setDifferedFromDefault parsePagesData',
                currentPage: 'changePage',
                elems: 'checkSpinner'
            },
            modules: {
                dnd: '${ $.dndConfig.name }'
            },
            pages: 1,
            pageSize: 20,
            relatedData: [],
            currentPage: 1,
            startIndex: 0
        },

        /**
         * Extends instance with default config, calls initialize of parent
         * class, calls initChildren method, set observe variable.
         * Use parent "track" method - wrapper observe array
         *
         * @returns {Object} Chainable.
         */
        initialize: function () {
            this._super()
                .initChildren()
                .initDnd()
                .setColumnsHeaderListener()
                .initDefaultRecord()
                .checkSpinner();

            return this;
        },

        /**
         * Calls 'initObservable' of parent
         *
         * @returns {Object} Chainable.
         */
        initObservable: function () {
            this._super()
                .track('childTemplate')
                .observe([
                    'pages',
                    'currentPage',
                    'recordData',
                    'columnsHeader',
                    'visible',
                    'disabled',
                    'labels',
                    'showSpinner',
                    'isDifferedFromDefault'
                ]);

            return this;
        },

        /**
         * Init DND module
         *
         * @returns {Object} Chainable.
         */
        initDnd: function () {
            if (this.dndConfig.enabled) {
                layout([this.dndConfig]);
            }

            return this;
        },

        /**
         * Check columnsHeaderAfterRender property,
         * and set listener on elems if needed
         *
         * @returns {Object} Chainable.
         */
        setColumnsHeaderListener: function () {
            if (this.columnsHeaderAfterRender) {
                this.on('recordData', this.renderColumnsHeader.bind(this));
            }

            return this;
        },

        /**
         * Render column header
         */
        renderColumnsHeader: function () {
            this.recordData().length ? this.columnsHeader(true) : this.columnsHeader(false);
        },

        /**
         * Init default record
         *
         * @returns Chainable.
         */
        initDefaultRecord: function () {
            if (this.defaultRecord && !this.recordData().length) {
                this.addChild();
            }

            return this;
        },

        /**
         * Create header template
         *
         * @param {Object} prop - instance obj
         *
         * @returns {Object} Chainable.
         */
        createHeaderTemplate: function (prop) {
            var visible = prop.visible !== false,
                disabled = _.isUndefined(prop.disabled) ? this.disabled() : prop.disabled;

            return {
                visible: ko.observable(visible),
                disabled: ko.observable(disabled)
            };
        },

        /**
         * Init header elements
         */
        initHeader: function () {
            var data;

            if (!this.labels().length) {
                _.each(this.childTemplate.children, function (cell) {
                    data = this.createHeaderTemplate(cell.config);

                    cell.config.labelVisible = false;
                    _.extend(data, {
                        label: cell.config.label,
                        name: cell.name,
                        columnsHeaderClasses: cell.config.columnsHeaderClasses
                    });

                    this.labels.push(data);
                }, this);
            }
        },

        /**
         * Set max element position
         *
         * @param {Number} position - element position
         * @param {Object} elem - instance
         */
        setMaxPosition: function (position, elem) {
            if (position) {
                this.checkMaxPosition(position);
                this.sort(position, elem);
            } else {
                this.maxPosition += 1;
            }
        },

        /**
         * Sort element by position
         *
         * @param {Number} position - element position
         * @param {Object} elem - instance
         */
        sort: function (position, elem) {
            var that = this,
                sorted,
                updatedCollection;

            if (this.elems().filter(function (el) {
                    return el.position;
                }).length !== this.getChildItems().length) {

                return false;
            }

            if (!elem.containers.length) {
                registry.get(elem.name, function () {
                    that.sort(position, elem);
                });

                return false;
            }

            sorted = this.elems().sort(function (propOne, propTwo) {
                return ~~propOne.position - ~~propTwo.position;
            });

            updatedCollection = this.updatePosition(sorted, position, elem.name);
            this.elems(updatedCollection);
        },

        /**
         * Checking loader visibility
         *
         * @param {Array} elems
         */
        checkSpinner: function (elems) {
            this.showSpinner(!(!this.recordData().length || elems && elems.length === this.getChildItems().length));
        },

        /**
         * Filtering data and calculates the quantity of pages
         *
         * @param {Array} data
         */
        parsePagesData: function (data) {
            var pages;

            this.relatedData = this.deleteProperty ?
                _.filter(data, function (elem) {
                    return elem[this.deleteProperty] !== this.deleteValue;
                }, this) : data;

            pages = Math.ceil(this.relatedData.length / this.pageSize) || 1;
            this.pages(pages);
        },

        /**
         * Get items to rendering on current page
         *
         * @returns {Array} data
         */
        getChildItems: function () {
            this.startIndex = (~~this.currentPage() - 1) * this.pageSize;

            return this.relatedData.slice(this.startIndex, this.startIndex + this.pageSize);
        },

        /**
         * Get number of columns
         *
         * @returns {Number} columns
         */
        getColumnsCount: function () {
            return this.labels().length + (this.dndConfig.enabled ? 1 : 0);
        },

        /**
         * Processing pages before addChild
         *
         * @param {Object} ctx - element context
         * @param {Number|String} index - element index
         * @param {Number|String} prop - additional property to element
         */
        processingAddChild: function (ctx, index, prop) {
            if (this.relatedData.length && this.relatedData.length % this.pageSize === 0) {
                this.clear();
                this.pages(this.pages() + 1);
                this.currentPage(this.pages());
            } else if (~~this.currentPage() !== this.pages()) {
                this.currentPage(this.pages());
            }

            this.addChild(ctx, index, prop);
        },

        /**
         * Processing pages before deleteRecord
         *
         * @param {Number|String} index - element index
         * @param {Number|String} recordId
         */
        processingDeleteRecord: function (index, recordId) {
            this.deleteRecord(index, recordId);

            if (this.getChildItems().length <= 0 && this.pages() !== 1) {
                this.pages(this.pages() - 1);
                this.currentPage(this.pages());
            }
        },

        /**
         * Change page
         *
         * @param {Number} page - current page
         */
        changePage: function (page) {
            if (page === 1 && !this.recordData().length) {
                return false;
            }

            if (~~page > this.pages()) {
                this.currentPage(this.pages());

                return false;
            } else if (~~page < 1) {
                this.currentPage(1);

                return false;
            }

            this.clear();
            this.initChildren();
        },

        /**
         * Check page
         *
         * @returns {Boolean} is page first or not
         */
        isFirst: function () {
            return this.currentPage() === 1;
        },

        /**
         * Check page
         *
         * @returns {Boolean} is page last or not
         */
        isLast: function () {
            return this.currentPage() === this.pages();
        },

        /**
         * Change page to next
         */
        nextPage: function () {
            this.currentPage(this.currentPage() + 1);
        },

        /**
         * Change page to previos
         */
        previousPage: function () {
            this.currentPage(this.currentPage() - 1);
        },

        /**
         * Check dependency and set position to elements
         *
         * @param {Array} collection - elems
         * @param {Number} position - current position
         * @param {String} elemName - element name
         *
         * @returns {Array} collection
         */
        updatePosition: function (collection, position, elemName) {
            var curPos,
                parsePosition = ~~position,
                result = _.filter(collection, function (record) {
                    return ~~record.position === parsePosition;
                });

            if (result[1]) {
                curPos = parsePosition + 1;
                result[0].name === elemName ? result[1].position = curPos : result[0].position = curPos;
                this.updatePosition(collection, curPos);
            }

            return collection;
        },

        /**
         * Check max elements position and set if max
         *
         * @param {Number} position - current position
         */
        checkMaxPosition: function (position) {
            var max = 0,
                pos;

            this.elems.each(function (record) {
                pos = ~~record.position;
                pos > max ? max = pos : false;
            });

            max < position ? max = position : false;
            this.maxPosition = max;
        },

        /**
         * Remove and set new max position
         */
        removeMaxPosition: function () {
            this.maxPosition = 0;
            this.elems.each(function (record) {
                this.maxPosition < record.position ? this.maxPosition = ~~record.position : false;
            }, this);
        },

        /**
         * Update record template and rerender elems
         *
         * @param {String} recordName - record name
         */
        onUpdateRecordTemplate: function (recordName) {
            if (recordName) {
                this.recordTemplate = recordName;
                this.reload();
            }
        },

        /**
         * Delete record
         *
         * @param {Number} index - row index
         *
         */
        deleteRecord: function (index, recordId) {
            var recordInstance,
                lastRecord,
                recordsData,
                childs;

            if (this.deleteProperty) {
                recordInstance = _.find(this.elems(), function (elem) {
                    return elem.index === index;
                });
                recordInstance.destroy();
                this.elems([]);
                this._updateCollection();
                this.removeMaxPosition();
                this.recordData()[recordInstance.index][this.deleteProperty] = this.deleteValue;
                this.recordData.valueHasMutated();
                childs = this.getChildItems();

                if (childs.length > this.elems().length) {
                    this.addChild(false, childs[childs.length - 1][this.identificationProperty], false);
                }
            } else {
                this.update = true;

                if (~~this.currentPage() === this.pages()) {
                    lastRecord =
                        _.findWhere(this.elems(), {
                            index: this.startIndex + this.getChildItems().length - 1
                        }) ||
                        _.findWhere(this.elems(), {
                            index: (this.startIndex + this.getChildItems().length - 1).toString()
                        });

                    lastRecord.destroy();
                }

                this.removeMaxPosition();
                recordsData = this._getDataByProp(recordId);
                this._updateData(recordsData);
                this.update = false;
            }

            if (this.pages() < ~~this.currentPage()) {
                this.currentPage(this.pages());
            }

            this._sort();
        },

        /**
         * Get data object by some property
         *
         * @param {Number} id - element id
         * @param {String} prop - property
         */
        _getDataByProp: function (id, prop) {
            prop = prop || this.identificationProperty;

            return _.reject(this.getChildItems(), function (recordData) {
                return ~~recordData[prop] === ~~id;
            }, this);
        },

        /**
         * Sort elems by position property
         */
        _sort: function () {
            this.elems(this.elems().sort(function (propOne, propTwo) {
                return ~~propOne.position - ~~propTwo.position;
            }));
        },

        /**
         * Set new data to dataSource,
         * delete element
         *
         * @param {Array} data - record data
         */
        _updateData: function (data) {
            var elems = _.clone(this.elems()),
                path,
                dataArr;

            dataArr = this.recordData.splice(this.startIndex, this.recordData().length - this.startIndex);
            dataArr.splice(0, this.pageSize);
            elems = _.sortBy(this.elems(), function (elem) {
                return ~~elem.index;
            });

            data.concat(dataArr).forEach(function (rec, idx) {
                if (elems[idx]) {
                    elems[idx].recordId = rec[this.identificationProperty];
                }

                if (!rec.position) {
                    rec.position = this.maxPosition;
                    this.setMaxPosition();
                }

                path = this.dataScope + '.' + this.index + '.' + (this.startIndex + idx);
                this.source.set(path, rec);
            }, this);

            this.elems(elems);
        },

        /**
         * Rerender dynamic-rows elems
         */
        reload: function () {
            this.clear();
            this.initChildren(false, true);
        },

        /**
         * Destroy all dynamic-rows elems
         *
         * @returns {Object} Chainable.
         */
        clear: function () {
            this.destroyChildren();

            return this;
        },

        /**
         * Reset data to initial value.
         * Call method reset on child elements.
         */
        reset: function () {
            var elems = this.elems();

            _.each(elems, function (elem) {
                if (_.isFunction(elem.reset)) {
                    elem.reset();
                }
            });
        },

        /**
         * Set classes
         *
         * @param {Object} data
         *
         * @returns {Object} Classes
         */
        setClasses: function (data) {
            var additional;

            if (_.isString(data.additionalClasses)) {
                additional = data.additionalClasses.split(' ');
                data.additionalClasses = {};

                additional.forEach(function (name) {
                    data.additionalClasses[name] = true;
                });
            }

            if (!data.additionalClasses) {
                data.additionalClasses = {};
            }

            _.extend(data.additionalClasses, {
                '_fit': data.fit,
                '_required': data.required,
                '_error': data.error,
                '_empty': !this.elems().length,
                '_no-header': this.columnsHeaderAfterRender || this.collapsibleHeader
            });

            return data.additionalClasses;
        },

        /**
         * Initialize children
         *
         * @returns {Object} Chainable.
         */
        initChildren: function () {
            this.showSpinner(true);
            this.getChildItems().forEach(function (data, index) {
                this.addChild(data, this.startIndex + index);
            }, this);

            return this;
        },

        /**
         * Set visibility to dynamic-rows child
         *
         * @param {Boolean} state
         */
        setVisible: function (state) {
            this.elems.each(function (record) {
                record.setVisible(state);
            }, this);
        },

        /**
         * Set disabled property to dynamic-rows child
         *
         * @param {Boolean} state
         */
        setDisabled: function (state) {
            this.elems.each(function (record) {
                record.setDisabled(state);
            }, this);
        },

        /**
         * Set visibility to column
         *
         * @param {Number} index - column index
         * @param {Boolean} state
         */
        setVisibilityColumn: function (index, state) {
            this.elems.each(function (record) {
                record.setVisibilityColumn(index, state);
            }, this);
        },

        /**
         * Set disabled property to column
         *
         * @param {Number} index - column index
         * @param {Boolean} state
         */
        setDisabledColumn: function (index, state) {
            this.elems.each(function (record) {
                record.setDisabledColumn(index, state);
            }, this);
        },

        /**
         * Add child components
         *
         * @param {Object} data - component data
         * @param {Number} index - record(row) index
         * @param {Number|String} prop - custom identify property
         *
         * @returns {Object} Chainable.
         */
        addChild: function (data, index, prop) {
            var template = this.templates.record,
                child;

            index = index || _.isNumber(index) ? index : this.recordData().length;
            prop = prop || _.isNumber(prop) ? prop : index;

            _.extend(this.templates.record, {
                recordId: prop
            });

            child = utils.template(template, {
                collection: this,
                index: index
            });

            layout([child]);

            return this;
        },

        /**
         * Restore value to default
         */
        restoreToDefault: function () {
            this.recordData(utils.copy(this.default));
            this.reload();
        },

        /**
         * Update whether value differs from default value
         */
        setDifferedFromDefault: function () {
            var recordData = utils.copy(this.recordData());

            Array.isArray(recordData) && recordData.forEach(function (item) {
                delete item['record_id'];
            });

            this.isDifferedFromDefault(!_.isEqual(recordData, this.default));
        }
    });
});