text:
extern crate c_ares_sys;

bitflags!(
    #[doc = "Flags that may be provided on a call to `get_name_info()`."]
    flags NIFlags: i32 {
        #[doc = "Only the nodename portion of the FQDN is returned for local"]
        #[doc = "hosts."]
        const NOFQDN = c_ares_sys::ARES_NI_NOFQDN,

        #[doc = "The numeric form of the hostname is returned rather than the"]
        #[doc = "name."]
        const NUMERICHOST = c_ares_sys::ARES_NI_NUMERICHOST,

        #[doc = "An error is returned if the hostname cannot be found in the"]
        #[doc = "DNS."]
        const NAMEREQD = c_ares_sys::ARES_NI_NAMEREQD,

        #[doc = "The numeric form of the service is returned rather than the"]
        #[doc = "name."]
        const NUMERICSERV = c_ares_sys::ARES_NI_NUMERICSERV,

        #[doc = "The service name is to be looked up for the TCP protocol."]
        const TCP = c_ares_sys::ARES_NI_TCP,

        #[doc = "The service name is to be looked up for the UDP protocol."]
        const UDP = c_ares_sys::ARES_NI_UDP,

        #[doc = "The service name is to be looked up for the SCTP protocol."]
        const SCTP = c_ares_sys::ARES_NI_SCTP,

        #[doc = "The service name is to be looked up for the DCCP protocol."]
        const DCCP = c_ares_sys::ARES_NI_DCCP,

        #[doc = "The numeric form of the scope ID is returned rather than"]
        #[doc = "the name."]
        const NUMERICSCOPE = c_ares_sys::ARES_NI_NUMERICSCOPE,

        #[doc = "A hostname lookup is being requested."]
        const LOOKUPHOST = c_ares_sys::ARES_NI_LOOKUPHOST,

        #[doc = "A service name lookup is being requested."]
        const LOOKUPSERVICE = c_ares_sys::ARES_NI_LOOKUPSERVICE,
    }
);


text:
require 'unit_spec_helper'

describe Shoulda::Matchers::ActiveModel::ValidatePresenceOfMatcher, type: :model do
  context 'a model with a presence validation' do
    it 'accepts' do
      expect(validating_presence).to matcher
    end

    it 'does not override the default message with a blank' do
      expect(validating_presence).to matcher.with_message(nil)
    end
  end

  context 'a model without a presence validation' do
    it 'rejects' do
      expect(define_model(:example, attr: :string).new).not_to matcher
    end
  end

  context 'an ActiveModel class with a presence validation' do
    it 'accepts' do
      expect(active_model_validating_presence).to matcher
    end

    it 'does not override the default message with a blank' do
      expect(active_model_validating_presence).to matcher.with_message(nil)
    end
  end

  context 'an ActiveModel class without a presence validation' do
    it 'rejects' do
      expect(active_model).not_to matcher
    end

    it 'provides the correct failure message' do
      message = %{Expected errors to include "can't be blank" when attr is set to nil,\ngot no errors}

      expect { expect(active_model).to matcher }.to fail_with_message(message)
    end
  end

  context 'a has_many association with a presence validation' do
    it 'requires the attribute to be set' do
      expect(has_many_children(presence: true)).to validate_presence_of(:children)
    end
  end

  context 'a has_many association without a presence validation' do
    it 'does not require the attribute to be set' do
      expect(has_many_children(presence: false)).
        not_to validate_presence_of(:children)
    end
  end

  context 'a required has_and_belongs_to_many association' do
    before do
      define_model :child
      @model = define_model :parent do
        has_and_belongs_to_many :children
        validates_presence_of :children
      end.new
      create_table 'children_parents', id: false do |t|
        t.integer :child_id
        t.integer :parent_id
      end
    end

    it 'accepts' do
      expect(@model).to validate_presence_of(:children)
    end
  end

  context 'an optional has_and_belongs_to_many association' do
    before do
      define_model :child
      @model = define_model :parent do
        has_and_belongs_to_many :children
      end.new
      create_table 'children_parents', id: false do |t|
        t.integer :child_id
        t.integer :parent_id
      end
    end

    it 'rejects' do
      expect(@model).not_to validate_presence_of(:children)
    end
  end

  context "an i18n translation containing %{attribute} and %{model}" do
    before do
      stub_translation(
        "activerecord.errors.messages.blank",
        "Please enter a %{attribute} for your %{model}")
    end

    after { I18n.backend.reload! }

    it "does not raise an exception" do
      expect {
        expect(validating_presence).to validate_presence_of(:attr)
      }.to_not raise_exception
    end
  end

  if active_model_3_2?
    context 'a strictly required attribute' do
      it 'accepts when the :strict options match' do
        expect(validating_presence(strict: true)).to matcher.strict
      end

      it 'rejects when the :strict options do not match' do
        expect(validating_presence(strict: false)).not_to matcher.strict
      end
    end

    it 'does not override the default message with a blank' do
      expect(validating_presence(strict: true)).
        to matcher.strict.with_message(nil)
    end
  end

  context "an attribute with a context-dependent validation" do
    context "without the validation context" do
      it "does not match" do
        expect(validating_presence(on: :customisable)).not_to matcher
      end
    end

    context "with the validation context" do
      it "matches" do
        expect(validating_presence(on: :customisable)).to matcher.on(:customisable)
      end
    end
  end

  context 'an active_resource model' do
    context 'with the validation context' do
      it 'does not raise an exception' do
        expect {
          expect(active_resource_model).to validate_presence_of(:attr)
        }.to_not raise_exception
      end
    end
  end

  if rails_4_x?
    context 'against a pre-set password in a model that has_secure_password' do
      it 'raises a CouldNotSetPasswordError exception' do
        user_class = define_model :user, password_digest: :string do
          has_secure_password validations: false
          validates_presence_of :password
        end

        user = user_class.new
        user.password = 'something'

        error_class = Shoulda::Matchers::ActiveModel::CouldNotSetPasswordError
        expect do
          expect(user).to validate_presence_of(:password)
        end.to raise_error(error_class)
      end
    end
  end

  context 'when the attribute typecasts nil to an empty array' do
    it 'accepts' do
      model = define_active_model_class :example do
        attr_reader :foo

        def foo=(value)
          @foo = Array.wrap(value)
        end
      end

      expect(model.new).to validate_presence_of(:foo)
    end
  end

  def matcher
    validate_presence_of(:attr)
  end

  def validating_presence(options = {})
    define_model :example, attr: :string do
      validates_presence_of :attr, options
    end.new
  end

  def active_model(&block)
    define_active_model_class('Example', accessors: [:attr], &block).new
  end

  def active_model_validating_presence
    active_model { validates_presence_of :attr }
  end

  def has_many_children(options = {})
    define_model :child
    define_model :parent do
      has_many :children
      if options[:presence]
        validates_presence_of :children
      end
    end.new
  end

  def active_resource_model
    define_active_resource_class :foo, attr: :string do
      validates_presence_of :attr
    end.new
  end
end

redpajama_set_name: RedPajamaGithub


text:
@interface KRNewsTableViewCell ()
//新闻图片
@property (weak, nonatomic) IBOutlet UIImageView *imgsrcImageView;
//新闻标题
@property (weak, nonatomic) IBOutlet UILabel *lblTitle;
//新闻来源
@property (weak, nonatomic) IBOutlet UILabel *lblSource;
//回复数据
@property (weak, nonatomic) IBOutlet UILabel *lblReplyCount;
@property (strong, nonatomic) IBOutletCollection(UIImageView) NSArray *iconImagesView;

@end

@implementation KRNewsTableViewCell

- (void)awakeFromNib {
    [super awakeFromNib];

    //  设置安装图片原始比例显示,但是会有图片超出情况
    self.imgsrcImageView.contentMode = UIViewContentModeScaleAspectFill;
    //超出部分裁剪
    self.imgsrcImageView.clipsToBounds = YES;

}

- (void)setNewsModel:(KRNewsModel *)newsModel
{
    _newsModel = newsModel;

    //新闻图片
    [self.imgsrcImageView sd_setImageWithURL:[NSURL URLWithString:newsModel.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    //标题
    self.lblTitle.text = newsModel.title;
    //来源
    self.lblSource.text = newsModel.source;
    //回复数
    self.lblReplyCount.text = [NSString stringWithFormat:@"%zd", newsModel.replyCount];

    //遍历多图数组
    for (int i = 0; i < self.iconImagesView.count; i++) {
        //获取对应的图片字典
//        NSDictionary *dic = newsModel.imgextra[i];
//        //通过key获取图片地址
//        NSString *imagePath = [dic objectForKey:@"imgsrc"];

        //根据下标获取对应的模型
        KRPicture *picture = newsModel.imgextra[i];
        //获取对应的imageview
        UIImageView *imageView = self.iconImagesView[i];
        //给imageView设置网络图片
//        [imageView sd_setImageWithURL:[NSURL URLWithString:imagePath] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
         [imageView sd_setImageWithURL:[NSURL URLWithString:picture.imgsrc] placeholderImage:[UIImage imageNamed:@"placeholderImage"]];
    }

}

@end


text:
import { getScroll } from '@uiw/utils';
import getBoundingClientRect, {
  IBoundingClientRect,
} from './util/getBoundingClientRect';
import getOuterSizes from './util/getOuterSizes';
import { OverlayStyl, OverlayTriggerProps, Placement } from './';

type GetStyleOptions = {
  trigger: HTMLElement | IBoundingClientRect;
  popup: HTMLElement | IBoundingClientRect;
  placement: OverlayStyl['placement'];
  usePortal: OverlayTriggerProps['usePortal'];
  autoAdjustOverflow: OverlayTriggerProps['autoAdjustOverflow'];
};

export function getStyle(options: GetStyleOptions) {
  let {
    trigger: triggerDom,
    popup: popupDom,
    placement,
    usePortal,
    autoAdjustOverflow,
  } = options || {};
  const sty = {} as OverlayStyl;
  if (!triggerDom || !popupDom || !document) {
    return sty;
  }

  const winSizeHeight = Math.max(
    document.documentElement.clientHeight,
    window.innerHeight || 0,
  );
  const winSizeWidth = Math.max(
    document.documentElement.clientWidth,
    window.innerWidth || 0,
  );

  sty.placement = placement;
  const scrollTop = getScroll(
    (triggerDom as HTMLElement).ownerDocument!.documentElement,
    true,
  );
  const scrollLeft = getScroll(
    (triggerDom as HTMLElement).ownerDocument!.documentElement,
  );
  const trigger = {
    ...getBoundingClientRect(triggerDom as HTMLElement),
    ...getOuterSizes(triggerDom as HTMLElement),
  };
  const popup = {
    ...getBoundingClientRect(popupDom as HTMLElement),
    ...getOuterSizes(popupDom as HTMLElement),
  };

  const bottom = winSizeHeight - trigger.bottom;
  const right = winSizeWidth - trigger.left - trigger.width;

  sty.top = trigger.top + scrollTop;
  sty.left = trigger.left;

  if (!usePortal) {
    sty.top = trigger.offsetTop as number;
    sty.left = trigger.offsetLeft as number;
  }

  if (placement && /^(top)/.test(placement)) {
    sty.top -= popup.height;
  }
  if (placement && /^(right)/.test(placement)) {
    sty.left += trigger.width;
  }
  if (placement && /^(bottom)/.test(placement)) {
    sty.top += trigger.height;
  }
  if (placement && /^(left)/.test(placement)) {
    sty.left -= popup.width;
  }
  switch (sty.placement) {
    case 'bottomLeft':
    case 'topLeft':
      break;
    case 'bottom':
    // eslint-disable-next-line
    case 'top':
      sty.left = sty.left - (popup.width - trigger.width) / 2;
      break;
    case 'bottomRight':
    case 'topRight':
      sty.left = sty.left + scrollLeft + trigger.width - popup.width;
      break;
    case 'rightTop':
    case 'leftTop':
      break;
    case 'right':
    // eslint-disable-next-line
    case 'left':
      sty.top = sty.top - (popup.height - trigger.height) / 2;
      break;
    case 'rightBottom':
    case 'leftBottom':
      sty.top = sty.top - popup.height + trigger.height;
      break;
    default:
      break;
  }
  if (autoAdjustOverflow) {
    if (
      placement &&
      /^(top)/.test(placement) &&
      trigger.top < popup.height &&
      bottom > popup.height
    ) {
      sty.placement = placement.replace(/^top/, 'bottom') as Placement;
      sty.top = sty.top + popup.height + trigger.height;
    }
    if (
      placement &&
      /^(bottom)/.test(placement) &&
      bottom < popup.height &&
      trigger.top > popup.height
    ) {
      sty.placement = placement.replace(/^bottom/, 'top') as Placement;
      sty.top = sty.top - popup.height - trigger.height;
    }
    if (placement && /^(right)/.test(placement) && right < popup.width) {
      sty.placement = placement.replace(/^right/, 'left') as Placement;
      sty.left = sty.left - trigger.width - popup.width;
    }
    if (placement && /^(left)/.test(placement) && trigger.left < popup.width) {
      sty.placement = placement.replace(/^left/, 'right') as Placement;
      sty.left = sty.left + trigger.width + popup.width;
    }

    if (placement && /^(left|right)/.test(placement) && usePortal) {
      // Top
      if (
        (/(Top)$/.test(placement) && trigger.top < 0) ||
        (/(right|left)$/.test(placement) &&
          trigger.top + trigger.height / 2 < popup.height / 2) ||
        (/(Bottom)$/.test(placement) &&
          trigger.top + trigger.height < popup.height)
      ) {
        sty.top = scrollTop;
      }
    } else {
      // Top
      if (placement && /(Top)$/.test(placement) && trigger.top < 0) {
        sty.top -= trigger.top;
      }
      if (
        placement &&
        /(Bottom)$/.test(placement) &&
        trigger.bottom < popup.height
      ) {
        // eslint-disable-next-line
        sty.top = sty.top + (popup.height - trigger.bottom);
      }
      if (
        placement &&
        /(right|left)$/.test(placement) &&
        trigger.bottom - trigger.height / 2 < popup.height / 2
      ) {
        sty.top =
          sty.top + popup.height / 2 - (trigger.bottom - trigger.height / 2);
      }
    }
    // Bottom Public Part
    if (placement && /^(left|right)/.test(placement)) {
      if (/(Top)$/.test(placement) && bottom + trigger.height < popup.height) {
        sty.top = sty.top - (popup.height - bottom - trigger.height); // eslint-disable-line
      }
      if (
        /(right|left)$/.test(placement) &&
        bottom + trigger.height / 2 < popup.height / 2
      ) {
        sty.top = sty.top - (popup.height / 2 - bottom - trigger.height / 2); // eslint-disable-line
      }
      if (/(Bottom)$/.test(placement) && bottom < 0) {
        sty.top = sty.top + bottom; // eslint-disable-line
      }
    }

    if (placement && /^(top|bottom)/.test(placement) && usePortal) {
      // left
      if (
        (/(Left)$/.test(placement) && trigger.left < 0) ||
        (/(top|bottom)$/.test(placement) &&
          trigger.left + trigger.width / 2 < popup.width / 2) ||
        (/(Right)$/.test(placement) &&
          trigger.left + trigger.width < popup.width)
      ) {
        sty.left = scrollLeft;
      }
      // right
      if (
        /(top|bottom)$/.test(placement) &&
        right + trigger.width / 2 < popup.width / 2
      ) {
        sty.left = trigger.left + trigger.width + right - popup.width;
      }
    } else if (
      placement &&
      /(top|bottom)$/.test(placement) &&
      right + trigger.width / 2 < popup.width / 2
    ) {
      sty.left = sty.left + (right + trigger.width / 2 - popup.width / 2); // eslint-disable-line
    }
    if (placement && /^(top|bottom)/.test(placement)) {
      if (/(Left)$/.test(placement) && trigger.width + right < popup.width) {
        sty.left = sty.left - (popup.width - trigger.width - right);
      }
      if (/(Right)$/.test(placement) && right < 0) {
        sty.left = sty.left + right; // eslint-disable-line
      }
    }
  }
  return sty;
}


text:
/*************************************************************************/
/*  option_button.h                                                      */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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.                */
/*************************************************************************/

#ifndef OPTION_BUTTON_H
#define OPTION_BUTTON_H

#include "scene/gui/button.h"
#include "scene/gui/popup_menu.h"

class OptionButton : public Button {
	GDCLASS(OptionButton, Button);

	PopupMenu *popup = nullptr;
	int current = -1;
	bool fit_to_longest_item = true;
	Vector2 _cached_size;
	bool cache_refresh_pending = false;

	void _focused(int p_which);
	void _selected(int p_which);
	void _select(int p_which, bool p_emit = false);
	void _select_int(int p_which);
	void _refresh_size_cache();
	void _queue_refresh_cache();

	virtual void pressed() override;

protected:
	Size2 get_minimum_size() const override;
	void _notification(int p_what);
	bool _set(const StringName &p_name, const Variant &p_value);
	bool _get(const StringName &p_name, Variant &r_ret) const;
	void _get_property_list(List<PropertyInfo> *p_list) const;
	void _validate_property(PropertyInfo &p_property) const;
	static void _bind_methods();

public:
	// ATTENTION: This is used by the POT generator's scene parser. If the number of properties returned by `_get_items()` ever changes,
	// this value should be updated to reflect the new size.
	static const int ITEM_PROPERTY_SIZE = 5;

	void add_icon_item(const Ref<Texture2D> &p_icon, const String &p_label, int p_id = -1);
	void add_item(const String &p_label, int p_id = -1);

	void set_item_text(int p_idx, const String &p_text);
	void set_item_icon(int p_idx, const Ref<Texture2D> &p_icon);
	void set_item_id(int p_idx, int p_id);
	void set_item_metadata(int p_idx, const Variant &p_metadata);
	void set_item_disabled(int p_idx, bool p_disabled);
	void set_item_tooltip(int p_idx, const String &p_tooltip);

	String get_item_text(int p_idx) const;
	Ref<Texture2D> get_item_icon(int p_idx) const;
	int get_item_id(int p_idx) const;
	int get_item_index(int p_id) const;
	Variant get_item_metadata(int p_idx) const;
	bool is_item_disabled(int p_idx) const;
	bool is_item_separator(int p_idx) const;
	String get_item_tooltip(int p_idx) const;

	bool has_selectable_items() const;
	int get_selectable_item(bool p_from_last = false) const;

	void set_item_count(int p_count);
	int get_item_count() const;
	void set_fit_to_longest_item(bool p_fit);
	bool is_fit_to_longest_item() const;

	void add_separator(const String &p_text = "");

	void clear();

	void select(int p_idx);
	int get_selected() const;
	int get_selected_id() const;
	Variant get_selected_metadata() const;

	void remove_item(int p_idx);

	PopupMenu *get_popup() const;

	virtual void get_translatable_strings(List<String> *p_strings) const override;

	OptionButton(const String &p_text = String());
	~OptionButton();
};

#endif // OPTION_BUTTON_H


text:
@interface BigLetterView : NSView {
	NSColor *bgColor;
	NSString *string;
	NSMutableDictionary *attributes;
	BOOL italic;
	BOOL bold;
}
@property (strong) NSColor *bgColor;
@property (copy) NSString *string;
@property (assign, nonatomic) BOOL italic;
@property (assign, nonatomic) BOOL bold;

- (void)prepareAttributes;

- (IBAction)savePDF:(id)sender;
- (IBAction)toggleBold:(id)sender;
- (IBAction)toggleItalic:(id)sender;

@end


text:
// If you make changes to this file, you should also make the corresponding change in ReplicaSet.

package replicationcontroller

import (
	"context"
	"fmt"

	metainternalversion "k8s.io/apimachinery/pkg/apis/meta/internalversion"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/watch"
	"k8s.io/apiserver/pkg/registry/rest"
	api "k8s.io/kubernetes/pkg/apis/core"
)

// Registry is an interface for things that know how to store ReplicationControllers.
type Registry interface {
	ListControllers(ctx context.Context, options *metainternalversion.ListOptions) (*api.ReplicationControllerList, error)
	WatchControllers(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error)
	GetController(ctx context.Context, controllerID string, options *metav1.GetOptions) (*api.ReplicationController, error)
	CreateController(ctx context.Context, controller *api.ReplicationController, createValidation rest.ValidateObjectFunc) (*api.ReplicationController, error)
	UpdateController(ctx context.Context, controller *api.ReplicationController, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc) (*api.ReplicationController, error)
	DeleteController(ctx context.Context, controllerID string) error
}

// storage puts strong typing around storage calls
type storage struct {
	rest.StandardStorage
}

// NewRegistry returns a new Registry interface for the given Storage. Any mismatched
// types will panic.
func NewRegistry(s rest.StandardStorage) Registry {
	return &storage{s}
}

func (s *storage) ListControllers(ctx context.Context, options *metainternalversion.ListOptions) (*api.ReplicationControllerList, error) {
	if options != nil && options.FieldSelector != nil && !options.FieldSelector.Empty() {
		return nil, fmt.Errorf("field selector not supported yet")
	}
	obj, err := s.List(ctx, options)
	if err != nil {
		return nil, err
	}
	return obj.(*api.ReplicationControllerList), err
}

func (s *storage) WatchControllers(ctx context.Context, options *metainternalversion.ListOptions) (watch.Interface, error) {
	return s.Watch(ctx, options)
}

func (s *storage) GetController(ctx context.Context, controllerID string, options *metav1.GetOptions) (*api.ReplicationController, error) {
	obj, err := s.Get(ctx, controllerID, options)
	if err != nil {
		return nil, err
	}
	return obj.(*api.ReplicationController), nil
}

func (s *storage) CreateController(ctx context.Context, controller *api.ReplicationController, createValidation rest.ValidateObjectFunc) (*api.ReplicationController, error) {
	obj, err := s.Create(ctx, controller, createValidation, false)
	if err != nil {
		return nil, err
	}
	return obj.(*api.ReplicationController), nil
}

func (s *storage) UpdateController(ctx context.Context, controller *api.ReplicationController, createValidation rest.ValidateObjectFunc, updateValidation rest.ValidateObjectUpdateFunc) (*api.ReplicationController, error) {
	obj, _, err := s.Update(ctx, controller.Name, rest.DefaultUpdatedObjectInfo(controller), createValidation, updateValidation)
	if err != nil {
		return nil, err
	}
	return obj.(*api.ReplicationController), nil
}

func (s *storage) DeleteController(ctx context.Context, controllerID string) error {
	_, _, err := s.Delete(ctx, controllerID, nil)
	return err
}


text:
// Copyright (c) 2018-2020 Alexander Bogarsukov.
// Licensed under the MIT license. See the LICENSE.md file in the project root for more information.

using System;
using System.Runtime.CompilerServices;
using System.Threading;

namespace UnityFx.Async.CompilerServices
{
#if !NET35

	/// <summary>
	/// Provides an object that waits for the completion of an asynchronous operation. This type and its members are intended for compiler use only.
	/// </summary>
	/// <seealso cref="IAsyncOperation{TResult}"/>
	public struct AsyncAwaiter<TResult> : INotifyCompletion
	{
		private readonly IAsyncOperation<TResult> _op;
		private readonly SynchronizationContext _syncContext;

		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncAwaiter{T}"/> struct.
		/// </summary>
		public AsyncAwaiter(IAsyncOperation<TResult> op)
		{
			_op = op;
			_syncContext = SynchronizationContext.Current;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="AsyncAwaiter{T}"/> struct.
		/// </summary>
		public AsyncAwaiter(IAsyncOperation<TResult> op, SynchronizationContext syncContext)
		{
			_op = op;
			_syncContext = syncContext;
		}

		/// <summary>
		/// Gets a value indicating whether the underlying operation is completed.
		/// </summary>
		/// <value>The operation completion flag.</value>
		public bool IsCompleted => _op.IsCompleted;

		/// <summary>
		/// Returns the source result value.
		/// </summary>
		/// <returns>Returns the underlying operation result.</returns>
		public TResult GetResult()
		{
			if (!_op.IsCompletedSuccessfully)
			{
				_op.ThrowIfNonSuccess();
			}

			return _op.Result;
		}

		/// <inheritdoc/>
		public void OnCompleted(Action continuation)
		{
			_op.AddCompletionCallback(continuation, _syncContext);
		}
	}

#endif
}


text:
using System;
using NodaTime;

namespace StudentsCalendar.Core
{
	/// <summary>
	/// Metody rozszerzające dla <see cref="IsoDyaOfWeek"/>.
	/// </summary>
	/// <remarks>
	/// Przez indeks dnia tygodnia rozumiemy wartość z przedziału 0..6, gdzie 0 odpowiada
	/// poniedziałkowi(<see cref="IsoDayOfWeek.Monday"/>), a 6 niedzieli(<see cref="IsoDayOfWeek.Sunday"/>).
	/// </remarks>
	public static class IsoDayOfWeekExtension
	{
		/// <summary>
		/// Konwertuje <see cref="IsoDayOfWeek"/> na odpowiedni indeks.
		/// </summary>
		/// <param name="day">Dzień tygodnia do skonwertowania.</param>
		/// <returns>Indeks odpowiadający parametrowi.</returns>
		public static int ToIndex(this IsoDayOfWeek day)
		{
			if (day == IsoDayOfWeek.None)
			{
				throw new ArgumentOutOfRangeException("Cannot convert value None to index.");
			}
			return (int)day - 1;
		}

		/// <summary>
		/// Konwertuje indeks na <see cref="IsoDayOfWeek"/>.
		/// </summary>
		/// <param name="index">Indeks, uzyskany przez wywołanie <see cref="ToIndex"/>.</param>
		/// <returns>Dzień tygodnia odpowiadający danemu indeksowi.</returns>
		public static IsoDayOfWeek ToDayOfWeek(this int index)
		{
			if (index < 0 || index > 6)
			{
				throw new ArgumentOutOfRangeException("index", "Index value must be in range 0..6 to be correct IsoDayOfWeek.");
			}
			return (IsoDayOfWeek)(index + 1);
		}
	}
}


text:
package com.acme;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import static org.springframework.xd.module.ModuleType.*;

import org.hamcrest.Matcher;
import org.junit.Test;

import org.springframework.xd.module.ModuleDefinition;
import org.springframework.xd.module.ModuleDefinitions;
import org.springframework.xd.module.options.DefaultModuleOptionsMetadataResolver;
import org.springframework.xd.module.options.ModuleOption;
import org.springframework.xd.module.options.ModuleOptionsMetadata;
import org.springframework.xd.module.options.ModuleOptionsMetadataResolver;

/**
 * Tests expected module properties are present.
 */
public class ExampleModulePropertiesTest {

	private String moduleName = "siDslModule";

	@Test
	public void testModuleProperties() {
		ModuleOptionsMetadataResolver moduleOptionsMetadataResolver = new DefaultModuleOptionsMetadataResolver();
		String resource = "classpath:/";
		ModuleDefinition definition = ModuleDefinitions.simple(moduleName, processor, resource);
		ModuleOptionsMetadata metadata = moduleOptionsMetadataResolver.resolve(definition);

		assertThat(
				metadata,
				containsInAnyOrder(moduleOptionNamed("prefix"), moduleOptionNamed("suffix"),
						moduleOptionNamed("prefixOnly")));
	}

	public static Matcher<ModuleOption> moduleOptionNamed(String name) {
		return hasProperty("name", equalTo(name));
	}
}


text:
package com.hazelcast.ringbuffer.impl.operations;

import com.hazelcast.config.Config;
import com.hazelcast.config.RingbufferConfig;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.ringbuffer.OverflowPolicy;
import com.hazelcast.ringbuffer.Ringbuffer;
import com.hazelcast.ringbuffer.impl.RingbufferService;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.spi.serialization.SerializationService;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import static com.hazelcast.ringbuffer.OverflowPolicy.FAIL;
import static com.hazelcast.ringbuffer.OverflowPolicy.OVERWRITE;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class AddAllOperationTest extends HazelcastTestSupport {

    private NodeEngineImpl nodeEngine;
    private SerializationService serializationService;
    private Ringbuffer<Object> ringbuffer;
    private RingbufferService ringbufferService;

    @Before
    public void setup() {
        RingbufferConfig rbConfig = new RingbufferConfig("foo").setCapacity(10).setTimeToLiveSeconds(10);

        Config config = new Config().addRingBufferConfig(rbConfig);

        HazelcastInstance hz = createHazelcastInstance(config);
        nodeEngine = getNodeEngineImpl(hz);
        serializationService = getSerializationService(hz);
        ringbuffer = hz.getRingbuffer(rbConfig.getName());
        ringbufferService = nodeEngine.getService(RingbufferService.SERVICE_NAME);
    }

    @Test
    public void whenFailOverflowPolicy_andNoRemainingCapacity() throws Exception {
        for (int k = 0; k < ringbuffer.capacity(); k++) {
            ringbuffer.add("item");
        }

        Data item = serializationService.toData("newItem");

        AddAllOperation addOperation = getAddAllOperation(new Data[]{item}, FAIL);
        addOperation.run();

        assertFalse(addOperation.shouldNotify());
        assertFalse(addOperation.shouldBackup());
        assertEquals(-1L, addOperation.getResponse());
    }

    @Test
    public void whenFailOverflowPolicy_andRemainingCapacity() throws Exception {
        for (int k = 0; k < ringbuffer.capacity() - 1; k++) {
            ringbuffer.add("item");
        }

        Data item = serializationService.toData("newItem");

        AddAllOperation addOperation = getAddAllOperation(new Data[]{item}, FAIL);
        addOperation.run();

        assertTrue(addOperation.shouldNotify());
        assertTrue(addOperation.shouldBackup());
        assertEquals(ringbuffer.tailSequence(), addOperation.getResponse());
    }

    @Test
    public void whenOverwritePolicy_andNoRemainingCapacity() throws Exception {
        for (int k = 0; k < ringbuffer.capacity(); k++) {
            ringbuffer.add("item");
        }

        Data item = serializationService.toData("newItem");

        AddAllOperation addOperation = getAddAllOperation(new Data[]{item}, OVERWRITE);
        addOperation.run();

        assertTrue(addOperation.shouldNotify());
        assertTrue(addOperation.shouldBackup());
        assertEquals(ringbuffer.tailSequence(), addOperation.getResponse());
    }

    @Test
    public void whenOverwritePolicy_andRemainingCapacity() throws Exception {
        for (int k = 0; k < ringbuffer.capacity() - 1; k++) {
            ringbuffer.add("item");
        }

        Data item = serializationService.toData("newItem");

        AddAllOperation addOperation = getAddAllOperation(new Data[]{item}, OVERWRITE);
        addOperation.run();

        assertTrue(addOperation.shouldNotify());
        assertTrue(addOperation.shouldBackup());
        assertEquals(ringbuffer.tailSequence(), addOperation.getResponse());
    }

    private AddAllOperation getAddAllOperation(Data[] items, OverflowPolicy policy) {
        AddAllOperation op = new AddAllOperation(ringbuffer.getName(), items, policy);
        op.setPartitionId(ringbufferService.getRingbufferPartitionId(ringbuffer.getName()));
        op.setNodeEngine(nodeEngine);
        return op;
    }
}


text:
package com.ppdai.open.core;

/**
 * Created by xuzhishen on 2016/3/16.
 */
public class Result {
    /**
     * 是否成功
     */
    private boolean sucess;

    /**
     * 报文内容
     */
    private String context;

    /**
     * 错误信息
     */
    private String errorMessage ;

    public boolean isSucess() {
        return sucess;
    }

    public void setSucess(boolean sucess) {
        this.sucess = sucess;
    }

    public String getContext() {
        return context;
    }

    public void setContext(String context) {
        this.context = context;
    }

    public String getErrorMessage() {
        return errorMessage;
    }

    public void setErrorMessage(String errorMessage) {
        this.errorMessage = errorMessage;
    }
}


text:
/**
 * Provides access to the native Geolocation API when running on a device. There are three implementations of this API:
 *
 * - Sencha Packager
 * - [PhoneGap](http://docs.phonegap.com/en/1.4.1/phonegap_device_device.md.html)
 * - Browser
 *
 * This class will automatically select the correct implementation depending on the device your application is running on.
 *
 * ## Examples
 *
 * Getting the current location:
 *
 *     Ext.device.Geolocation.getCurrentPosition({
 *         success: function(position) {
 *             console.log(position.coords);
 *         },
 *         failure: function() {
 *             console.log('something went wrong!');
 *         }
 *     });
 *
 * Watching the current location:
 *
 *     Ext.device.Geolocation.watchPosition({
 *         frequency: 3000, // Update every 3 seconds
 *         callback: function(position) {
 *             console.log('Position updated!', position.coords);
 *         },
 *         failure: function() {
 *             console.log('something went wrong!');
 *         }
 *     });
 *
 * @mixins Ext.device.geolocation.Abstract
 */
Ext.define('Ext.device.Geolocation', {
    singleton: true,

    requires: [
        'Ext.device.Communicator',
        'Ext.device.geolocation.Cordova',
        'Ext.device.geolocation.Simulator'
    ],

    constructor: function() {
        var browserEnv = Ext.browser.is;
        if (browserEnv.WebView) {
            if (browserEnv.Cordova) {
                return Ext.create('Ext.device.geolocation.Cordova');
            }
        }

        return Ext.create('Ext.device.geolocation.Simulator');
    }
});


text:
// Design Basic Game Solo Challenge

// This is a solo challenge

// Your mission description:
// Overall mission: Stop the baby from crying
// Goals: Stop the baby from crying
// Characters: Dad, Baby
// Objects: Dad, Baby
// Functions: moveUp, moveDown, moveLeft, moveRight, cry, soothe

// Pseudocode
// Declare an object named dad with a random start position position.
//  - def methods to have the player move up,right,down,left.
// Declare an object named baby with a random position.
// - def method to have the baby cry if it is far away from the dad, and stop otherwise.
//
//

// Initial Code

var dad = {
posX: Math.floor((Math.random() * 100) + 1),
posY: Math.floor((Math.random() * 100) + 1),
move: function(way){
	if(way === "up"){
		dad.posY += 10;
	}
	else if(way === "right"){
		dad.posX += 10;
	}
	else if(way === "down"){
		dad.posY -= 10;
	}
	else if(way === "left"){
		dad.posX -=10;
	}
}
}

var baby = {
posX: Math.floor((Math.random() * 100) + 1),
posY: Math.floor((Math.random() * 100) + 1),
cry: "Wahhh",
soothe: function(posX, posY) {
	if(baby.posX - dad.posX >= 10 || baby.posY - dad.posY >= 10){
		console.log(baby.cry)
	}
	else if(baby.posX - dad.posX < 10 && baby.posY - dad.posY < 10){
		console.log("Dad is nearby!")
	}
	}
}

console.log("The dad's start point is " + dad.posX + ", " + dad.posY + ".");
console.log("The baby's position is " + baby.posX + ", " + baby.posY + ".");
baby.soothe(baby.posX, baby.posY);
dad.move("up");
dad.move("right");
console.log("The dad's current position is " + dad.posX + ", " + dad.posY + ".");
baby.soothe(baby.posX, baby.posY);
dad.move("down");
dad.move("right");
console.log("The dad's current position is " + dad.posX + ", " + dad.posY + ".");
baby.soothe(baby.posX, baby.posY);

// Refactored Code

// Reflection
/*
What was the most difficult part of this challenge?

The most difficult part of this challenge was determining what I wanted to do and getting the code to work in the correct manner.
Initially my game had 3 objects and the goal was to find the baby and put it in a crib, but I was having some difficulties early on
so I simplified it and went with the minimalist approach.

What did you learn about creating objects and functions that interact with one another?

I learned that I can call on different elements of an object within another object. For instance
in the soothe function which was a function for the baby I used the dad.posX in the formula. I also
learned that you can only use the function that are created within a given object on that object only.

Did you learn about any new built-in methods you could use in your refactored solution? If so, what were they and how do they work?

My code was pretty simple so I did not refactor it or find any built-in methods.

How can you access and manipulate properties of objects?

You can access and manipulate properties of objects by taking the object and using .property after it to alter it.
If I wanted to set the dad's posX to 0 I would write dad.posX = 0; or if I wanted to add a new property to the baby such as eye color
I would write baby.eyecolor = "brown".
*/


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    // [Optional] Power your app with Local Datastore. For more info, go to
    // https://parse.com/docs/ios_guide#localdatastore/iOS
    [Parse enableLocalDatastore];

    // Initialize Parse.
    [Parse setApplicationId:@"6zCpTgtIMp9RdZvQGLzdqcvw3VqNAbBi4SX2sZGN"
                  clientKey:@"4KrUWPcgGUlgXSE6uqwaRN8aYglyiuxmnomWyivZ"];

    // [Optional] Track statistics around application opens.
    [PFAnalytics trackAppOpenedWithLaunchOptions:launchOptions];

    // ...
//    PFQuery *query = [PFQuery queryWithClassName:@"Default"];
//    [query getObjectInBackgroundWithId:@"UYs0sixfYO" block:^(PFObject *object, NSError *error) {
//        PFFile *file = object[@"exercises"];
//        [file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
//            NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
//            NSLog(@"Check this shiz out: %@", array);
//                              }];
//    }];

    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text: Supported by the National Park Service and National Conference of State Historic Preservation Officers.


text:
interface CssExports {
  'lockedPerk': string;
  'partialDescription': string;
  'plug': string;
  'plugInfo': string;
  'plugTitle': string;
  'requirement': string;
  'unselectable': string;
}
export const cssExports: CssExports;
export default cssExports;


text:
require 'spec_helper'

describe TmCheckout do
  it 'has a version number' do
    expect(TmCheckout::VERSION).not_to be nil
  end

  describe TmCheckout::Wizard do
    subject do
      TmCheckout::Wizard.gather do
        # prices
        fr1 3.11
        ap1 5.00, 3 => 4.50
        cf1 11.23

        # buy 1 get 1 free
        ___ fr1, ap1
      end
    end

    describe '.rules' do
      subject { super().rules }

      it do
        is_expected.to eq(
          :FR1 => [3.11],
          :AP1 => [5.0, 3 => 4.5],
          :CF1 => [11.23],
          :___ => [:FR1, :AP1]
        )
      end
    end
  end

  describe TmCheckout::Calculator do
    let(:instance) do
      TmCheckout::Calculator.new do
        # prices
        fr1 3.11
        ap1 5.00, 3 => 4.50
        cf1 11.23

        # buy 1 get 1 free
        ___ fr1
      end
    end

    subject{ instance }

    context 'when incorrect rules passed' do
      subject{ lambda{ TmCheckout::Calculator.new('rules') } }

      it{ is_expected.to raise_error(TmCheckout::IncorrectRules) }
    end

    describe '.scan' do
      context 'when incorrect code passed' do
        subject{ lambda{ TmCheckout::Calculator.new.scan('code') } }

        it do
          is_expected.to raise_error(TmCheckout::WrongCode)
            .with_message('code is not among [:FR1, :AP1, :CF1]')
        end
      end

      context 'when lowercased code passed' do
        subject{ lambda{ TmCheckout::Calculator.new.scan('fr1') } }

        it do
          is_expected.to_not raise_error
        end
      end
    end

    describe '.price_for' do
      subject{ instance.price_for :fr1 }

      context 'when no discounters specified' do
        before{ instance.rules = {fr1: 3.0} }

        context 'when single item is purchased' do
          before{ instance.scan :fr1 }
          it{ is_expected.to eq 3.0 }
        end

        context 'when 5 items is purchased' do
          before{ 5.times { instance.scan :fr1 } }
          it{ is_expected.to eq 3.0 }
        end

        context 'when 50 items is purchased' do
          before{ 50.times{ instance.scan :fr1 } }
          it{ is_expected.to eq 3.0 }
        end
      end

      context 'when discounters specified as single hash' do
        before{ instance.rules = {fr1: [3.0, 10 => 2.0]} }

        context 'when single item is purchased' do
          before{ instance.scan :fr1 }
          it{ is_expected.to eq 3.0 }
        end

        context 'when 5 items is purchased' do
          before{ 5.times { instance.scan :fr1 } }
          it{ is_expected.to eq 3.0 }
        end

        context 'when 50 items is purchased' do
          before{ 50.times{ instance.scan :fr1 } }
          it{ is_expected.to eq 2.0 }
        end
      end

      context 'when discounters specified as multiple hashes' do
        before{ instance.rules = {fr1: [3.0, 4 => 2.0, 30 => 1.0]} }

        context 'when single item is purchased' do
          before{ instance.scan :fr1 }
          it{ is_expected.to eq 3.0 }
        end

        context 'when 5 items is purchased' do
          before{ 5.times { instance.scan :fr1 } }
          it{ is_expected.to eq 2.0 }
        end

        context 'when 50 items is purchased' do
          before{ 50.times{ instance.scan :fr1 } }
          it{ is_expected.to eq 1.0 }
        end
      end
    end

    describe '.codes' do
      before{ 3.times { instance.scan :fr1 } }

      context 'when called directly' do
        subject{ instance.codes }
        it{ is_expected.to eq [:FR1]*3 }
      end

      context 'when called thru alias' do
        subject{ instance.to_a }
        it{ is_expected.to eq [:FR1]*3 }
      end
    end

    describe '.calculate' do
      context 'when called directly' do
        subject{ instance.calculate }

        context 'with sequence 1' do
          before do
            instance.scan :fr1
            instance.scan :ap1
            instance.scan :fr1
            instance.scan :cf1
          end

          it{ is_expected.to eq 22.25 }
        end

        context 'with sequence 2' do
          before do
            instance.scan :fr1
            instance.scan :fr1
          end

          it{ is_expected.to eq 3.11 }
        end

        context 'with sequence 3' do
          before do
            instance.scan :ap1
            instance.scan :ap1
            instance.scan :fr1
            instance.scan :ap1
          end

          it{ is_expected.to eq 16.61 }
        end
      end
    end
  end
end


text:
package org.alicebot.ab;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class NodemapperOperator {
    /**
     * number of branches from node
     *
     * @param node    Nodemapper object
     * @return        number of branches
     */
    public static int size(Nodemapper node) {
        HashSet set = new HashSet();
        if (node.shortCut) set.add("<THAT>");
        if (node.key != null) set.add(node.key);
        if (node.map != null) set.addAll(node.map.keySet());
        return set.size();
    }

    /**
     * insert a new link from this node to another, by adding a key, value pair
     *
     * @param node       Nodemapper object
     * @param key        key word
     * @param value      word maps to this next node
     */
   public static void put(Nodemapper node, String key, Nodemapper value) {
       if (node.map != null) {
           node.map.put(key, value);
       }
       else { // node.type == unary_node_mapper
             node.key = key;
             node.value = value;

       }
   }

    /**
     * get the node linked to this one by the word key
     *
     * @param node     Nodemapper object
     * @param key      key word to map
     * @return         the mapped node or null if the key is not found
     */
   public static Nodemapper get(Nodemapper node, String key) {
       if (node.map != null) {
           return node.map.get(key);
       }
       else {// node.type == unary_node_mapper
           if (key.equals(node.key)) return node.value;
           else return null;
       }

   }

    /**
     * check whether a node contains a particular key
     *
     * @param node    Nodemapper object
     * @param key     key to test
     * @return        true or false
     */
   public static boolean containsKey(Nodemapper node, String key)  {
       //System.out.println("containsKey: Node="+node+" Map="+node.map);
       if (node.map != null) {
           return node.map.containsKey(key) ;
       }
       else {// node.type == unary_node_mapper
           if (key.equals(node.key)) return true;
           else return false;
       }
   }

    /**
     * print all node keys
     *
     * @param node Nodemapper object
     */
    public static void printKeys (Nodemapper node)  {
        Set set = keySet(node);
        Iterator iter = set.iterator();
        while (iter.hasNext()) {
            System.out.println("" + iter.next());
        }
    }

    /**
     * get key set of a node
     *
     * @param node    Nodemapper object
     * @return        set of keys
     */
    public static Set<String> keySet(Nodemapper node) {
        if (node.map != null) {
            return node.map.keySet();
        }
        else {// node.type == unary_node_mapper
            Set set = new HashSet<String>();
            if (node.key != null) set.add(node.key);
            return set;
        }

    }

    /**
     * test whether a node is a leaf
     *
     * @param node     Nodemapper object
     * @return         true or false
     */
    public static boolean isLeaf(Nodemapper node) {
        return (node.category != null);
    }

    /**
     * upgrade a node from a singleton to a multi-way map
     *
     * @param node  Nodemapper object
     */
    public static void upgrade(Nodemapper node) {
        //System.out.println("Upgrading "+node.id);
        //node.type = MagicNumbers.hash_node_mapper;
        node.map = new HashMap<String, Nodemapper>();
        node.map.put(node.key, node.value);
        node.key = null;
        node.value = null;
    }
}


text:
- [ ] I've read the [guidelines for Contributing to Roots Projects](https://github.com/roots/guidelines/blob/master/CONTRIBUTING.md)
- [ ] This is a feature request
- [ ] This is a bug report
- [ ] This request isn't a duplicate of an [existing issue](https://github.com/roots/trellis/issues)
- [ ] I've read the [docs](https://roots.io/trellis/docs) and followed them (if applicable)
- [ ] This is not a personal support request that should be posted on the [Roots Discourse](https://discourse.roots.io/c/trellis) forums

Replace any `X` with your information.

---

**What is the current behavior?**

X

**What is the expected or desired behavior?**

X

---

## Bug report

(delete this section if not applicable)

**Please provide steps to reproduce, including full log output:**

X

**Please describe your local environment:**

Ansible version: X

OS: X

Vagrant version: X

**Where did the bug happen? Development or remote servers?**

X

**Please provide a repository or your `wordpress_sites` config (if possible):**

X

**Is there a related [Discourse](https://discourse.roots.io/) thread or were any utilized (please link them)?**

X

---

## Feature Request

(delete this section if not applicable)

**Please provide use cases for changing the current behavior:**

X

**Other relevant information:**

X


text:
#ifndef __VCGLIB_POLYGON_SUPPORT
#define __VCGLIB_POLYGON_SUPPORT

#include <vcg/simplex/face/jumping_pos.h>
#include <vcg/space/planar_polygon_tessellation.h>

namespace vcg {
namespace tri {
    /// \ingroup trimesh

    /// \headerfile polygon_support.h vcg/complex/algorithms/polygon_support.h

    /// \brief This class is used convert between polygonal meshes and triangular meshes

    /**
    This class contains two members that allow to build a triangular mesh from a polygonal mesh
    and viceversa. In a trimesh, the generic polygons with n sides are codified represented by
    tagging the internal edge of the face as 'faux' with the SetF.
    */

    template <class TriMeshType,class PolyMeshType >
    class PolygonSupport{
      typedef typename TriMeshType::FaceIterator  TriFaceIterator;
      typedef typename PolyMeshType::FaceIterator PolyFaceIterator;
      typedef typename TriMeshType::VertexIterator  TriVertexIterator;
      typedef typename PolyMeshType::VertexIterator PolyVertexIterator;
      typedef typename TriMeshType::CoordType::ScalarType Scalar;

    public:
    /**
    Given a tri mesh (with per-face normals and FF connectivity),
    merges flat faces into larger polygons.
    The merging is done only by setting the faux bit
    **/
    static void MergeFlatFaces(TriMeshType & tm, double tolerance = 0.1E-4)
    {
        typedef typename TriMeshType::FaceType FaceType;
        Scalar minDist = 1 - Scalar(tolerance);
        for (TriFaceIterator fi=tm.face.begin(); fi!=tm.face.end(); fi++) {
            FaceType *fa = &*fi;
            for (int w=0; w<3; w++) {
                FaceType *fb = fa->FFp(w);
                if ( (fb>fa) && (fa->N()*fb->N() > minDist) ) {
                    fa->SetF( w );
                    fb->SetF( fa->FFi(w) ); // reciprocate
                }
            }
        }
    }

    /**
    Import a  trianglemesh from a polygon mesh
    **/
    static void ImportFromPolyMesh(TriMeshType & tm,  PolyMeshType & pm)
    {
      tri::RequirePolygonalMesh(pm);
      std::vector<typename PolyMeshType::CoordType> points;

      // the vertices are the same, simply import them
      PolyVertexIterator vi;
      TriVertexIterator tvi = Allocator<TriMeshType>::AddVertices(tm,pm.vert.size());
      int cnt = 0;
      for(tvi = tm.vert.begin(),vi = pm.vert.begin(); tvi != tm.vert.end(); ++tvi,++vi,++cnt)
        if(!(*vi).IsD()) (*tvi).ImportData(*vi); else tri::Allocator<TriMeshType>::DeleteVertex(tm,(*tvi));

      for(PolyFaceIterator fi = pm.face.begin(); fi != pm.face.end(); ++fi)
      {
        if(!((*fi).IsD())){
          points.clear();
          for(int i  = 0; i < (*fi).VN(); ++i) {
            typename	PolyMeshType::VertexType * v = (*fi).V(i);
            points.push_back(v->P());
          }
          std::vector<int> faces;
          TessellatePlanarPolygon3(points,faces);
          for(size_t i = 0; i<faces.size();i+=3){
            TriFaceIterator tfi = Allocator<TriMeshType>::AddFace(tm,
                  tri::Index(pm,(*fi).V( faces[i+0] )),
                  tri::Index(pm,(*fi).V( faces[i+1] )),
                  tri::Index(pm,(*fi).V( faces[i+2] )) );

            tfi->ImportData(*fi);
            // set the F flags
            if( (faces[i  ]+1)%points.size() != size_t(faces[i+1])) (*tfi).SetF(0);
            if( (faces[i+1]+1)%points.size() != size_t(faces[i+2])) (*tfi).SetF(1);
            if( (faces[i+2]+1)%points.size() != size_t(faces[i  ])) (*tfi).SetF(2);
          }
        }
      }
    }

    /**
    \brief Import a polygon mesh from a triangle mesh

    It assumes that the mesh has the faux edges bit set for a polygonal mesh and that have the FFAdjacency already computed.
    **/
    static void ImportFromTriMesh( PolyMeshType & pm,  TriMeshType & tm)
    {
      tri::RequirePolygonalMesh(pm);
      tri::RequireTriangularMesh(tm);

      tri::RequireCompactness(tm);
      tri::RequireFFAdjacency(tm);
      tri::UpdateFlags<TriMeshType>::FaceClearV(tm);
      // the vertices are the same, simply import them
        int cnt = 0;
        typename TriMeshType ::ConstVertexIterator tvi;
        typename PolyMeshType::VertexIterator vi  = tri::Allocator<PolyMeshType>::AddVertices(pm,tm.vert.size());
        for(tvi = tm.vert.begin(); tvi != tm.vert.end(); ++tvi,++vi,++cnt)
            (*vi).ImportData(*tvi);

        // convert the faces
        typename TriMeshType::FaceIterator tfi;
        face::JumpingPos<typename TriMeshType::FaceType> p;

        for( tfi = tm.face.begin(); tfi != tm.face.end(); ++tfi) if(!(*tfi).IsV())
        {
            std::vector<typename TriMeshType::VertexPointer> vs;// vertices of the polygon
            ExtractPolygon(&*tfi,vs);
            std::reverse(vs.begin(),vs.end());
            //now vs  contains all the vertices of the polygon (still in the trimesh)
            if (vs.size()==0)continue;
            typename PolyMeshType::FaceIterator pfi =  tri::Allocator<PolyMeshType>::AddFaces(pm,1);
            (*pfi).Alloc(vs.size());
            for(size_t i  = 0 ; i < vs.size(); ++i)
                (*pfi).V(i) = ( typename PolyMeshType::VertexType*)  & pm.vert[vs[i]-&(*tm.vert.begin())];
            if(tri::HasPerFaceColor(tm) && tri::HasPerFaceColor(pm)) pfi->C()=tfi->C();
            if(tri::HasPerFaceQuality(tm) && tri::HasPerFaceQuality(pm)) pfi->Q()=tfi->Q();
        }
    }
    /// \brief Collect tris and verts of a polygonal face marked by FauxEdges
    ///
    /// Given a face pointer, it builds a vector with all the face and vertex pointers
    /// around the polygonal face determined by the current FAUX-EDGE markings.
    /// It assumes that the mesh is 2Manifold and has FF adjacency already computed
    /// per face visited flag cleared.
    /// NOTE: All the faces touched are marked as visited and it assumes that you
    /// do not call this function on a visited face.
    static void ExtractPolygon(typename TriMeshType::FacePointer tfp,
                               std::vector<typename TriMeshType::VertexPointer> &vs,
                               std::vector<typename TriMeshType::FacePointer> &fs)
    {
        vs.clear();
        fs.clear();
        // find a non faux edge
        int se = -1;
        for(int i=0; i<3; i++) if (!( tfp->IsF(i))) { se = i; break;}

        // all faux edges return an empty vertex vector!
        if(se==-1) return;
        if(tfp->IsV()) return;

        // initialize a pos on the first non faux edge
        face::Pos<typename TriMeshType::FaceType> start(tfp,se,tfp->V(se));
        face::Pos<typename TriMeshType::FaceType> p(start);

        fs.push_back(p.F());
        p.F()->SetV();

        do
        {
            assert(!p.F()->IsF(p.E()));
            vs.push_back(p.V());
            p.FlipE();
            while( p.F()->IsF(p.E()) )
            {
                p.FlipF();
                if(!p.F()->IsV()) {
                  fs.push_back(p.F());
                  p.F()->SetV();
                }
                p.FlipE();
            }
            p.FlipV();
        } while(p!=start);
        //assert(vs.size() == fs.size()+2);
    }
    static void ExtractPolygon(typename TriMeshType::FacePointer tfp, std::vector<typename TriMeshType::VertexPointer> &vs)
    {
      std::vector<typename TriMeshType::FacePointer> fs;
      ExtractPolygon(tfp,vs,fs);
    }
}; // end of struct
}} // end namespace tri

#endif // __VCGLIB_TRI_CLIP


text:
// Morse library
// 10/3/2015 by Peter Dalmaris <peter@txplore.com>
// Source repository: https://github.com/futureshocked/arduino_sbs/tree/master/HowToMakeALibrary/Morse

#include <Morse.h>
#include <Arduino.h>

//Create the constructors
Morse::Morse()
{
  _dot_length_ms  = 50;                 //The duration of a dot
  _dash_legth     = 3 * _dot_length_ms; // One dash is three dots
  _part_gap       = 1 * _dot_length_ms; // Space between parts of a letter is one dot
  _letter_space   = 3 * _dot_length_ms; // Space between letters
  _words_space    = 7 * _dot_length_ms; // Space between words
  _led_pin        = 13;
  pinMode(_led_pin, OUTPUT);
}

Morse::Morse(int dot_duration)
{
  _dot_length_ms  = dot_duration;       //The duration of a dot
  _dash_legth     = 3 * _dot_length_ms; // One dash is three dots
  _part_gap       = 1 * _dot_length_ms; // Space between parts of a letter is one dot
  _letter_space   = 3 * _dot_length_ms; // Space between letters
  _words_space    = 7 * _dot_length_ms; // Space between words
  _led_pin        = 13;
  pinMode(_led_pin, OUTPUT);

}

Morse::Morse(int dot_duration, int led_pin)
{
  _dot_length_ms  = dot_duration;       //The duration of a dot
  _dash_legth     = 3 * _dot_length_ms; // One dash is three dots
  _part_gap       = 1 * _dot_length_ms; // Space between parts of a letter is one dot
  _letter_space   = 3 * _dot_length_ms; // Space between letters
  _words_space    = 7 * _dot_length_ms; // Space between words
  _led_pin        = led_pin;
  pinMode(_led_pin, OUTPUT);
}

void Morse::transmit(String text_to_transmit)
{
  //For each letter, find its code and transmit it
  for (int letter = 0; letter < text_to_transmit.length(); letter++)
  {
    int code_index = 0;
    for (int i = 0; i < TOTAL_MORSE_CODE_ITEMS; i++)
    {
       if (codes[i].character == text_to_transmit[letter])
       {
         code_index = i;
         break;
       }
    }
    Serial.print(text_to_transmit[letter]);
    Serial.print("-->");
    //Make flashes for letter at index code_index
    for (int i = 0; i < codes[code_index].code.length(); i++)
    {
      Serial.print(codes[code_index].code[i]);
      flash_led(codes[code_index].code[i]);

    }
      flash_led(' '); //Space in between words is three units
      Serial.println();
  }
}

void Morse::flash_led(char code)
{
    digitalWrite( _led_pin, HIGH);
    if (code == '.')
        delay(_dot_length_ms);
    else if (code == ' ')
        delay(_words_space);
    else
        delay(_dash_legth);

    digitalWrite( _led_pin, LOW);
    delay(_letter_space);
}


text:
require 'spec_helper'

describe Polterheist do
end


text:
#pragma once

/**
 * Disable copy macro.
 */
#define DISABLE_COPY(CLASS_NAME)\
  CLASS_NAME(CLASS_NAME &&) = delete; \
  CLASS_NAME(const CLASS_NAME &other) = delete; \
  CLASS_NAME& operator=(const CLASS_NAME &other) = delete


text:
namespace hsql {
  enum InsertType {
    kInsertValues,
    kInsertSelect
  };

  // Represents SQL Insert statements.
  // Example: "INSERT INTO students VALUES ('Max', 1112233, 'Musterhausen', 2.3)"
  struct InsertStatement : SQLStatement {
    InsertStatement(InsertType type);
    virtual ~InsertStatement();

    InsertType type;
    char* tableName;
    std::vector<char*>* columns;
    std::vector<Expr*>* values;
    SelectStatement* select;
  };

} // namsepace hsql

#endif


text:
#ifndef CPP_GRPC_RETRY_H
#define CPP_GRPC_RETRY_H

#include <set>

#include "async_grpc/common/optional.h"
#include "async_grpc/common/time.h"
#include "grpc++/grpc++.h"

namespace async_grpc {

using common::Duration;
using common::optional;

using RetryStrategy = std::function<optional<Duration>(
    int /* failed_attempts */, const ::grpc::Status &)>;
using RetryIndicator =
    std::function<bool(int /* failed_attempts */, const ::grpc::Status &)>;
using RetryDelayCalculator = std::function<Duration(int /* failed_attempts */)>;

RetryStrategy CreateRetryStrategy(RetryIndicator retry_indicator,
                                  RetryDelayCalculator retry_delay_calculator);

RetryIndicator CreateLimitedRetryIndicator(int max_attempts);
RetryIndicator CreateUnlimitedRetryIndicator();
RetryIndicator CreateUnlimitedRetryIndicator(
    const std::set<::grpc::StatusCode> &unrecoverable_codes);
RetryDelayCalculator CreateBackoffDelayCalculator(Duration min_delay,
                                                  float backoff_factor);
RetryDelayCalculator CreateConstantDelayCalculator(Duration delay);
RetryStrategy CreateLimitedBackoffStrategy(Duration min_delay,
                                           float backoff_factor,
                                           int max_attempts);
RetryStrategy CreateUnlimitedConstantDelayStrategy(Duration delay);
RetryStrategy CreateUnlimitedConstantDelayStrategy(
    Duration delay, const std::set<::grpc::StatusCode> &unrecoverable_codes);

bool RetryWithStrategy(RetryStrategy retry_strategy,
                       std::function<::grpc::Status()> op,
                       std::function<void()> reset = nullptr);

}  // namespace async_grpc

#endif  // CPP_GRPC_RETRY_H


text:
package org.jboss.netty.handler.codec.replay;

import org.jboss.netty.buffer.ChannelBufferFactory;
import org.jboss.netty.buffer.DynamicChannelBuffer;

/**
 * @author The Netty Project
 * @author Trustin Lee
 *
 * @version $Rev: 2080 $, $Date: 2010-01-26 18:04:19 +0900 (Tue, 26 Jan 2010) $
 *
 */
class UnsafeDynamicChannelBuffer extends DynamicChannelBuffer {

    UnsafeDynamicChannelBuffer(ChannelBufferFactory factory) {
        super(factory.getDefaultOrder(), 256, factory);
    }

    @Override
    protected void checkReadableBytes(int minReaderRemaining) {
        // Do not check here - ReplayingDecoderBuffer will check.
    }
}


text:
<?php

namespace GuzzleHttp\Adapter;

use GuzzleHttp\Exception\RequestException;

/**
 * Decorates a regular AdapterInterface object and creates a
 * ParallelAdapterInterface object that sends multiple HTTP requests serially.
 */
class FakeParallelAdapter implements ParallelAdapterInterface
{
    /** @var AdapterInterface */
    private $adapter;

    /**
     * @param AdapterInterface $adapter Adapter used to send requests
     */
    public function __construct(AdapterInterface $adapter)
    {
        $this->adapter = $adapter;
    }

    public function sendAll(\Iterator $transactions, $parallel)
    {
        foreach ($transactions as $transaction) {
            try {
                $this->adapter->send($transaction);
            } catch (RequestException $e) {
                // no op for batch transaction
            }
        }
    }
}


text:
#include <QtCore/QDebug>
#include "net/AbstractNetHandler.h"
#include "net/NetAbstract.h"

NetAbstract::NetAbstract(QObject * parent)
    : QObject(parent)
{

}

void NetAbstract::registerHandler(const QString & packetName, AbstractNetHandler * handler)
{
    if (handlerExists(packetName, handler)) return;

    if (!m_netHandlers.contains(packetName))
        m_netHandlers.insert(packetName, new QList<AbstractNetHandler*>());

    m_netHandlers.value(packetName)->append(handler);
}

bool NetAbstract::handlerExists(const QString & packetName, AbstractNetHandler * handler)
{
    return m_netHandlers.contains(packetName) &&
        (handler == NULL || m_netHandlers.value(packetName)->contains(handler));
}


text:
include_recipe "postgresql::server"

# Probably don't need this, given we have IDENT security
file "/root/postgresql.passwd" do
  content node['postgresql']['password']['postgres']
end

file "/var/tmp/create_chiminey_db.sql" do
  action :create_if_missing
  owner "postgres"
  content <<-EOH
  CREATE USER bdphpc;
  CREATE DATABASE bdphpc OWNER bdphpc;
  EOH
end

bash "create_my_chiminey_db" do
  # previous event-driven version never got triggered for me (SB)
  user "postgres"
  code "psql < /var/tmp/create_chiminey_db.sql"
end


text:
""" Singleton """

class Singleton(type):
  def __call__(cls, *args):
    if not hasattr(cls, 'instance'):
      cls.instance = super(Singleton, cls).__call__(*args)
    return cls.instance


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = createLoggerMiddleware;
var DEFAULT_LOGGER = function defaultLogger(_ref) {
  var oldState = _ref.oldState,
      newState = _ref.newState,
      change = _ref.change;

  console.log(change.name, oldState, newState);
};

function createLoggerMiddleware() {
  var logger = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : DEFAULT_LOGGER;

  return function loggerMiddleware(next, oldState, change) {
    for (var _len = arguments.length, args = Array(_len > 3 ? _len - 3 : 0), _key = 3; _key < _len; _key++) {
      args[_key - 3] = arguments[_key];
    }

    var newState = next.apply(undefined, [oldState, change].concat(args));
    logger({ oldState: oldState, newState: newState, change: change, args: args });
    return newState;
  };
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Parmelia dubia f. marginata Hillmann

### Remarks
null


text:
#ifndef HK_EASE_PENETRATION_ACTION_H
#define HK_EASE_PENETRATION_ACTION_H

#include <Physics2012/Dynamics/Action/hkpUnaryAction.h>
#include <Common/Base/hkBase.h>

	/// You can use this action to reduce CPU hits that occur when a new body is added to a hkpWorld in a penetrating state.
	///
	/// When you add a simple shape, like a box, and place it in a way that it deeply intersects with around 8 triangles of a landscape
	/// mesh -- then you can expect high numbers of unjustified TOI events being handled. In a simple test case we performed, there were
	/// around 10 TOIs for a moving-quality body, and around 80 for a critical-quality body.
	///
	/// This utility controls the m_allowedPenetrationDepth property of a rigid body over a short time of, e.g., a few seconds, to
	/// avoid those unneeded TOIs and to allow the bodies to recover from penetration with normal collision response.
	/// After m_timePassed reaches m_duration, the m_alloedPenetrationDepth of the hkpRigidBody is set back to its original value.
	///
	/// Additionally this utility can also reduce the strength at which the solver corrects inter-body penetrations. This is done by
	/// iterating over all contact points, and reducing the penetration distance, that is later fed into the constraint solver.
	/// As the result, less jitter may occur when bodies recover from penetration.
class hkpEasePenetrationAction : public hkpUnaryAction
{
	public:
	HK_DECLARE_CLASS_ALLOCATOR(HK_MEMORY_CLASS_BASE);
			// This allows you to specify duration of the action. Other values can be set directly after the action is constructed.
		hkpEasePenetrationAction(hkpEntity* entity, hkReal duration);

		virtual	~hkpEasePenetrationAction();

			// hkpAction implementation.
		virtual void applyAction( const hkStepInfo& stepInfo );

		virtual hkpAction* clone( const hkArray<hkpEntity*>& newEntities, const hkArray<hkpPhantom*>& newPhantoms ) const ;

	public:

			/// Duration of this action. After the time passes the action removes itself from the hkpWorld.
		hkReal m_duration;

			/// Initial multiplier for the m_entity's m_allowedPenetrationDepth. It's reduced linearly with time to reach 1.0f at the end of m_duration.
		hkReal m_initialAllowedPenetrationDepthMultiplier;
			/// Initial added value for the m_entity's m_allowedPenetrationDepth. It's reduced linearly with time to reach 0.0f at the end of m_duration.
		hkReal m_initialAdditionalAllowedPenetrationDepth;

			/// Shall the action soften the solver response too, by reducing penetration distances for contact points.
		bool m_reducePenetrationDistance;

			/// Initial distance multiplier applied for all penetrating contact points. It's reduced linearly with time to reach 1.0f at the end of m_duration.
			/// Don't use small values, as this may cause bodies to fall through the ground. It's set to 0.2 by default.
		hkReal m_initialContactDepthMultiplier;

	private:
			/// Time passed since the action was added to the world.
		hkReal m_timePassed;
			/// Original allowed penetration depth of the m_entity.
		hkReal m_originalAllowedPenetrationDepth;
};

#endif // HK_EASE_PENETRATION_ACTION_H

/*
 * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20140907)
 *
 * Confidential Information of Havok.  (C) Copyright 1999-2014
 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok
 * Logo, and the Havok buzzsaw logo are trademarks of Havok.  Title, ownership
 * rights, and intellectual property rights in the Havok software remain in
 * Havok and/or its suppliers.
 *
 * Use of this software for evaluation purposes is subject to and indicates
 * acceptance of the End User licence Agreement for this product. A copy of
 * the license is included with this software and is also available at www.havok.com/tryhavok.
 *
 */


text:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/order_record_entry"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/m4399_rec_record_entry_bg"
    android:clickable="true"
    android:focusable="true"
    android:gravity="center"
    android:paddingBottom="4dp"
    android:paddingLeft="6dp"
    android:paddingRight="6dp"
    android:paddingTop="4dp"
    android:text="@string/m4399_rec_entry_text"
    android:textColor="#ffffff"
    android:textSize="16sp" >

</TextView>


text:
var react = require('react');
var Tiles = require('react-tiles');,
var resolver = require('react-tiles/src/react-router-resolver');

var App = React.createClass({
  render(){
    return (
      <Tiles resolver={ resolver } { ...this.props } />
    )
  }
});

module.exports = App;


text:
"""The task manager window to display and kill processes"""

from PyQt4 import QtGui, QtCore
from Core.globals import mainWidgets
from Dockable import *

class TaskManagerWindow(Dockable):
    def __init__(self, parent = None):
        """
        Create a task manager window.
        """
        Dockable.__init__(self, parent=parent)

        self.widget = QtGui.QWidget()
        self.layout = QtGui.QVBoxLayout()
        self.list = QtGui.QListWidget()
        self.button = QtGui.QPushButton("Kill")
        self.layout.addWidget(self.list)
        self.layout.addWidget(self.button)
        self.widget.setLayout(self.layout)

        self.setWidget(self.widget)

        self.connect(self.button, QtCore.SIGNAL("clicked()"), self.kill)
        self.connect(self,
                     QtCore.SIGNAL("topLevelChanged(bool)"),
                     self.dockChanged)

    def dockChanged(self, floating):
        """
        Handle a change in the dock location or state.
        """
        if floating:
            self.setWindowOpacity(0.8)

    def kill(self):
        """
        Kill the selected process.
        """
        for item in self.list.selectedItems():
            entry = str(item.text())
            device, pid, status = entry.split("\t", 2)
            client = mainWidgets["client"]
            if client:
                client.send("kill " + pid)

    def update(self, device, pid, status):
        """
        Update the pid and status of a device in the list.
        """
        entries = self.list.findItems(device+"\t", QtCore.Qt.MatchStartsWith)
        entry = device + "\t" + pid + "\t" + status
        if entries:
            if entry == entries[0]:
                return
            entries[0].setText(entry)
        else:
            self.list.addItem(entry)

        mainWidgets["main"].updateProgressBar()

    def getPID(self, device):
        """
        Get the pid from a device in the list.
        """
        entries = self.list.findItems(device+"\t", QtCore.Qt.MatchStartsWith)
        if entries:
            device, pid, status = str(entries[0].text()).split("\t", 2)
            return pid
        else:
            return False

    def clear(self):
        """
        Clear the list.
        """
        self.list.clear()


text:
namespace ModelMatcher.Assertions
{
    using System.Collections.Generic;

    public static class SingleItemMatchextensions
    {
        public static void ShouldMatch<T>(this T itemUnderTest, T expected)
        {
            var matchResult = SingleItemMatcher.MatchSingleItem(itemUnderTest, expected, MatchCondition.Match);

            if (!matchResult.Matches)
                throw new DidNotMatch(matchResult.Exceptions);
        }

        public static void ShouldMatch<T>(this T itemUnderTest, T expected, IEnumerable<Condition> conditions)
        {
            var matchResult = SingleItemMatcher.MatchSingleItem(itemUnderTest, expected, MatchCondition.Match,
                conditions);

            if (!matchResult.Matches)
                throw new DidNotMatch(matchResult.Exceptions);
        }

        public static void ShouldMatchNonDefaultProperties<T>(this T itemUnderTest, T expected)
        {
            var matchResult = SingleItemMatcher.MatchSingleItem(itemUnderTest, expected,
                MatchCondition.IgnoreIfDefaultInExpectedModel);

            if (!matchResult.Matches)
                throw new DidNotMatch(matchResult.Exceptions);
        }

        public static void ShouldMatchNonDefaultProperties<T>(this T itemUnderTest, T expected, IEnumerable<Condition> conditions)
        {
            var matchResult = SingleItemMatcher.MatchSingleItem(itemUnderTest, expected,
                MatchCondition.IgnoreIfDefaultInExpectedModel, conditions);

            if (!matchResult.Matches)
                throw new DidNotMatch(matchResult.Exceptions);
        }
    }
}


text:
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Autofac;
using Xunit.Abstractions;
using Xunit.Sdk;

namespace Xunit.Ioc.Autofac.TestFramework
{
    public class AutofacTestAssemblyRunner : TestAssemblyRunner<AutofacTestCase>
    {
        public AutofacTestAssemblyRunner(IContainer container, ITestAssembly testAssembly, IEnumerable<AutofacTestCase> testCases, IMessageSink diagnosticMessageSink, IMessageSink executionMessageSink,
            ITestFrameworkExecutionOptions executionOptions)
            : base(testAssembly, testCases, diagnosticMessageSink, executionMessageSink, executionOptions)
        {
            _container = container;
        }

        protected override string GetTestFrameworkDisplayName()
        {
            return "Autofac Test Framework";
        }

        protected override Task<RunSummary> RunTestCollectionAsync(IMessageBus messageBus, ITestCollection testCollection, IEnumerable<AutofacTestCase> testCases, CancellationTokenSource cancellationTokenSource)
        {
            return new AutofacTestCollectionRunner(_container, testCollection, testCases, DiagnosticMessageSink, messageBus, TestCaseOrderer, new ExceptionAggregator(Aggregator), cancellationTokenSource)
                .RunAsync();
        }

        private readonly IContainer _container;
    }
}


text:
package com.xinyu.mwp.adapter;

import android.content.Context;
import android.content.DialogInterface;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.xinyu.mwp.R;
import com.xinyu.mwp.adapter.base.BaseListViewAdapter;
import com.xinyu.mwp.adapter.viewholder.BaseViewHolder;
import com.xinyu.mwp.constant.Constant;
import com.xinyu.mwp.entity.MyPushOrderEntity;
import com.xinyu.mwp.entity.MyPushOrderItemEntity;
import com.xinyu.mwp.listener.OnItemChildViewClickListener;
import com.xinyu.mwp.util.LogUtil;
import com.xinyu.mwp.util.ToastUtils;
import com.xinyu.mwp.view.CustomDialog;

import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;

import java.util.List;

/**
 * Created by Benjamin on 17/1/11.
 */

public class MyPushOrderAdapter extends BaseListViewAdapter<MyPushOrderItemEntity> {

    private static final int TYPE_WIN = 0; //本月,本周胜率
    private static final int TYPE_ORDER = 1; //好友订单信息

    public MyPushOrderAdapter(Context context) {
        super(context);
    }

    /**
     * 自定义itemType
     *
     * @param position 条目位置
     * @return type类型
     */
    @Override
    public int getItemViewType(int position) {
        int viewType;
        if (position < 2) {
            viewType = TYPE_WIN;
        } else {
            viewType = TYPE_ORDER;
        }
        return viewType;
    }

    @Override
    public int getViewTypeCount() {
        return 2;
    }

    @Override
    protected BaseViewHolder<MyPushOrderItemEntity> getViewHolder(int position) {
        int itemViewType = getItemViewType(position);
        if (itemViewType == TYPE_WIN) {
            return new MyPushOrderViewHolder(context);
        } else {
            return new MyPushOrderInfoViewHolder(context);
        }
    }

    class MyPushOrderViewHolder extends BaseViewHolder<MyPushOrderItemEntity> {
        @ViewInject(R.id.sucOdds)
        private TextView sucOdds;
        @ViewInject(R.id.sucCount)
        private TextView sucCount;
        @ViewInject(R.id.sucProfit)
        private TextView sucProfit;
        @ViewInject(R.id.progressBar)
        private ProgressBar progressBar;

        public MyPushOrderViewHolder(Context context) {
            super(context);
        }

        @Override
        protected int layoutId() {
            return R.layout.item_mypushorder;
        }

        @Override
        protected void update(MyPushOrderItemEntity data) {
            sucOdds.setText("本月胜率:" + data.getSucOdds() + "%");
            sucCount.setText("胜场:" + data.getSucCount());
            LogUtil.d(" sss+data.getProfit()" + data.getProfit());
            float sp = 0;
            if (data.getProfit() != null) {
                sp = Float.parseFloat(data.getProfit());
            }

            if (sp < 0) {
                sucProfit.setTextColor(context.getResources().getColor(R.color.default_green));
                progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.bg_progress_default_green));
            } else {
                sucProfit.setTextColor(context.getResources().getColor(R.color.default_red));
                progressBar.setProgressDrawable(context.getResources().getDrawable(R.drawable.bg_progress_default_red));
            }
            //防止进度条太短,很难看。
            progressBar.setProgress(Math.abs((int) sp) < 10 ? 10 : Math.abs((int) sp));
            sucProfit.setText(data.getProfit() + "%");
        }
    }

    //推单,好友推单详情
    private class MyPushOrderInfoViewHolder extends BaseViewHolder<MyPushOrderItemEntity> {
        @ViewInject(R.id.tv_push_order_name)
        private TextView orderNname;
        @ViewInject(R.id.tv_push_order_open_time)
        private TextView time;
        @ViewInject(R.id.tv_push_order_price)
        private TextView orderPrice;

        public MyPushOrderInfoViewHolder(Context context) {
            super(context);
        }

        @Override
        protected int layoutId() {
            return R.layout.item_push_order_info;
        }

        @Override
        protected void update(MyPushOrderItemEntity data) {
            time.setText(data.getTime());
            orderPrice.setText(data.getOrderPrice());
            orderNname.setText(data.getOrderNname());
        }

//        去掉跟单功能
//        @Event(value = R.id.btn_follow_order)
//        private void click(View v) {
//           //需要判断被点击的是买涨,买跌,然后跟单
//            showDialog(Constant.TYPE_BUY_MINUS);
//        }
//        private void showDialog(int type) {
//            String buyType = null;
//            if (type == Constant.TYPE_BUY_MINUS) {
//                buyType = "买跌";
//            } else if (type == Constant.TYPE_BUY_PLUS) {
//                buyType = "买涨";
//            }
//            CustomDialog.Builder builder = new CustomDialog.Builder(context, type);
//
//            builder.setPositiveButton(buyType, new DialogInterface.OnClickListener() {
//                public void onClick(DialogInterface dialog, int which) {
//                    dialog.dismiss();
//                    //买涨点击后操作
//                    ToastUtils.show(context, "买跌");
//                }
//            });
//
//            builder.setNegativeButton("取消",
//                    new android.content.DialogInterface.OnClickListener() {
//                        public void onClick(DialogInterface dialog, int which) {
//                            dialog.dismiss();
//                            //取消点击后操作
//                            ToastUtils.show(context, "取消");
//                        }
//                    });
//            builder.create().show();
//        }
    }
}


text:
package org.springframework.boot.docs.features.testing.springbootapplications.usingapplicationarguments;

import org.junit.jupiter.api.Test;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.test.context.SpringBootTest;

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

@SpringBootTest(args = "--app.test=one")
class MyApplicationArgumentTests {

	@Test
	void applicationArgumentsPopulated(@Autowired ApplicationArguments args) {
		assertThat(args.getOptionNames()).containsOnly("app.test");
		assertThat(args.getOptionValues("app.test")).containsOnly("one");
	}

}


text:
package com.badr.infodota.stream.fragment;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.MenuItemCompat;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.ActionMenuView;
import android.support.v7.widget.PopupMenu;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;

import com.badr.infodota.BeanContainer;
import com.badr.infodota.R;
import com.badr.infodota.base.activity.ListHolderActivity;
import com.badr.infodota.stream.adapter.pager.TwitchPagerAdapter;
import com.badr.infodota.stream.api.Stream;
import com.badr.infodota.stream.service.TwitchService;

/**
 * User: ABadretdinov
 * Date: 07.03.14
 * Time: 15:18
 */
public class TwitchHolder extends Fragment { //pullToRefresh + FloatingActionButton.

    public static final int REFRESH = 6001;
    public static final int ADD_CHANNEL = 322;
    public static final int PLAYER_TYPE = 1403;
    private TwitchPagerAdapter adapter;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.twitch_holder, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        menu.clear();
        ActionMenuView actionMenuView = ((ListHolderActivity) getActivity()).getActionMenuView();
        actionMenuView.getMenu().clear();

        MenuItem add = menu.add(1, ADD_CHANNEL, 0, R.string.add_channel);
        add.setIcon(R.drawable.ic_menu_add);
        MenuItemCompat.setShowAsAction(add, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (Build.VERSION.SDK_INT < 14) {
            preferences.edit().putInt("player_type", 1).commit();
            actionMenuView.setVisibility(View.GONE);
        } else {
            actionMenuView.setVisibility(View.VISIBLE);
            int currentPlayer = preferences.getInt("player_type", 0);
            Menu actionMenu = actionMenuView.getMenu();
            MenuItem player = actionMenu.add(1, PLAYER_TYPE, 1, getResources().getStringArray(R.array.player_types)[currentPlayer]);
            MenuItemCompat.setShowAsAction(player, MenuItemCompat.SHOW_AS_ACTION_ALWAYS);
            actionMenuView.setOnMenuItemClickListener(new ActionMenuView.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    return onOptionsItemSelected(menuItem);
                }
            });
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == ADD_CHANNEL) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            final EditText textView = new EditText(getActivity());
            ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            textView.setLayoutParams(lp);
            textView.setHint(R.string.channel_name);
            builder.setTitle(R.string.add_channel);
            builder.setView(textView);
            builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.setPositiveButton(R.string.add, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    String channelName = textView.getText().toString();
                    if (!TextUtils.isEmpty(channelName)) {
                        TwitchService twitchService = BeanContainer.getInstance().getTwitchService();
                        Stream stream = new Stream();
                        stream.setChannel(channelName);
                        twitchService.addStream(getActivity(), stream);
                    }
                    dialog.dismiss();
                    adapter.updateList();
                }
            });
            builder.show();
            return true;
        } else if (item.getItemId() == PLAYER_TYPE) {
            final MenuItem player = item;
            PopupMenu popup = new PopupMenu(getActivity(), getActivity().findViewById(item.getItemId()));
            final Menu menu = popup.getMenu();
            String[] playerTypes = getResources().getStringArray(R.array.player_types);
            for (int i = 0; i < playerTypes.length; i++) {
                menu.add(2, i, 0, playerTypes[i]);
            }
            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem menuItem) {
                    player.setTitle(menuItem.getTitle());
                    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    preferences.edit().putInt("player_type", menuItem.getItemId()).commit();
                    return true;
                }
            });
            popup.show();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        if (!prefs.getBoolean("twitchDialogShowed", false)) {
            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
            builder.setTitle(R.string.attention);
            builder.setMessage(R.string.twitch_attention);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
                    SharedPreferences.Editor editor = prefs.edit();
                    editor.putBoolean("twitchDialogShowed", true);
                    editor.commit();
                    dialog.dismiss();
                }
            });
            builder.show();
        }
        initPager();
    }

    public TwitchPagerAdapter getAdapter() {
        return adapter;
    }

    private void initPager() {

        adapter = new TwitchPagerAdapter(getChildFragmentManager(), getActivity());

        ViewPager pager = (ViewPager) getView().findViewById(R.id.pager);
        pager.setAdapter(adapter);
        pager.setOffscreenPageLimit(1);

        TabLayout tabLayout = (TabLayout) getView().findViewById(R.id.tabs);
        tabLayout.setupWithViewPager(pager);
    }
}


text:
var lingon = require('../../../lib/boot');

lingon.config.sourcePath = 'source-renamed';
lingon.config.buildPath = 'build-renamed';


text:
import Constants from 'expo-constants';
import prettyFormat from 'pretty-format';
import parseErrorStack from 'react-native/Libraries/Core/Devtools/parseErrorStack';
import symbolicateStackTrace from 'react-native/Libraries/Core/Devtools/symbolicateStackTrace';
import ReactNodeFormatter from './format/ReactNodeFormatter';
export const EXPO_CONSOLE_METHOD_NAME = '__expoConsoleLog';
async function serializeLogDataAsync(data, level) {
    let serializedValues;
    let includesStack = false;
    if (_stackTraceLogsSupported()) {
        if (_isUnhandledPromiseRejection(data, level)) {
            const rawStack = data[0];
            const syntheticError = { stack: rawStack };
            const stack = await _symbolicateErrorAsync(syntheticError);
            if (!stack.length) {
                serializedValues = _stringifyLogData(data);
            }
            else {
                // NOTE: This doesn't handle error messages with newlines
                const errorMessage = rawStack.split('\n')[1];
                serializedValues = [
                    {
                        message: `[Unhandled promise rejection: ${errorMessage}]`,
                        stack: _formatStack(stack),
                    },
                ];
                includesStack = true;
            }
        }
        else if (data.length === 1 && data[0] instanceof Error) {
            // When there's only one argument to the log function and that argument is an error, we
            // include the error's stack. If there's more than one argument then we don't include the
            // stack because it's not easy to display nicely in our current UI.
            const serializedError = await _serializeErrorAsync(data[0]);
            serializedValues = [serializedError];
            includesStack = serializedError.hasOwnProperty('stack');
        }
        else if (level === 'warn' || level === 'error') {
            // For console.warn and console.error it is usually useful to know the stack that leads to the
            // warning or error, so we provide this information to help out with debugging
            const error = _captureConsoleStackTrace();
            // ["hello", "world"] becomes "hello, world"
            const errorMessage = _stringifyLogData(data).join(', ');
            const serializedError = await _serializeErrorAsync(error, errorMessage);
            serializedValues = [serializedError];
            includesStack = serializedError.hasOwnProperty('stack');
        }
        else {
            serializedValues = _stringifyLogData(data);
        }
    }
    else {
        serializedValues = _stringifyLogData(data);
    }
    return {
        body: [...serializedValues],
        includesStack,
    };
}
function _stringifyLogData(data) {
    return data.map((item) => {
        // define the max length for log msg to be first 10000 characters
        const LOG_MESSAGE_MAX_LENGTH = 10000;
        const result = typeof item === 'string' ? item : prettyFormat(item, { plugins: [ReactNodeFormatter] });
        // check the size of string returned
        if (result.length > LOG_MESSAGE_MAX_LENGTH) {
            let truncatedResult = result.substring(0, LOG_MESSAGE_MAX_LENGTH);
            // truncate the result string to the max length
            truncatedResult += `...(truncated to the first ${LOG_MESSAGE_MAX_LENGTH} characters)`;
            return truncatedResult;
        }
        else {
            return result;
        }
    });
}
async function _serializeErrorAsync(error, message) {
    if (message == null) {
        message = error.message;
    }
    if (!error.stack || !error.stack.length) {
        return prettyFormat(error);
    }
    const stack = await _symbolicateErrorAsync(error);
    const formattedStack = _formatStack(stack);
    return { message, stack: formattedStack };
}
async function _symbolicateErrorAsync(error) {
    // @ts-ignore: parseErrorStack accepts nullable string after RN 0.64 but @types/react-native does not updated yet.
    const parsedStack = parseErrorStack(error?.stack);
    let symbolicatedStack;
    try {
        // @ts-ignore: symbolicateStackTrace has different real/Flow declaration
        // than the one in DefinitelyTyped.
        symbolicatedStack = (await symbolicateStackTrace(parsedStack))?.stack ?? null;
    }
    catch (error) {
        return parsedStack;
    }
    // In this context an unsymbolicated stack is better than no stack
    if (!symbolicatedStack) {
        return parsedStack;
    }
    // Clean the stack trace
    return symbolicatedStack.map(_removeProjectRoot);
}
function _formatStack(stack) {
    return stack
        .map((frame) => {
        let line = `${frame.file}:${frame.lineNumber}`;
        if (frame.column != null) {
            line += `:${frame.column}`;
        }
        line += ` in ${frame.methodName}`;
        return line;
    })
        .join('\n');
}
function _removeProjectRoot(frame) {
    let filename = frame.file;
    if (filename == null) {
        return frame;
    }
    const projectRoot = _getProjectRoot();
    if (projectRoot == null) {
        return frame;
    }
    if (filename.startsWith(projectRoot)) {
        filename = filename.substring(projectRoot.length);
        if (filename[0] === '/' || filename[0] === '\\') {
            filename = filename.substring(1);
        }
        frame.file = filename;
    }
    return frame;
}
/**
 * Returns whether the development server that served this project supports logs with a stack trace.
 * Specifically, the version of Expo CLI that includes `projectRoot` in the manifest also accepts
 * payloads of the form:
 *
 * {
 *   includesStack: boolean, body: [{ message: string, stack: string }],
 * }
 */
function _stackTraceLogsSupported() {
    return !!(__DEV__ && _getProjectRoot());
}
function _isUnhandledPromiseRejection(data, level) {
    return (level === 'warn' &&
        typeof data[0] === 'string' &&
        /^Possible Unhandled Promise Rejection/.test(data[0]));
}
function _captureConsoleStackTrace() {
    try {
        throw new Error();
    }
    catch (error) {
        let stackLines = error.stack.split('\n');
        const consoleMethodIndex = stackLines.findIndex((frame) => frame.includes(EXPO_CONSOLE_METHOD_NAME));
        if (consoleMethodIndex !== -1) {
            stackLines = stackLines.slice(consoleMethodIndex + 1);
            error.stack = stackLines.join('\n');
        }
        return error;
    }
}
function _getProjectRoot() {
    return (Constants.manifest?.developer?.projectRoot ??
        Constants.manifest2?.extra?.expoGo?.developer?.projectRoot ??
        null);
}
export default {
    serializeLogDataAsync,
};
//# sourceMappingURL=LogSerialization.js.map


text:
static CGFloat kLZMembersCellLineSpacing = 10;
static CGFloat kLZMembersCellInterItemSpacing = 20;

@protocol LZMembersCellDelegate <NSObject>

- (void)didSelectMember:(LZMember *)member;

- (void)didLongPressMember:(LZMember *)member;

- (void)displayAvatarOfMember:(LZMember *)member atImageView:(UIImageView *)imageView;

@end

@interface LZMembersCell : UITableViewCell

@property (nonatomic, strong) NSArray *members;

@property (nonatomic, strong) id <LZMembersCellDelegate> membersCellDelegate;

+ (CGFloat)heightForMemberCount:(NSInteger )count;

+ (LZMembersCell *)dequeueOrCreateCellByTableView:(UITableView *)tableView;

@end