text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Threading;
using Nova.Controls;
using Nova.Library;
using Nova.Shell.Domain;
using Nova.Shell.Library;
using Nova.Shell.Views;
using Nova.Threading.Metadata;

namespace Nova.Shell.Actions.Session
{
    /// <summary>
    /// Navigational action
    /// </summary>
    [Blocking]
    public class NavigationAction : Actionflow<SessionView, SessionViewModel>
    {
        private IView _nextView;
        private IView _current;

        private Type _viewType;
        private Type _viewModelType;

        private bool _navigatingInsideMultiStep;

        public override bool CanExecute()
        {
            var sessionViewModel = ViewModel;
            var currentView = sessionViewModel.CurrentView;

            return !sessionViewModel.IsStacked && (currentView == null || !currentView.IsLoading);
        }

        public override void OnBefore()
        {
            _current = ActionContext.GetValue<IView>(ActionContextConstants.CurrentViewConstant);
        }

        public override bool Execute()
        {
            var actionContextEntries = ActionContext.GetEntries().ToList();

            _viewType = ActionContext.GetValue<Type>(ActionContextConstants.ViewTypeConstant);
            _viewModelType = ActionContext.GetValue<Type>(ActionContextConstants.ViewModelTypeConstant);

            var currentlyInsideMultistep = typeof(IMultistepContentViewModel).IsAssignableFrom(_viewModelType);
            var triggerValidation = !currentlyInsideMultistep;

            NovaTreeNodeStep novaTreeNodeStep = null;
            var hasStep = false;
            if (currentlyInsideMultistep)
            {
                Guid key;

                if (!ActionContext.TryGetValue(ActionContextConstants.NodeId, out key))
                    throw new NotSupportedException("Navigating to a multistep view without providing a step key is not supported.");

                novaTreeNodeStep = View._NovaTree.FindStep(key);

                if (novaTreeNodeStep == null)
                    throw new NotSupportedException("Navigating to an unknown step.");

                var multistep = _current as MultiStepView;

                if (multistep != null)
                {
                    hasStep = multistep.HasStep(novaTreeNodeStep);
                    triggerValidation = !hasStep;
                }
            }

            var triggerEntry = ActionContextEntry.Create(ActionContextConstants.TriggerValidation, triggerValidation, false);
            actionContextEntries.Add(triggerEntry);

            var entries = actionContextEntries.ToArray();

            return LeavePreviousView(entries) && CreateNextView(currentlyInsideMultistep, novaTreeNodeStep, hasStep, entries);
        }

        public override void ExecuteCompleted()
        {
            if (_navigatingInsideMultiStep)
            {
                ((MultiStepView)ViewModel.CurrentView).DoStep(_nextView);
            }
            else
            {
                ViewModel.CurrentView = _nextView;
            }

            Guid key;
            ActionContext.TryGetValue(ActionContextConstants.NodeId, out key);
            View._NovaTree.ReevaluateState(key, _viewType, _viewModelType);
        }

        protected override void DisposeManagedResources()
        {
            _current = null;
            _nextView = null;
        }

        private bool LeavePreviousView(ActionContextEntry[] entries)
        {
            return _current == null || _current.ViewModel.Leave(entries).Result;
        }

        private bool CreateNextView(bool currentlyInsideMultistep, NovaTreeNodeStep novaTreeNodeStep, bool hasStep,
            ActionContextEntry[] entries)
        {
            if (currentlyInsideMultistep)
                CreateMultistep(novaTreeNodeStep, hasStep);
            else
                CreateNormalView();

            var result = _nextView != null && _nextView.ViewModel.Enter(entries).Result;

            if (result) return true;

            CreateNotAvailableView();

            return true;
        }

        private void CreateMultistep(NovaTreeNodeStep novaTreeNodeStep, bool hasChild)
        {
            var multistep = _current as MultiStepView;
            _navigatingInsideMultiStep = hasChild && multistep != null && Dispatch(() => multistep.GetOrCreateStep(novaTreeNodeStep, out _nextView));

            if (_navigatingInsideMultiStep) return;
            //Create new one.
            var steps = novaTreeNodeStep.Parent.Steps.Select(x => x.ConvertToNovaStep());

            var list = new LinkedList<NovaStep>(steps);
            var initialView = GetInitialView(novaTreeNodeStep, list);

            var groupId = novaTreeNodeStep.GroupId;
            _nextView = Dispatch(() => new MultiStepView(View, ViewModel, groupId, initialView));
        }

        private void CreateNormalView()
        {
            var createNextView = ActionContext.GetValue<Func<IView>>(ActionContextConstants.CreateNextViewConstant);
            if (createNextView != null)
            {
                _nextView = Dispatch(createNextView);
            }
        }

        private static LinkedListNode<NovaStep> GetInitialView(NovaTreeNode treeNode, LinkedList<NovaStep> list)
        {
            var node = list.First;

            while (node != null)
            {
                if (node.Value.NodeId == treeNode.Id)
                    return node;

                node = node.Next;
            }

            return list.First;
        }

        private void CreateNotAvailableView()
        {
            StepNotAvailableView notAvailableView = null;

            Dispatch(() =>
            {
                notAvailableView = ViewModel.CreateControl<StepNotAvailableView, StepNotAvailableViewModel>();
                notAvailableView.ViewModel.StepName = /* TODO View._NovaTree.FindTitle(_viewType, _viewModelType) ?? */_viewType.Name;
            });

            _nextView = notAvailableView;
        }

        /// <summary>
        /// Dispatches the specified action.
        /// </summary>
        /// <param name="action">The action.</param>
        private void Dispatch(Action action)
        {
            View.Dispatcher.Invoke(action, DispatcherPriority.Send);
        }

        /// <summary>
        /// Dispatches the specified function.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="function">The function.</param>
        /// <returns></returns>
        private T Dispatch<T>(Func<T> function)
        {
            return View.Dispatcher.Invoke(function, DispatcherPriority.Send);
        }
    }
}


text:
package org.jcows.model.vc;
/**
 * Class that parses a {@link java.lang.String} to a double value.
 *
 * @author Marco Schmid (marco.schmid@jcows.org)
 * @version $LastChangedRevision: 222 $, $LastChangedDate: 2006-11-07 07:35:44 +0000 (Tue, 07 Nov 2006) $
 */
public class DoubleValidator implements IValidator {

  public boolean validate(String value) {
    if(value==null)
      return false;
    try {
      Double.parseDouble(value);
    }
    catch(NumberFormatException e) {
      /*
       * Ignore NumberFormatException. Validation failed.
       */
      return false;
    }
    return true;
  }

}

redpajama_set_name: RedPajamaGithub


text:
this plugin form change monitoring.
form childs element change or keydown callback function.

```
(function(){
    $('form#form').formMonitoring({
        ajax: true,     // boolean or $.ajax() option paramater
        ajaxLoading: function(elm){
            // if ajax option then call ajax before call
        },
        callback : function(elm){
            // callback change...
        }
    });

    // input change
    $('#input').formMonitoring(function(){
        //callback here
    });
($));
```

```
<form action="" id="form">
    <input type="text" name="name" value="">
    <select name="type">
        <option value="1">apple</option>
        <option value="2">orange</option>
    </select>
</form>
<input id="input" value="">
```


text:
import { IReadonlyTheme } from '@microsoft/sp-component-base';
import { css } from '@uifabric/utilities/lib/css';
import { IconButton } from 'office-ui-fabric-react/lib/Button';
import * as React from 'react';
import Slider from 'react-slick';
import { SPComponentLoader } from '@microsoft/sp-loader';
import styles from "./FilmstripLayout.module.scss";
import { useRef } from 'react';
import useComponentSize, { ComponentSize } from '@rehooks/component-size';

function useBreakpoints(currentWidth: number, breakpoints: number[]) {
  return breakpoints.map(breakpoint => currentWidth < breakpoint);
}

/**
 * Filmstrip layout
 * Presents the child compoments as a slick slide
 */
export const FilmstripLayout = (props: { children?: any; clientWidth?: number; themeVariant?: IReadonlyTheme, ariaLabel?: string; }) => {
  let ref: React.MutableRefObject<HTMLDivElement> = useRef<HTMLDivElement>(null);
  let size: ComponentSize = useComponentSize(ref);
  let { width } = size;

  // // the slick slider used in normal views
  let _slider: React.MutableRefObject<Slider> = useRef<Slider>(null);

  SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick.min.css');
  SPComponentLoader.loadCss('https://cdnjs.cloudflare.com/ajax/libs/slick-carousel/1.8.1/slick-theme.min.css');

  const [isSmall, isMedium] = useBreakpoints(props.clientWidth, [696, 928]);

  // slick seems to have an issue with having "infinite" mode set to true and having less items than the number of slides per page
  // set infinite to true only if there are more than 3 children
  let numSlides: number = 3;
  if (width) {
    if (width > 927) {
      numSlides = 4;
    } else if (width <= 695) {
      numSlides = 2;
    }
  }

  var isInfinite: boolean = React.Children.count(props.children) > numSlides;
  var settings: any = {
    accessibility: true,
    arrows: false,
    autoplaySpeed: 5000,
    dots: true,
    customPaging: (i: number) => {
      return (

          <div role="button" className={styles.carouselDotsContainer} aria-label={`Carousel Dot ${i}`} data-is-focusable={true} tabIndex={0}>

      );
    },
    infinite: isInfinite,
    slidesToShow: numSlides,
    slidesToScroll: numSlides,
    speed: 500,
    centerPadding: styles.centerPadding,
    pauseOnHover: true,
    variableWidth: false,
    useCSS: true,
    rows: 1,
    respondTo: "slider",
  };

  return (

      {props.themeVariant &&
      }

        <Slider ref={_slider} {...settings}>
          {props.children}
        </Slider>

 _slider.current.slickPrev()}
        >
          <IconButton
            className={css(styles.indexButton, styles.leftPositioned)}
            iconProps={{ iconName: "ChevronLeft", styles: { root: { fontSize: '28px', fontWeight: '400' } } }}
          />

 _slider.current.slickNext()}
        >
          <IconButton
            className={css(styles.indexButton, styles.rightPositioned)}
            iconProps={{ iconName: "ChevronRight", styles: { root: { fontSize: '28px', fontWeight: '400' } } }}
          />

  );
};


text:
package com.amazonaws.services.codedeploy.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum ComputePlatform {

    Server("Server"),
    Lambda("Lambda"),
    ECS("ECS");

    private String value;

    private ComputePlatform(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return ComputePlatform corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static ComputePlatform fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (ComputePlatform enumEntry : ComputePlatform.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
/**
 * Field and method binding for Android views which uses annotation processing to generate
 * boilerplate code for you.
 *

 *

 *
Eliminate {@link android.view.View#findViewById findViewById} calls by using
 * {@link butterknife.Bind @Bind} on fields.

 *
Group multiple views in a {@linkplain java.util.List list} or array.
 * Operate on all of them at once with
 * {@linkplain butterknife.ButterKnife#apply(java.util.List, butterknife.ButterKnife.Action)
 * actions}, {@linkplain butterknife.ButterKnife#apply(java.util.List,
 * butterknife.ButterKnife.Setter, Object) setters}, or
 * {@linkplain butterknife.ButterKnife#apply(java.util.List, android.util.Property, Object)
 * properties}.

 *
Eliminate anonymous inner-classes for listeners by annotating methods with
 * {@link butterknife.OnClick @OnClick} and others.

 *
Eliminate resource lookups by using resource annotations on fields.

 *

 */
package butterknife;


text:
package net.mayee.alice.entity.menu.nanbar;

import java.io.Serializable;

/**
 * Created by mayee on 15/9/16.
 */
public class NavbarMenu implements Serializable {

    private String id;
    private String name;
    private String messageKey;
    private String href;
    private String icon;
    private Boolean hadBottomLine = false;

    public NavbarMenu(String id, String name,String messageKey, String href, String icon) {
        this.id = id;
        this.name = name;
        this.messageKey = messageKey;
        this.href = href;
        this.icon = icon;
    }

    public String getId() {
        return id;
    }

    public String getMessageKey() {
        return messageKey;
    }

    public void setMessageKey(String messageKey) {
        this.messageKey = messageKey;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public String getIcon() {
        return icon;
    }

    public void setIcon(String icon) {
        this.icon = icon;
    }

    public Boolean getHadBottomLine() {
        return hadBottomLine;
    }

    public void setHadBottomLine(Boolean hadBottomLine) {
        this.hadBottomLine = hadBottomLine;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        NavbarMenu that = (NavbarMenu) o;

        return id.equals(that.id);

    }

    @Override
    public int hashCode() {
        return id.hashCode();
    }
}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: android/libcore/luni/src/main/java/java/lang/NoSuchFieldError.java
//

#include "../../J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_JavaLangNoSuchFieldError")
#ifdef RESTRICT_JavaLangNoSuchFieldError
#define INCLUDE_ALL_JavaLangNoSuchFieldError 0
#else
#define INCLUDE_ALL_JavaLangNoSuchFieldError 1
#endif
#undef RESTRICT_JavaLangNoSuchFieldError

#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"

#if !defined (JavaLangNoSuchFieldError_) && (INCLUDE_ALL_JavaLangNoSuchFieldError || defined(INCLUDE_JavaLangNoSuchFieldError))
#define JavaLangNoSuchFieldError_

#define RESTRICT_JavaLangIncompatibleClassChangeError 1
#define INCLUDE_JavaLangIncompatibleClassChangeError 1
#include "../../java/lang/IncompatibleClassChangeError.h"

/*!
 @brief Thrown when the VM notices that a program tries to reference,
 on a class or object, a field that does not exist.

 Note that this can only occur when inconsistent class files are being loaded.
 */
@interface JavaLangNoSuchFieldError : JavaLangIncompatibleClassChangeError

#pragma mark Public

/*!
 @brief Constructs a new NoSuchFieldError that includes the current stack
 trace.
 */
- (instancetype)init;

/*!
 @brief Constructs a new NoSuchFieldError with the current stack trace
 and the specified detail message.
 @param detailMessage
 the detail message for this error.
 */
- (instancetype)initWithNSString:(NSString *)detailMessage;

@end

J2OBJC_EMPTY_STATIC_INIT(JavaLangNoSuchFieldError)

FOUNDATION_EXPORT void JavaLangNoSuchFieldError_init(JavaLangNoSuchFieldError *self);

FOUNDATION_EXPORT JavaLangNoSuchFieldError *new_JavaLangNoSuchFieldError_init() NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaLangNoSuchFieldError *create_JavaLangNoSuchFieldError_init();

FOUNDATION_EXPORT void JavaLangNoSuchFieldError_initWithNSString_(JavaLangNoSuchFieldError *self, NSString *detailMessage);

FOUNDATION_EXPORT JavaLangNoSuchFieldError *new_JavaLangNoSuchFieldError_initWithNSString_(NSString *detailMessage) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT JavaLangNoSuchFieldError *create_JavaLangNoSuchFieldError_initWithNSString_(NSString *detailMessage);

J2OBJC_TYPE_LITERAL_HEADER(JavaLangNoSuchFieldError)

#endif

#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_JavaLangNoSuchFieldError")


text:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
	name:String,
	email:String
});

mongoose.model('user',UserSchema);


text:
class Category < ActiveRecord::Base
  validates :name, presence: true

  has_and_belongs_to_many :resources

  acts_as_taggable_on :tags

  default_scope { order('name ASC') } # Returns resources in Alphabetaical order via names
    searchkick

    def self.get_categories
        Category.all
    end

    def self.get_category_names
        Category.pluck("category_name")
    end
end


text:
/**
 * Creates an empty multi dictionary.
 * @class
A multi dictionary is a special kind of dictionary that holds
 * multiple values against each key. Setting a value into the dictionary will
 * add the value to a list at that key. Getting a key will return a list
 * holding all the values associated with that key.
 * This implementation accepts any kind of objects as keys.

 *
 *
If the keys are custom objects, a function that converts keys to unique strings must be
 * provided at construction time.

 *
Example:

 *

 * function petToString(pet) {
 *  return pet.type + ' ' + pet.name;
 * }
 *

 *
If the values are custom objects, a function to check equality between values
 * must be provided.

 *
Example:

 *

 * function petsAreEqualByAge(pet1,pet2) {
 *  return pet1.age===pet2.age;
 * }
 *

 * @constructor
 * @param {function(Object):string=} toStrFunction optional function
 * to convert keys to strings. If the keys aren't strings or if toString()
 * is not appropriate, a custom function which receives a key and returns a
 * unique string must be provided.
 * @param {function(Object,Object):boolean=} valuesEqualsFunction optional
 * function to check if two values are equal.
 *
 */
buckets.MultiDictionary = function (toStrFunction, valuesEqualsFunction) {

    /**
     * @exports multiDict as buckets.MultiDictionary
     * @private
     */
    var multiDict = {},
        // Call the parent constructor
        parent = new buckets.Dictionary(toStrFunction),
        equalsF = valuesEqualsFunction || buckets.defaultEquals;

    /**
     * Returns an array holding the values associated with
     * the specified key.
     * @param {Object} key The key.
     * @return {Array} An array holding the values or an
     * empty array if the dictionary contains no
     * mappings for the provided key.
     */
    multiDict.get = function (key) {
        var values = parent.get(key);
        if (buckets.isUndefined(values)) {
            return [];
        }
        return buckets.arrays.copy(values);
    };

    /**
     * Associates the specified value with the specified key if
     * it's not already present.
     * @param {Object} key The Key.
     * @param {Object} value The value to associate.
     * @return {boolean} True if the value was not already associated with that key.
     */
    multiDict.set = function (key, value) {
        var array;
        if (buckets.isUndefined(key) || buckets.isUndefined(value)) {
            return false;
        }
        if (!multiDict.containsKey(key)) {
            parent.set(key, [value]);
            return true;
        }
        array = parent.get(key);
        if (buckets.arrays.contains(array, value, equalsF)) {
            return false;
        }
        array.push(value);
        return true;
    };

    /**
     * Removes the specified value from the list of values associated with the
     * provided key. If a value isn't given, all values associated with the specified
     * key are removed.
     * @param {Object} key The key.
     * @param {Object=} value Optional argument to specify the element to remove
     * from the list of values associated with the given key.
     * @return {*} True if the dictionary changed, false if the key doesn't exist or
     * if the specified value isn't associated with the given key.
     */
    multiDict.remove = function (key, value) {
        var v, array;
        if (buckets.isUndefined(value)) {
            v = parent.remove(key);
            if (buckets.isUndefined(v)) {
                return false;
            }
            return true;
        }
        array = parent.get(key);
        if (buckets.isUndefined(array)) {
            return false;
        }
        if (buckets.arrays.remove(array, value, equalsF)) {
            if (array.length === 0) {
                parent.remove(key);
            }
            return true;
        }
        return false;
    };

    /**
     * Returns an array containing all the keys in the dictionary.
     * @return {Array} An array containing all the keys in the dictionary.
     */
    multiDict.keys = function () {
        return parent.keys();
    };

    /**
     * Returns an array containing all the values in the dictionary.
     * @return {Array} An array containing all the values in the dictionary.
     */
    multiDict.values = function () {
        var values = parent.values(),
            array = [],
            i,
            j,
            v;
        for (i = 0; i < values.length; i += 1) {
            v = values[i];
            for (j = 0; j < v.length; j += 1) {
                array.push(v[j]);
            }
        }
        return array;
    };

    /**
     * Returns true if the dictionary has at least one value associatted with the specified key.
     * @param {Object} key The key.
     * @return {boolean} True if the dictionary has at least one value associatted
     * the specified key.
     */
    multiDict.containsKey = function (key) {
        return parent.containsKey(key);
    };

    /**
     * Removes all keys and values from the dictionary.
     */
    multiDict.clear = function () {
        return parent.clear();
    };

    /**
     * Returns the number of keys in the dictionary.
     * @return {number} The number of keys in the dictionary.
     */
    multiDict.size = function () {
        return parent.size();
    };

    /**
     * Returns true if the dictionary contains no mappings.
     * @return {boolean} True if the dictionary contains no mappings.
     */
    multiDict.isEmpty = function () {
        return parent.isEmpty();
    };

    /**
     * Executes the provided function once per key
     * present in the multi dictionary.
     * @param {function(Object, Array):*} callback Function to execute. Receives
     * 2 arguments: key and an array of values. To break the iteration you can
     * optionally return false inside the callback.
     */
    multiDict.forEach = function (callback) {
        return parent.forEach(callback);
    };

    /**
     * Returns true if the multi dictionary is equal to another multi dictionary.
     * Two dictionaries are equal if they have the same keys and the same values per key.
     * @param {buckets.MultiDictionary} other The other dictionary.
     * @return {boolean} True if the dictionary is equal to the given dictionary.
     */
    multiDict.equals = function (other) {
        var isEqual = true,
            thisValues;

        if (buckets.isUndefined(other) || typeof other.values !== 'function') {
            return false;
        }
        if (multiDict.size() !== other.size()) {
            return false;
        }

        other.forEach(function (key, otherValues) {
            thisValues = multiDict.get(key) || [];
            if (thisValues.length !== otherValues.length) {
                isEqual = false;
            } else {
                buckets.arrays.forEach(thisValues, function (value) {
                    isEqual = buckets.arrays.contains(otherValues, value, equalsF);
                    return isEqual;
                });
            }
            return isEqual;
        });
        return isEqual;
    };

    return multiDict;
};


text:
{{ partial "head" . }}

{{ partial "nav-home" . }}

# Users

Release strategies

Advanced canary release

Feature toggling

A/B testing

Continuous validation

Vamp observability

IT monitoring integrations

Business monitoring integrations

Support

Online documentation

Onboarding support one-off fee

Service window for incidents

Weekends

Support through Slack

Email

SLA

Managed service

Easy

€1,500 p/m

# Users

3

Advanced canary release

Feature toggling

A/B testing

Vamp observability

IT monitoring integrations

Standard

Business monitoring integrations

Standard

A/B testing

Onboarding support one-off fee

€1,500

Service window for incidents

-

Weekends

-

Support through Slack

-

Email

Yes

SLA

Best effort

Managed service

-

                Get a guided tour

Professional

€4,500 p/m

# Users

4-25

Advanced canary release

Feature toggling

A/B testing

Vamp observability

IT monitoring integrations

2 custom integrations

Business monitoring integrations

1 custom integration

A/B testing

Onboarding support one-off fee

€4,500

Service window for incidents

09:00 - 17:00

Weekends

-

Support through Slack

Yes

Email

Yes

SLA

4 hours

Managed service

-

                Get a guided tour

Enterprise

Custom quote

# Users

Unlimited

Advanced canary release

Feature toggling

A/B testing

Vamp observability

IT monitoring integrations

Custom

Business monitoring integrations

Custom

A/B testing

Onboarding support one-off fee

€8,000

Service window for incidents

24x7

Weekends

Yes

Support through Slack

Yes

Email

Yes

SLA

2 hours

Managed service

Available

                Get a guided tour

{{ partial "footer" .}}


text:
/**
 * Created by dllo on 17/8/29.
 */
import React, {Component} from 'react'
import userImg from '../../assets/images/user-default-img.png'
const md5 = require('md5')
const dateformat = require('dateformat')
const base64 = require('Base64')

class Stars extends Component {
  constructor (props) {
    super(props)
    this.state = {
      data: [],
      minIndex: 0
    }
  }
  ajaxData = (interFace) => {
    const time = new Date()
    // 2.根据当前时间, 进行格式化 yyyymmddHHMMss
    const timestamp = dateformat(time.getTime(), 'yyyymmddHHMMss')
    // 3.将字符串 0+''+timestamp 转成MD5, 并变为全大写
    const sig = md5('0' + '' + timestamp).toUpperCase()
    const Authorization = base64.btoa('' + ':' + timestamp)
    const url = '/api' + interFace + '&sig=' + sig
    fetch(url, {
      method: 'GET',
      headers: {
        Authorization: Authorization
      }
    })
      .then(response => {
        return response.json()
      })
      .then(response => {
        // console.log(response.data)
        this.setState({
          data: this.state.data.concat(response.data)
        })
      })
  }
  // 滚轮事件
  scroll = () => {
    // console.log(document.body.scrollTop)
    // console.log(document.body.scrollHeight - document.documentElement.clientHeight)
    // 判断条件为 滚动到底部
    if (document.body.scrollTop >= document.body.scrollHeight - document.documentElement.clientHeight) {
      this.setState({
        minIndex: this.state.data.length - 1
      }, () => {
        let interFace = '/attention/stars.php' + location.search + '&minId=' + this.state.data[this.state.minIndex].id
        this.ajaxData(interFace)
      })
    }
  }
  componentDidMount() {
    this.ajaxData('/attention/stars.php' + location.search + '&minId=')
    document.body.onscroll = this.scroll
  }
  render () {
    return (

        {
          this.state.data.map((item, index) => {
            const desc = item.desc === '' ? '这是一个还没有简介的Pianker~' : item.desc
            const imgUrl = item.icon === '' ? userImg : item.icon
            return (

{item.uname}

{desc}

关注

            )
          })
        }

    )
  }
}

export default Stars


text:
using System.Collections.Generic;
using Loki.Collections;
using Loki.Maple.Life;
using Loki.Net;

namespace Loki.Maple.Characters
{
    // NOTE: I removed interface inheritance because interfaces are a mess: We need multiple inheritance, but we don't have it.

    public class ControlledMobs : NumericalKeyedCollection<Mob>
    {
        public Character Parent { get; private set; }

        public ControlledMobs(Character parent)
        {
            this.Parent = parent;
        }

        protected override int GetKeyForItem(Mob item)
        {
            return item.ObjectID;
        }

        protected override void InsertItem(int index, Mob item)
        {
            lock (this)
            {
                if (this.Parent.Client.IsAlive)
                {
                    item.Controller = this.Parent;
                    base.InsertItem(index, item);

                    using (Packet requestControl = item.GetControlRequestPacket())
                    {
                        item.Controller.Client.Send(requestControl);
                    }
                }
                else
                {
                    item.AssignController();
                }
            }
        }

        protected override void RemoveItem(int index)
        {
            lock (this)
            {
                Mob item = this.GetAtIndex(index);

                if (item.Controller.Client.IsAlive)
                {
                    using (Packet cancelControl = item.GetControlCancelPacket())
                    {
                        item.Controller.Client.Send(cancelControl);
                    }
                }

                item.Controller = null;
                base.RemoveItem(index);
            }
        }

        protected override void ClearItems()
        {
            lock (this)
            {
                List<Mob> toRemove = new List<Mob>();

                foreach (Mob loopController in this)
                {
                    toRemove.Add(loopController);
                }

                foreach (Mob loopController in toRemove)
                {
                    this.Remove(loopController);
                }
            }
        }

        public void Move(Packet inPacket)
        {
            int objectId = inPacket.ReadInt();

            lock (this)
            {
                if (this.Contains(objectId))
                {
                    this[objectId].Move(inPacket);
                }
            }
        }
    }
}


text:
<!DOCTYPE html>

        <meta charset="utf-8" />
        <title>Neural Network activations</title>

        <link id="bootstrap-style" href="/assets/webjars/bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet">

                    DeepLearning4j UI


text:
package org.aksw.mlbenchmark.validation.measures;

public class AccMethodAMeasure implements MeasureMethodTwoValued, MeasureMethodWithBeta {

	protected double beta = 0;

	public double getMeasure(int tp, int fn, int fp, int tn) {
		double recall = Heuristics.divideOrZero( tp , tp+fn );
		double precision = Heuristics.divideOrZero( tp , tp+fp );

		if (beta == 0) {
			return Heuristics.getAScore(recall, precision);
		} else {
			return Heuristics.getAScore(recall, precision, beta);
		}
	}

	public void setBeta(double beta) {
		this.beta = beta;
	}
}


text:
package org.apache.ignite.java8.examples;

/**
 * Multi-node test for {@link org.apache.ignite.examples.java8.datagrid.hibernate.HibernateL2CacheExample}.
 */
public class HibernateL2CacheExampleMultiNodeSelfTest extends HibernateL2CacheExampleSelfTest {
    /** {@inheritDoc} */
    @Override protected void beforeTest() throws Exception {
        for (int i = 0; i < RMT_NODES_CNT; i++)
            startGrid("node-" + i, "examples/config/example-ignite.xml");
    }
}


text:
function Set-UnattendedKickstartFirewallState
{
    param
    (
        [Parameter(Mandatory = $true)]
        [boolean]$State
    )

    if ($State)
    {
        $script:un.Add('firewall --enabled')
    }
    else
    {
        $script:un.Add('firewall --disabled')
    }
}


text:
@interface SNNavigationController ()<UINavigationControllerDelegate,UIViewControllerTransitioningDelegate,UIGestureRecognizerDelegate>
{
    AlphaPresentAnimation *animationAlpha;
    RotateAniamtion *animationRotate;
    TransitionInteractionController *transitionIntercation;
}
@end

@implementation SNNavigationController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    animationAlpha = [[AlphaPresentAnimation alloc] init];
    animationRotate = [[RotateAniamtion alloc] init];
    transitionIntercation = [[TransitionInteractionController alloc] init];

    self.delegate = self;
    self.transitioningDelegate = self;
    self.interactivePopGestureRecognizer.delegate = self;
    [self setNavigationBarHidden:YES];
}

- (nullable id <UIViewControllerInteractiveTransitioning>)navigationController:(UINavigationController *)navigationController
                                   interactionControllerForAnimationController:(id <UIViewControllerAnimatedTransitioning>) animationController
{
    if (animationController == animationRotate) {
        return nil;
    }
    return transitionIntercation.transitionInProgress ? transitionIntercation : nil;
}

- (void)navigationController:(UINavigationController *)navigationController didShowViewController:(UIViewController *)viewController animated:(BOOL)animated
{
    if (navigationController.viewControllers.count == 2) {
        [transitionIntercation removeGesutreRecognizer];
    }
}

//进行Push Pop 或者其他操作的时候,会触发次方法
- (nullable id <UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController
                                            animationControllerForOperation:(UINavigationControllerOperation)operation
                                                         fromViewController:(UIViewController *)fromVC
                                                           toViewController:(UIViewController *)toVC  NS_AVAILABLE_IOS(7_0)
{
    if (operation == UINavigationControllerOperationPush) {
        if (navigationController.viewControllers.count > 2) {
            [transitionIntercation attachToViewController:toVC];
        }
        return animationRotate;
    }
    else if (operation == UINavigationControllerOperationPop && navigationController.viewControllers.count > 1) {
        return animationAlpha;
    }
    return nil;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
//---------------------------------------------------------------------
// <copyright file="ResourceAttribute.cs" company="Microsoft">
//      Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information.
// </copyright>
//---------------------------------------------------------------------

using System;
using System.Linq;
using System.Collections.Generic;       //IEnumerable<T>
using System.Collections;               //IEnumerator
using System.Data.Test.Astoria.ReflectionProvider;
using System.Xml;

namespace System.Data.Test.Astoria
{
    public abstract class ResourceAttribute : Node
    {
        private static List<ResourceAttribute> allAttributes = new List<ResourceAttribute>();
        public static IEnumerable<ResourceAttribute> GetAllAttributes()
        {
            return allAttributes.AsEnumerable();
        }

        protected List<string> orderedParams;
        protected Dictionary<string,string> namedParams;

        protected ResourceAttribute(string name)
            : base(name)
        {
            orderedParams = new List<string>();
            namedParams = new Dictionary<string, string>();
            allAttributes.Add(this);
        }

        // Apply as code
        public virtual void Apply(CSharpCodeLanguageHelper codeHelper)
        {
            codeHelper.WriteAttribute(this.Name, namedParams, orderedParams.ToArray());
        }

        // for IDSQ/MP
        public virtual string InstantiationCode
        {
            get
            {
                return "new " + this.Name + "(" + string.Join(",", this.orderedParams.ToArray()) + ")";
            }
        }

        // Apply as csdl
        public abstract void Apply(XmlDocument csdl);
    }

    public class ResourceAttributeFacet : NodeFacet
    {
        public ResourceAttributeFacet(ResourceAttribute att)
            : base(FacetKind.Attributes, new NodeValue(att, null))
        { }
    }

    ////////////////////////////////////////////////////////
    // Specific feature attributes
    // TODO: seperate file? in with the feature-specific tests?
    //       it might get annoying to keep them all here
    //
    ////////////////////////////////////////////////////////
    //public class FriendlyFeedsAttribute : ResourceAttribute
    //{
    //    public string EntityName
    //    {
    //        get;
    //        private set;
    //    }
    //    public string PropertyName
    //    {
    //        get;
    //        private set;
    //    }
    //    public string TargetName
    //    {
    //        get;
    //        private set;
    //    }
    //    public bool KeepInContent
    //    {
    //        get;
    //        private set;
    //    }
    //    public FriendlyFeedsAttribute(string entityName, string propertyName, string targetName, bool keepInContent)
    //        : base("FriendlyFeeds")
    //    {
    //        this.EntityName = entityName;
    //        this.PropertyName = propertyName;
    //        this.TargetName = targetName;
    //        this.KeepInContent = keepInContent;
    //    }

    //    public override void Apply(XmlDocument csdl)
    //    {
    //        string searchString = null;

    //        searchString = String.Format("//csdl:EntityType[@Name='{0}']", this.EntityName);
    //        searchString = String.Concat(searchString, String.Format("//csdl:Property[@Name='{0}']", this.PropertyName));

    //        System.Xml.XmlNode propNode = TestUtil.AssertSelectSingleElement(csdl, searchString);
    //        propNode.ToString();

    //        return;
    //    }
    //}

    // This class is not working at the moment, please do not remove it or uncomment it
    //// these will be inferred from the service container where possible
    //public class PrimaryKeyAttribute : ResourceAttribute
    //{
    //    private List<string> keyPropertyNames;
    //    private bool inferredFromType;
    //    private ResourceType type;

    //    private PrimaryKeyAttribute(ResourceType type, bool inferred, IEnumerable<string> propertyNames)
    //        : base("DataServiceKey")
    //    {
    //        this.inferredFromType = inferred;
    //        this.type = type;
    //        this.keyPropertyNames = propertyNames.ToList();

    //        if (keyPropertyNames.Count() > 1)
    //        {
    //            string[] orignalOrder = keyPropertyNames.ToArray();
    //            for (int i = 1; i < orignalOrder.Length; i++)
    //                if (String.Compare(orignalOrder[i - 1], orignalOrder[i], false, Globalization.CultureInfo.InvariantCulture) > 0)
    //                {
    //                    AstoriaTestLog.WriteLine("Warning: Compound key properties on type '{0}' are not in alphabetical order, this may cause problems", type.Name);
    //                    break;
    //                }
    //        }

    //        this.orderedParams = keyPropertyNames.Select(n => "\"" + n + "\"").ToList();
    //    }

    //    public PrimaryKeyAttribute(ResourceType type)
    //        : this(type, true, type.Key.Properties.Select(p => p.Name))
    //    { }

    //    // This might not work, provided for completeness
    //    public PrimaryKeyAttribute(ResourceType type, IEnumerable<string> names)
    //        : this(type, false, names)
    //    {
    //        type.Key = new PrimaryKey("PK_" + type.Name, type.Properties.Where(p => names.Contains(p.Name)).ToArray());
    //    }

    //    // This might not work, provided for completeness
    //    public PrimaryKeyAttribute(ResourceType type, params string[] names)
    //        : this(type, names.AsEnumerable())
    //    { }

    //    // This might not work, provided for completeness
    //    public override void Apply(XmlDocument csdl)
    //    {
    //        if (!inferredFromType)
    //        {
    //            XmlElement keyNode = TestUtil.AssertSelectSingleElement(csdl, String.Format("//csdl:EntityType[@Name='{0}']/csdl:Key"));

    //            IEnumerable<string> present = keyNode.ChildNodes.OfType<XmlElement>().Select(x => x.GetAttribute("Name"));
    //            IEnumerable<string> toAdd = keyPropertyNames.Except(present);
    //            IEnumerable<string> toRemove = present.Except(keyPropertyNames);

    //            foreach (string remove in toRemove)
    //                keyNode.RemoveChild(TestUtil.AssertSelectSingleElement(keyNode, String.Format("//csdl:PropertyRef[@Name='{0}']", remove)));

    //            foreach (string add in toAdd)
    //            {
    //                XmlElement propRef = csdl.CreateElement("csdl:PropertyRef");
    //                propRef.SetAttribute("Name", add);
    //                keyNode.AppendChild(propRef);
    //            }
    //        }
    //    }
    //}
}


text:
using testing::_;
using testing::BitEq;
using testing::IsNaN;

namespace v8 {
namespace internal {
namespace compiler {

namespace {

const size_t kIndices[] = {0, 1, 42, 100, 1024};

Type const kJSTypes[] = {Type::Undefined(), Type::Null(),   Type::Boolean(),
                         Type::Number(),    Type::String(), Type::Object()};

}  // namespace

class JSTypedLoweringTest : public TypedGraphTest {
 public:
  JSTypedLoweringTest() : TypedGraphTest(3), javascript_(zone()) {}
  ~JSTypedLoweringTest() override = default;

 protected:
  Reduction Reduce(Node* node) {
    MachineOperatorBuilder machine(zone());
    SimplifiedOperatorBuilder simplified(zone());
    JSGraph jsgraph(isolate(), graph(), common(), javascript(), &simplified,
                    &machine);
    // TODO(titzer): mock the GraphReducer here for better unit testing.
    GraphReducer graph_reducer(zone(), graph());
    JSTypedLowering reducer(&graph_reducer, &jsgraph, broker(), zone());
    return reducer.Reduce(node);
  }

  Handle<JSArrayBuffer> NewArrayBuffer(void* bytes, size_t byte_length) {
    Handle<JSArrayBuffer> buffer =
        factory()->NewJSArrayBuffer(SharedFlag::kNotShared);
    JSArrayBuffer::Setup(buffer, isolate(), true, bytes, byte_length);
    return buffer;
  }

  JSOperatorBuilder* javascript() { return &javascript_; }

 private:
  JSOperatorBuilder javascript_;
};

// -----------------------------------------------------------------------------
// JSToName

TEST_F(JSTypedLoweringTest, JSToNameWithString) {
  Node* const input = Parameter(Type::String(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

TEST_F(JSTypedLoweringTest, JSToNameWithSymbol) {
  Node* const input = Parameter(Type::Symbol(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

TEST_F(JSTypedLoweringTest, JSToNameWithAny) {
  Node* const input = Parameter(Type::Any(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToName(), input, context,
                                        EmptyFrameState(), effect, control));
  ASSERT_FALSE(r.Changed());
}

// -----------------------------------------------------------------------------
// JSToNumber

TEST_F(JSTypedLoweringTest, JSToNumberWithPlainPrimitive) {
  Node* const input = Parameter(Type::PlainPrimitive(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r =
      Reduce(graph()->NewNode(javascript()->ToNumber(), input, context,
                              EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsPlainPrimitiveToNumber(input));
}

// -----------------------------------------------------------------------------
// JSToObject

TEST_F(JSTypedLoweringTest, JSToObjectWithAny) {
  Node* const input = Parameter(Type::Any(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToObject(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsPhi(MachineRepresentation::kTagged, _, _, _));
}

TEST_F(JSTypedLoweringTest, JSToObjectWithReceiver) {
  Node* const input = Parameter(Type::Receiver(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToObject(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_EQ(input, r.replacement());
}

// -----------------------------------------------------------------------------
// JSToString

TEST_F(JSTypedLoweringTest, JSToStringWithBoolean) {
  Node* const input = Parameter(Type::Boolean(), 0);
  Node* const context = Parameter(Type::Any(), 1);
  Node* const frame_state = EmptyFrameState();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->ToString(), input,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(),
              IsSelect(MachineRepresentation::kTagged, input,
                       IsHeapConstant(factory()->true_string()),
                       IsHeapConstant(factory()->false_string())));
}

// -----------------------------------------------------------------------------
// JSStrictEqual

TEST_F(JSTypedLoweringTest, JSStrictEqualWithTheHole) {
  Node* const the_hole = HeapConstant(factory()->the_hole_value());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FOREACH(Type, type, kJSTypes) {
    Node* const lhs = Parameter(type);
    Reduction r = Reduce(
        graph()->NewNode(javascript()->StrictEqual(CompareOperationHint::kAny),
                         lhs, the_hole, context, effect, control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(), IsFalseConstant());
  }
}

TEST_F(JSTypedLoweringTest, JSStrictEqualWithUnique) {
  Node* const lhs = Parameter(Type::Unique(), 0);
  Node* const rhs = Parameter(Type::Unique(), 1);
  Node* const context = Parameter(Type::Any(), 2);
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r = Reduce(
      graph()->NewNode(javascript()->StrictEqual(CompareOperationHint::kAny),
                       lhs, rhs, context, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsReferenceEqual(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftLeft

TEST_F(JSTypedLoweringTest, JSShiftLeftWithSigned32AndConstant) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(javascript()->ShiftLeft(), lhs,
                                          NumberConstant(rhs), context,
                                          EmptyFrameState(), effect, control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftLeft(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftLeftWithSigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r =
      Reduce(graph()->NewNode(javascript()->ShiftLeft(), lhs, rhs, context,
                              EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftLeft(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftRight

TEST_F(JSTypedLoweringTest, JSShiftRightWithSigned32AndConstant) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(javascript()->ShiftRight(), lhs,
                                          NumberConstant(rhs), context,
                                          EmptyFrameState(), effect, control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftRight(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftRightWithSigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Signed32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r =
      Reduce(graph()->NewNode(javascript()->ShiftRight(), lhs, rhs, context,
                              EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftRight(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSShiftRightLogical

TEST_F(JSTypedLoweringTest,
                   JSShiftRightLogicalWithUnsigned32AndConstant) {
  Node* const lhs = Parameter(Type::Unsigned32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FORRANGE(double, rhs, 0, 31) {
    Reduction r = Reduce(graph()->NewNode(javascript()->ShiftRightLogical(),
                                          lhs, NumberConstant(rhs), context,
                                          EmptyFrameState(), effect, control));
    ASSERT_TRUE(r.Changed());
    EXPECT_THAT(r.replacement(),
                IsNumberShiftRightLogical(lhs, IsNumberConstant(BitEq(rhs))));
  }
}

TEST_F(JSTypedLoweringTest, JSShiftRightLogicalWithUnsigned32AndUnsigned32) {
  Node* const lhs = Parameter(Type::Unsigned32());
  Node* const rhs = Parameter(Type::Unsigned32());
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction r =
      Reduce(graph()->NewNode(javascript()->ShiftRightLogical(), lhs, rhs,
                              context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsNumberShiftRightLogical(lhs, rhs));
}

// -----------------------------------------------------------------------------
// JSLoadContext

TEST_F(JSTypedLoweringTest, JSLoadContext) {
  Node* const context = Parameter(Type::Any());
  Node* const effect = graph()->start();
  static bool kBooleans[] = {false, true};
  TRACED_FOREACH(size_t, index, kIndices) {
    TRACED_FOREACH(bool, immutable, kBooleans) {
      Reduction const r1 = Reduce(graph()->NewNode(
          javascript()->LoadContext(0, index, immutable), context, effect));
      ASSERT_TRUE(r1.Changed());
      EXPECT_THAT(r1.replacement(),
                  IsLoadField(AccessBuilder::ForContextSlot(index), context,
                              effect, graph()->start()));

      Reduction const r2 = Reduce(graph()->NewNode(
          javascript()->LoadContext(1, index, immutable), context, effect));
      ASSERT_TRUE(r2.Changed());
      EXPECT_THAT(r2.replacement(),
                  IsLoadField(AccessBuilder::ForContextSlot(index),
                              IsLoadField(AccessBuilder::ForContextSlot(
                                              Context::PREVIOUS_INDEX),
                                          context, effect, graph()->start()),
                              _, graph()->start()));
    }
  }
}

// -----------------------------------------------------------------------------
// JSStoreContext

TEST_F(JSTypedLoweringTest, JSStoreContext) {
  Node* const context = Parameter(Type::Any());
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  TRACED_FOREACH(size_t, index, kIndices) {
    TRACED_FOREACH(Type, type, kJSTypes) {
      Node* const value = Parameter(type);

      Reduction const r1 =
          Reduce(graph()->NewNode(javascript()->StoreContext(0, index), value,
                                  context, effect, control));
      ASSERT_TRUE(r1.Changed());
      EXPECT_THAT(r1.replacement(),
                  IsStoreField(AccessBuilder::ForContextSlot(index), context,
                               value, effect, control));

      Reduction const r2 =
          Reduce(graph()->NewNode(javascript()->StoreContext(1, index), value,
                                  context, effect, control));
      ASSERT_TRUE(r2.Changed());
      EXPECT_THAT(r2.replacement(),
                  IsStoreField(AccessBuilder::ForContextSlot(index),
                               IsLoadField(AccessBuilder::ForContextSlot(
                                               Context::PREVIOUS_INDEX),
                                           context, effect, graph()->start()),
                               value, _, control));
    }
  }
}

// -----------------------------------------------------------------------------
// JSLoadNamed

TEST_F(JSTypedLoweringTest, JSLoadNamedStringLength) {
  VectorSlotPair feedback;
  Handle<Name> name = factory()->length_string();
  Node* const receiver = Parameter(Type::String(), 0);
  Node* const context = UndefinedConstant();
  Node* const effect = graph()->start();
  Node* const control = graph()->start();
  Reduction const r =
      Reduce(graph()->NewNode(javascript()->LoadNamed(name, feedback), receiver,
                              context, EmptyFrameState(), effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsStringLength(receiver));
}

// -----------------------------------------------------------------------------
// JSAdd

TEST_F(JSTypedLoweringTest, JSAddWithString) {
  BinaryOperationHint const hint = BinaryOperationHint::kAny;
  Node* lhs = Parameter(Type::String(), 0);
  Node* rhs = Parameter(Type::String(), 1);
  Node* context = Parameter(Type::Any(), 2);
  Node* frame_state = EmptyFrameState();
  Node* effect = graph()->start();
  Node* control = graph()->start();
  Reduction r = Reduce(graph()->NewNode(javascript()->Add(hint), lhs, rhs,
                                        context, frame_state, effect, control));
  ASSERT_TRUE(r.Changed());
  EXPECT_THAT(r.replacement(), IsStringConcat(_, lhs, rhs));
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
package com.beirtipol.svnmergeutils;

import java.io.File;
import java.io.FileFilter;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeSet;

import org.kohsuke.args4j.Option;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNWCClient;

/**
 * When using SVN merge and recording merge information, it is suggested to always record merge information at the
 * project level. This is because when you attempt to merge,or use the MissingMergeChecker to detect eligible merges,
 * you will sometimes see classes which appear to have not been merged but in fact have. This is due to merge
 * information being duplicated at different levels of the tree.
 *
 * This program aggregates all merge information in a directory tree up to the level specified as the workingCopyRoot.
 *
 * @author beirtipol@gmail.com
 *
 */
public class MergeInformationAggregator extends AbstractWorker {
	private static final Logger	LOGGER				= LoggerFactory.getLogger(MergeInformationAggregator.class);

	public static final String	SVN_MERGEINFO_PROP	= "svn:mergeinfo";

	@Option(name = "--workingCopyRoot", usage = "Path to aggregate merge information to.", required = true)
	private File				workingCopyRoot;

	@Option(name = "--mergeSourcesRoot", usage = "Root folder of merge source directories, relative to the repository root. Should include leading and trailing slashes. e.g. '/myproject/branches/'", required = true)
	private String				mergeSourcesRoot;

	private SVNClientManager	clientManager;

	public static void main(String[] args) throws SVNException {
		new MergeInformationAggregator().doMain(args);
	}

	public MergeInformationAggregator() throws SVNException {
		// noargs constructor for command line execution
		clientManager = SVNClientManager.newInstance();
	}

	private void walkFileTree(File path, SortedMap<String, Set<Long>> mergedRevisions) throws SVNException {
		File[] files = path.listFiles(new FileFilter() {
			@Override
			public boolean accept(File pathname) {
				return !pathname.getName().equals(".svn");
			}
		});
		if (files == null) {
			return;
		}
		for (File file : files) {
			SortedMap<String, Set<Long>> fileMergedRevisions = SVNUtils.parseMergeInfoPropertyData(SVNUtils.getMergeInformation(clientManager, file));
			joinMergeInfo(mergedRevisions, fileMergedRevisions);
			SVNWCClient wcClient = clientManager.getWCClient();
			wcClient.doSetProperty(file, SVN_MERGEINFO_PROP, null, true, SVNDepth.EMPTY, null, null);
			walkFileTree(file, mergedRevisions);
		}
	}

	private void joinMergeInfo(SortedMap<String, Set<Long>> to, SortedMap<String, Set<Long>> from) {
		for (Entry<String, Set<Long>> entry : from.entrySet()) {
			String branch = entry.getKey();
			if (branch.startsWith(mergeSourcesRoot)) {
				String branchName = branch.replaceFirst(mergeSourcesRoot, "").split("/")[0];
				branch = mergeSourcesRoot + branchName;
			}

			Set<Long> revisions = to.get(branch);
			if (revisions == null) {
				revisions = new TreeSet<>();
				to.put(branch, revisions);
			}
			revisions.addAll(entry.getValue());
		}
	}

	private void doMain(String[] args) throws SVNException {
		if (!handleArgs(args)) {
			return;
		}
		SortedMap<String, Set<Long>> rootMergeInfo = SVNUtils.parseMergeInfoPropertyData(SVNUtils.getMergeInformation(clientManager, workingCopyRoot));
		walkFileTree(workingCopyRoot, rootMergeInfo);
		SVNPropertyValue propValue = SVNUtils.createMergeInfoPropertyValue(rootMergeInfo);
		clientManager.getWCClient().doSetProperty(workingCopyRoot, SVN_MERGEINFO_PROP, propValue, true, SVNDepth.EMPTY, null, null);
	}

	@Override
	protected Logger getLogger() {
		return LOGGER;
	}

}


text:
namespace BUR_UI.Entities
{
    public class AccountGridModel
    {
        public string AcctCode { get; set; }
        public string AcctName { get; set; }
        public string AcctClass { get; set; }
        public decimal AB { get; set; }
    }
}


text:
module Azure::ARM::Resources
  module Models
    #
    # Export resource group template request parameters.
    #
    class ExportTemplateRequest

      include MsRestAzure

      # @return [Array<String>] The IDs of the resources. The only supported
      # string currently is '*' (all resources). Future updates will support
      # exporting specific resources.
      attr_accessor :resources

      # @return [String] The export template options. Supported values include
      # 'IncludeParameterDefaultValue', 'IncludeComments' or
      # 'IncludeParameterDefaultValue, IncludeComments
      attr_accessor :options

      #
      # Mapper for ExportTemplateRequest class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          required: false,
          serialized_name: 'ExportTemplateRequest',
          type: {
            name: 'Composite',
            class_name: 'ExportTemplateRequest',
            model_properties: {
              resources: {
                required: false,
                serialized_name: 'resources',
                type: {
                  name: 'Sequence',
                  element: {
                      required: false,
                      serialized_name: 'StringElementType',
                      type: {
                        name: 'String'
                      }
                  }
                }
              },
              options: {
                required: false,
                serialized_name: 'options',
                type: {
                  name: 'String'
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
import UtilString = require('./UtilString');
import EventDispatcher = require('./EventDispatcher');
import ElementClassNameCase = require('../Enum/ElementClassNameCase');
import ClassNameSeparatorForBEM = require('../Enum/ClassNameSeparatorForBEM');
import IElement = require('../Interface/IElement');

const HYPHEN: string = '-';
const DOUBLE_HYPHEN: string = '--';
const UNDERSCORE: string = '_';
const DOUBLE_UNDERSCORE: string = '__';

/**
 * DOM要素の抽象クラス
 *
 * DOM要素操作に関するjQueryのメソッドは極力ここに集約したい
 * 脱jQueryの際にこのクラスを改修するだけで済むようにする
 *
 * @version 0.9.0
 * @since 0.0.1
 *
 */
class BaserElement extends EventDispatcher implements IElement {

	/**
	 * クラス名のデフォルトのプレフィックス
	 *
	 * @version 0.1.0
	 * @since 0.1.0
	 *
	 */
	public static classNameDefaultPrefix: string = '-bc';

	/**
	 * インスタンスに付加するデフォルトのクラス名
	 *
	 * @version 0.1.0
	 * @since 0.1.0
	 *
	 */
	public static classNameElementCommon: string = 'element';

	/**
	 * クラス名のデフォルトの単語繋ぎの形式
	 *
	 * @version 0.1.0
	 * @since 0.1.0
	 *
	 */
	public static classNameDefaultCase: ElementClassNameCase = ElementClassNameCase.HYPHEN_DELIMITED;

	/**
	 * BEMのエレメントのクラス名の繋ぎ文字
	 *
	 * @version 0.1.0
	 * @since 0.1.0
	 *
	 */
	public static classNameDefaultSeparatorForElement: ClassNameSeparatorForBEM = ClassNameSeparatorForBEM.DOUBLE_UNDERSCORE;

	/**
	 * BEMのモディファイアのクラス名の繋ぎ文字
	 *
	 * @version 0.1.0
	 * @since 0.1.0
	 *
	 */
	public static classNameDefaultSeparatorForModifier: ClassNameSeparatorForBEM = ClassNameSeparatorForBEM.DOUBLE_HYPHEN;

	/**
	 * 【廃止予定】管理するDOM要素のjQueryオブジェクト
	 *
	 * @deprecated
	 * @version 0.0.1
	 * @since 0.0.1
	 *
	 */
	public $el: JQuery;

	/**
	 * 管理するDOM要素
	 *
	 * @version 0.9.0
	 * @since 0.9.0
	 *
	 */
	public el: HTMLElement;

	/**
	 * 管理するDOM要素のid属性値
	 *
	 * @version 0.0.1
	 * @since 0.0.1
	 *
	 */
	public id: string;

	/**
	 * 管理するDOM要素のname属性値
	 *
	 * @version 0.0.1
	 * @since 0.0.1
	 *
	 */
	public name: string = '';

	/**
	 * baserJSのエレメント化してたかどうか
	 *
	 * @version 0.8.0
	 * @since 0.8.0
	 *
	 */
	protected _elementized: boolean = false;

	/**
	 * BEMベースでクラス名文字列を生成する
	 *
	 * @version 0.9.0
	 * @since 0.1.0
	 * @param blockName ブロック名
	 * @param elementName 要素名
	 * @param modifierName 状態名
	 * @return 生成されたクラス名
	 *
	 */
	public static createClassName (blockNames: string, elementNames: string = '', modifierName: string = ''): string {
		let className: string = '';
		let prefix: string;
		let separator: string;
		let elementSeparator: string;
		let modifierSeparator: string;
		switch (BaserElement.classNameDefaultCase) {
			case ElementClassNameCase.HYPHEN_DELIMITED: {
				separator = HYPHEN;
				blockNames = UtilString.hyphenDelimited(blockNames);
				elementNames = UtilString.hyphenDelimited(elementNames);
				modifierName = UtilString.hyphenDelimited(modifierName);
			}
			break;
			case ElementClassNameCase.SNAKE_CASE: {
				separator = UNDERSCORE;
				blockNames = UtilString.snakeCase(blockNames);
				elementNames = UtilString.snakeCase(elementNames);
				modifierName = UtilString.snakeCase(modifierName);
			}
			break;
			case ElementClassNameCase.CAMEL_CASE: {
				separator = '';
				blockNames = UtilString.camelCase(blockNames, true);
				elementNames = UtilString.camelCase(elementNames);
				modifierName = UtilString.camelCase(modifierName);
			}
			break;
			default: {
				// void
			}
		}
		switch (BaserElement.classNameDefaultSeparatorForElement) {
			case ClassNameSeparatorForBEM.HYPHEN: {
				elementSeparator = HYPHEN;
			}
			break;
			case ClassNameSeparatorForBEM.DOUBLE_HYPHEN: {
				elementSeparator = DOUBLE_HYPHEN;
			}
			break;
			case ClassNameSeparatorForBEM.UNDERSCORE: {
				elementSeparator = UNDERSCORE;
			}
			break;
			case ClassNameSeparatorForBEM.DOUBLE_UNDERSCORE: {
				elementSeparator = DOUBLE_UNDERSCORE;
			}
			break;
			case ClassNameSeparatorForBEM.CAMEL_CASE: {
				elementSeparator = '';
			}
			break;
			default: {
				// void
			}
		}
		switch (BaserElement.classNameDefaultSeparatorForModifier) {
			case ClassNameSeparatorForBEM.HYPHEN: {
				modifierSeparator = HYPHEN;
			}
			break;
			case ClassNameSeparatorForBEM.DOUBLE_HYPHEN: {
				modifierSeparator = DOUBLE_HYPHEN;
			}
			break;
			case ClassNameSeparatorForBEM.UNDERSCORE: {
				modifierSeparator = UNDERSCORE;
			}
			break;
			case ClassNameSeparatorForBEM.DOUBLE_UNDERSCORE: {
				modifierSeparator = DOUBLE_UNDERSCORE;
			}
			break;
			case ClassNameSeparatorForBEM.CAMEL_CASE: {
				modifierSeparator = '';
			}
			break;
			default: {
				// void
			}
		}
		if (BaserElement.classNameDefaultPrefix) {
			prefix = BaserElement.classNameDefaultPrefix;
			prefix = prefix
				// 先頭のアルファベット・アンダースコア・ハイフン以外を削除
				.replace(/^[^a-z_-]/i, '')
				// アルファベット・数字・アンダースコア・ハイフン以外を削除
				.replace(/[^a-z0-9_-]+/ig, '')
				// 先頭の2個以上連続するハイフンを削除
				.replace(/^--+/, '-');
			className += prefix;
		}
		className += separator + blockNames;
		if (elementNames) {
			className += elementSeparator + elementNames;
		}
		if (modifierName) {
			className += modifierSeparator + modifierName;
		}
		return className;
	}

	/**
	 * 要素の属性の真偽を判定する
	 *
	 * DOM APIの標準で判定できるものはそれで判断
	 * 値なし属性の場合は存在すれば真
	 * 値あり属性の場合は偽相等の文字列でなければ全て真とする
	 * ただし値なし属性の場合は値が空文字列のため、偽相等の文字列の例外とする
	 *
	 * @version 0.10.0
	 * @since 0.2.0
	 * @param elem 対象のDOM要素
	 * @param attrName 確認したい属性名
	 * @return 結果
	 *
	 */
	public static getBoolAttr (elem: HTMLElement, attrName: string): boolean {
		let value: any;
		// DOM APIの標準で判定できるものはそれで判断
		value = elem[attrName];
		if (value === true) {
			return true;
		}
		const attr: Attr = elem.attributes.getNamedItem(attrName);
		if (attr) {
			value = attr.value;
			if (value === '') {
				// 値なし属性の場合は存在すれば真
				return true;
			} else {
				return !UtilString.isFalsy(`${value}`);
			}
		} else {
			// 属性がない場合は偽
			return false;
		}
	}

	/**
	 * クラス名を付加する
	 *
	 * use: jQuery
	 *
	 * @version 0.9.0
	 * @since 0.1.0
	 * @param elem 対象のDOM要素
	 * @param blockName ブロック名
	 * @param elementName 要素名
	 * @param modifierName 状態名
	 *
	 */
	public static addClass (elem: HTMLElement, blockNames: string, elementNames: string = '', modifierName: string = ''): void {
		const $elem: JQuery = $(elem);
		const className: string = BaserElement.createClassName(blockNames, elementNames, modifierName);
		$elem.addClass(className);
	}

	/**
	 * 【廃止予定】クラス名を付加する
	 *
	 * use: jQuery
	 *
	 * @deprecated
	 * @version 0.1.0
	 * @since 0.1.0
	 * @param $elem 対象のDOM要素
	 * @param blockName ブロック名
	 * @param elementName 要素名
	 * @param modifierName 状態名
	 *
	 */
	public static addClassTo ($elem: JQuery, blockNames: string, elementNames: string = '', modifierName: string = ''): void {
		const className: string = BaserElement.createClassName(blockNames, elementNames, modifierName);
		$elem.addClass(className);
	}

	/**
	 * クラス名を取り除く
	 *
	 * use: jQuery
	 *
	 * @version 0.9.0
	 * @since 0.1.0
	 * @param elem 対象のDOM要素
	 * @param blockName ブロック名
	 * @param elementName 要素名
	 * @param modifierName 状態名
	 *
	 */
	public static removeClass (elem: HTMLElement, blockNames: string, elementNames: string = '', modifierName: string = ''): void {
		const $elem: JQuery = $(elem);
		const className: string = BaserElement.createClassName(blockNames, elementNames, modifierName);
		$elem.removeClass(className);
	}

	/**
	 * 【廃止予定】クラス名を取り除く
	 *
	 * use: jQuery
	 *
	 * @deprecated
	 * @version 0.1.0
	 * @since 0.1.0
	 * @param $elem 対象のDOM要素
	 * @param blockName ブロック名
	 * @param elementName 要素名
	 * @param modifierName 状態名
	 *
	 */
	public static removeClassFrom ($elem: JQuery, blockNames: string, elementNames: string = '', modifierName: string = ''): void {
		const className: string = BaserElement.createClassName(blockNames, elementNames, modifierName);
		$elem.removeClass(className);
	}

	/**
	 * CSSプロパティをDOM要素から取り除く
	 *
	 * @version 0.9.0
	 * @since 0.2.2
	 * @param elem 対象のDOM要素
	 * @param propName 取り除くCSSプロパティ
	 *
	 */
	public static removeCSSProp (elem: HTMLElement, propName: string): void {
		const style: CSSStyleDeclaration = elem.style;
		// IE8以下はCSSStyleDeclarationのインターフェイスが標準でないのでメソッド定義チェックでエラーになる
		if (style) {
			const styleIE8lt: any = <any> style;
			if (style.removeProperty) {
				style.removeProperty(propName);
			} else if (styleIE8lt.removeAttribute) {
				styleIE8lt.removeAttribute(propName);
			}
		}
	}

	/**
	 * 【廃止予定】CSSプロパティをDOM要素から取り除く
	 *
	 * use: jQuery
	 *
	 * @deprecated
	 * @version 0.9.0
	 * @since 0.2.2
	 * @param propName 取り除くCSSプロパティ
	 * @param elem 対象のDOM要素
	 *
	 */
	public static removeCSSPropertyFromDOMElement (propertyName: string, elem: HTMLElement): void {
		BaserElement.removeCSSProp(elem, propertyName);
	}

	/**
	 * 【廃止予定】CSSプロパティを取り除く
	 *
	 * use: jQuery
	 *
	 * @version 0.9.0
	 * @since 0.2.2
	 * @param propName 取り除くCSSプロパティ
	 * @param $elem 対象のDOM要素
	 *
	 */
	public static removeCSSProperty (propertyName: string, $elem: JQuery): void {
		$elem.each( (i: number, elem: HTMLElement) => {
			BaserElement.removeCSSProp(elem, propertyName);
		});
	}

	/**
	 * コンストラクタ
	 *
	 * use: jQuery
	 *
	 * TODO: クラス名のつき方の規則をきちんと決める
	 * TODO: コンストラクタの引数をネイティブのDOM要素にする
	 *
	 * @version 0.9.0
	 * @since 0.0.1
	 * @param $el 管理するDOM要素
	 *
	 */
	constructor (el: HTMLElement) {
		super();
		this.el = el;
		this.$el = $(el);
		// 既にbaserJSのエレメント化している場合
		if (this.$el.data('bc-element')) {
			if ('console' in window) {
				console.warn('This element is elementized of baserJS.');
			}
			this._elementized = true;
			return;
		}
		this.$el.data('bc-element', this);
		// ID・nameの抽出 & 生成
		const id: string = el.id || UtilString.UID();
		const name: string = el.getAttribute('name');
		el.id = id;
		this.id = id;
		this.name = name;
		// 共通クラスの付加
		this.addClass(BaserElement.classNameElementCommon);
	}

	/**
	 * クラス名を付加する
	 *
	 * @version 0.9.0
	 * @since 0.1.0
	 *
	 */
	public addClass (blockNames: string, elementNames: string = '', modifierName: string = ''): void {
		BaserElement.addClass(this.el, blockNames, elementNames, modifierName);
	}

	/**
	 * 要素の属性の真偽を判定する
	 *
	 * `BaserElement.getBoolAttr` のインスタンスメソッド版
	 *
	 * @version 0.9.0
	 * @since 0.2.0
	 *
	 */
	public getBoolAttr (attrName: string): boolean {
		return BaserElement.getBoolAttr(this.el, attrName);
	}

	/**
	 * オプションとdata属性の値、属性の値をマージする
	 *
	 * use: jQuery
	 *
	 * TODO: テストを書く
	 * TODO: サブクラスに反映させる
	 *
	 * @version 0.9.1
	 * @since 0.8.0
	 *
	 */
	public mergeOptions (defaultOptions: any, options: any): any {
		const attrs: { [option: string ]: any } = {};
		const dataAttrs: { [option: string ]: any } = {};

		for (const optName in defaultOptions) {
			if (defaultOptions.hasOwnProperty(optName)) {
				// 属性はidとclassは除外する
				switch (optName) {
					case 'id':
					case 'class':
					break;
					default: {
						attrs[optName] = this.$el.attr(optName);
					}
				}
				dataAttrs[optName] = this.$el.data(optName);
			}
		}
		return $.extend({}, defaultOptions, options, dataAttrs, attrs);
	}

}

export = BaserElement;


text:
package flag

import (
	"strings"

	flags "github.com/jessevdk/go-flags"
)

type Color struct {
	Color bool
}

func (_ Color) Complete(prefix string) []flags.Completion {
	return completions([]string{"true", "false"}, prefix, false)
}

func (c *Color) UnmarshalFlag(val string) error {
	switch strings.ToLower(val) {
	case "true":
		c.Color = true
	case "false":
		c.Color = false
	default:
		return &flags.Error{
			Type:    flags.ErrRequired,
			Message: `COLOR must be "true" or "false"`,
		}
	}

	return nil
}


text:
package org.ice4j.pseudotcp;

import static org.junit.Assert.*;

import java.io.*;
import java.net.*;
import java.util.logging.*;

/**
 *
 * @author Pawel Domas
 */
public class PseudoTcpStreamTest
    extends MultiThreadSupportTest
{
    /**
     * The logger.
     */
    private static final Logger logger = Logger
        .getLogger(PseudoTcpStreamTest.class.getName());

    public PseudoTcpStreamTest()
    {
    }

    /**
     * Test one-way transfer with @link(PseudoTcpStream)
     * @throws IOException
     */
    public void testConnectTransferClose()
        throws IOException
    {
        Thread.setDefaultUncaughtExceptionHandler(this);
        final int server_port = 49999;
        int transferTimeout = 5000;

        // bytes that will be read as a single byte
        final int singleStepCount = 34;
        final byte[] bufferSingle =
            PseudoTcpTestBase.createDummyData(singleStepCount);
        final int sizeA = 138746;
        final byte[] bufferA = PseudoTcpTestBase.createDummyData(sizeA);
        final int sizeB = 983746;
        final byte[] bufferB = PseudoTcpTestBase.createDummyData(sizeB);
        final InetSocketAddress serverAddress =
            new InetSocketAddress(InetAddress.getLocalHost(), server_port);
        final PseudoTcpSocket server =
            new PseudoTcpSocketFactory().createSocket();
        Thread serverThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    server.setDebugName("L");
                    server.bind(serverAddress);
                    server.accept(5000);
                    byte[] rcvdSingle = new byte[singleStepCount];
                    // read by one byte
                    for (int i = 0; i < singleStepCount; i++)
                        rcvdSingle[i] = (byte) server.getInputStream().read();
                    assertArrayEquals(bufferSingle, rcvdSingle);
                    // receive buffer A
                    byte[] recvdBufferA =
                        receiveBuffer(server.getInputStream(), sizeA);
                    assertArrayEquals(bufferA, recvdBufferA);
                    // receive buffer B
                    byte[] recvdBufferB =
                        receiveBuffer(server.getInputStream(), sizeB);
                    assertArrayEquals(bufferB, recvdBufferB);
                    // server.close();
                }
                catch (IOException ex)
                {
                    throw new RuntimeException(ex);
                }
            }
        });

        final PseudoTcpSocket client =
            new PseudoTcpSocketFactory().createSocket();
        Thread clientThread = new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    client.setDebugName("R");
                    client.connect(serverAddress, 5000);
                    // write single array
                    for (int i = 0; i < singleStepCount; i++)
                        client.getOutputStream().write(bufferSingle[i]);
                    // write whole array
                    client.getOutputStream().write(bufferA);
                    // write by parts
                    int partCount = 7;
                    boolean notExact = sizeB % partCount != 0;
                    int[] partsSize =
                        notExact ? new int[partCount + 1] : new int[partCount];
                    for (int i = 0; i < partsSize.length; i++)
                    {
                        if (notExact && i == partCount)
                            partsSize[i] = sizeB % partCount;
                        else
                            partsSize[i] = sizeB / partCount;
                    }
                    int written = 0;
                    for (int i = 0; i < partsSize.length; i++)
                    {
                        client.getOutputStream().write(bufferB, written,
                            partsSize[i]);
                        written += partsSize[i];
                    }
                    assertEquals(sizeB, written);
                    client.getOutputStream().flush();
                    client.close();
                }
                catch (IOException ex)
                {
                    throw new RuntimeException(ex);
                }
            }
        });

        serverThread.start();
        clientThread.start();
        try
        {
            boolean success = assert_wait_until(new WaitUntilDone()
            {
                @Override
                public boolean isDone()
                {
                    return client.getState() == PseudoTcpState.TCP_CLOSED;
                }
            }, transferTimeout);
            if (success)
            {
                clientThread.join();
                serverThread.join();
                server.close();
            }
            else
            {
                fail("Transfer timeout");
            }
        }
        catch (InterruptedException ex)
        {
            throw new RuntimeException(ex);
        }
    }

    private static byte[] receiveBuffer(InputStream input, int size)
        throws IOException
    {
        int rcvd = 0;
        byte[] buffer = new byte[size];
        rcvd += input.read(buffer);
        while (rcvd != size)
        {
            rcvd += input.read(buffer, rcvd, size - rcvd);
            if (logger.isLoggable(Level.FINER))
            {
                logger.log(Level.FINER, "Received: " + rcvd);
            }
        }

        return buffer;
    }

    /**
     * Test the timeout on accept method
     */
    public void testAccept()
    {
        try
        {
            PseudoTcpSocketImpl server = new PseudoTcpSocketImpl(0);
            server.accept(10);
            fail("Should throw timeout exception");
        }
        catch (IOException ex)
        {
            // success
        }
    }

    /**
     * Interface used to pass timeout test function
     * @author Pawel Domas
     *
     */
    private interface TimeoutOperationTest
    {
        void testTimeout(PseudoTcpSocketImpl socket) throws IOException;
    }

    /**
     *
     * @param testOperation
     * @throws UnknownHostException
     */
    private void doTestTimeout(final TimeoutOperationTest testOperation)
        throws Exception
    {
        Thread.setDefaultUncaughtExceptionHandler(this);
        final PseudoTcpSocketImpl server;
        final PseudoTcpSocketImpl client;
        final int server_port = 49998;
        final InetSocketAddress serverAddress =
            new InetSocketAddress(InetAddress.getLocalHost(), server_port);
        server =
            new PseudoTcpSocketImpl(0,new DatagramSocket(serverAddress));
        client = new PseudoTcpSocketImpl(0);
        //Servers thread waiting for connection
        new Thread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    server.accept(2000);
                }
                catch (IOException e)
                {
                    throw new RuntimeException(e);
                }
                try
                {
                    testOperation.testTimeout(server);
                    fail("No expected timeout occured on operation");
                }
                catch (IOException e)
                {
                    //success
                    try
                    {
                        server.close();
                    }
                    catch (IOException exc)
                    {
                        throw new RuntimeException(exc);
                    }
                }
            }
        }).start();
        //Clients thread connects and closes socket
        new Thread(new Runnable()
        {

            @Override
            public void run()
            {
                try
                {
                    client.connect(serverAddress, 2000);
                    Thread.sleep(500);
                    client.close();
                }
                catch (Exception e)
                {
                    throw new RuntimeException(e);
                }
            }
        }).start();
        //Waits for server to close socket
        boolean done = assert_wait_until(new WaitUntilDone()
        {

            @Override
            public boolean isDone()
            {
                return server.getState() == PseudoTcpState.TCP_CLOSED;
            }
        }, 3000);
        if(!done)
        {
            fail("Test timed out");
        }
    }

    /**
     * Tests timeout on read method
     * @throws UnknownHostException
     */
    public void testReadTimeout() throws Exception
    {
        doTestTimeout(new TimeoutOperationTest()
        {

            @Override
            public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
            {
                socket.setPTCPOption(Option.OPT_READ_TIMEOUT, 300);
                socket.getInputStream().read(new byte[500]);
            }
        });
    }

    /**
     * Tests timeout on write method
     * @throws UnknownHostException
     */
    public void testWriteTimeout() throws Exception
    {
        doTestTimeout(new TimeoutOperationTest()
        {
            @Override
            public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
            {
                //buffer that will exceed stack's buffer size
                byte[] bigBuffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE*2];
                socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
                socket.getOutputStream().write(bigBuffer);
            }
        });
    }

    /**
     * Tests timeout on flush method
     * @throws UnknownHostException
     */
    public void testFlushTimeout() throws Exception
    {
        doTestTimeout(new TimeoutOperationTest()
        {
            @Override
            public void testTimeout(PseudoTcpSocketImpl socket) throws IOException
            {
                //buffer that will exceed stack's buffer size
                byte[] buffer = new byte[PseudoTCPBase.DEFAULT_SND_BUF_SIZE];
                socket.setPTCPOption(Option.OPT_WRITE_TIMEOUT, 300);
                try
                {
                    socket.getOutputStream().write(buffer);
                }
                catch(IOException e)
                {
                    throw new RuntimeException("Unexpected exception: "+e);
                }
                socket.getOutputStream().flush();
            }
        });
    }

}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
  <component name="ProjectInspectionProfilesVisibleTreeState">
    <entry key="Project Default">
      <profile-state>
        <expanded-state>
          <State>
            <id />
          </State>
          <State>
            <id>Bitwise operation issuesJavaScript</id>
          </State>
          <State>
            <id>Control flow issuesJavaScript</id>
          </State>
          <State>
            <id>DOM issuesJavaScript</id>
          </State>
          <State>
            <id>Data flow issuesJavaScript</id>
          </State>
          <State>
            <id>GeneralJavaScript</id>
          </State>
          <State>
            <id>GeneralPHP</id>
          </State>
          <State>
            <id>JavaScript</id>
          </State>
          <State>
            <id>PHP</id>
          </State>
          <State>
            <id>Potentially confusing code constructsJavaScript</id>
          </State>
          <State>
            <id>RELAX NG</id>
          </State>
          <State>
            <id>UndefinedPHP</id>
          </State>
        </expanded-state>
        <selected-state>
          <State>
            <id>Blade files</id>
          </State>
        </selected-state>
      </profile-state>
    </entry>
  </component>
  <component name="ProjectLevelVcsManager" settingsEditedManually="false">
    <OptionsSetting value="true" id="Add" />
    <OptionsSetting value="true" id="Remove" />
    <OptionsSetting value="true" id="Checkout" />
    <OptionsSetting value="true" id="Update" />
    <OptionsSetting value="true" id="Status" />
    <OptionsSetting value="true" id="Edit" />
    <ConfirmationsSetting value="0" id="Add" />
    <ConfirmationsSetting value="0" id="Remove" />
  </component>
</project>


text:
using BluffinMuffin.Protocol.DataTypes;
using BluffinMuffin.Protocol.DataTypes.EventHandling;

namespace BluffinMuffin.Client.DataTypes.EventHandling
{
    public class MinMaxEventArgs : PlayerInfoEventArgs
    {
        public int Minimum { get; private set; }
        public int Maximum { get; private set; }

        public MinMaxEventArgs(PlayerInfo player, int min, int max) : base(player)
        {
            Minimum = min;
            Maximum = max;
        }
    }
}


text:
import { css } from '@emotion/react/macro'

const thing = function someName() {
  return css`
    color: hotpink;
  `
}


text:
package org.apache.camel.component.rest.openapi;

import java.util.Arrays;
import java.util.Collections;

import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.MethodSource;

import static org.assertj.core.api.Assertions.assertThat;

public class RestOpenApiEndpointUriParsingTest {

    @ParameterizedTest
    @MethodSource("parameters")
    public void shouldParseEndpointUri(String uri, String remaining, String specificationUri, String operationId) {
        final RestOpenApiComponent component = new RestOpenApiComponent();

        final RestOpenApiEndpoint endpoint = new RestOpenApiEndpoint(
                specificationUri, remaining, component,
                Collections.emptyMap());

        assertThat(endpoint.getSpecificationUri().toString()).isEqualTo(specificationUri);
        assertThat(endpoint.getOperationId()).isEqualTo(operationId);
    }

    public static Iterable<Object[]> parameters() {
        return Arrays.asList(params("rest-openapi:operation", "operation", "openapi.json", "operation"),
                params("rest-openapi:my-api.json#operation", "my-api.json#operation", "my-api.json", "operation"),
                params("rest-openapi:http://api.example.com/swagger.json#operation",
                        "http://api.example.com/swagger.json#operation", "http://api.example.com/swagger.json", "operation"));
    }

    static Object[] params(final String uri, final String remaining, final String specificationUri, final String operationId) {
        return new Object[] { uri, remaining, specificationUri, operationId };
    }
}


text:
ng-app-template
===============

##### Build

`gulp build`

Executes the tasks that are required to run the application in development. Compiles LESS files to CSS, runs test,
lint files, create angular template from html files.

The built files are placed in the `/build` directory

##### Dist

`gulp dist`

Executes the tasks that are required to run the application in production. Concatenates and minify application files
in bundle.js and vendor files in bundle_vendor.js.

The files are placed in the `/dist` directory

##### Watch

`gulp watch`

When a js file changes runs the build task


text:
<?php

namespace MA\LrmBundle\Listener;

use AncaRebeca\FullCalendarBundle\Model\FullCalendarEvent;
use MA\LrmBundle\Entity\CalendarEvent as MyCustomEvent;

class LoadDataListener
{
    /**
     * @param MyCustomEvent $calendarEvent
     *
     * @return FullCalendarEvent[]
     */

    public function loadData(MyCustomEvent $calendarEvent)
    {

/*        $title = $calendarEvent->getTitle();
        $startDate = $calendarEvent->getStartDate();
        $endDate = $calendarEvent->getEndDate();
        $filters = $calendarEvent->getFilters();

        //You may want do a custom query to populate the events

        $calendarEvent->addEvent(new MyCustomEvent('Event Title 1', new \DateTime()));
        $calendarEvent->addEvent(new MyCustomEvent('Event Title 2', new \DateTime()));*/

        return $calendarEvent->toArray();
    }
}


text:
/* global Promise require:true */
import axios        from 'axios'
const qs = require( 'qs' )

axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

export const apiDiscoverInfo = ( cityCode ) => {
    return new Promise( function( resolve, reject ) {
        axios.post( 'http://app.aplusoffice.cn/api/index', qs.stringify({
            'cityCode': cityCode,
            'page': 1
        }) )
        .then( response => {
            let resultData = response.data.resultData
            resolve( resultData )
        })
        .catch( error => {
            reject( error )
        })
    })
}


text:
//  Permission is hereby granted, free of charge, to any person obtaining a copy of
//  this software and associated documentation files (the "Software"), to deal in
//  the Software without restriction, including without limitation the rights to
//  use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
//  of the Software, and to permit persons to whom the Software is furnished to do
//  so, subject to the following conditions:

//  The above copyright notice and this permission notice shall be included in all
//  copies or substantial portions of the Software.

//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
//  SOFTWARE.

// VsPkg.cs : Implementation of YAMLLanguage
//

using System;
using System.Diagnostics;
using System.Globalization;
using System.Runtime.InteropServices;
using System.ComponentModel.Design;
using Microsoft.Win32;
using Microsoft.VisualStudio.Shell.Interop;
using Microsoft.VisualStudio.OLE.Interop;
using Microsoft.VisualStudio.Shell;

namespace Company.YAMLLanguage
{
    /// <summary>
    /// This is the class that implements the package exposed by this assembly.
    ///
    /// The minimum requirement for a class to be considered a valid package for Visual Studio
    /// is to implement the IVsPackage interface and register itself with the shell.
    /// This package uses the helper classes defined inside the Managed Package Framework (MPF)
    /// to do it: it derives from the Package class that provides the implementation of the
    /// IVsPackage interface and uses the registration attributes defined in the framework to
    /// register itself and its components with the shell.
    /// </summary>
    // This attribute tells the registration utility (regpkg.exe) that this class needs
    // to be registered as package.
    [PackageRegistration(UseManagedResourcesOnly = true)]
    // A Visual Studio component can be registered under different regitry roots; for instance
    // when you debug your package you want to register it in the experimental hive. This
    // attribute specifies the registry root to use if no one is provided to regpkg.exe with
    // the /root switch.
    [DefaultRegistryRoot("Software\\Microsoft\\VisualStudio\\9.0")]
    // This attribute is used to register the informations needed to show the this package
    // in the Help/About dialog of Visual Studio.
    [InstalledProductRegistration(false, "#110", "#112", "1.0", IconResourceID = 400)]
    // In order be loaded inside Visual Studio in a machine that has not the VS SDK installed,
    // package needs to have a valid load key (it can be requested at
    // http://msdn.microsoft.com/vstudio/extend/). This attributes tells the shell that this
    // package has a load key embedded in its resources.
    [ProvideLoadKey("Standard", "1.0", "YAML Language", "Company", 1)]
	[ProvideService(typeof(YAMLLanguageService), ServiceName = "YAML Language")]
	[ProvideLanguageService(typeof(YAMLLanguageService), "YAML Language", 106, MatchBracesAtCaret = true, EnableCommenting = true, DefaultToInsertSpaces = true, ShowMatchingBrace = true, RequestStockColors = false)]
	[ProvideLanguageExtension(typeof(YAMLLanguageService), ".yaml")]
    [Guid(GuidList.guidYAMLLanguagePkgString)]
    public sealed class YAMLLanguagePackage : Package
    {
        /// <summary>
        /// Default constructor of the package.
        /// Inside this method you can place any initialization code that does not require
        /// any Visual Studio service because at this point the package object is created but
        /// not sited yet inside Visual Studio environment. The place to do all the other
        /// initialization is the Initialize method.
        /// </summary>
        public YAMLLanguagePackage()
        {
            Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "Entering constructor for: {0}", this.ToString()));
        }

        /////////////////////////////////////////////////////////////////////////////
        // Overriden Package Implementation
        #region Package Members

        /// <summary>
        /// Initialization of the package; this method is called right after the package is sited, so this is the place
        /// where you can put all the initilaization code that rely on services provided by VisualStudio.
        /// </summary>
        protected override void Initialize()
        {
            Trace.WriteLine (string.Format(CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString()));
            base.Initialize();

			IServiceContainer serviceContainer = this;
			YAMLLanguageService languageService = new YAMLLanguageService();
			languageService.SetSite(this);
			serviceContainer.AddService(typeof(YAMLLanguageService), languageService, true);
        }
        #endregion

    }
}


text:
worker_processes 8
listen "/tmp/.sock", :backlog => 4096

preload_app true
GC.respond_to?(:copy_on_write_friendly=) and
  GC.copy_on_write_friendly = true

  before_fork do |server, worker|
    # the following is highly recomended for Rails + "preload_app true"
    # as there's no need for the master process to hold a connection
    #defined?(ActiveRecord::Base) and
    #  ActiveRecord::Base.connection.disconnect!

    # The following is only recommended for memory/DB-constrained
    # installations.  It is not needed if your system can house
    # twice as many worker_processes as you have configured.
    #
    # # This allows a new master process to incrementally
    # # phase out the old master process with SIGTTOU to avoid a
    # # thundering herd (especially in the "preload_app false" case)
    # # when doing a transparent upgrade.  The last worker spawned
    # # will then kill off the old master process with a SIGQUIT.
    # old_pid = "#{server.config[:pid]}.oldbin"
    # if old_pid != server.pid
    #   begin
    #     sig = (worker.nr + 1) >= server.worker_processes ? :QUIT : :TTOU
    #     Process.kill(sig, File.read(old_pid).to_i)
    #   rescue Errno::ENOENT, Errno::ESRCH
    #   end
    # end
    #
    # Throttle the master from forking too quickly by sleeping.  Due
    # to the implementation of standard Unix signal handlers, this
    # helps (but does not completely) prevent identical, repeated signals
    # from being lost when the receiving process is busy.
    # sleep 1
  end

  after_fork do |server, worker|
    # per-process listener ports for debugging/admin/migrations
    # addr = "127.0.0.1:#{9293 + worker.nr}"
    # server.listen(addr, :tries => -1, :delay => 5, :tcp_nopush => true)

    # the following is *required* for Rails + "preload_app true",
    #defined?(ActiveRecord::Base) and
    #  ActiveRecord::Base.establish_connection

    # if preload_app is true, then you may also want to check and
    # restart any other shared sockets/descriptors such as Memcached,
    # and Redis.  TokyoCabinet file handles are safe to reuse
    # between any number of forked children (assuming your kernel
    # correctly implements pread()/pwrite() system calls)
  end


text:
package com.example.brahma.coolweather.util;

import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.util.AttributeSet;

/**
 * Created by 10750 on 2017/8/3.
 */

public class MyDrawerLayout extends DrawerLayout {

    public MyDrawerLayout(Context context) {
        super(context, null);
    }

    public MyDrawerLayout(Context context, AttributeSet attrs) {
        super(context, attrs, 0);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//-2147482892,-2147481812
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);//756
        int widthSpec = MeasureSpec.makeMeasureSpec(widthSize, MeasureSpec.EXACTLY);//1073742580

        int heightSize = MeasureSpec.getSize(heightMeasureSpec);//1836
        int heightSpec = MeasureSpec.makeMeasureSpec(heightSize, MeasureSpec.EXACTLY);//1073743660

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}