text:
package migrations

import (
	"fmt"

	"xorm.io/xorm"
)

func addBranchProtectionCanPushAndEnableWhitelist(x *xorm.Engine) error {
	type ProtectedBranch struct {
		CanPush                   bool    `xorm:"NOT NULL DEFAULT false"`
		EnableApprovalsWhitelist  bool    `xorm:"NOT NULL DEFAULT false"`
		ApprovalsWhitelistUserIDs []int64 `xorm:"JSON TEXT"`
		ApprovalsWhitelistTeamIDs []int64 `xorm:"JSON TEXT"`
		RequiredApprovals         int64   `xorm:"NOT NULL DEFAULT 0"`
	}

	type User struct {
		ID   int64 `xorm:"pk autoincr"`
		Type int

		// Permissions
		IsAdmin      bool
		IsRestricted bool `xorm:"NOT NULL DEFAULT false"`
		Visibility   int  `xorm:"NOT NULL DEFAULT 0"`
	}

	type Review struct {
		ID       int64 `xorm:"pk autoincr"`
		Official bool  `xorm:"NOT NULL DEFAULT false"`

		ReviewerID int64 `xorm:"index"`
		IssueID    int64 `xorm:"index"`
	}

	if err := x.Sync2(new(ProtectedBranch)); err != nil {
		return err
	}

	if err := x.Sync2(new(Review)); err != nil {
		return err
	}

	const (
		// ReviewTypeApprove approves changes
		ReviewTypeApprove int = 1
		// ReviewTypeReject gives feedback blocking merge
		ReviewTypeReject int = 3

		// VisibleTypePublic Visible for everyone
		VisibleTypePublic int = 0
		// VisibleTypePrivate Visible only for organization's members
		VisibleTypePrivate int = 2

		// UnitTypeCode is unit type code
		UnitTypeCode int = 1

		// AccessModeNone no access
		AccessModeNone int = 0
		// AccessModeRead read access
		AccessModeRead int = 1
		// AccessModeWrite write access
		AccessModeWrite int = 2
		// AccessModeOwner owner access
		AccessModeOwner int = 4
	)

	// Repository represents a git repository.
	type Repository struct {
		ID      int64 `xorm:"pk autoincr"`
		OwnerID int64 `xorm:"UNIQUE(s) index"`

		IsPrivate bool `xorm:"INDEX"`
	}

	type PullRequest struct {
		ID int64 `xorm:"pk autoincr"`

		BaseRepoID int64 `xorm:"INDEX"`
		BaseBranch string
	}

	// RepoUnit describes all units of a repository
	type RepoUnit struct {
		ID     int64
		RepoID int64 `xorm:"INDEX(s)"`
		Type   int   `xorm:"INDEX(s)"`
	}

	type Permission struct {
		AccessMode int
		Units      []*RepoUnit
		UnitsMode  map[int]int
	}

	type TeamUser struct {
		ID     int64 `xorm:"pk autoincr"`
		TeamID int64 `xorm:"UNIQUE(s)"`
		UID    int64 `xorm:"UNIQUE(s)"`
	}

	type Collaboration struct {
		ID     int64 `xorm:"pk autoincr"`
		RepoID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		UserID int64 `xorm:"UNIQUE(s) INDEX NOT NULL"`
		Mode   int   `xorm:"DEFAULT 2 NOT NULL"`
	}

	type Access struct {
		ID     int64 `xorm:"pk autoincr"`
		UserID int64 `xorm:"UNIQUE(s)"`
		RepoID int64 `xorm:"UNIQUE(s)"`
		Mode   int
	}

	type TeamUnit struct {
		ID     int64 `xorm:"pk autoincr"`
		OrgID  int64 `xorm:"INDEX"`
		TeamID int64 `xorm:"UNIQUE(s)"`
		Type   int   `xorm:"UNIQUE(s)"`
	}

	// Team represents a organization team.
	type Team struct {
		ID        int64 `xorm:"pk autoincr"`
		OrgID     int64 `xorm:"INDEX"`
		Authorize int
	}

	// getUserRepoPermission static function based on models.IsOfficialReviewer at 5d78792385
	getUserRepoPermission := func(sess *xorm.Session, repo *Repository, user *User) (Permission, error) {
		var perm Permission

		repoOwner := new(User)
		has, err := sess.ID(repo.OwnerID).Get(repoOwner)
		if err != nil || !has {
			return perm, err
		}

		// Prevent strangers from checking out public repo of private orginization
		// Allow user if they are collaborator of a repo within a private orginization but not a member of the orginization itself
		hasOrgVisible := true
		// Not SignedUser
		if user == nil {
			hasOrgVisible = repoOwner.Visibility == VisibleTypePublic
		} else if !user.IsAdmin {
			hasMemberWithUserID, err := sess.
				Where("uid=?", user.ID).
				And("org_id=?", repoOwner.ID).
				Table("org_user").
				Exist()
			if err != nil {
				hasOrgVisible = false
			}
			if (repoOwner.Visibility == VisibleTypePrivate || user.IsRestricted) && !hasMemberWithUserID {
				hasOrgVisible = false
			}
		}

		isCollaborator, err := sess.Get(&Collaboration{RepoID: repo.ID, UserID: user.ID})
		if err != nil {
			return perm, err
		}

		if repoOwner.Type == 1 && !hasOrgVisible && !isCollaborator {
			perm.AccessMode = AccessModeNone
			return perm, err
		}

		var units []*RepoUnit
		if err := sess.Where("repo_id = ?", repo.ID).Find(&units); err != nil {
			return perm, err
		}
		perm.Units = units

		// anonymous visit public repo
		if user == nil {
			perm.AccessMode = AccessModeRead
			return perm, err
		}

		// Admin or the owner has super access to the repository
		if user.IsAdmin || user.ID == repo.OwnerID {
			perm.AccessMode = AccessModeOwner
			return perm, err
		}

		accessLevel := func(user *User, repo *Repository) (int, error) {
			mode := AccessModeNone
			var userID int64
			restricted := false

			if user != nil {
				userID = user.ID
				restricted = user.IsRestricted
			}

			if !restricted && !repo.IsPrivate {
				mode = AccessModeRead
			}

			if userID == 0 {
				return mode, nil
			}

			if userID == repo.OwnerID {
				return AccessModeOwner, nil
			}

			a := &Access{UserID: userID, RepoID: repo.ID}
			if has, err := sess.Get(a); !has || err != nil {
				return mode, err
			}
			return a.Mode, nil
		}

		// plain user
		perm.AccessMode, err = accessLevel(user, repo)
		if err != nil {
			return perm, err
		}

		// If Owner is no Org
		if repoOwner.Type != 1 {
			return perm, err
		}

		perm.UnitsMode = make(map[int]int)

		// Collaborators on organization
		if isCollaborator {
			for _, u := range units {
				perm.UnitsMode[u.Type] = perm.AccessMode
			}
		}

		// get units mode from teams
		var teams []*Team
		err = sess.
			Join("INNER", "team_user", "team_user.team_id = team.id").
			Join("INNER", "team_repo", "team_repo.team_id = team.id").
			Where("team.org_id = ?", repo.OwnerID).
			And("team_user.uid=?", user.ID).
			And("team_repo.repo_id=?", repo.ID).
			Find(&teams)
		if err != nil {
			return perm, err
		}

		// if user in an owner team
		for _, team := range teams {
			if team.Authorize >= AccessModeOwner {
				perm.AccessMode = AccessModeOwner
				perm.UnitsMode = nil
				return perm, err
			}
		}

		for _, u := range units {
			var found bool
			for _, team := range teams {

				var teamU []*TeamUnit
				var unitEnabled bool
				err = sess.Where("team_id = ?", team.ID).Find(&teamU)

				for _, tu := range teamU {
					if tu.Type == u.Type {
						unitEnabled = true
						break
					}
				}

				if unitEnabled {
					m := perm.UnitsMode[u.Type]
					if m < team.Authorize {
						perm.UnitsMode[u.Type] = team.Authorize
					}
					found = true
				}
			}

			// for a public repo on an organization, a non-restricted user has read permission on non-team defined units.
			if !found && !repo.IsPrivate && !user.IsRestricted {
				if _, ok := perm.UnitsMode[u.Type]; !ok {
					perm.UnitsMode[u.Type] = AccessModeRead
				}
			}
		}

		// remove no permission units
		perm.Units = make([]*RepoUnit, 0, len(units))
		for t := range perm.UnitsMode {
			for _, u := range units {
				if u.Type == t {
					perm.Units = append(perm.Units, u)
				}
			}
		}

		return perm, err
	}

	// isOfficialReviewer static function based on 5d78792385
	isOfficialReviewer := func(sess *xorm.Session, issueID int64, reviewer *User) (bool, error) {
		pr := new(PullRequest)
		has, err := sess.ID(issueID).Get(pr)
		if err != nil {
			return false, err
		} else if !has {
			return false, fmt.Errorf("PullRequest for issueID %d not exist", issueID)
		}

		baseRepo := new(Repository)
		has, err = sess.ID(pr.BaseRepoID).Get(baseRepo)
		if err != nil {
			return false, err
		} else if !has {
			return false, fmt.Errorf("baseRepo with id %d not exist", pr.BaseRepoID)
		}
		protectedBranch := new(ProtectedBranch)
		has, err = sess.Where("repo_id=? AND branch_name=?", baseRepo.ID, pr.BaseBranch).Get(protectedBranch)
		if err != nil {
			return false, err
		}
		if !has {
			return false, nil
		}

		if !protectedBranch.EnableApprovalsWhitelist {

			perm, err := getUserRepoPermission(sess, baseRepo, reviewer)
			if err != nil {
				return false, err
			}
			if perm.UnitsMode == nil {
				for _, u := range perm.Units {
					if u.Type == UnitTypeCode {
						return AccessModeWrite <= perm.AccessMode, nil
					}
				}
				return false, nil
			}
			return AccessModeWrite <= perm.UnitsMode[UnitTypeCode], nil
		}
		for _, id := range protectedBranch.ApprovalsWhitelistUserIDs {
			if id == reviewer.ID {
				return true, nil
			}
		}

		// isUserInTeams
		return sess.Where("uid=?", reviewer.ID).In("team_id", protectedBranch.ApprovalsWhitelistTeamIDs).Exist(new(TeamUser))
	}

	if _, err := x.Exec("UPDATE `protected_branch` SET `enable_whitelist` = ? WHERE enable_whitelist IS NULL", false); err != nil {
		return err
	}
	if _, err := x.Exec("UPDATE `protected_branch` SET `can_push` = `enable_whitelist`"); err != nil {
		return err
	}
	if _, err := x.Exec("UPDATE `protected_branch` SET `enable_approvals_whitelist` = ? WHERE `required_approvals` > ?", true, 0); err != nil {
		return err
	}

	var pageSize int64 = 20
	qresult, err := x.QueryInterface("SELECT max(id) as max_id FROM issue")
	if err != nil {
		return err
	}
	var totalIssues int64
	totalIssues, ok := qresult[0]["max_id"].(int64)
	if !ok {
		// If there are no issues at all we ignore it
		return nil
	}
	totalPages := totalIssues / pageSize

	executeBody := func(page, pageSize int64) error {
		// Find latest review of each user in each pull request, and set official field if appropriate
		reviews := []*Review{}

		if err := x.SQL("SELECT * FROM review WHERE id IN (SELECT max(id) as id FROM review WHERE issue_id > ? AND issue_id <= ? AND type in (?, ?) GROUP BY issue_id, reviewer_id)",
			page*pageSize, (page+1)*pageSize, ReviewTypeApprove, ReviewTypeReject).
			Find(&reviews); err != nil {
			return err
		}

		if len(reviews) == 0 {
			return nil
		}

		sess := x.NewSession()
		defer sess.Close()

		if err := sess.Begin(); err != nil {
			return err
		}

		var updated int
		for _, review := range reviews {
			reviewer := new(User)
			has, err := sess.ID(review.ReviewerID).Get(reviewer)
			if err != nil || !has {
				// Error might occur if user doesn't exist, ignore it.
				continue
			}

			official, err := isOfficialReviewer(sess, review.IssueID, reviewer)
			if err != nil {
				// Branch might not be proteced or other error, ignore it.
				continue
			}
			review.Official = official
			updated++
			if _, err := sess.ID(review.ID).Cols("official").Update(review); err != nil {
				return err
			}
		}

		if updated > 0 {
			return sess.Commit()
		}
		return nil
	}

	var page int64
	for page = 0; page <= totalPages; page++ {
		if err := executeBody(page, pageSize); err != nil {
			return err
		}
	}

	return nil
}


text:
    module.exports = header: 'HBase Thrift Wait', handler: ({options}) ->

## HTTP Port

      @connection.wait
        header: 'HTTP'
        servers: options.http

## HTTP Info Port

      @connection.wait
        header: 'HTTP Info'
        servers: options.http_info

redpajama_set_name: RedPajamaGithub


text:
import random

name = 'cardsagainsthumanity'
enabled = False
operator = False

def cmd(self, c, e, line, message_source, target):
        if self.cah_in_progress:
            self.send(c, target, "Error - Game already in progress")
        elif not message_source == "public":
            self.send(c, target, "Error - Game must be started in a channel")
        elif len(line) < 2:
            self.send(c, target, "Error - Not enough arguments")
        else:
            self.send(c, target, u'\u0002Starting game of Cards Against Humanity!  Type ,in to join!\u000F')

            self.cah_channel = target
            self.cah_in_progress = True
            self.cah_started = False
            self.cah_players = []
            self.cah_scores = []
            self.cah_judging = False
            deck = file("whitedeck.txt", "r")
            self.cah_white_deck = deck.readlines()
            deck.close()
            deck = file("blackdeck.txt", "r")
            self.cah_black_deck = deck.readlines()
            deck.close()
            deck = file("blackdeckproperties.txt", "r")
            self.cah_black_deck_properties = deck.readlines()
            deck.close()

            self.cah_points_to_win = int(line[1])

            indexes = range(len(self.cah_black_deck))
            random.shuffle(indexes)
            temp_a, temp_b = [], []
            for i in indexes:
                temp_a.append(self.cah_black_deck[i])
                temp_b.append(self.cah_black_deck_properties[i])
            self.cah_black_deck = temp_a
            self.cah_black_deck_properties = temp_b
            random.shuffle(self.cah_white_deck)

def init(self):
    self.cah_unsubmitted_string = "seuft5h7"
    self.cah_judge_string = "uoaygwrg"
    self.cah_in_progress = False
    self.cah_started = False
    self.cah_channel = None
    self.cah_white_deck = []
    self.cah_black_deck = []
    self.cah_black_deck_properties = []
    self.cah_black_card = None
    self.cah_black_card_properties = 1
    self.cah_players = []
    self.cah_hands = [[]]
    self.cah_submissions = []
    self.cah_submissions2 = []
    self.cah_submissions3 = []
    self.cah_list_submissions = []
    self.cah_scores = []
    self.cah_judging = False
    self.cah_players_old = []
    self.cah_scores_old = []
    self.cah_points_to_win = 8


text:
/* heading */
/* paragraph */
body {
  background-color: #f5f5f5;
  -webkit-font-smoothing: antialiased;
  min-width: 320px;
  background-image: url("../images/bcg_wall.jpg");
  background-repeat: no-repeat;
  /*background-size: cover;*/
  background-attachment: fixed;
  height: 100%;
  font-family: 'Just Another Hand', cursive; }
  @media screen and (max-width: 768px) {
    body {
      background-position: -650px; } }

.margin-top {
  margin-top: 20px; }

#to-do-form .heading {
  font-size: 40px;
  font-weight: 700;
  color: #f5f8fa; }
#to-do-form .to-do-field {
  background-image: url("../images/yellow-notepad-paper.png");
  background-repeat: repeat-y;
  background-position: -80px;
  background-size: 110%;
  border-radius: 4px;
  padding-left: 20px;
  border: 1px solid #ccc;
  color: #555;
  border-radius: 2px;
  font-size: 30px; }
  @media screen and (max-width: 768px) {
    #to-do-form .to-do-field {
      background-size: 200%; } }
#to-do-form .btn-submit, #to-do-form .to-do-field {
  height: 50px;
  width: 100%; }

.lists {
  padding-left: 0; }
  .lists .list {
    position: relative;
    list-style-type: none;
    background-image: url("../images/yellow-notepad-paper.png");
    background-repeat: repeat-y;
    background-position: -102px;
    background-size: 110%;
    border: 1px solid #555;
    background-color: #f5f5f5;
    border-radius: 4px;
    margin-top: 20px;
    padding: 20px 20px;
    backface-visibility: hidden; }
    @media screen and (max-width: 768px) {
      .lists .list {
        background-size: 200%; } }
    .lists .list:hover {
      /*scaling causes weird pixelated/blurry text effect */
      /*@include transform(perspective(1px) scale(1.005));*/
      margin-left: -3px;
      margin-right: -3px;
      -webkit-transition: margin 0.35s ease-in-out;
      -moz-transition: margin 0.35s ease-in-out;
      -o-transition: margin 0.35s ease-in-out;
      transition: margin 0.35s ease-in-out; }
    .lists .list .list-description {
      font-size: 30px;
      padding-left: 10px;
      width: 80%;
      padding-right: 30px;
      display: inline-block;
      vertical-align: top; }
      .lists .list .list-description.done {
        text-decoration: line-through; }
      .lists .list .list-description .time-stamp {
        color: #797979;
        font-size: 20px;
        display: none; }
        .lists .list .list-description .time-stamp.active {
          display: inline; }
      @media screen and (max-width: 544px) {
        .lists .list .list-description {
          width: 87%;
          padding-right: 0; } }

.list-container .checkbox {
  display: inline;
  zoom: 2; }
.list-container .input-cannot-be-empty, .list-container .no-list-to-delete {
  display: none;
  font-size: 25px; }
  .list-container .input-cannot-be-empty.active, .list-container .no-list-to-delete.active {
    display: block;
    margin-top: 10px;
    margin-left: 10px; }
.list-container .options-wrapper {
  margin-top: 10px; }
  .list-container .options-wrapper .toggle-time-btn {
    display: inline-block;
    margin-left: 15px;
    color: white;
    vertical-align: top; }
    .list-container .options-wrapper .toggle-time-btn .time-desc {
      font-size: 20px;
      margin-top: -5px;
      margin-bottom: -5px; }
    .list-container .options-wrapper .toggle-time-btn #toggle-time-stamp .btn-time-hide, .list-container .options-wrapper .toggle-time-btn #toggle-time-stamp .btn-time-show {
      font-size: 15px;
      padding-bottom: 0; }
.list-container .btn-delete-all, .list-container .btn-no, .list-container .btn-yes {
  width: 100px; }
.list-container .messages .confirmation-text {
  font-size: 30px; }
  .list-container .messages .confirmation-text .red {
    color: red; }
.list-container .messages #delete-all-confirmation {
  margin-top: 10px; }
.list-container .messages .btn-no, .list-container .messages .btn-yes {
  margin-right: 15px; }
.list-container .btn-delete {
  position: absolute;
  right: 20px;
  width: 100px;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  -o-transform: translateY(-50%);
  transform: translateY(-50%); }
  @media screen and (max-width: 544px) {
    .list-container .btn-delete {
      position: static;
      display: block;
      width: 100%;
      margin-top: 10px;
      -webkit-transform: none;
      -ms-transform: none;
      -o-transform: none;
      transform: none; } }

.btn {
  font-size: 25px; }

.done-true {
  text-decoration: line-through; }

/*# sourceMappingURL=style.css.map */


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.spring.messaging.eventhubs.core.checkpoint;

import com.azure.spring.messaging.ListenerMode;

/**
 * The offset commit behavior enumeration.
 */
public enum CheckpointMode {

    /**
     * Checkpoint after each processed record.
     * Makes sense only if {@link ListenerMode#RECORD} is used.
     */
    RECORD,

    /**
     * Checkpoint after each processed batch of records.
     */
    BATCH,

    /**
     * User decide when to checkpoint manually
     */
    MANUAL,

    /**
     * Checkpoint once for number of message specified by {@link CheckpointConfig#getCount()} ()}
     * in each partition
     */
    PARTITION_COUNT,

    /**
     * Checkpoint once for each time interval specified by {@link CheckpointConfig#getInterval()} ()}
     */
    TIME,
}


text:
package com.outbrain.aletheia;

import com.google.common.base.Predicate;
import com.outbrain.aletheia.configuration.routing.Route;
import org.apache.commons.lang3.RandomStringUtils;
import org.joda.time.Instant;
import org.junit.Test;

/**
 * Created by slevin on 8/16/14.
 */
public class SampleDomainClassDatumTest extends AletheiaIntegrationTest<SampleDomainClass> {

  public static final Route AVRO_ROUTE = new Route("test_endpoint_1", "avro");
  public static final Route JSON_ROUTE = new Route("test_endpoint_2", "json");

  private final Predicate<SampleDomainClass> filter = new Predicate<SampleDomainClass>() {
    @Override
    public boolean apply(final SampleDomainClass input) {
      return input.isDiscarded();
    }
  };

  public SampleDomainClassDatumTest() {
    super(SampleDomainClass.class);
  }

  @Override
  protected SampleDomainClass domainClassRandomDatum(final boolean shouldBeSent) {
    return new SampleDomainClass(random.nextInt(),
                                 random.nextDouble(),
                                 RandomStringUtils.randomAlphanumeric(random.nextInt(20)),
                                 new Instant(),
                                 shouldBeSent);
  }

  @Test
  public void test_avro_route() throws InterruptedException {
    testRoutes(AVRO_ROUTE);
  }

  @Test
  public void test_json_route() throws InterruptedException {
    testRoutes(JSON_ROUTE);
  }

  @Test
  public void test_multiple_routes() throws InterruptedException {
    testRoutes(AVRO_ROUTE, JSON_ROUTE);
  }
}


text:
#pragma once

// Equivalent of a C# Delegate

/************************************************************************/
/*                                                                      */
/* INCLUDE                                                              */
/*                                                                      */
/************************************************************************/
#include "common.h"
#include "criticalsection.h"

#include <vector>

/************************************************************************/
/*                                                                      */
/* DEFINES AND CONSTANTS                                                */
/*                                                                      */
/************************************************************************/
// Infoknowledge Management System

/************************************************************************/
/*                                                                      */
/* MACROS                                                               */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* TYPES                                                                */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* STRUCTS                                                              */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* CLASSES                                                              */
/*                                                                      */
/************************************************************************/

template <typename ...ARGS>
class Event
{
   public:
      // TYPES:
      struct event_sub_t;
      typedef void (*cb_t)( event_sub_t*, ARGS... );
      typedef void (*cb_with_arg_t)( void*, ARGS... );
      // subscription - when subscribing this is the identifying
      // information (what to call, and what to call with)

      struct event_sub_t
      {
         cb_t cb;
         void *secondary_cb;
         void *user_arg;
      };

      // STATIC FUNCTIONS AS GO BETWEENS BETWEEN
      // THE EXPECTED CALLBACK AND UNIVERSAL CALLBACK
      static void FunctionWithArgumentCallback( event_sub_t *sub, ARGS ...args );

      template <typename T, typename MCB>
      static void MethodCallback( event_sub_t *sub, ARGS ...args );

   public:
      Event()
      {
      }

      ~Event()
      {
         subscriptions.clear();
      }

      // Subscribe a single function (
      void subscribe( void *user_arg, cb_with_arg_t cb )
      {
         // Good safeguard in debug to add is to make sure
         // you're not double subscribing to an event
         // with a similar pair.
         // TODO - ASSERT AGAINST ABOVE

         // Add subscriptoin
         event_sub_t sub;
         sub.cb = FunctionWithArgumentCallback;
         sub.secondary_cb = cb;
         sub.user_arg = user_arg;
         subscriptions.push_back( sub );
      }

      // Unsubscribe a function (using user argument as well)
      void unsubscribe( void *user_arg, void* cb )
      {
         for (int i = 0; i < subscriptions.size(); ++i) {
            event_sub_t &sub = subscriptions[i];
            if ((sub.secondary_cb == cb) && (sub.user_arg == user_arg)) {
               subscriptions.erase( subscriptions.begin() + i );
               return; // should be unique, so return immeidately
            }
         }
      }

      // remove all subscriptions using this user arg.
      void unsubscribe_by_argument( void *user_arg )
      {
         for (int i = 0; i < subscriptions.size(); ++i) {
            event_sub_t &sub = subscriptions[i];
            if (sub.user_arg == obj) {
               // don't return, just remove this object [could do a fast removal if order doesn't matter
               // by just setting last to this and popping back]
               subscriptions.erase( subscriptions.begin() + i );
               --i;
            }
         }
      }

      // Be able to subscribe a method;
      template <typename T>
      void subscribe_method( T *obj, void (T::*mcb)( ARGS... ) )
      {
         event_sub_t sub;
         sub.cb = MethodCallback<T, decltype(mcb)>;
         sub.secondary_cb = *(void**)(&mcb);
         sub.user_arg = obj;
         subscriptions.push_back( sub );
      }

      // unsubscribe - just forwards to normal unsubscribe
      template <typename T>
      void unsubscribe_method( T *obj, void (T::*mcb)( ARGS... ) )
      {
         unsubscribe( obj, *(void**)&mcb );
      }

      // unsubscribe all allocations for this object;
      template <typename T>
      void unsubscribe_object( T *obj )
      {
         unsubscribe_by_argument( obj );
      }

      // Triggers the call - calls all registered callbacks;
      void trigger( ARGS ...args )
      {
         for (int i = 0; i < subscriptions.size(); ++i) {
            event_sub_t &sub = subscriptions[i];
            sub.cb( &sub, args... );
         }
      }

   public:
      std::vector<event_sub_t> subscriptions;
};

//--------------------------------------------------------------------
template <typename ...ARGS>
void Event<ARGS...>::FunctionWithArgumentCallback( event_sub_t *sub, ARGS ...args )
{
   cb_with_arg_t cb = (cb_with_arg_t)(sub->secondary_cb);
   cb( sub->user_arg, args... );
}

//--------------------------------------------------------------------
template <typename ...ARGS>
template <typename T, typename MCB>
void Event<ARGS...>::MethodCallback( event_sub_t *sub, ARGS ...args )
{
   MCB mcb = *(MCB*)&(sub->secondary_cb);
   T *obj = (T*)(sub->user_arg);
   (obj->*mcb)( args... );
}

/************************************************************************/
/*                                                                      */
/* GLOBAL VARIABLES                                                     */
/*                                                                      */
/************************************************************************/

/************************************************************************/
/*                                                                      */
/* FUNCTION PROTOTYPES                                                  */
/*                                                                      */
/************************************************************************/
void EventTest();


text:
namespace autofill_assistant {

// Flag to enable site per process to enforce OOPIFs.
const char* kSitePerProcess = "site-per-process";

BaseBrowserTest::BaseBrowserTest() = default;
BaseBrowserTest::~BaseBrowserTest() {}

void BaseBrowserTest::SetUpCommandLine(base::CommandLine* command_line) {
  command_line->AppendSwitch(kSitePerProcess);
  // Necessary to avoid flakiness or failure due to input arriving
  // before the first compositor commit.
  command_line->AppendSwitch(blink::switches::kAllowPreCommitInput);
}

void BaseBrowserTest::SetUpOnMainThread() {
  ContentBrowserTest::SetUpOnMainThread();

  // Start a mock server for hosting an OOPIF.
  http_server_iframe_ = std::make_unique<net::EmbeddedTestServer>(
      net::EmbeddedTestServer::TYPE_HTTP);
  http_server_iframe_->ServeFilesFromSourceDirectory(
      "components/test/data/autofill_assistant/html_iframe");
  ASSERT_TRUE(http_server_iframe_->Start(8081));

  // Start the main server hosting the test page.
  http_server_ = std::make_unique<net::EmbeddedTestServer>(
      net::EmbeddedTestServer::TYPE_HTTP);
  http_server_->ServeFilesFromSourceDirectory(
      "components/test/data/autofill_assistant/html");
  ASSERT_TRUE(http_server_->Start(8080));
  ASSERT_TRUE(NavigateToURL(shell(), http_server_->GetURL(kTargetWebsitePath)));
}

}  // namespace autofill_assistant


text:
	module.exports = function(grunt) {
	grunt.initConfig({
		pkg: grunt.file.readJSON('package.json'),
		less: {
			development: {
				files: {
					"src/styles/css/style.css": "src/styles/less/style.less"
				}
			}
		},
		autoprefixer: {
			single_file: {
				options: {

				},
				src: "src/styles/css/style.css",
				dest: "public/assets/styles/style.css"
			}
		},
		cssmin: {
			development: {
				options: {
					banner: "/* Minified style */"
				},
				files: {
					"public/assets/styles/style.min.css": ["public/assets/styles/style.css"]
				}
			}
		},
		concat: {
			angular_app: {
				files: {
					'public/assets/scripts/app/app.js': ['src/scripts/*.js', 'src/scripts/**/*.js']
				},
			},
		},
		watch: {
			styles: {
				options: {
					livereload: true
				},
				files: "src/styles/**/*.less",
				tasks: ["styles"]
			},
			scripts: {
				options: {
					livereload: true
				},
				files: "src/scripts/**/*.js",
				tasks: ["scripts"]
			}
		}
	});

	grunt.loadNpmTasks("grunt-contrib-less");
	grunt.loadNpmTasks("grunt-autoprefixer");
	grunt.loadNpmTasks("grunt-contrib-cssmin");
	grunt.loadNpmTasks("grunt-contrib-concat");
	grunt.loadNpmTasks("grunt-contrib-watch");

	grunt.registerTask("default", ["less", "autoprefixer", "cssmin", "concat"]);
	grunt.registerTask("styles", ["less", "autoprefixer", "cssmin"]);
	grunt.registerTask("scripts", ["concat"]);
};


text:
Black Pepper Support Mail Test
==============================

Support for testing with the [JavaMail API](http://www.oracle.com/technetwork/java/javamail/index.html).

License
-------

* [Apache License 2.0](http://www.apache.org/licenses/LICENSE-2.0.html)

[![Build Status](https://travis-ci.org/BlackPepperSoftware/bp-support-mail-test.svg?branch=master)](https://travis-ci.org/BlackPepperSoftware/bp-support-mail-test)


text:
require 'spec_helper'

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


text:
MACRO(GDCM_PLATFORM_CXX_TEST var description invert)
  IF(NOT DEFINED "${var}_COMPILED")
    MESSAGE(STATUS "${description}")
    TRY_COMPILE(${var}_COMPILED
      ${CMAKE_CURRENT_BINARY_DIR}
      ${CMAKE_CURRENT_SOURCE_DIR}/CMake/gdcmPlatformCxxTests.cxx
      COMPILE_DEFINITIONS -DTEST_${var} ${GDCM_PLATFORM_CXX_TEST_DEFINES}
      OUTPUT_VARIABLE OUTPUT)
    IF(${var}_COMPILED)
      FILE(APPEND ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CMakeOutput.log
        "${description} compiled with the following output:\n${OUTPUT}\n\n")
    ELSE(${var}_COMPILED)
      FILE(APPEND ${CMAKE_CURRENT_BINARY_DIR}/CMakeFiles/CMakeError.log
        "${description} failed to compile with the following output:\n${OUTPUT}\n\n")
    ENDIF(${var}_COMPILED)
    IF(${invert} MATCHES INVERT)
      IF(${var}_COMPILED)
        MESSAGE(STATUS "${description} - no")
      ELSE(${var}_COMPILED)
        MESSAGE(STATUS "${description} - yes")
      ENDIF(${var}_COMPILED)
    ELSE(${invert} MATCHES INVERT)
      IF(${var}_COMPILED)
        MESSAGE(STATUS "${description} - yes")
      ELSE(${var}_COMPILED)
        MESSAGE(STATUS "${description} - no")
      ENDIF(${var}_COMPILED)
    ENDIF(${invert} MATCHES INVERT)
  ENDIF()
  IF(${invert} MATCHES INVERT)
    IF(${var}_COMPILED)
      SET(${var} 0)
    ELSE(${var}_COMPILED)
      SET(${var} 1)
    ENDIF(${var}_COMPILED)
  ELSE(${invert} MATCHES INVERT)
    IF(${var}_COMPILED)
      SET(${var} 1)
    ELSE(${var}_COMPILED)
      SET(${var} 0)
    ENDIF(${var}_COMPILED)
  ENDIF(${invert} MATCHES INVERT)
ENDMACRO(GDCM_PLATFORM_CXX_TEST)


text:
/**
 * WebSocket4Net未提供异步方法,所以此类需要用Thread封装一下
 *
 */
using System;
using System.Collections.Generic;
using WebSocket4Net;

namespace Alkaid
{
    public class WebSocketConnector : INetConnector
    {
        WebSocket mSocket;

        // 缓冲区
        private NetStream mNetStream;
        // 临时解析
        private int tempReadPacketLength;
        private int tempReadPacketType;
        private Byte[] tempReadPacketData;

        private AsyncThread mSendThread = null;

        public WebSocketConnector(IPacketFormat packetFormat, IPacketHandlerManager packetHandlerManager) : base(packetFormat, packetHandlerManager)
        {
            mSocket = null;
            mNetStream = new NetStream(INetConnector.MAX_SOCKET_BUFFER_SIZE * 2);
            tempReadPacketLength = 0;
            tempReadPacketType = 0;
            tempReadPacketData = null;

            mSendThread = new AsyncThread(SendLogic);
            mSendThread.Start();
        }

        public override bool Init()
        {
            base.Init();

            return true;
        }

        public override void Tick(float interval)
        {
            base.Tick(interval);

            doDecodeMessage();

            //doSendMessage(); // will do in other thread
        }

        public override void Destroy()
        {
            base.Destroy();

            mSendThread.Stop();

            DisConnect();
        }

        public override ConnectionType GetConnectionType()
        {
            return ConnectionType.WEBSOCKET;
        }

        public override void Connect(string address, int port)
        {
            base.Connect(address, port);

            string url = mRemoteHost.GetAddress();
            if (port > 0 && !mRemoteHost.GetAddress().Contains(":"))
            {
                url = string.Format("ws://{0}:{1}/", mRemoteHost.GetAddress(), mRemoteHost.GetPort());
            }

            mSocket = new WebSocket(url);
            if (mSocket == null) return;
            mSocket.EnableAutoSendPing = true;
            mSocket.AutoSendPingInterval = 10;
            mSocket.Opened += new System.EventHandler(OnOpenedCallback);
            mSocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(OnErrorCallback);
            mSocket.Closed += new System.EventHandler(OnClosedCallback);
            mSocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(OnMessageReceivedCallback);
            mSocket.DataReceived += new EventHandler<DataReceivedEventArgs>(OnDataReceivedCallback);
            mSocket.Open();

        }

        public override void SendPacket(IPacket packet)
        {
            Byte[] buffer = null;
            mPacketFormat.GenerateBuffer(ref buffer, packet);
            mNetStream.PushOutStream(buffer);
        }

        public override void DisConnect()
        {
            if (IsConnected())
            {
				SetConnectStatus (ConnectionStatus.DISCONNECTED);

                mSocket.Close();
                mSocket = null;
                mNetStream.Clear();

                CallbackDisconnected();
            }
        }

        private void OnOpenedCallback(object sender, EventArgs e)
        {
			SetConnectStatus (ConnectionStatus.CONNECTED);

            CallbackConnected(IsConnected());
        }

        private void OnErrorCallback(object sender, SuperSocket.ClientEngine.ErrorEventArgs e)
        {
            Exception exc = e.Exception;
            LoggerSystem.Instance.Error(exc.Message);

            DisConnect();

            CallbackError();
        }

        private void OnClosedCallback(object sender, EventArgs e)
        {
            DisConnect();
        }

        private void OnMessageReceivedCallback(object sender, MessageReceivedEventArgs me)
        {
            if (!string.IsNullOrEmpty(me.Message))
            {
                mNetStream.PushInStream(Convert.FromBase64String(me.Message));
            }
            else
            {
                LoggerSystem.Instance.Error("读取数据为0,将要断开此链接接:ws://" + mRemoteHost.ToString());
                DisConnect();
            }
        }

        private void OnDataReceivedCallback(object sender, DataReceivedEventArgs de)
        {
            if (de.Data.Length > 0)
            {
                mNetStream.PushInStream(de.Data);
            }
            else
            {
                LoggerSystem.Instance.Error("读取数据为0,将要断开此链接接:ws://" + mRemoteHost.ToString());
                DisConnect();
            }
        }

        private void doDecodeMessage()
        {
            while (mNetStream.InStreamLength > 0 && mPacketFormat.CheckHavePacket(mNetStream.InStream, mNetStream.InStreamLength))
            {
                // 开始读取
                mPacketFormat.DecodePacket(mNetStream.InStream, ref tempReadPacketLength, ref tempReadPacketType, ref tempReadPacketData);

                mPacketHandlerManager.DispatchHandler(tempReadPacketType, tempReadPacketData);

                CallbackRecieved(tempReadPacketType, tempReadPacketData);

                // 偏移
                mNetStream.PopInStream(tempReadPacketLength);
            }
        }

        private void SendLogic(AsyncThread thread)
        {
            while (thread.IsWorking())
            {
                doSendMessage();

                System.Threading.Thread.Sleep(30);
            }
        }

        private void doSendMessage()
        {
            int length = mNetStream.OutStreamLength;
            if (IsConnected() && mNetStream.AsyncPipeOutIdle && length > 0 && mSocket.State == WebSocketState.Open)
            {
                mSocket.Send(mNetStream.AsyncPipeOut, 0, length);
                mNetStream.FinishedOut(length);
            }
        }

    }
}


text:
package pl.devoxx.dojrzewatr.brewing.model;

public enum IngredientType {
    MALT, WATER, HOP, YIEST
}


text:
package net.sf.jabref.specialfields;

import java.util.ArrayList;
import java.util.List;

import javax.swing.Icon;

import net.sf.jabref.gui.IconTheme;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.entry.SpecialFields;

public class Priority extends SpecialField {

    private static Priority INSTANCE;

    private final Icon icon = IconTheme.JabRefIcon.PRIORITY.getSmallIcon();

    private Priority() {
        List<SpecialFieldValue> values = new ArrayList<>();
        values.add(new SpecialFieldValue(this, null, "clearPriority", Localization.lang("Clear priority"), null,
                Localization.lang("No priority information")));
        Icon tmpicon;
        tmpicon = IconTheme.JabRefIcon.PRIORITY_HIGH.getSmallIcon();
        // DO NOT TRANSLATE "prio1" etc. as this makes the .bib files non portable
        values.add(new SpecialFieldValue(this, "prio1", "setPriority1", Localization.lang("Set priority to high"),
                tmpicon, Localization.lang("Priority high")));
        tmpicon = IconTheme.JabRefIcon.PRIORITY_MEDIUM.getSmallIcon();
        values.add(new SpecialFieldValue(this, "prio2", "setPriority2", Localization.lang("Set priority to medium"),
                tmpicon, Localization.lang("Priority medium")));
        tmpicon = IconTheme.JabRefIcon.PRIORITY_LOW.getSmallIcon();
        values.add(new SpecialFieldValue(this, "prio3", "setPriority3", Localization.lang("Set priority to low"),
                tmpicon, Localization.lang("Priority low")));
        this.setValues(values);
    }

    public static Priority getInstance() {
        if (Priority.INSTANCE == null) {
            Priority.INSTANCE = new Priority();
        }
        return Priority.INSTANCE;
    }

    @Override
    public String getFieldName() {
        return SpecialFields.FIELDNAME_PRIORITY;
    }

    @Override public String getLocalizedFieldName() {
        return Localization.lang("Priority");
    }

    @Override
    public Icon getRepresentingIcon() {
        return this.icon;
    }
}


text: Hello! I will fail :)))


text:
<?php

/**
 *
 * @package CRM
 * @copyright CiviCRM LLC (c) 2004-2015
 * $Id$
 */

/**
 * This class is used to retrieve and display a range of
 * contacts that match the given criteria (specifically for
 * results of advanced search options.
 */
class CRM_Pledge_Selector_Search extends CRM_Core_Selector_Base {

  /**
   * This defines two actions- View and Edit.
   *
   * @var array
   */
  static $_links = NULL;

  /**
   * We use desc to remind us what that column is, name is used in the tpl
   *
   * @var array
   */
  static $_columnHeaders;

  /**
   * Properties of contact we're interested in displaying
   * @var array
   */
  static $_properties = array(
    'contact_id',
    'sort_name',
    'display_name',
    'pledge_id',
    'pledge_amount',
    'pledge_create_date',
    'pledge_total_paid',
    'pledge_next_pay_date',
    'pledge_next_pay_amount',
    'pledge_outstanding_amount',
    'pledge_status_id',
    'pledge_status',
    'pledge_is_test',
    'pledge_contribution_page_id',
    'pledge_financial_type',
    'pledge_campaign_id',
    'pledge_currency',
  );

  /**
   * Are we restricting ourselves to a single contact
   *
   * @var boolean
   */
  protected $_single = FALSE;

  /**
   * Are we restricting ourselves to a single contact
   *
   * @var boolean
   */
  protected $_limit = NULL;

  /**
   * What context are we being invoked from
   *
   * @var string
   */
  protected $_context = NULL;

  /**
   * QueryParams is the array returned by exportValues called on
   * the HTML_QuickForm_Controller for that page.
   *
   * @var array
   */
  public $_queryParams;

  /**
   * Represent the type of selector
   *
   * @var int
   */
  protected $_action;

  /**
   * The additional clause that we restrict the search with
   *
   * @var string
   */
  protected $_additionalClause = NULL;

  /**
   * The query object
   *
   * @var string
   */
  protected $_query;

  /**
   * Class constructor.
   *
   * @param array $queryParams
   *   Array of parameters for query.
   * @param \const|int $action - action of search basic or advanced.
   * @param string $additionalClause
   *   If the caller wants to further restrict the search (used in participations).
   * @param bool $single
   *   Are we dealing only with one contact?.
   * @param int $limit
   *   How many signers do we want returned.
   *
   * @param string $context
   *
   * @return \CRM_Pledge_Selector_Search
   */
  public function __construct(
    &$queryParams,
    $action = CRM_Core_Action::NONE,
    $additionalClause = NULL,
    $single = FALSE,
    $limit = NULL,
    $context = 'search'
  ) {
    // submitted form values
    $this->_queryParams = &$queryParams;

    $this->_single = $single;
    $this->_limit = $limit;
    $this->_context = $context;

    $this->_additionalClause = $additionalClause;

    // type of selector
    $this->_action = $action;

    $this->_query = new CRM_Contact_BAO_Query($this->_queryParams, NULL, NULL, FALSE, FALSE,
      CRM_Contact_BAO_Query::MODE_PLEDGE
    );

    $this->_query->_distinctComponentClause = "civicrm_pledge.id";
    $this->_query->_groupByComponentClause = " GROUP BY civicrm_pledge.id ";
  }

  /**
   * This method returns the links that are given for each search row.
   *
   * Currently the links added for each row are:
   * - View
   * - Edit
   *
   * @return array
   */
  public static function &links() {
    $args = func_get_args();
    $hideOption = CRM_Utils_Array::value(0, $args);
    $key = CRM_Utils_Array::value(1, $args);

    $extraParams = ($key) ? "&key={$key}" : NULL;

    $cancelExtra = ts('Cancelling this pledge will also cancel any scheduled (and not completed) pledge payments.') . ' ' . ts('This action cannot be undone.') . ' ' . ts('Do you want to continue?');
    self::$_links = array(
      CRM_Core_Action::VIEW => array(
        'name' => ts('View'),
        'url' => 'civicrm/contact/view/pledge',
        'qs' => 'reset=1&id=%%id%%&cid=%%cid%%&action=view&context=%%cxt%%&selectedChild=pledge' . $extraParams,
        'title' => ts('View Pledge'),
      ),
      CRM_Core_Action::UPDATE => array(
        'name' => ts('Edit'),
        'url' => 'civicrm/contact/view/pledge',
        'qs' => 'reset=1&action=update&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
        'title' => ts('Edit Pledge'),
      ),
      CRM_Core_Action::DETACH => array(
        'name' => ts('Cancel'),
        'url' => 'civicrm/contact/view/pledge',
        'qs' => 'reset=1&action=detach&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
        'extra' => 'onclick = "return confirm(\'' . $cancelExtra . '\');"',
        'title' => ts('Cancel Pledge'),
      ),
      CRM_Core_Action::DELETE => array(
        'name' => ts('Delete'),
        'url' => 'civicrm/contact/view/pledge',
        'qs' => 'reset=1&action=delete&id=%%id%%&cid=%%cid%%&context=%%cxt%%' . $extraParams,
        'title' => ts('Delete Pledge'),
      ),
    );

    if (in_array('Cancel', $hideOption)) {
      unset(self::$_links[CRM_Core_Action::DETACH]);
    }

    return self::$_links;
  }

  /**
   * Getter for array of the parameters required for creating pager.
   *
   * @param $action
   * @param array $params
   */
  public function getPagerParams($action, &$params) {
    $params['status'] = ts('Pledge') . ' %%StatusMessage%%';
    $params['csvString'] = NULL;
    if ($this->_limit) {
      $params['rowCount'] = $this->_limit;
    }
    else {
      $params['rowCount'] = CRM_Utils_Pager::ROWCOUNT;
    }

    $params['buttonTop'] = 'PagerTopButton';
    $params['buttonBottom'] = 'PagerBottomButton';
  }

  /**
   * Returns total number of rows for the query.
   *
   * @param int $action
   *
   * @return int
   *   Total number of rows
   */
  public function getTotalCount($action) {
    return $this->_query->searchQuery(0, 0, NULL,
      TRUE, FALSE,
      FALSE, FALSE,
      FALSE,
      $this->_additionalClause
    );
  }

  /**
   * Returns all the rows in the given offset and rowCount.
   *
   * @param string $action
   *   The action being performed.
   * @param int $offset
   *   The row number to start from.
   * @param int $rowCount
   *   The number of rows to return.
   * @param string $sort
   *   The sql string that describes the sort order.
   * @param string $output
   *   What should the result set include (web/email/csv).
   *
   * @return int
   *   the total number of rows for this action
   */
  public function &getRows($action, $offset, $rowCount, $sort, $output = NULL) {
    $result = $this->_query->searchQuery($offset, $rowCount, $sort,
      FALSE, FALSE,
      FALSE, FALSE,
      FALSE,
      $this->_additionalClause
    );

    // process the result of the query
    $rows = array();

    // get all pledge status
    $pledgeStatuses = CRM_Core_OptionGroup::values('contribution_status',
      FALSE, FALSE, FALSE, NULL, 'name', FALSE
    );

    //get all campaigns.
    $allCampaigns = CRM_Campaign_BAO_Campaign::getCampaigns(NULL, NULL, FALSE, FALSE, FALSE, TRUE);

    //4418 check for view, edit and delete
    $permissions = array(CRM_Core_Permission::VIEW);
    if (CRM_Core_Permission::check('edit pledges')) {
      $permissions[] = CRM_Core_Permission::EDIT;
    }
    if (CRM_Core_Permission::check('delete in CiviPledge')) {
      $permissions[] = CRM_Core_Permission::DELETE;
    }
    $mask = CRM_Core_Action::mask($permissions);

    while ($result->fetch()) {
      $row = array();
      // the columns we are interested in
      foreach (self::$_properties as $property) {
        if (isset($result->$property)) {
          $row[$property] = $result->$property;
        }
      }

      //carry campaign on selectors.
      $row['campaign'] = CRM_Utils_Array::value($result->pledge_campaign_id, $allCampaigns);
      $row['campaign_id'] = $result->pledge_campaign_id;

      // add pledge status name
      $row['pledge_status_name'] = CRM_Utils_Array::value($row['pledge_status_id'],
        $pledgeStatuses
      );
      // append (test) to status label
      if (!empty($row['pledge_is_test'])) {
        $row['pledge_status'] .= ' (test)';
      }

      $hideOption = array();
      if (CRM_Utils_Array::key('Cancelled', $row) ||
        CRM_Utils_Array::key('Completed', $row)
      ) {
        $hideOption[] = 'Cancel';
      }

      $row['checkbox'] = CRM_Core_Form::CB_PREFIX . $result->pledge_id;

      $row['action'] = CRM_Core_Action::formLink(self::links($hideOption, $this->_key),
        $mask,
        array(
          'id' => $result->pledge_id,
          'cid' => $result->contact_id,
          'cxt' => $this->_context,
        ),
        ts('more'),
        FALSE,
        'pledge.selector.row',
        'Pledge',
        $result->pledge_id
      );

      $row['contact_type'] = CRM_Contact_BAO_Contact_Utils::getImage($result->contact_sub_type ? $result->contact_sub_type : $result->contact_type, FALSE, $result->contact_id
      );
      $rows[] = $row;
    }
    return $rows;
  }

  /**
   * Get qill (display what was searched on).
   *
   * @inheritDoc
   */
  public function getQILL() {
    return $this->_query->qill();
  }

  /**
   * Returns the column headers as an array of tuples.
   *
   * Keys are name, sortName, key to the sort array
   *
   * @param string $action
   *   The action being performed.
   * @param string $output
   *   What should the result set include (web/email/csv).
   *
   * @return array
   *   the column headers that need to be displayed
   */
  public function &getColumnHeaders($action = NULL, $output = NULL) {
    if (!isset(self::$_columnHeaders)) {
      self::$_columnHeaders = array(
        array(
          'name' => ts('Pledged'),
          'sort' => 'pledge_amount',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array(
          'name' => ts('Total Paid'),
          'sort' => 'pledge_total_paid',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array(
          'name' => ts('Balance'),
        ),
        array(
          'name' => ts('Pledged For'),
          'sort' => 'pledge_financial_type',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array(
          'name' => ts('Pledge Made'),
          'sort' => 'pledge_create_date',
          'direction' => CRM_Utils_Sort::DESCENDING,
        ),
        array(
          'name' => ts('Next Pay Date'),
          'sort' => 'pledge_next_pay_date',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array(
          'name' => ts('Next Amount'),
          'sort' => 'pledge_next_pay_amount',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array(
          'name' => ts('Status'),
          'sort' => 'pledge_status',
          'direction' => CRM_Utils_Sort::DONTCARE,
        ),
        array('desc' => ts('Actions')),
      );

      if (!$this->_single) {
        $pre = array(
          array('desc' => ts('Contact ID')),
          array(
            'name' => ts('Name'),
            'sort' => 'sort_name',
            'direction' => CRM_Utils_Sort::DONTCARE,
          ),
        );

        self::$_columnHeaders = array_merge($pre, self::$_columnHeaders);
      }
    }
    return self::$_columnHeaders;
  }

  /**
   * Get sql query string.
   *
   * @return string
   */
  public function &getQuery() {
    return $this->_query;
  }

  /**
   * Name of export file.
   *
   * @param string $output
   *   Type of output.
   *
   * @return string
   *   name of the file
   */
  public function getExportFileName($output = 'csv') {
    return ts('Pledge Search');
  }

}


text:
package com.jensen.draculadaybyday.sql_lite.DateConstraintArg;

public abstract class BeforeAfterDateConstraintArg extends DateConstraintArg {

    boolean inclusive;

    BeforeAfterDateConstraintArg() {

    }

    BeforeAfterDateConstraintArg(boolean inclusive) {
        this.inclusive = inclusive;
    }

    public boolean getInclusive() {
        return inclusive;
    }

    public void setInclusive(boolean inclusive) { this.inclusive = inclusive; }

    @Override
    public boolean isValueDefault() {
        return super.isValueDefault() && !inclusive;
    }

}


text:
import { h } from 'preact' // eslint-disable-line no-unused-vars
import PreactRedux from 'preact-redux'
import { getPosts } from './../store/selectors/posts'
import { updateLocation } from './../store/actions/meta'
import Link from './Link'
const { connect } = PreactRedux

const Post = ({ post, _updateLocation }) => (

    <Link href={`/blog/${post.id}`} onClick={() => _updateLocation(`/blog/${post.id}`)}>
      {post.title}
    </Link>

)

const Posts = ({ posts, _updateLocation }) => (

    {posts.map((post, i) => (
      <Post _updateLocation={_updateLocation} post={post} key={i} />
    ))}

)

export default connect(
  (state) => ({
    posts: getPosts(state)
  }),
  (dispatch) => ({
    _updateLocation: (url) => dispatch(updateLocation(url))
  })
)(Posts)


text:
<?php

namespace Fuel\Core;

/**
 * Numeric helper class. Provides additional formatting methods for working with
 * numeric values.
 *
 * Credit is left where credit is due.
 *
 * Techniques and inspiration were taken from all over, including:
 *	Kohana Framework: kohanaframework.org
 *	CakePHP: cakephp.org
 *
 * @package		Fuel
 * @category	Core
 * @author      Chase "Syntaqx" Hutchins
 */
class Num
{

	/**
	 * Cached byte units
	 *
	 * @var   array
	 */
	protected static $byte_units;

	/**
	 * Cached configuration values
	 *
	 * @var   array
	 */
	protected static $config;

	/**
	 * Class initialization callback
	 *
	 * @return   void
	 */
	public static function _init()
	{
		\Lang::load('byte_units', true);

		static::$config     = \Config::load('num', true);
		static::$byte_units = \Lang::get('byte_units');
	}

	/**
	 * Converts a file size number to a byte value. File sizes are defined in
	 * the format: SB, where S is the size (1, 8.5, 300, etc.) and B is the
	 * byte unit (K, MiB, GB, etc.). All valid byte units are defined in
	 * static::$byte_units
	 *
	 * Usage:
	 *
	 * echo Num::bytes('200K');  // 204800
	 * echo static::bytes('5MiB');  // 5242880
	 * echo static::bytes('1000');  // 1000
	 * echo static::bytes('2.5GB'); // 2684354560
	 *
	 *
	 * @author     Kohana Team
	 * @copyright  (c) 2009-2011 Kohana Team
	 * @license    http://kohanaframework.org/license
	 * @param      string   file size in SB format
	 * @return     float
	 */
	public static function bytes($size = 0)
	{
		// Prepare the size
		$size = trim((string) $size);

		// Construct an OR list of byte units for the regex
		$accepted = implode('|', array_keys(static::$byte_units));

		// Construct the regex pattern for verifying the size format
		$pattern = '/^([0-9]+(?:\.[0-9]+)?)('.$accepted.')?$/Di';

		// Verify the size format and store the matching parts
		if (!preg_match($pattern, $size, $matches))
		{
			throw new \Exception('The byte unit size, "'.$size.'", is improperly formatted.');
		}

		// Find the float value of the size
		$size = (float) $matches[1];

		// Find the actual unit, assume B if no unit specified
		$unit = \Arr::get($matches, 2, 'B');

		// Convert the size into bytes
		$bytes = $size * pow(2, static::$byte_units[$unit]);

		return $bytes;
	}

	/**
	 * Converts a number of bytes to a human readable number by taking the
	 * number of that unit that the bytes will go into it. Supports TB value.
	 *
	 * Note: Integers in PHP are limited to 32 bits, unless they are on 64 bit
	 * architectures, then they have 64 bit size. If you need to place the
	 * larger size then what the PHP integer type will hold, then use a string.
	 * It will be converted to a double, which should always have 64 bit length.
	 *
	 * @param   integer
	 * @param   integer
	 * @return  boolean|string
	 */
	public static function format_bytes($bytes = 0, $decimals = 0)
	{
		$quant = array(
			'TB' => 1099511627776,  // pow( 1024, 4)
			'GB' => 1073741824,     // pow( 1024, 3)
			'MB' => 1048576,        // pow( 1024, 2)
			'KB' => 1024,           // pow( 1024, 1)
			'B ' => 1,              // pow( 1024, 0)
		);

		foreach ($quant as $unit => $mag )
		{
			if (doubleval($bytes) >= $mag)
			{
				return sprintf('%01.'.$decimals.'f', ($bytes / $mag)).' '.$unit;
			}
		}

		return false;
	}

	/**
	 * Converts a number into a more readable human-type number.
	 *
	 * Usage:
	 *
	 * echo Num::quantity(7000); // 7K
	 * echo Num::quantity(7500); // 8K
	 * echo Num::quantity(7500, 1); // 7.5K
	 *
	 *
	 * @param   integer
	 * @param   integer
	 * @return  string
	 */
	public static function quantity($num, $decimals = 0)
	{
		if ($num >= 1000 && $num < 1000000)
		{
			return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000)).'K';
		}
		elseif ($num >= 1000000 && $num < 1000000000)
		{
			return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000)).'M';
		}
		elseif ($num >= 1000000000)
		{
			return sprintf('%01.'.$decimals.'f', (sprintf('%01.0f', $num) / 1000000000)).'B';
		}

		return $num;
	}

	/**
	 * Formats a number by injecting non-numeric characters in a specified
	 * format into the string in the positions they appear in the format.
	 *
	 * Usage:
	 *
	 * echo Num::format('1234567890', '(000) 000-0000'); // (123) 456-7890
	 * echo Num::format('1234567890', '000.000.0000'); // 123.456.7890
	 *
	 *
	 * @link    http://snippets.symfony-project.org/snippet/157
	 * @param   string     the string to format
	 * @param   string     the format to apply
	 * @return  string
	 */
	public static function format($string = '', $format = '')
	{
		if(empty($format) or empty($string))
		{
			return $string;
		}

		$result = '';
		$fpos = 0;
		$spos = 0;

		while ((strlen($format) - 1) >= $fpos)
		{
			if (ctype_alnum(substr($format, $fpos, 1)))
			{
				$result .= substr($string, $spos, 1);
				$spos++;
			}
			else
			{
				$result .= substr($format, $fpos, 1);
			}

			$fpos++;
		}

		return $result;
	}

	/**
	 * Transforms a number by masking characters in a specified mask format, and
	 * ignoring characters that should be injected into the string without
	 * matching a character from the original string (defaults to space).
	 *
	 * Usage:
	 *
	 * echo Num::mask_string('1234567812345678', '************0000'); ************5678
	 * echo Num::mask_string('1234567812345678', '**** **** **** 0000'); // **** **** **** 5678
	 * echo Num::mask_string('1234567812345678', '**** - **** - **** - 0000', ' -'); // **** - **** - **** - 5678
	 *
	 *
	 * @link    http://snippets.symfony-project.org/snippet/157
	 * @param   string     the string to transform
	 * @param   string     the mask format
	 * @param   string     a string (defaults to a single space) containing characters to ignore in the format
	 * @return  string     the masked string
	 */
	public static function mask_string($string = '', $format = '', $ignore = ' ')
	{
		if(empty($format) or empty($string))
		{
			return $string;
		}

		$result = '';
		$fpos = 0;
		$spos = 0;

		while ((strlen($format) - 1) >= $fpos)
		{
			if (ctype_alnum(substr($format, $fpos, 1)))
			{
				$result .= substr($string, $spos, 1);
				$spos++;
			}
			else
			{
				$result .= substr($format, $fpos, 1);

				if (strpos($ignore, substr($format, $fpos, 1)) === false)
				{
					++$spos;
				}
			}

			++$fpos;
		}

		return $result;
	}

	/**
	 * Formats a phone number.
	 *
	 * @link    http://snippets.symfony-project.org/snippet/157
	 * @param   string the unformatted phone number to format
	 * @param   string the format to use, defaults to '(000) 000-0000'
	 * @return  string the formatted string
	 * @see     format
	 */
	public static function format_phone($string = '', $format = null)
	{
		is_null($format) and $format = static::$config['formatting']['phone'];
		return static::format($string, $format);
	}

	/**
	 * Formats a variable length phone number, using a standard format.
	 *
	 * Usage:
	 *
	 * echo Num::smart_format_phone('1234567'); // 123-4567
	 * echo Num::smart_format_phone('1234567890'); // (123) 456-7890
	 * echo Num::smart_format_phone('91234567890'); // 9 (123) 456-7890
	 * echo Num::smart_format_phone('123456'); // => 123456
	 *
	 *
	 * @param   string     the unformatted phone number to format
	 * @see     format
	 */
	public static function smart_format_phone($string)
	{
		$formats = static::$config['formatting']['smart_phone'];

		if(is_array($formats) and isset($formats[strlen($string)]))
		{
			return static::format($string, $formats[strlen($string)]);
		}

		return $string;
	}

	/**
	 * Formats a credit card expiration string. Expects 4-digit string (MMYY).
	 *
	 * @param   string     the unformatted expiration string to format
	 * @param   string     the format to use, defaults to '00-00'
	 * @see     format
	 */
	public static function format_exp($string, $format = null)
	{
		is_null($format) and $format = static::$config['formatting']['exp'];
		return static::format($string, $format);
	}

	/**
	 * Formats (masks) a credit card.
	 *
	 * @param   string     the unformatted credit card number to format
	 * @param   string     the format to use, defaults to '**** **** **** 0000'
	 * @see     mask_string
	 */
	public static function mask_credit_card($string, $format = null)
	{
		is_null($format) and $format = static::$config['formatting']['credit_card'];
		return static::mask_string($string, $format);
	}
}

/* End of file num.php */


text:
package aural

type MessageHandler func(*Playstate, []string)
type handlerMap map[string]MessageHandler

const (
	DEFAULT_PORT int = 28346
)

var handlers handlerMap

func init() {
	handlers = make(handlerMap)

	handlers["LOAD"] = LoadHandler
	handlers["CLEAR"] = ClearHandler
}

func LoadHandler(playstate *Playstate, arguments []string) {
	playstate.Playlist.Queue(arguments[0])
}

func ClearHandler(playstate *Playstate, arguments []string) {
	playstate.Clear()
}

func HandleRequest(playstate *Playstate, kind string, arguments []string) {
	handler, ok := handlers[kind]

	if !ok {
		return
	}

	handler(playstate, arguments)
}


text:
<?php
/**
 * This file belongs to the YIT Plugin Framework.
 *
 * This source file is subject to the GNU GENERAL PUBLIC LICENSE (GPL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.gnu.org/licenses/gpl-3.0.txt
 */

/**
 * ON-OFF Plugin Admin View
 *
 * @package    Yithemes
 * @author     Emanuela Castorina <emanuela.castorina@yithemes.it>
 * @since      1.0.0
 */

if ( ! defined( 'ABSPATH' ) ) {
    exit;
} // Exit if accessed directly

$id = $this->get_id_field( $option['id'] );
$name = $this->get_name_field( $option['id'] );

?>
<div id="<?php echo $id ?>-container" <?php if ( isset( $option['deps'] ) ): ?>data-field="<?php echo $id ?>" data-dep="<?php echo $this->get_id_field( $option['deps']['ids'] ) ?>" data-value="<?php echo $option['deps']['values'] ?>" <?php endif ?> class="onoff_container yit_options rm_option rm_input rm_onoff">

        <input type="checkbox" name="<?php echo $name ?>" id="<?php echo $id ?>" value="<?php echo esc_attr( $db_value ) ?>" <?php checked( $db_value, 'yes' ); ?> class="on_off<?php if ( $db_value == 'yes' ): ?> onoffchecked<?php endif ?>" <?php echo $custom_attributes ?>/>

    <?php echo $option['desc'] ?>


text:
title: React Table component
components: Table, TableBody, TableCell, TableContainer, TableFooter, TableHead, TablePagination, TableRow, TableSortLabel
---

# Table (テーブル)

Tables display sets of data. それらは完全にカスタマイズできます。

[Tables](https://material.io/design/components/data-tables.html) display information in a way that's easy to scan, so that users can look for patterns and insights. Cardなどの他のプライマリーコンテンツを埋め込むことができます。

Tables can include:

- 対応の可視化
- ナビゲーション
- データを照会および操作するためのツール

ツールを含めるときは、ツールをテーブルの真上または真下に配置します。

## Structure

飾り気のないシンプルな例です。

Data tableの上部には、列名をリストするヘッダー行があり、その後にデータ用の行が続きます。

## Sorting & Selecting

The `Table` component has a close mapping to the native `<table>` elements. This constraint makes building rich data tables challenging.

The [`DataGrid` component](/components/data-grid/) is designed for use-cases that are focused around handling a large amounts of tabular data. While it comes with a more rigid structure, in exchange, you gain more powerful features.

{{"demo": "pages/components/tables/DataTable.js", "bg": "inline"}}

## Simple Table

ユーザーがデータを選択または操作する必要がある場合は、チェックボックスを各行に付ける必要があります。

{{"demo": "pages/components/tables/DenseTable.js", "bg": true}}

## Dense Table

An example of a table with expandable rows, revealing more information. It utilizes the [`Collapse`](/api/collapse/) component.

テーブルは水平スクロールを示すために固定幅が与えられています。 テーブルは水平スクロールを示すために固定幅が与えられています。 ページ付けコントロールがスクロールするのを防ぐために、TablePaginationコンポーネントはTableの外側で使用されます。 (下記の ['カスタムテーブルページネーションアクション'の例](#custom-pagination-actions) は、TableFooter内のページネーションを示しています。) テーブルは水平スクロールを示すために固定幅が与えられています。 テーブルは水平スクロールを示すために固定幅が与えられています。 ページ付けコントロールがスクロールするのを防ぐために、TablePaginationコンポーネントはTableの外側で使用されます。 (下記の ['カスタムテーブルページネーションアクション'の例](#custom-pagination-actions) は、TableFooter内のページネーションを示しています。) テーブルは水平スクロールを示すために固定幅が与えられています。 ページ付けコントロールがスクロールするのを防ぐために、TablePaginationコンポーネントはTableの外側で使用されます。 (下記の ['カスタムテーブルページネーションアクション'の例](#custom-pagination-actions) は、TableFooter内のページネーションを示しています。)

{{"demo": "pages/components/tables/EnhancedTable.js", "bg": true}}

## Customized tables

コンポーネントのカスタマイズ例を次に示します。 コンポーネントのカスタマイズ例を次に示します。 コンポーネントのカスタマイズ例を次に示します。 詳細については、 [オーバーライドのドキュメントページ](/customization/components/)を参照してください。

{{"demo": "pages/components/tables/CustomizedTables.js", "bg": true}}

### Custom pagination options

It's possible to customise the options shown in the "Rows per page" select using the `rowsPerPageOptions` prop. You should either provide an array of:

- **numbers**, each number will be used for the option's label and value.

    ```jsx
    <TablePagination rowsPerPageOptions={[10, 50]} />
    ```

- **objects**, the `value` and `label` keys will be used respectively for the value and label of the option (useful for language strings such as 'All').

    ```jsx
    <TablePagination rowsPerPageOptions={[10, 50, { value: -1, label: 'All' }]} />
    ```

### Custom pagination actions

The `ActionsComponent` prop of the `TablePagination` component allows the implementation of custom actions.

{{"demo": "pages/components/tables/CustomPaginationActionsTable.js", "bg": true}}

## 固定ヘッダー

An example of a table with scrollable rows and fixed column headers. It leverages the `stickyHeader` prop (⚠ no IE 11 support).

{{"demo": "pages/components/tables/StickyHeadTable.js", "bg": true}}

## Collapsible table

An example of a table with expandable rows, revealing more information. It utilizes the [`Collapse`](/api/collapse/) component.

{{"demo": "pages/components/tables/CollapsibleTable.js", "bg": true}}

## Spanning Table

行 & 列にまたがる単純な例です。

{{"demo": "pages/components/tables/SpanningTable.js", "bg": true}}

## Virtualized Table

次の例では、 `Table` コンポーネントで [react-virtualized](https://github.com/bvaughn/react-virtualized) を使用する方法を示します。 これは200行をレンダリングし、より多くを簡単に処理できます。 仮想化はパフォーマンスの問題に役立ちます。

{{"demo": "pages/components/tables/ReactVirtualizedTable.js", "bg": true}}

## アクセシビリティ

(WAI tutorial: https://www.w3.org/WAI/tutorials/tables/)

### Caption

A caption functions like a heading for a table. Most screen readers announce the content of captions. Captions help users to find a table and understand what it's about and decide if they want to read it.

{{"demo": "pages/components/tables/AcccessibleTable.js", "bg": true}}


text:
module Bluepill
  def self.application(app_name, options = {}, &block)
    app_proxy = AppProxy.new(app_name, options)
    if block.arity == 0
      app_proxy.instance_eval &block
    else
      app_proxy.instance_exec(app_proxy, &block)
    end
    app_proxy.app.load
  end
end


text:
#include "stdafx.h"
#include "progress_dlg.h"
#include "base/utility.h"
#include "crash_info_reader.h"

LRESULT CProgressDlg::OnInitDialog(UINT /*uMsg*/, WPARAM /*wParam*/,
    LPARAM /*lParam*/, BOOL& /*bHandled*/) {
  // Check if current UI language is an RTL language
  CString sRTL = Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T(
      "Settings"), _T("RTLReading"));
  if (sRTL.CompareNoCase(_T("1")) == 0) {
    // Mirror this window
    Utility::SetLayoutRTL( m_hWnd);
  }

  HICON hIcon = NULL;

  // Try to load custom icon
  hIcon = g_CrashInfo.GetCustomIcon();
  if (hIcon == NULL)
    hIcon = ::LoadIcon(_Module.GetResourceInstance(), MAKEINTRESOURCE(
        IDR_MAINFRAME));

  SetIcon(hIcon, FALSE);
  SetIcon(hIcon, TRUE);

  m_statText = GetDlgItem(IDC_TEXT);
  m_statText.SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
      _T("ProgressDlg"), _T("CollectingCrashInfo")));

  m_prgProgress = GetDlgItem(IDC_PROGRESS);
  m_prgProgress.SetRange(0, 100);
  m_prgProgress.ModifyStyle(0, PBS_MARQUEE);

  m_listView = GetDlgItem(IDC_LIST);
  m_listView.SetExtendedListViewStyle(LVS_EX_FULLROWSELECT,
      LVS_EX_FULLROWSELECT);
  m_listView.InsertColumn(0, _T("Status"), LVCFMT_LEFT, 2048);

  m_btnCancel = GetDlgItem(IDCANCEL);
  m_btnCancel.SetWindowText(Utility::GetINIString(g_CrashInfo.m_sLangFileName,
      _T("ProgressDlg"), _T("Cancel")));

  m_ActionOnCancel = DONT_CLOSE;
  m_ActionOnClose = CLOSE_MYSELF;

  DlgResize_Init();

  return TRUE;
}

LRESULT CProgressDlg::OnClose(UINT /*uMsg*/, WPARAM /*wParam*/,
    LPARAM /*lParam*/, BOOL& /*bHandled*/) {
  if (m_ActionOnClose == CLOSE_MYSELF_AND_PARENT) {
    AnimateWindow(m_hWnd, 200, AW_HIDE | AW_BLEND);

    HWND hWndParent = ::GetParent(m_hWnd);
    ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
    return 0;
  } else if (m_ActionOnClose == CLOSE_MYSELF) {
    AnimateWindow(m_hWnd, 200, AW_HIDE | AW_BLEND);
    return 0;
  }

  return 0;
}

LRESULT CProgressDlg::OnCancel(WORD /*wNotifyCode*/, WORD /*wID*/,
    HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
  if (m_ActionOnCancel == CLOSE_MYSELF_AND_PARENT) {
    AnimateWindow(m_hWnd, 200, AW_HIDE | AW_BLEND);

    HWND hWndParent = ::GetParent(m_hWnd);
    ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
    return 0;
  } else if (m_ActionOnCancel == CLOSE_MYSELF) {
    AnimateWindow(m_hWnd, 200, AW_HIDE | AW_BLEND);
    return 0;
  }

  // Start cancelling the worker thread
  g_ErrorReportSender.Cancel();

  // Disable Cancel button
  m_btnCancel.EnableWindow(0);

  return 0;
}

void CProgressDlg::Start(BOOL bCollectInfo, BOOL bMakeVisible) {
  if (bCollectInfo) {
    CString sCaption;
    sCaption.Format(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T(
        "ProgressDlg"), _T("DlgCaption2")), g_CrashInfo.m_sAppName);
    SetWindowText(sCaption);
  } else {
    CString sCaption;
    sCaption.Format(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T(
        "ProgressDlg"), _T("DlgCaption")), g_CrashInfo.m_sAppName);
    SetWindowText(sCaption);
  }

  SetWindowPos(HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE);

  // Center the dialog on the screen
  CenterWindow();

  if (!g_CrashInfo.m_bSilentMode && bMakeVisible) {
    ShowWindow( SW_SHOW);
    SetFocus();
  }

  if (!bCollectInfo) {
    SetTimer(1, 3000); // Hide this dialog in 3 sec.
  }

  SetTimer(0, 200); // Update this dialog each 200 ms.

  m_ActionOnCancel = DONT_CLOSE;
}

void CProgressDlg::Stop() {
  KillTimer(0);
  KillTimer(1);
}
// TODO(yesp) : Öع¹¸Ãº¯Êý£¬
//  Ó¦¸ÃʹÓÃstatic textÈ¡´úÕâÀïµÄlist,·ñÔòÏÔʾ̫¶àµÄÐÅÏ¢²»ºÃ¡£
//  ²¢ÇÒÕû¸ö·¢Ë͹ý³ÌÓ¦¸ÃÊÇÓÐÒ»¸ö½ø¶ÈÌõ£¬¶ø²»ÊÇÒ»¸öСÈÎÎñ¾Í100%¡£
//  ÿ¸öС¹ý³ÌÓ¦¸Ã¶¯Ì¬¸üÐÂstatic textµÄÎı¾£¬²¢ÇÒ¸üнø¶ÈÌõ¼´¿É¡£
LRESULT CProgressDlg::OnTimer(UINT /*uMsg*/, WPARAM wParam, LPARAM /*lParam*/,
    BOOL& /*bHandled*/) {
  WORD wTimerId = (WORD) wParam;

  if (wTimerId == 0) // Dialog update timer
  {
    // Get current progress
    int nProgressPct = 0;
    std::vector<CString> messages;
    g_ErrorReportSender.GetStatus(nProgressPct, messages);

    // Update progress bar
    m_prgProgress.SetPos(nProgressPct);

    int attempt = 0; // Sending attempt

    unsigned i;
    for (i = 0; i < messages.size(); i++) {
      if (messages[i].CompareNoCase(_T("[creating_dump]")) == 0) {
        m_ActionOnCancel = DONT_CLOSE;
        m_ActionOnClose = CLOSE_MYSELF_AND_PARENT;
        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T(
                "CollectingCrashInfo")));
      } else if (messages[i].CompareNoCase(_T("[copying_files]")) == 0) {
        m_ActionOnCancel = DONT_CLOSE;
        m_ActionOnClose = CLOSE_MYSELF_AND_PARENT;
        // Remove marquee style from progress bar
        m_prgProgress.ModifyStyle(PBS_MARQUEE, 0);
      } else if (messages[i].CompareNoCase(_T("[confirm_send_report]")) == 0) {
        m_ActionOnCancel = CLOSE_MYSELF_AND_PARENT;

        if (!g_CrashInfo.m_bSilentMode)
          ShowWindow( SW_HIDE);

        HWND hWndParent = ::GetParent(m_hWnd);
        ::PostMessage(hWndParent, WM_COMPLETECOLLECT, 0, 0);
      } else if (messages[i].CompareNoCase(_T("[exporting_report]")) == 0) {
        m_ActionOnCancel = DONT_CLOSE;
        m_ActionOnClose = DONT_CLOSE;
        CString sCaption;
        sCaption.Format(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T(
            "ProgressDlg"), _T("DlgCaptionExport")), g_CrashInfo.m_sAppName);
        SetWindowText(sCaption);

        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T(
                "CompressingFiles")));

        m_btnCancel.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T("Cancel")));

        ShowWindow( SW_SHOW);
      } else if (messages[i].CompareNoCase(_T("[end_exporting_report_ok]"))
          == 0) {
        m_ActionOnCancel = CLOSE_MYSELF;
        ShowWindow( SW_HIDE);
      } else if (messages[i].CompareNoCase(_T("[end_exporting_report_failed]"))
          == 0) {
        m_ActionOnCancel = CLOSE_MYSELF;
        m_ActionOnClose = CLOSE_MYSELF;
        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T(
                "ExportedWithErrors")));
        m_btnCancel.EnableWindow(1);
        m_btnCancel.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T("Close")));
      } else if (messages[i].CompareNoCase(_T("[compressing_files]")) == 0) {
        m_ActionOnCancel = DONT_CLOSE;
        m_ActionOnClose = CLOSE_MYSELF;
        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T(
                "CompressingFiles")));
        m_btnCancel.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T("Cancel")));
      } else if (messages[i].CompareNoCase(_T("[end_compressing_files]")) == 0) {
        if (!g_CrashInfo.m_bSendErrorReport && g_CrashInfo.m_bStoreZIPArchives) {
          m_ActionOnCancel = CLOSE_MYSELF;
          m_ActionOnClose = CLOSE_MYSELF;
          HWND hWndParent = ::GetParent(m_hWnd);
          ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
        }
      } else if (messages[i].CompareNoCase(_T("[status_success]")) == 0) {
        m_ActionOnCancel = CLOSE_MYSELF_AND_PARENT;
        m_ActionOnClose = CLOSE_MYSELF_AND_PARENT;
        HWND hWndParent = ::GetParent(m_hWnd);
        ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
      } else if (messages[i].CompareNoCase(_T("[status_failed]")) == 0) {
        m_ActionOnCancel = CLOSE_MYSELF_AND_PARENT;
        m_ActionOnClose = CLOSE_MYSELF_AND_PARENT;
        KillTimer(1);
        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T(
                "CompletedWithErrors")));

        m_btnCancel.EnableWindow(1);
        m_btnCancel.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T("Close")));

        if (!g_CrashInfo.m_bSilentMode)
          ShowWindow( SW_SHOW);
        else {
          HWND hWndParent = ::GetParent(m_hWnd);
          ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
        }
      } else if (messages[i].CompareNoCase(_T("[exit_silently]")) == 0) {
        m_ActionOnCancel = CLOSE_MYSELF_AND_PARENT;
        m_ActionOnClose = CLOSE_MYSELF_AND_PARENT;
        KillTimer(1);
        HWND hWndParent = ::GetParent(m_hWnd);
        ::PostMessage(hWndParent, WM_CLOSE, 0, 0);
      } else if (messages[i].CompareNoCase(_T("[cancelled_by_user]")) == 0) {
        m_statText.SetWindowText(Utility::GetINIString(
            g_CrashInfo.m_sLangFileName, _T("ProgressDlg"), _T("Cancelling")));
      } else if (messages[i].CompareNoCase(_T("[sending_attempt]")) == 0) {
        attempt++;
        CString str;
        str.Format(Utility::GetINIString(g_CrashInfo.m_sLangFileName, _T(
            "ProgressDlg"), _T("StatusText")), attempt);
        m_statText.SetWindowText(str);
      }

      int count = m_listView.GetItemCount();
      int indx = m_listView.InsertItem(count, messages[i]);
      m_listView.EnsureVisible(indx, TRUE);

    }
  } else if (wTimerId == 1) // The timer that hides this window
  {
    if (!g_CrashInfo.m_bSilentMode)
      AnimateWindow(m_hWnd, 200, AW_HIDE | AW_BLEND);
    KillTimer(1);
  }

  return 0;
}

//  Õâ¸öÖ÷ÒªÊǽâ¾ö·¢ËͱÀÀ£±¨¸æʧ°ÜµÄÇé¿ö¡£
// µ«ÊÇÈç¹ûÊÇ¿Í»§¶ËÈí¼þ£¬Èç¹ûʧ°Ü±ãÓ¦¸ÃÍ˳ö£¬ÕâÑùÓû§ÌåÑé»á±È½ÏºÃ£¬
//  ²¢ÇÒÒ²²»ºÏÊÊ͸¶̫¶àÊÕ¼¯±ÀÀ£±¨¸æµÄ¾ßÌåϸ½Ú¡£
LRESULT CProgressDlg::OnListRClick(int /*idCtrl*/, LPNMHDR pnmh, BOOL& /*bHandled*/) {
  LPNMITEMACTIVATE lpnmitem = (LPNMITEMACTIVATE) pnmh;

  POINT pt;
  GetCursorPos(&pt);

  CMenu popup_menu;
  popup_menu.LoadMenu(IDR_POPUPMENU);

  CMenu submenu = popup_menu.GetSubMenu(0);

  if (lpnmitem->iItem < 0) {
    submenu.EnableMenuItem(ID_MENU1_COPYSEL, MF_BYCOMMAND | MF_GRAYED);
  }

  CString sCopySelLines = Utility::GetINIString(g_CrashInfo.m_sLangFileName,
      _T("ProgressDlg"), _T("CopySelectedLines"));
  CString sCopyWholeLog = Utility::GetINIString(g_CrashInfo.m_sLangFileName,
      _T("ProgressDlg"), _T("CopyTheWholeLog"));

  MENUITEMINFO mii;
  memset(&mii, 0, sizeof(MENUITEMINFO));
  mii.cbSize = sizeof(MENUITEMINFO);
  mii.fMask = MIIM_STRING;

  mii.dwTypeData = sCopySelLines.GetBuffer(0);
  mii.cch = sCopySelLines.GetLength();
  submenu.SetMenuItemInfo(ID_MENU1_COPYSEL, FALSE, &mii);

  mii.dwTypeData = sCopyWholeLog.GetBuffer(0);
  mii.cch = sCopyWholeLog.GetLength();
  submenu.SetMenuItemInfo(ID_MENU1_COPYLOG, FALSE, &mii);

  submenu.TrackPopupMenu(TPM_LEFTALIGN, pt.x, pt.y, m_hWnd);
  return 0;
}

LRESULT CProgressDlg::OnCopySel(WORD /*wNotifyCode*/, WORD /*wID*/,
    HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
  CString sData;
  int i;
  for (i = 0; i < m_listView.GetItemCount(); i++) {
    DWORD dwState = m_listView.GetItemState(i, LVIS_SELECTED);
    if (dwState == 0)
      continue;

    TCHAR buf[4096];
    buf[0] = 0;
    int n = m_listView.GetItemText(i, 0, buf, 4095);
    sData += CString(buf, n);
    sData += "\r\n";
  }

  SetClipboard(sData);

  return 0;
}

LRESULT CProgressDlg::OnCopyLog(WORD /*wNotifyCode*/, WORD /*wID*/,
    HWND /*hWndCtl*/, BOOL& /*bHandled*/) {
  CString sData;
  int i;
  for (i = 0; i < m_listView.GetItemCount(); i++) {
    TCHAR buf[4096];
    buf[0] = 0;
    int n = m_listView.GetItemText(i, 0, buf, 4095);
    sData += CString(buf, n);
    sData += "\r\n";
  }

  SetClipboard(sData);

  return 0;
}

int CProgressDlg::SetClipboard(CString& sData) {
  if (OpenClipboard()) {
    EmptyClipboard();
    HGLOBAL hClipboardData;
    DWORD dwSize = (sData.GetLength() + 1) * sizeof(TCHAR);
    hClipboardData = GlobalAlloc(GMEM_DDESHARE, dwSize);
    TCHAR* pszData = (TCHAR*) GlobalLock(hClipboardData);
    if (pszData != NULL) {
      _TCSNCPY_S(pszData, dwSize/sizeof(TCHAR), sData, sData.GetLength()*sizeof(TCHAR));
      GlobalUnlock(hClipboardData);
#ifdef _UNICODE
      SetClipboardData(CF_UNICODETEXT, hClipboardData);
#else
      SetClipboardData(CF_TEXT, hClipboardData);
#endif
      CloseClipboard();
      return 0;
    }
    CloseClipboard();
  }

  return 1;
}


text:
<?php

namespace Batna\ArchiBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilder;

class VariableType extends AbstractType
{
    public function buildForm(FormBuilder $builder, array $options)
    {
        $builder
            ->add('name')
        ;
    }

    public function getName()
    {
        return 'batna_archibundle_variabletype';
    }
}


text:
package io.crate.execution.engine.collect.files;

import org.locationtech.spatial4j.shape.Point;

public class SummitsContext {

    public final String mountain;
    public final Integer height;
    public final Integer prominence;
    public final Point coordinates;
    public final String range;
    public final String region;
    public final String classification;
    public final String country;
    public final Integer firstAscent;

    SummitsContext(String mountain,
                   Integer height,
                   Integer prominence,
                   Point coordinates,
                   String region,
                   String classification,
                   String range,
                   String country,
                   Integer firstAscent) {
        this.mountain = mountain;
        this.height = height;
        this.prominence = prominence;
        this.coordinates = coordinates;
        this.range = range;
        this.region = region;
        this.classification = classification;
        this.country = country;
        this.firstAscent = firstAscent;
    }

    public String mountain() {
        return mountain;
    }

    public Integer height() {
        return height;
    }

    public Integer prominence() {
        return prominence;
    }

    public Point coordinates() {
        return coordinates;
    }

    public String range() {
        return range;
    }

    public String region() {
        return region;
    }

    public String classification() {
        return classification;
    }

    public String country() {
        return country;
    }

    public Integer firstAscent() {
        return firstAscent;
    }
}


text:
{% extends "comments/base_comments.html" %}

{% load i18n %}

{% block title %}{% trans "Edit comment" %}{% endblock %}

{% block content_title %}

{% trans "Edit comment" %}

{% endblock %}

{% block content %}
  {% load stringutils %}

  <form action=".{% if request.GET.next %}?next={{ request.GET.next }}{% endif %}" method="post">{% csrf_token %}
    {{ form|format_fields }}

      <button type="submit">{% trans "Save" %}</button>

  </form>
{% endblock %}


text:
<?php

/**
 * Tour form view.
 *
 * @var \yii\base\View $this View
 * @var \yii\widgets\ActiveForm $form Form
 * @var \modules\directory\models\Tour $model Model
 * @var \vova07\themes\admin\widgets\Box $box Box widget instance
 */

use modules\directory\Module;
use yii\helpers\Html;
use yii\helpers\Url;
use modules\base\components\ActiveForm;
use yii\helpers\ArrayHelper;
use dosamigos\fileinput\BootstrapFileInput;
use modules\translations\models\Lang;
use kartik\switchinput\SwitchInput;
use kartik\date\DatePicker;
use kartik\depdrop\DepDrop;
use modules\users\models\User;
use modules\directory\models\TourType;
use modules\directory\models\Region;
use modules\directory\models\Province;
use modules\directory\models\City;
use modules\directory\models\TourOfferType;
?>
<?php $form = ActiveForm::begin([
    'enableAjaxValidation' => true,
    'enableClientValidation' => false,
    'options' => [
        'id' => 'tour_form',
        'enctype' => 'multipart/form-data',
    ]
]); ?>
<?php $box->beginBody(); ?>
    <?if($model->id):?>

                <?=Html::label($formModel->getAttributeLabel('id'))?>
                <?= $model->id ?>

    <?endif?>

            <?= $form->field($formModel, 'frontend')->widget(SwitchInput::className(), []) ?>

            <?= $form->field($formModel, 'provider_id')->dropDownList(ArrayHelper::map(User::find()->all(), 'id', 'username')) ?>

            <?= $form->field($formModel, 'seller_name')->textInput() ?>

            <?= $form->field($formModel, 'seller_phone')->textInput() ?>

            <?= $form->field($formModel, 'seller_email')->textInput() ?>

            <?= $form->field($formModel, 'tour_type_id')->dropDownList(ArrayHelper::map(TourType::find()->all(), 'id', 'name')) ?>

    <?
    $languages = Lang::find()->all();
    foreach($languages as $language):?>

                <?= $form->field($formModel, 'translationName[' . $language->id . ']', ['options' => ['class' => 'form-group']])->textInput()->label(
                    $formModel->getAttributeLabel('translationName').', '.$language->name
                );?>

    <?endforeach;?>

            <?= $form->field($formModel, 'days_cnt')->textInput() ?>

            <?= $form->field($formModel, 'nights_cnt')->textInput() ?>

            <?=$form->field($formModel, 'region_id')->dropDownList(ArrayHelper::map(Region::find()->all(), 'id', 'name'), [
                'id'=>'tourform-region_id',
                'prompt' => $formModel->getAttributeLabel('region_id'),
            ])?>

            <?= $form->field($formModel, 'province_id')->widget(DepDrop::classname(), [
                'id'=>'tourform-province_id',
                'data'=> ArrayHelper::map(Province::find()->where(['region_id'=>$formModel->region_id])->all(), 'id', 'name'),
                'options'=>[
                    'prompt' => $formModel->getAttributeLabel('province_id'),
                ],
                'pluginOptions'=>[
                    'depends'=>['tourform-region_id'],
                    'placeholder' => $formModel->getAttributeLabel('province_id'),
                    'url'=>Url::to(['/base/ajax/get-provinces']),
                ],
                'pluginEvents' => [
                    "depdrop.afterChange"=>"function(event, id, value) {}",
                ],
            ]);?>

            <?= $form->field($formModel, 'city_id')->widget(DepDrop::classname(), [
                'data'=> ArrayHelper::map(City::find()->where(['province_id'=>$formModel->province_id])->all(), 'id', 'name'),
                'options'=>[
                    'prompt' => $formModel->getAttributeLabel('city_id'),
                ],
                'pluginOptions'=>[
                    'depends'=>['tourform-region_id', 'tourform-province_id'],
                    'placeholder' => $formModel->getAttributeLabel('city_id'),
                    'url'=>Url::to(['/base/ajax/get-cities']),
                ],
                'pluginEvents' => [
                    "depdrop.afterChange"=>"function(event, id, value) {}",
                ],
            ]);?>

            <?= $form->field($formModel, 'date_start')->widget(DatePicker::className(), [
                'type' => DatePicker::TYPE_COMPONENT_APPEND,
                'pluginOptions' => [
                    'format' => 'dd.mm.yyyy',
                ]
            ]) ?>

            <?= $form->field($formModel, 'price')->textInput()->label($formModel->getAttributeLabel('price').', EUR') ?>

            <?= $form->field($formModel, 'tour_offer_type_id')->dropDownList(ArrayHelper::map(TourOfferType::find()->orderBy('id')->all(), 'id', 'name')) ?>

<?//= $form->field($formModel, 'food_type_id')->dropDownList(ArrayHelper::map(FoodType::find()->all(), 'id', 'name')) ?>

            <?= $form->field($formModel, 'short_description')->textInput() ?>

            <?= $form->field($formModel, 'description')->textarea() ?>

            <?
            $initialPreview = [];
            $previewConfig = [];
            if($formModel->image){
                $initialPreview[] = 'image->getSrc().'" alt="" class="file-preview-image">';
                $previewConfig[] = [
                    'url' => Url::toRoute(['image-delete']),
                    'key' => $formModel->image->id,
                ];
            }
            ?>
            <?= $form->field($formModel, 'image')->widget(BootstrapFileInput::className(), [
                'options' => ['accept' => 'image/*'],
                'clientOptions' => [
                    'browseClass' => 'btn btn-success',
                    'uploadClass' => 'btn btn-info',
                    'removeClass' => 'btn btn-danger',
                    'removeIcon' => ' ',
                    'showUpload' => false,
                    'initialPreview' => $initialPreview,
                    'initialPreviewConfig' => $previewConfig,
                    'showRemove' => false,
                ]
            ]);?>

            <?
            $initialPreview = [];
            $previewConfig = [];
            if($formModel->additional_image){
                $initialPreview[] = 'additional_image->getSrc().'" alt="" class="file-preview-image">';
                $previewConfig[] = [
                    'url' => Url::toRoute(['image-delete']),
                    'key' => $formModel->additional_image->id,
                ];
            }
            ?>
            <?= $form->field($formModel, 'additional_image')->widget(BootstrapFileInput::className(), [
                'options' => ['accept' => 'image/*'],
                'clientOptions' => [
                    'browseClass' => 'btn btn-success',
                    'uploadClass' => 'btn btn-info',
                    'removeClass' => 'btn btn-danger',
                    'removeIcon' => ' ',
                    'showUpload' => false,
                    'initialPreview' => $initialPreview,
                    'initialPreviewConfig' => $previewConfig,
                    'showRemove' => false,
                ]
            ]);?>

<?php $box->endBody(); ?>
<?php $box->beginFooter(); ?>
<?= Html::submitButton(
    $model->isNewRecord ? Module::t('showplace', 'BACKEND_CREATE_SUBMIT') : Module::t(
        'showplace',
        'BACKEND_UPDATE_SUBMIT'
    ),
    [
        'class' => $model->isNewRecord ? 'btn btn-primary btn-large' : 'btn btn-success btn-large'
    ]
) ?>
<?php $box->endFooter(); ?>
<?php ActiveForm::end(); ?>


text:
/**
 * You need to provide compile flag -DHZ_BUILD_WITH_SSL when compiling since Aws
 * depends on openssl library.
 *
 * DO NOT FORGET to make sure that openssl is installed.
 *
 */
#include <hazelcast/client/hazelcast_client.h>

int
main()
{
    hazelcast::client::client_config clientConfig;

    // Your instance should be inside AWS and the instance profile should have
    // an instance profile associated for a valid IAM role. See
    // http://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html
    clientConfig.get_network_config()
      .get_aws_config()
      .set_enabled(true)
      .set_tag_key("aws-test-tag")
      .set_tag_value("aws-tag-value-1")
      .set_iam_role("MyInstanceRole")
      .set_inside_aws(true);

    auto hz = hazelcast::new_client(std::move(clientConfig)).get();

    auto map = hz.get_map("MyMap").get();

    map->put(1, 100).get();
    map->put(2, 200).get();

    auto value = map->get<int, int>(1).get();

    if (value) {
        std::cout << "Value for key 1 is " << value.value() << std::endl;
    }

    std::cout << "Finished" << std::endl;

    return 0;
}