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

#pragma once

union ActivationOperatorDescUnion
{
    DML_ACTIVATION_IDENTITY_OPERATOR_DESC identity;
    DML_ACTIVATION_ELU_OPERATOR_DESC elu;
    DML_ACTIVATION_CELU_OPERATOR_DESC celu;
    DML_ACTIVATION_HARDMAX_OPERATOR_DESC hardmax;
    DML_ACTIVATION_HARDMAX1_OPERATOR_DESC hardmax1;
    DML_ACTIVATION_HARD_SIGMOID_OPERATOR_DESC hardSigmoid;
    DML_ACTIVATION_LEAKY_RELU_OPERATOR_DESC leakyRelu;
    DML_ACTIVATION_LINEAR_OPERATOR_DESC linear;
    DML_ACTIVATION_LOG_SOFTMAX_OPERATOR_DESC logSoftmax;
    DML_ACTIVATION_LOG_SOFTMAX1_OPERATOR_DESC logSoftmax1;
    DML_ACTIVATION_PARAMETERIZED_RELU_OPERATOR_DESC parameterizedRelu;
    DML_ACTIVATION_PARAMETRIC_SOFTPLUS_OPERATOR_DESC parametricSoftplus;
    DML_ACTIVATION_RELU_OPERATOR_DESC relu;
    DML_ACTIVATION_SCALED_TANH_OPERATOR_DESC scaledTanh;
    DML_ACTIVATION_SCALED_ELU_OPERATOR_DESC scaledElu;
    DML_ACTIVATION_SIGMOID_OPERATOR_DESC sigmoid;
    DML_ACTIVATION_SOFTMAX_OPERATOR_DESC softmax;
    DML_ACTIVATION_SOFTMAX1_OPERATOR_DESC softmax1;
    DML_ACTIVATION_SOFTPLUS_OPERATOR_DESC softplus;
    DML_ACTIVATION_SOFTSIGN_OPERATOR_DESC softsign;
    DML_ACTIVATION_TANH_OPERATOR_DESC tanh;
    DML_ACTIVATION_THRESHOLDED_RELU_OPERATOR_DESC thresholdedRelu;
    DML_ACTIVATION_SHRINK_OPERATOR_DESC shrink;
    DML_ACTIVATION_GELU_OPERATOR_DESC gelu;
};

struct ActivationOperatorDesc
{
    ActivationOperatorDescUnion params;
    DML_OPERATOR_TYPE activationType;

    #pragma warning(push)
    #pragma warning(disable:4702)
    DML_OPERATOR_DESC GetDmlDesc() const
    {
        switch (activationType)
        {
        case DML_OPERATOR_ACTIVATION_ELU: return { activationType, &params.elu };
        case DML_OPERATOR_ACTIVATION_CELU: return { activationType, &params.celu };
        case DML_OPERATOR_ACTIVATION_HARDMAX: return { activationType, &params.hardmax };
        case DML_OPERATOR_ACTIVATION_HARDMAX1: return { activationType, &params.hardmax1 };
        case DML_OPERATOR_ACTIVATION_HARD_SIGMOID: return { activationType, &params.sigmoid };
        case DML_OPERATOR_ACTIVATION_IDENTITY: return { activationType, &params.identity };
        case DML_OPERATOR_ACTIVATION_LEAKY_RELU: return { activationType, &params.leakyRelu };
        case DML_OPERATOR_ACTIVATION_LINEAR: return { activationType, &params.linear };
        case DML_OPERATOR_ACTIVATION_LOG_SOFTMAX: return { activationType, &params.logSoftmax };
        case DML_OPERATOR_ACTIVATION_LOG_SOFTMAX1: return { activationType, &params.logSoftmax1 };
        case DML_OPERATOR_ACTIVATION_PARAMETERIZED_RELU: return { activationType, &params.parameterizedRelu };
        case DML_OPERATOR_ACTIVATION_PARAMETRIC_SOFTPLUS: return { activationType, &params.parametricSoftplus };
        case DML_OPERATOR_ACTIVATION_RELU: return { activationType, &params.relu };
        case DML_OPERATOR_ACTIVATION_SCALED_ELU: return { activationType, &params.scaledElu };
        case DML_OPERATOR_ACTIVATION_SCALED_TANH: return { activationType, &params.scaledTanh };
        case DML_OPERATOR_ACTIVATION_SIGMOID: return { activationType, &params.sigmoid };
        case DML_OPERATOR_ACTIVATION_SOFTMAX: return { activationType, &params.softmax };
        case DML_OPERATOR_ACTIVATION_SOFTMAX1: return { activationType, &params.softmax1 };
        case DML_OPERATOR_ACTIVATION_SOFTPLUS: return { activationType, &params.softplus };
        case DML_OPERATOR_ACTIVATION_SOFTSIGN: return { activationType, &params.softsign };
        case DML_OPERATOR_ACTIVATION_TANH: return { activationType, &params.tanh };
        case DML_OPERATOR_ACTIVATION_THRESHOLDED_RELU: return { activationType, &params.thresholdedRelu };
        case DML_OPERATOR_ACTIVATION_SHRINK: return { activationType, &params.shrink };
        case DML_OPERATOR_ACTIVATION_GELU: return { activationType, &params.gelu };
        default:
            ORT_THROW_HR(E_INVALIDARG);
            return { activationType, &params.relu };
        }
    }
    #pragma warning(pop)
};

// DML_BUFFER_TENSOR_DESC (DML_TENSOR_TYPE_BUFFER)
struct DmlBufferTensorDesc
{
    DML_TENSOR_DATA_TYPE dataType = DML_TENSOR_DATA_TYPE_UNKNOWN;
    DML_TENSOR_FLAGS flags = DML_TENSOR_FLAG_NONE;
    std::vector<uint32_t> sizes;
    std::optional<std::vector<uint32_t>> strides;
    uint64_t totalTensorSizeInBytes = 0;
    uint32_t guaranteedBaseOffsetAlignment = 0;

    DmlBufferTensorDesc() = default;

    /*implicit*/ DmlBufferTensorDesc(const DML_BUFFER_TENSOR_DESC& desc)
        : dataType(desc.DataType)
        , flags(desc.Flags)
        , sizes(desc.Sizes, desc.Sizes + desc.DimensionCount)
        , totalTensorSizeInBytes(desc.TotalTensorSizeInBytes)
        , guaranteedBaseOffsetAlignment(desc.GuaranteedBaseOffsetAlignment)
    {
        if (desc.Strides)
        {
            strides.emplace(desc.Strides, desc.Strides + desc.DimensionCount);
        }
    }

    // Constructs a DmlBufferTensorDesc from a generic DML_TENSOR_DESC. The type must be DML_TENSOR_TYPE_BUFFER.
    /*implicit*/ DmlBufferTensorDesc(const DML_TENSOR_DESC& desc)
        : DmlBufferTensorDesc(*static_cast<const DML_BUFFER_TENSOR_DESC*>(desc.Desc))
    {
        assert(desc.Type == DML_TENSOR_TYPE_BUFFER);
    }
};

template <size_t Size>
class StackAllocator
{
public:
    StackAllocator() = default;

    // Non-copiable, non-movable
    StackAllocator(const StackAllocator&) = delete;
    StackAllocator& operator=(const StackAllocator&) = delete;
    StackAllocator(StackAllocator&&) = delete;
    StackAllocator& operator=(StackAllocator&&) = delete;

    template <typename T>
    T* Allocate(size_t count = 1)
    {
        static_assert(std::is_trivial_v<T>,
            "This class may only be used to allocate trivial types, as it does not invoke constructors.");

        // Allocate from the fixed bucket before falling back to dynamic
        Bucket* lastBucket = m_dynamic.empty() ? static_cast<Bucket*>(&m_fixed) : static_cast<Bucket*>(&m_dynamic.back());

        size_t sizeInBytes = sizeof(T) * count;
        void* memory = lastBucket->TryAllocate(sizeInBytes, alignof(T));

        if (!memory)
        {
            // Not enough capacity remains; allocate a new dynamic bucket
            size_t minimumSize = sizeInBytes;
            m_dynamic.emplace_back(minimumSize);

            memory = m_dynamic.back().TryAllocate(sizeInBytes, alignof(T));
        }

        assert(memory != nullptr);
        return reinterpret_cast<T*>(memory);
    }

    void Reset()
    {
        m_fixed.allocatedSize = 0;
        m_dynamic.clear();
    }

private:
    struct Bucket
    {
        void* data;
        size_t allocatedSize;
        size_t capacity;

        Bucket() = default;

        // Non-copiable, non-movable
        Bucket(const Bucket&) = delete;
        Bucket& operator=(const Bucket&) = delete;
        Bucket(Bucket&&) = delete;
        Bucket& operator=(Bucket&&) = delete;

        void* TryAllocate(size_t sizeInBytes, size_t alignment)
        {
            size_t alignedOffset = RoundUpToMultiple(allocatedSize, alignment);
            size_t newAllocatedSize = alignedOffset + sizeInBytes;

            if (newAllocatedSize > capacity)
            {
                return nullptr; // Not enough capacity
            }

            allocatedSize = newAllocatedSize;
            return static_cast<byte*>(data) + alignedOffset;
        }

        template <typename T>
        static T RoundUpToMultiple(T value, T multiple)
        {
            static_assert(std::is_integral_v<T>);

            T remainder = value % multiple;
            if (remainder != 0)
            {
            	value += multiple - remainder;
            }

            return value;
        }

    };

    struct FixedBucket : Bucket
    {
        std::array<byte, Size> stack;

        FixedBucket()
        {
            this->data = stack.data();
            this->allocatedSize = 0;
            this->capacity = stack.size();
        }
    };

    struct DynamicBucket : Bucket
    {
        explicit DynamicBucket(size_t minimumSize)
        {
            this->allocatedSize = 0;
            this->capacity = this->template RoundUpToMultiple<size_t>(minimumSize, 4096); // Round up to nearest page granularity

            this->data = VirtualAlloc(nullptr, this->capacity, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
            ORT_THROW_LAST_ERROR_IF_NULL(this->data);
        }

        ~DynamicBucket()
        {
            if (this->data)
            {
                (void)VirtualFree(this->data, 0, MEM_RELEASE);
            }
        }
    };

    // This allocator first retrieves memory from a fixed-size stack-allocated array before falling back to dynamically
    // allocated memory if the fixed stack array is exhausted.
    FixedBucket m_fixed;
    std::deque<DynamicBucket> m_dynamic;
};


text:
package git4idea.actions;

import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.progress.ProgressIndicator;
import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.progress.Task;
import com.intellij.openapi.project.DumbAwareAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.containers.ContainerUtil;
import git4idea.rebase.GitRebaseActionDialog;
import git4idea.rebase.GitRebaseUtils;
import git4idea.repo.GitRepository;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.Collection;

import static com.intellij.util.ObjectUtils.assertNotNull;
import static com.intellij.util.containers.ContainerUtil.newArrayList;
import static git4idea.GitUtil.*;

public abstract class GitAbstractRebaseAction extends DumbAwareAction {

  @Override
  public void update(@NotNull AnActionEvent e) {
    super.update(e);
    Project project = e.getProject();
    if (project == null || !hasGitRepositories(project)) {
      e.getPresentation().setEnabledAndVisible(false);
    }
    else {
      e.getPresentation().setEnabledAndVisible(hasRebaseInProgress(project));
    }
  }

  @Override
  public final void actionPerformed(@NotNull AnActionEvent e) {
    final Project project = e.getRequiredData(CommonDataKeys.PROJECT);
    if (getRepositoryManager(project).hasOngoingRebase()) {
      ProgressManager.getInstance().run(new Task.Backgroundable(project, getProgressTitle()) {
        @Override
        public void run(@NotNull ProgressIndicator indicator) {
          performActionForProject(project, indicator);
        }
      });
    }
    else {
      final GitRepository repositoryToOperate = chooseRepository(project, GitRebaseUtils.getRebasingRepositories(project));
      if (repositoryToOperate != null) {
        performInBackground(repositoryToOperate);
      }
    }
  }

  public void performInBackground(@NotNull GitRepository repositoryToOperate) {
    ProgressManager.getInstance().run(new Task.Backgroundable(repositoryToOperate.getProject(), getProgressTitle()) {
      @Override
      public void run(@NotNull ProgressIndicator indicator) {
        performActionForRepository(repositoryToOperate.getProject(), repositoryToOperate, indicator);
      }
    });
  }

  @NotNull
  protected abstract String getProgressTitle();

  protected abstract void performActionForProject(@NotNull Project project, @NotNull ProgressIndicator indicator);

  protected abstract void performActionForRepository(@NotNull Project project,
                                                     @NotNull GitRepository repository,
                                                     @NotNull ProgressIndicator indicator);

  private static boolean hasRebaseInProgress(@NotNull Project project) {
    return !GitRebaseUtils.getRebasingRepositories(project).isEmpty();
  }

  @Nullable
  private GitRepository chooseRepository(@NotNull Project project, @NotNull Collection<GitRepository> repositories) {
    GitRepository firstRepo = assertNotNull(ContainerUtil.getFirstItem(repositories));
    if (repositories.size() == 1) return firstRepo;
    ArrayList<VirtualFile> roots = newArrayList(getRootsFromRepositories(repositories));
    GitRebaseActionDialog dialog = new GitRebaseActionDialog(project, getTemplatePresentation().getText(), roots, firstRepo.getRoot());
    dialog.show();
    VirtualFile root = dialog.selectRoot();
    if (root == null) return null;
    return getRepositoryManager(project).getRepositoryForRootQuick(root); // TODO avoid root <-> GitRepository double conversion
  }
}

redpajama_set_name: RedPajamaGithub


text:
package storage

import (
	"context"
	"database/sql"
	"time"

	"github.com/matrix-org/dendrite/mediaapi/types"
	"github.com/matrix-org/gomatrixserverlib"
)

const thumbnailSchema = `
-- The mediaapi_thumbnail table holds metadata for each thumbnail file stored and accessible to the local server,
-- the actual file is stored separately.
CREATE TABLE IF NOT EXISTS mediaapi_thumbnail (
    -- The id used to refer to the media.
    -- For uploads to this server this is a base64-encoded sha256 hash of the file data
    -- For media from remote servers, this can be any unique identifier string
    media_id TEXT NOT NULL,
    -- The origin of the media as requested by the client. Should be a homeserver domain.
    media_origin TEXT NOT NULL,
    -- The MIME-type of the thumbnail file.
    content_type TEXT NOT NULL,
    -- Size of the thumbnail file in bytes.
    file_size_bytes BIGINT NOT NULL,
    -- When the thumbnail was generated in UNIX epoch ms.
    creation_ts BIGINT NOT NULL,
    -- The width of the thumbnail
    width INTEGER NOT NULL,
    -- The height of the thumbnail
    height INTEGER NOT NULL,
    -- The resize method used to generate the thumbnail. Can be crop or scale.
    resize_method TEXT NOT NULL
);
CREATE UNIQUE INDEX IF NOT EXISTS mediaapi_thumbnail_index ON mediaapi_thumbnail (media_id, media_origin, width, height, resize_method);
`

const insertThumbnailSQL = `
INSERT INTO mediaapi_thumbnail (media_id, media_origin, content_type, file_size_bytes, creation_ts, width, height, resize_method)
    VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
`

// Note: this selects one specific thumbnail
const selectThumbnailSQL = `
SELECT content_type, file_size_bytes, creation_ts FROM mediaapi_thumbnail WHERE media_id = $1 AND media_origin = $2 AND width = $3 AND height = $4 AND resize_method = $5
`

// Note: this selects all thumbnails for a media_origin and media_id
const selectThumbnailsSQL = `
SELECT content_type, file_size_bytes, creation_ts, width, height, resize_method FROM mediaapi_thumbnail WHERE media_id = $1 AND media_origin = $2
`

type thumbnailStatements struct {
	insertThumbnailStmt  *sql.Stmt
	selectThumbnailStmt  *sql.Stmt
	selectThumbnailsStmt *sql.Stmt
}

func (s *thumbnailStatements) prepare(db *sql.DB) (err error) {
	_, err = db.Exec(thumbnailSchema)
	if err != nil {
		return
	}

	return statementList{
		{&s.insertThumbnailStmt, insertThumbnailSQL},
		{&s.selectThumbnailStmt, selectThumbnailSQL},
		{&s.selectThumbnailsStmt, selectThumbnailsSQL},
	}.prepare(db)
}

func (s *thumbnailStatements) insertThumbnail(
	ctx context.Context, thumbnailMetadata *types.ThumbnailMetadata,
) error {
	thumbnailMetadata.MediaMetadata.CreationTimestamp = types.UnixMs(time.Now().UnixNano() / 1000000)
	_, err := s.insertThumbnailStmt.ExecContext(
		ctx,
		thumbnailMetadata.MediaMetadata.MediaID,
		thumbnailMetadata.MediaMetadata.Origin,
		thumbnailMetadata.MediaMetadata.ContentType,
		thumbnailMetadata.MediaMetadata.FileSizeBytes,
		thumbnailMetadata.MediaMetadata.CreationTimestamp,
		thumbnailMetadata.ThumbnailSize.Width,
		thumbnailMetadata.ThumbnailSize.Height,
		thumbnailMetadata.ThumbnailSize.ResizeMethod,
	)
	return err
}

func (s *thumbnailStatements) selectThumbnail(
	ctx context.Context,
	mediaID types.MediaID,
	mediaOrigin gomatrixserverlib.ServerName,
	width, height int,
	resizeMethod string,
) (*types.ThumbnailMetadata, error) {
	thumbnailMetadata := types.ThumbnailMetadata{
		MediaMetadata: &types.MediaMetadata{
			MediaID: mediaID,
			Origin:  mediaOrigin,
		},
		ThumbnailSize: types.ThumbnailSize{
			Width:        width,
			Height:       height,
			ResizeMethod: resizeMethod,
		},
	}
	err := s.selectThumbnailStmt.QueryRowContext(
		ctx,
		thumbnailMetadata.MediaMetadata.MediaID,
		thumbnailMetadata.MediaMetadata.Origin,
		thumbnailMetadata.ThumbnailSize.Width,
		thumbnailMetadata.ThumbnailSize.Height,
		thumbnailMetadata.ThumbnailSize.ResizeMethod,
	).Scan(
		&thumbnailMetadata.MediaMetadata.ContentType,
		&thumbnailMetadata.MediaMetadata.FileSizeBytes,
		&thumbnailMetadata.MediaMetadata.CreationTimestamp,
	)
	return &thumbnailMetadata, err
}

func (s *thumbnailStatements) selectThumbnails(
	ctx context.Context, mediaID types.MediaID, mediaOrigin gomatrixserverlib.ServerName,
) ([]*types.ThumbnailMetadata, error) {
	rows, err := s.selectThumbnailsStmt.QueryContext(
		ctx, mediaID, mediaOrigin,
	)
	if err != nil {
		return nil, err
	}

	var thumbnails []*types.ThumbnailMetadata
	for rows.Next() {
		thumbnailMetadata := types.ThumbnailMetadata{
			MediaMetadata: &types.MediaMetadata{
				MediaID: mediaID,
				Origin:  mediaOrigin,
			},
		}
		err = rows.Scan(
			&thumbnailMetadata.MediaMetadata.ContentType,
			&thumbnailMetadata.MediaMetadata.FileSizeBytes,
			&thumbnailMetadata.MediaMetadata.CreationTimestamp,
			&thumbnailMetadata.ThumbnailSize.Width,
			&thumbnailMetadata.ThumbnailSize.Height,
			&thumbnailMetadata.ThumbnailSize.ResizeMethod,
		)
		if err != nil {
			return nil, err
		}
		thumbnails = append(thumbnails, &thumbnailMetadata)
	}

	return thumbnails, err
}


text:
<?php

namespace upendo\exceptions;

class Exception extends \Exception
{
    public function __construct($message = null, $code = 0)
    {
        parent::__construct($message, $code);
    }
}


text:
Joose.Meta.Class = new Joose.Managed.Class('Joose.Meta.Class', {

    isa                         : Joose.Managed.Class,

    does                        : Joose.Managed.Bootstrap,

    have : {
        defaultSuperClass       : Joose.Meta.Object
    }

}).c


text:
package org.clamshellcli.api;

import java.util.regex.Pattern;

/**
 * The role of the InputController component is to take a input from the command line
 * and interpret it accordingly.  A simple implementation may include all logic,
 * however, more sophisticated implementations may delegate workload to Command
 * objects.
 * @author vladimir.vivien
 */
public interface InputController extends Plugin{
    /**
     * This method is invoked when there is an input from the console to be interpreted.
     * The input value is passed to the controller via the context instance
     * as Context.KEY_COMMAND_LINE_INPUT.  Implementors should return a boolean
     * indicating if the controller handled the input.
     *
     * @param ctx instance of Context
     * @return true - if handled by the controller, false if not.
     */
    public boolean handle(Context ctx);

    /**
     * This method returns a pre-compiled instance of the command-line pattern
     * that the controller responds to.  This mechanism provides a command
     * filter for the controller avoiding unnecessary handle() calls.
     * @return
     */
    public Pattern respondsTo();

    /**
     * A method to set command-line pattern this controller handles.
     * @param p
     */
    public void setInputPattern(Pattern p);

    /**
     * A flag that indicates if the controller is enabled and should participate
     * in input control.
     * @return
     */
    public Boolean isEnabled();

    /**
     * Sets enabled-flag.  When true, controller will receive handling call.
     * @param flag
     */
    public void setEnabled(Boolean flag);
}


text:
var PriorityQueue = function(size) {
    var me = {}, slots, i, total = null;

    // initialize arrays to hold queue elements
    size = Math.max(+size | 0, 1);
    slots = [];
    for (i = 0; i < size; i += 1) {
        slots.push([]);
    }

    //  Public methods
    me.size = function () {
        var i;
        if (total === null) {
            total = 0;
            for (i = 0; i < size; i += 1) {
                total += slots[i].length;
            }
        }
        return total;
    };

    me.enqueue = function (obj, priority) {
        var priorityOrig;

        // Convert to integer with a default value of 0.
        priority = priority && + priority | 0 || 0;

        // Clear cache for total.
        total = null;
        if (priority) {
            priorityOrig = priority;
            if (priority < 0 || priority >= size) {
                priority = (size - 1);
                // put obj at the end of the line
                console.error("invalid priority: " + priorityOrig + " must be between 0 and " + priority);
            }
        }

        slots[priority].push(obj);
    };

    me.dequeue = function (callback) {
        var obj = null, i, sl = slots.length;

        // Clear cache for total.
        total = null;
        for (i = 0; i < sl; i += 1) {
            if (slots[i].length) {
                obj = slots[i].shift();
                break;
            }
        }
        return obj;
    };

    return me;
};

function Bottleneck(maxConcurrent, rateLimit, priorityRange, defaultPriority, cluster) {
    if(isNaN(maxConcurrent) || isNaN(rateLimit)) {
        throw "maxConcurrent and rateLimit must be numbers";
    }

    priorityRange = priorityRange || 1;
    if(isNaN(priorityRange)) {
        throw "priorityRange must be a number";
    }
    priorityRange = parseInt(priorityRange);
    defaultPriority = defaultPriority ? defaultPriority : Math.floor(priorityRange/2);
    if(isNaN(defaultPriority)) {
        throw "defaultPriority must be a number";
    }
    defaultPriority = defaultPriority >= priorityRange ? priorityRange-1 : defaultPriority;
    defaultPriority = parseInt(defaultPriority);

    this.cluster = cluster;
    this.rateLimit = parseInt(rateLimit);
    this.maxConcurrent = this.rateLimit ? 1 : parseInt(maxConcurrent);
    this._waitingClients = new PriorityQueue(priorityRange);
    this._priorityRange = priorityRange;
    this._defaultPriority = defaultPriority;
    this._nextRequest = Date.now();
    this._tasksRunning = 0;
}

Bottleneck.prototype.setName = function(name) {
    this.name = name;
}

Bottleneck.prototype.submit = function(options, clientCallback) {
    var self = this;
    var priority = null;
    if(typeof options == "number") {
        priority = parseInt(options);
    } else {
        priority = options.priority;
    }
    priority = Number.isInteger(priority) ? priority: self._defaultPriority;
    priority = priority > self._priorityRange-1 ? self._priorityRange-1 : priority;
    this._waitingClients.enqueue(clientCallback, priority);
    self._tryToRun();
    return;
}

Bottleneck.prototype._tryToRun = function() {
    var self = this;
    if(self._tasksRunning < self.maxConcurrent && self.hasWaitingClients()) {
        ++self._tasksRunning;
        var wait = Math.max(self._nextRequest - Date.now(), 0);
        self._nextRequest = Date.now() + wait + self.rateLimit;
        var obj = self.dequeue();
	var next = obj.next;
	var limiter = obj.limiter;
        setTimeout(function(){
            var done = function() {
                --self._tasksRunning;
                self._tryToRun();
            }
            next(done, limiter);
        }, wait);
    }
    return;
}

Bottleneck.prototype.hasWaitingClients = function() {
    if(this._waitingClients.size()) {
	return true;
    }
    if(this.cluster && this.cluster._waitingClients()) {
	return true;
    }
    return false;
}

Bottleneck.prototype.dequeue = function() {
    if(this._waitingClients.size()) {
	return {
	    next: this._waitingClients.dequeue(),
	    limiter: null
	};
    }
    return this.cluster.dequeue(this.name);
}

Bottleneck.Cluster = Bottleneck.prototype.Cluster = require("./Cluster");

module.exports = Bottleneck;


text:
package org.docksidestage.mysql.dbflute.allcommon;

import org.dbflute.Entity;
import org.dbflute.bhv.BehaviorReadable;
import org.dbflute.bhv.BehaviorSelector;
import org.dbflute.bhv.core.BehaviorCommandInvoker;
import org.dbflute.cbean.ConditionBean;
import org.dbflute.cbean.result.ListResultBean;
import org.dbflute.dbmeta.DBMeta;
import org.docksidestage.mysql.dbflute.bsentity.dbmeta.MemberDbm;
import org.docksidestage.mysql.dbflute.cbean.MemberCB;
import org.docksidestage.mysql.dbflute.exbhv.MemberBhv;
import org.docksidestage.mysql.dbflute.exentity.Member;
import org.docksidestage.mysql.unit.UnitContainerTestCase;
import org.seasar.framework.util.DisposableUtil;

/**
 * The test of behaviorSelector.
 * @author jflute
 * @since 0.8.3 (2008/11/05 Wednesday)
 */
public class BehaviorSelectorTest extends UnitContainerTestCase {

    // ===================================================================================
    //                                                                           Attribute
    //                                                                           =========
    private BehaviorSelector behaviorSelector;

    private MemberBhv memberBhv;

    private BehaviorCommandInvoker invoker;

    private ImplementedInvokerAssistant invokerAssistant;

    // ===================================================================================
    //                                                                          Initialize
    //                                                                          ==========
    public void test_BehaviorSelector_initializeConditionBeanMetaData() {
        // ## Arrange ##
        DisposableUtil.dispose();
        assertTrue(invoker.isExecutionCacheEmpty());
        assertFalse(invokerAssistant.isDisposable());

        // ## Act ##
        behaviorSelector.initializeConditionBeanMetaData();

        // ## Assert ##
        assertFalse(invoker.isExecutionCacheEmpty());
        assertTrue(invokerAssistant.isDisposable());
        memberBhv.selectList(new MemberCB()); // Expect no exception!
        memberBhv.selectList(new MemberCB()); // Expect no exception!
        DisposableUtil.dispose();
        assertTrue(invoker.isExecutionCacheEmpty());
        assertFalse(invokerAssistant.isDisposable());
        behaviorSelector.initializeConditionBeanMetaData();
        assertFalse(invoker.isExecutionCacheEmpty());
        assertTrue(invokerAssistant.isDisposable());
        memberBhv.selectList(new MemberCB()); // Expect no exception!
        memberBhv.selectList(new MemberCB()); // Expect no exception!
    }

    // ===================================================================================
    //                                                                              byName
    //                                                                              ======
    public void test_BehaviorSelector_byName_and_getTablePropertyName() {
        // ## Arrange ##
        final String tableDbName = "MEMBER";

        // ## Act ##
        final BehaviorReadable bhv = behaviorSelector.byName(tableDbName);
        final DBMeta dbmeta = bhv.asDBMeta();
        final String tablePropertyName = dbmeta.getTablePropertyName();

        // ## Assert ##
        assertNotNull(tablePropertyName);
        log("/********************************");
        log("tablePropertyName=" + tablePropertyName);
        log("**********/");
        assertNotNull(MemberDbm.getInstance().getTablePropertyName(), tablePropertyName);
    }

    public void test_BehaviorSelector_byName_and_readCount() {
        // ## Arrange ##
        final String tableDbName = "MEMBER";

        // ## Act ##
        final BehaviorReadable bhv = behaviorSelector.byName(tableDbName);
        final ConditionBean cb = bhv.newConditionBean();
        final int count = bhv.readCount(cb);

        // ## Assert ##
        log("/********************************");
        log("count=" + count);
        log("**********/");
        assertEquals(memberBhv.selectCount(new MemberCB()), count);
    }

    public void test_BehaviorSelector_byName_and_readList() {
        // ## Arrange ##
        final String tableDbName = "MEMBER";

        // ## Act ##
        final BehaviorReadable bhv = behaviorSelector.byName(tableDbName);
        final ConditionBean cb = bhv.newConditionBean();
        cb.addOrderBy_PK_Desc();
        final ListResultBean<? extends Entity> entityList = bhv.readList(cb);

        // ## Assert ##
        assertNotNull(entityList);
        log("/********************************");
        for (Entity entity : entityList) {
            log("entity=" + entity);
        }
        log("**********/");
        final MemberCB expectedCB = new MemberCB();
        expectedCB.addOrderBy_PK_Desc();
        final ListResultBean<Member> expectedList = memberBhv.selectList(expectedCB);
        assertEquals(expectedList, entityList);
    }
}


text:
/* ------------------
 * java.lang.Object
 * ------------------ */

/** @constructor */
ScalaJS.c.O = function() {
};

/** @constructor */
ScalaJS.h.O = function() {};
ScalaJS.h.O.prototype = ScalaJS.c.O.prototype;

ScalaJS.c.O.prototype.init___ = function() {
  return this;
}

ScalaJS.c.O.prototype.getClass__jl_Class = function() {
  return this.$classData.getClassOf();
}

ScalaJS.c.O.prototype.hashCode__I = function() {
  // TODO
  return 42;
}

ScalaJS.c.O.prototype.equals__O__Z = function(rhs) {
  return this === rhs;
}

ScalaJS.c.O.prototype.clone__O = function() {
  if (ScalaJS.is.jl_Cloneable(this)) {
    function Clone(from) {
      for (var field in from)
        if (from["hasOwnProperty"](field))
          this[field] = from[field];
    }
    Clone.prototype = ScalaJS.g["Object"]["getPrototypeOf"](this);
    return new Clone(this);
  } else {
    throw new ScalaJS.c.jl_CloneNotSupportedException().init___();
  }
}

ScalaJS.c.O.prototype.toString__T = function() {
  // getClass().getName() + "@" + Integer.toHexString(hashCode())
  var className = this.getClass__jl_Class().getName__T();
  var hashCode = this.hashCode__I();
  return className + '@' + hashCode.toString(16);
}

// JSExport for toString(). We always need to export this, since we
// rely on JS calling it automatically when we do things like:
// `"" + obj`
ScalaJS.c.O.prototype.toString = function() {
  return this.toString__T();
}

// Notify and notify all:
// Although we do not support wait on Object as it does not make sense in JS, we
// allow notify to be called in order to support code that calls only notify but
// never wait. Further, note that these methods are not in the sjsinfo file.
// Therefore, dce will complain about them not being reachable, but the code
// will still work.
ScalaJS.c.O.prototype.notify__V = function() {}
ScalaJS.c.O.prototype.notifyAll__V = function() {}

ScalaJS.c.O.prototype.finalize__V = function() {}

// Reflective call proxies for methods on java.lang.Object
// Note that we do not need to proxy the following methods, since they are
// defined on Any in the Scala hierarchy and therefore a reflective call is
// never issued:
// - equals
// - getClass
// - hashCode
// - toString
ScalaJS.c.O.prototype.clone__ = function() {
  return this.clone__O()
}
ScalaJS.c.O.prototype.notify__ = function() {
  return this.notify__V()
}
ScalaJS.c.O.prototype.notifyAll__ = function() {
  return this.notifyAll__V()
}
ScalaJS.c.O.prototype.finalize__ = function() {
  return this.finalize__V()
}

// Instance tests

ScalaJS.is.O = function(obj) {
  return !!((obj && obj.$classData &&
    obj.$classData.ancestors.O) ||
    (typeof(obj) === "string") ||
    (typeof(obj) === "number") ||
    (typeof(obj) === "boolean") ||
    obj === void 0);
};

ScalaJS.as.O = function(obj) {
  if (ScalaJS.is.O(obj) || obj === null)
    return obj;
  else
    ScalaJS.throwClassCastException(obj, "java.lang.Object");
};

ScalaJS.isArrayOf.O = (function(obj, depth) {
  var data = obj && obj.$classData;
  if (!data)
    return false;
  var arrayDepth = data.arrayDepth || 0;

  if (arrayDepth < depth)
    return false; // because Array[A] </: Array[Array[A]]
  else if (arrayDepth > depth)
    return true; // because Array[Array[A]] <: Array[Object]
  else
    return !data.arrayBase["isPrimitive"]; // because Array[Int] </: Array[Object]
});

ScalaJS.asArrayOf.O = (function(obj, depth) {
  if ((ScalaJS.isArrayOf.O(obj, depth) || (obj === null))) {
    return obj
  } else {
    ScalaJS.throwArrayCastException(obj, "Ljava.lang.Object;", depth)
  }
});

// Data

ScalaJS.d.O =
  new ScalaJS.ClassTypeData(
    {O:0},
    false, "java.lang.Object", null,
    {O:1},
    ScalaJS.is.O,
    ScalaJS.isArrayOf.O);

ScalaJS.c.O.prototype.$classData = ScalaJS.d.O;


text:
Superstitious
Different ways of looking at unusual occurrences

Introduction
An idea is believed to be superstitious when there is no scientific evidence or logical ideas to support it.

A lot of superstitions are believed to be true by people because of certain coincidences. For example, a person who had a lucky occurrence might decide that it was the new red underpants that he was wearing that brought him the good luck.

Other people determine that a superstition is true based on the high frequency of occurrences of the event. For example, Joe believes that the house located a block away from where he lives is haunted because a lot of car accidents have happened in front of it.


text:
/*(C) 2007-2012 Alibaba Group Holding Limited.
 *This program is free software; you can redistribute it and/or modify
*it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
* Authors:
*   junyu <junyu@taobao.com> , shenxun <shenxun@taobao.com>,
*   linxuan <linxuan@taobao.com> ,qihao <qihao@taobao.com>
*/
package com.hyena.ddsl.group.parameter;

import java.sql.PreparedStatement;
import java.sql.SQLException;

public class SetNull2Handler implements ParameterHandler {
	public void setParameter(PreparedStatement stmt, Object[] args)
			throws SQLException {
		stmt.setNull((Integer) args[0], (Integer) args[1], (String) args[2]);
	}
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.facebook.presto.sql.planner.iterative;

import com.facebook.presto.spi.plan.PlanNode;
import com.facebook.presto.sql.planner.plan.InternalPlanVisitor;

import java.util.List;
import java.util.stream.Collectors;

import static java.util.Objects.requireNonNull;

public class Plans
{
    public static PlanNode resolveGroupReferences(PlanNode node, Lookup lookup)
    {
        requireNonNull(node, "node is null");
        return node.accept(new ResolvingVisitor(lookup), null);
    }

    private static class ResolvingVisitor
            extends InternalPlanVisitor<PlanNode, Void>
    {
        private final Lookup lookup;

        public ResolvingVisitor(Lookup lookup)
        {
            this.lookup = requireNonNull(lookup, "lookup is null");
        }

        @Override
        public PlanNode visitPlan(PlanNode node, Void context)
        {
            List<PlanNode> children = node.getSources().stream()
                    .map(child -> child.accept(this, context))
                    .collect(Collectors.toList());

            return node.replaceChildren(children);
        }

        @Override
        public PlanNode visitGroupReference(GroupReference node, Void context)
        {
            return lookup.resolve(node).accept(this, context);
        }
    }

    private Plans() {}
}


text:
package com.bukhmastov.cdoitmo.fragment.presenter.impl;

import com.bukhmastov.cdoitmo.factory.AppComponentProvider;
import com.bukhmastov.cdoitmo.firebase.FirebaseAnalyticsProvider;
import com.bukhmastov.cdoitmo.util.Log;
import com.bukhmastov.cdoitmo.util.Storage;
import com.bukhmastov.cdoitmo.util.StoragePref;
import com.bukhmastov.cdoitmo.util.Thread;

import javax.inject.Inject;

public abstract class ConnectedFragmentBasePresenterImpl {

    @Inject
    Log log;
    @Inject
    Thread thread;
    @Inject
    Storage storage;
    @Inject
    StoragePref storagePref;
    @Inject
    FirebaseAnalyticsProvider firebaseAnalyticsProvider;

    public ConnectedFragmentBasePresenterImpl() {
        AppComponentProvider.getComponent().inject(this);
    }
}


text:
from django.test import TestCase

from colorfield.widgets import ColorWidget

class ColorWidgetTestCase(TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass


text:
import {
  LOGIN, LOGOUT,
  REGISTER_REQUEST, REGISTER_RESPONSE, REGISTER_ERROR,
  FETCH_PROFILE,
} from '../actions/auth';
import { createNotification } from './notifications';
import { BASE } from '../../config/config';
import request from 'axios';

// We can't really use apiMiddleware here, since we want to chain actions.
export const register = (username, password) => {
  return (dispatch) => {
    dispatch(registerRequest());
    request({
      url: BASE + '/register',
      method: 'POST',
      data: {
        username, password
      }
    }).then((res) => {
      dispatch(registerResponse(res.response));
      dispatch(login(username, password));
    }).catch((error) => {
      dispatch(registerError(error.response.data));
      dispatch(createNotification('error', error.response.data));
    });
  };
};

export const login = (username, password) => ({
  type: LOGIN,
  api: {
    url: BASE + '/login',
    method: 'POST',
    data: {
      username,
      password
    }
  }
});

export const logout = () => ({
  type: LOGOUT
});

export const validateToken = () => {
  return (dispatch, getState) => {
    const token = getState().auth.token;

    if (token) {
      dispatch(fetchProfile(token));
    }
  };
};

export const fetchProfile = (token) => ({
  type: FETCH_PROFILE,
  // This token will be used if the API call succeeds and it doesn't return a token.
  // If the call does return a token, we'll use that in the reducer instead.
  token,
  api: {
    url: BASE + '/profile',
    method: 'GET',
    headers: {
      Authorization: token
    }
  }
});

/* Helper functions */
const registerRequest = () => ({
  type: REGISTER_REQUEST
});
const registerResponse = (response) => ({
  type: REGISTER_RESPONSE,
  payload: response
});
const registerError = (errorResponse) => ({
  type: REGISTER_ERROR,
  error: errorResponse
});


text:
SnackBar demo

    Message: <mat-form-field><input matInput type="text" [(ngModel)]="message"></mat-form-field>

Position in page:

    <mat-form-field>
      <mat-select [(ngModel)]="horizontalPosition">
        <mat-option value="start">Start</mat-option>
        <mat-option value="end">End</mat-option>
        <mat-option value="left">Left</mat-option>
        <mat-option value="right">Right</mat-option>
        <mat-option value="center">Center</mat-option>
      </mat-select>
    </mat-form-field>
    <mat-form-field>
      <mat-select [(ngModel)]="verticalPosition">
        <mat-option value="top">Top</mat-option>
        <mat-option value="bottom">Bottom</mat-option>
      </mat-select>
    </mat-form-field>

    <mat-checkbox [(ngModel)]="action">

Show button on snack bar

      <mat-form-field *ngIf="action">
        <input matInput
               type="text"
               class="demo-button-label-input"
               placeholder="Snack bar action label"
               [(ngModel)]="actionButtonLabel">
      </mat-form-field>
    </mat-checkbox>

    <mat-checkbox [(ngModel)]="setAutoHide">

Auto hide after duration

      <mat-form-field *ngIf="setAutoHide">
        <input matInput
               type="number"
               class="demo-button-label-input"
               placeholder="Auto Hide Duration in ms"
               [(ngModel)]="autoHide">
      </mat-form-field>
    </mat-checkbox>

    <mat-checkbox [(ngModel)]="addExtraClass">Add extra class to container</mat-checkbox>

<button mat-raised-button (click)="open()">OPEN</button>


text:
require "danger/danger_core/message_group"
require "danger/helpers/message_groups_array_helper"

module Danger
  class MessageAggregator
    def self.aggregate(*args)
      new(*args).aggregate
    end

    def initialize(warnings: [],
                   errors: [],
                   messages: [],
                   markdowns: [],
                   danger_id: "danger")
      @messages = warnings + errors + messages + markdowns
      @danger_id = danger_id
    end

    # aggregates the messages into an array of MessageGroups
    # @return [[MessageGroup]]
    def aggregate
      # oookay I took some shortcuts with this one.
      # first, sort messages by file and line
      @messages.sort! { |a, b| a.compare_by_file_and_line(b) }

      # now create an initial empty message group
      first_group = MessageGroup.new(file: nil,
                                     line: nil)
      @message_groups = @messages.reduce([first_group]) do |groups, msg|
        # We get to take a shortcut because we sorted the messages earlier - only
        # have to see if we can append msg to the last group in the list
        if groups.last << msg
          # we appended it, so return groups unchanged
          groups
        else
          # have to create a new group since msg wasn't appended to the other
          # group
          new_group = MessageGroup.new(file: msg.file,
                                       line: msg.line)
          new_group << msg
          groups << new_group
        end
      end

      @message_groups.extend(Helpers::MessageGroupsArrayHelper)
    end
  end
end


text:
require 'gaddag'

describe GADDAG::Path, '#include_delimiter?' do
  context 'when the path includes a delimiter' do
    subject { GADDAG::Path.new(%w[R B] + [GADDAG::Path::DELIMITER] + %w[E A K]) }
    specify { expect(subject.include_delimiter?).to be_truthy }
  end

  context 'when the path does not include a delimiter' do
    subject { GADDAG::Path.new(%w[K A E R B]) }
    specify { expect(subject.include_delimiter?).to be_falsey }
  end
end


text:
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FleetManagmentSystem.Common.Models
{
    public abstract class DeletableEntity : AuditInfo, IDeletableEntity
    {
        [Editable(false)]
        public bool IsDeleted { get; set; }

        [Editable(false)]
        [DataType(DataType.Date)]
        [DisplayFormat(DataFormatString = "{0:MM/dd/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? DeletedOn { get; set; }
    }
}


text:
package javax.jbi.messaging;

import javax.jbi.servicedesc.ServiceEndpoint;

import javax.xml.namespace.QName;

/**
 * Bi-directional communication channel used to interact with the Normalized
 * Message Service.
 *
 * @author JSR208 Expert Group
 */
public interface DeliveryChannel
{
    /**
     * Closes the delivery channel, halting all message traffic.
     *
     * @throws MessagingException fatal error while closing channel.
     */
    void close() throws MessagingException;

    /**
     * Create a message exchange factory. This factory will create exchange
     * instances with all appropriate properties set to null.
     *
     * @return a message exchange factory
     */
    MessageExchangeFactory createExchangeFactory();

    /**
     * Create a message exchange factory for the given interface name.
     *
     * @param interfaceName name of the interface for which all exchanges
     *                      created by the returned factory will be set
     * @return an exchange factory that will create exchanges for the given
     *         interface; must be non-null
     */
    MessageExchangeFactory createExchangeFactory(QName interfaceName);

    /**
     * Create a message exchange factory for the given service name.
     *
     * @param serviceName name of the service for which all exchanges
     *                    created by the returned factory will be set
     * @return an exchange factory that will create exchanges for the given
     *         service; must be non-null
     */
    MessageExchangeFactory createExchangeFactoryForService(QName serviceName);

    /**
     * Create a message exchange factory for the given endpoint.
     *
     * @param endpoint endpoint for which all exchanges created by the
     *                 returned factory will be set for
     * @return an exchange factory that will create exchanges for the
     *         given endpoint
     */
    MessageExchangeFactory createExchangeFactory(ServiceEndpoint endpoint);

    /**
     * Blocking call used to service a MessageExchange instance which has
     * been initiated by another component.  This method supports concurrent
     * invocation for multi-threaded environments.
     *
     * @return mesage exchange instance
     * @throws MessagingException failed to accept
     */
    MessageExchange accept() throws MessagingException;

    /**
     * Identical to accept(), but returns after specified interval even if
     * a message exchange is unavailable.
     *
     * @param timeout time to wait in milliseconds
     * @return mesage exchange instance or null if timeout is reached
     * @throws MessagingException failed to accept
     */
    MessageExchange accept(long timeout) throws MessagingException;

    /**
     * Routes a MessageExchange instance through the Normalized Message Service
     * to the appropriate servicing component. This method supports concurrent
     * invocation for multi-threaded environments.
     *
     * @param exchange message exchange to send
     * @throws MessagingException unable to send exchange
     */
    void send(MessageExchange exchange) throws MessagingException;

    /**
     * Routes a MessageExchange instance through the Normalized Message Service
     * to the appropriate servicing component, blocking until the exchange is
     * returned.  This method supports concurrent invocation for multi-threaded
     * environments.
     *
     * @param exchange message exchange to send
     * @return true if the exchange has been processed and returned by the
     *         servicing component, false otherwise.
     * @throws MessagingException unable to send exchange
     */
    boolean sendSync(MessageExchange exchange) throws MessagingException;

    /**
     * Routes a MessageExchange instance through the Normalized Message Service
     * to the appropriate servicing component, blocking until the specified
     * timeout is reached.  This method supports concurrent invocation for
     * multi-threaded environments.
     *
     * @param exchange message exchange to send
     * @param timeout time to wait in milliseconds
     * @return true if the exchange has been processed and returned by the
     *         servicing component, false in the case of timeout.
     * @throws MessagingException unable to send exchange
     */
    boolean sendSync(MessageExchange exchange, long timeout) throws MessagingException;

}


text:
@class NSData, NSDictionary, NSString;

@interface CBaseContact : NSObject <PBCoding, NSCoding>
{
    NSString *m_nsUsrName;
    NSString *m_nsEncodeUserName;
    NSString *m_nsAliasName;
    unsigned int m_uiConType;
    NSString *m_nsNickName;
    NSString *m_nsFullPY;
    NSString *m_nsShortPY;
    NSString *m_nsRemark;
    NSString *m_nsRemarkPYShort;
    NSString *m_nsRemarkPYFull;
    NSString *m_nsDisplayNamePY;
    unsigned int m_uiSex;
    unsigned int m_uiType;
    unsigned int m_uiChatState;
    NSData *m_dtUsrImg;
    NSString *m_nsImgStatus;
    NSString *m_nsHDImgStatus;
    NSString *m_nsHeadImgUrl;
    NSString *m_nsHeadHDImgUrl;
    NSString *m_nsHeadHDMd5;
    NSString *m_nsDraft;
    unsigned int m_uiDraftTime;
    NSString *m_nsAtUserList;
    unsigned int m_uiQQUin;
    NSString *m_nsQQNickName;
    NSString *m_nsQQRemark;
    NSString *m_nsMobileIdentify;
    NSString *m_nsGoogleContactName;
    NSString *m_nsGoogleContactNickName;
    unsigned int m_uiFriendScene;
    unsigned int m_uiImgKey;
    unsigned int m_uiExtKey;
    unsigned int m_uiImgKeyAtLastGet;
    unsigned int m_uiExtKeyAtLastGet;
    _Bool m_hasDetectPlugin;
    _Bool m_isPlugin;
    _Bool m_hasDetectSelf;
    _Bool m_isSelf;
    NSString *m_nsAntispamTicket;
    NSDictionary *_externalInfoJSONCache;
}

+ (void)initialize;
@property(retain, nonatomic) NSDictionary *externalInfoJSONCache; // @synthesize externalInfoJSONCache=_externalInfoJSONCache;
@property(retain, nonatomic) NSString *m_nsDisplayNamePY; // @synthesize m_nsDisplayNamePY;
@property(retain, nonatomic) NSString *m_nsAntispamTicket; // @synthesize m_nsAntispamTicket;
@property(retain, nonatomic) NSString *m_nsShortPY; // @synthesize m_nsShortPY;
@property(retain, nonatomic) NSString *m_nsAtUserList; // @synthesize m_nsAtUserList;
@property(nonatomic) unsigned int m_uiDraftTime; // @synthesize m_uiDraftTime;
@property(nonatomic) unsigned int m_uiFriendScene; // @synthesize m_uiFriendScene;
@property(retain, nonatomic) NSString *m_nsGoogleContactNickName; // @synthesize m_nsGoogleContactNickName;
@property(retain, nonatomic) NSString *m_nsGoogleContactName; // @synthesize m_nsGoogleContactName;
@property(retain, nonatomic) NSString *m_nsMobileIdentify; // @synthesize m_nsMobileIdentify;
@property(retain, nonatomic) NSString *m_nsQQRemark; // @synthesize m_nsQQRemark;
@property(retain, nonatomic) NSString *m_nsQQNickName; // @synthesize m_nsQQNickName;
@property(nonatomic) unsigned int m_uiQQUin; // @synthesize m_uiQQUin;
@property(nonatomic) unsigned int m_uiExtKeyAtLastGet; // @synthesize m_uiExtKeyAtLastGet;
@property(nonatomic) unsigned int m_uiImgKeyAtLastGet; // @synthesize m_uiImgKeyAtLastGet;
@property(nonatomic) unsigned int m_uiExtKey; // @synthesize m_uiExtKey;
@property(nonatomic) unsigned int m_uiImgKey; // @synthesize m_uiImgKey;
@property(retain, nonatomic) NSString *m_nsDraft; // @synthesize m_nsDraft;
@property(retain, nonatomic) NSString *m_nsHeadHDMd5; // @synthesize m_nsHeadHDMd5;
@property(retain, nonatomic) NSString *m_nsHeadHDImgUrl; // @synthesize m_nsHeadHDImgUrl;
@property(retain, nonatomic) NSString *m_nsHeadImgUrl; // @synthesize m_nsHeadImgUrl;
@property(retain, nonatomic) NSString *m_nsHDImgStatus; // @synthesize m_nsHDImgStatus;
@property(retain, nonatomic) NSString *m_nsImgStatus; // @synthesize m_nsImgStatus;
@property(retain, nonatomic) NSData *m_dtUsrImg; // @synthesize m_dtUsrImg;
@property(nonatomic) unsigned int m_uiChatState; // @synthesize m_uiChatState;
@property(nonatomic) unsigned int m_uiType; // @synthesize m_uiType;
@property(nonatomic) unsigned int m_uiSex; // @synthesize m_uiSex;
@property(retain, nonatomic) NSString *m_nsRemarkPYFull; // @synthesize m_nsRemarkPYFull;
@property(retain, nonatomic) NSString *m_nsRemarkPYShort; // @synthesize m_nsRemarkPYShort;
@property(retain, nonatomic) NSString *m_nsRemark; // @synthesize m_nsRemark;
@property(retain, nonatomic) NSString *m_nsFullPY; // @synthesize m_nsFullPY;
@property(nonatomic) unsigned int m_uiConType; // @synthesize m_uiConType;
@property(retain, nonatomic) NSString *m_nsAliasName; // @synthesize m_nsAliasName;
@property(retain, nonatomic) NSString *m_nsEncodeUserName; // @synthesize m_nsEncodeUserName;
@property(retain, nonatomic) NSString *m_nsUsrName; // @synthesize m_nsUsrName;
- (void).cxx_destruct;
@property(readonly, nonatomic) _Bool m_isPlugin; // @synthesize m_isPlugin;
- (id)localizedStringForMale:(id)arg1 female:(id)arg2 andUnkownSex:(id)arg3;
- (int)getImageStatusCode;
- (_Bool)isHasGMail;
- (id)getQQDisplayName;
- (_Bool)isHasQQDisplayName;
- (_Bool)isHasQQ;
- (_Bool)isWeixinTeamContact;
- (_Bool)isSelf;
- (_Bool)hasContactDisplayUsrNameByCache;
- (_Bool)hasContactDisplayUsrName;
- (id)getContactDisplayUsrName;
- (id)getContactTalkRoomName;
- (id)getContactDisplayName;
- (void)setDisplayNamePY;
- (id)getRemark;
- (void)saveUserImage;
- (id)getContactHeadImage;
- (_Bool)isNeedGetHDImg;
- (_Bool)isHasHDImg;
- (_Bool)isNeedGetUsrImgWithoutCheckLocalFile;
- (_Bool)isNeedGetUsrImg;
- (_Bool)isEnterpriseContact;
- (_Bool)isWeSportContact;
- (_Bool)isChatStatusNotifyOpen;
- (_Bool)isMacHelper;
- (_Bool)isQQ;
- (_Bool)isQQMBlog;
- (_Bool)isTemplateMsgHolder;
- (_Bool)isFileHelper;
- (_Bool)isBrandSessionHolder;
- (_Bool)isGroupCard;
- (_Bool)isChatroom;
- (_Bool)isLbsroom;
- (_Bool)isWeixin;
- (_Bool)isMMContact;
- (_Bool)isFavour;
- (void)setSnsBlack:(_Bool)arg1;
- (_Bool)isSnsBlack;
- (void)setBlack:(_Bool)arg1;
- (_Bool)isBlack;
- (_Bool)isEqualToName:(id)arg1;
- (_Bool)isEqualToContact:(id)arg1;
- (id)getEncodeUserName;
- (_Bool)isValid;
- (void)setChatRoomTopic:(id)arg1;
- (id)chatRoomTopic;
- (long long)compare:(id)arg1;
@property(readonly, copy) NSString *description;
- (_Bool)copyFrom:(id)arg1;
- (id)initWithCoder:(id)arg1;
- (void)encodeWithCoder:(id)arg1;
- (id)init;
- (void)setRemarkWithoutEmojiChange:(id)arg1;
- (void)setNickNameWithoutEmojiChange:(id)arg1;
@property(retain, nonatomic) NSString *m_nsNickName; // @synthesize m_nsNickName;
- (const map_0e718273 *)getValueTagIndexMap;
- (id)getValueTypeTable;

// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.gluu</groupId>
    <artifactId>oxauth-pingid</artifactId>
    <version>1.0</version>
    <packaging>jar</packaging>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
        <log4j.version>2.17.1</log4j.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.gluu</groupId>
            <artifactId>oxauth-model</artifactId>
            <version>4.2.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.gluu</groupId>
            <artifactId>oxcore-util</artifactId>
            <version>4.2.3.Final</version>
        </dependency>
        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20200518</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcprov-jdk15on</artifactId>
            <version>1.67</version>
        </dependency>
        <dependency>
            <groupId>org.bouncycastle</groupId>
            <artifactId>bcpkix-jdk15on</artifactId>
            <version>1.67</version>
        </dependency>

        <!-- LOGGING -->
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-slf4j-impl</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>${log4j.version}</version>
        </dependency>

        <dependency>
            <groupId>commons-httpclient</groupId>
            <artifactId>commons-httpclient</artifactId>
            <version>3.1</version>
        </dependency>

        <!-- RESTEASY -->
        <dependency>
            <groupId>org.jboss.resteasy</groupId>
            <artifactId>resteasy-client</artifactId>
            <version>3.13.0.Final</version>
        </dependency>
    </dependencies>

    <repositories>
        <repository>
            <id>gluu</id>
            <name>Gluu repository</name>
            <url>https://maven.gluu.org/maven</url>
        </repository>
    </repositories>
</project>


text:
import static org.junit.Assert.*;

import java.io.*;
import java.net.*;
import net.java.sip.communicator.impl.netaddr.*;
import org.junit.*;

public class Win32LocalhostTest
{
    @Test
    public void testBestAdapterRoute() throws IOException
    {
        InetAddress localhost = Win32LocalhostRetriever
            .getSourceForDestination(InetAddress.getLoopbackAddress());
        assertEquals(InetAddress.getLoopbackAddress(), localhost);

        System.setProperty("java.net.preferIPv6Addresses", "true");
        localhost = Win32LocalhostRetriever
            .getSourceForDestination(InetAddress.getLoopbackAddress());
        assertEquals(InetAddress.getLoopbackAddress(), localhost);
    }
}


text:
package org.deeplearning4j.nn.conf.misc;

import lombok.AllArgsConstructor;
import org.deeplearning4j.nn.api.TrainingConfig;
import org.deeplearning4j.nn.conf.GradientNormalization;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.learning.config.IUpdater;
import org.nd4j.linalg.learning.config.NoOp;
import org.nd4j.linalg.learning.regularization.Regularization;

import java.util.List;

@AllArgsConstructor
public class DummyConfig implements TrainingConfig {
    private final String name;

    @Override
    public String getLayerName() {
        return name;
    }

    @Override
    public List<Regularization> getRegularizationByParam(String paramName) {
        return null;
    }

    @Override
    public boolean isPretrainParam(String paramName) {
        return false;
    }

    @Override
    public IUpdater getUpdaterByParam(String paramName) {
        return new NoOp();
    }

    @Override
    public GradientNormalization getGradientNormalization() {
        return GradientNormalization.None;
    }

    @Override
    public double getGradientNormalizationThreshold() {
        return 1.0;
    }

    @Override
    public void setDataType(DataType dataType) {

    }
}


text:
namespace Google.Cloud.Monitoring.V3.Snippets
{
    // [START monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_sync_flattened]
    using Google.Cloud.Monitoring.V3;

    public sealed partial class GeneratedUptimeCheckServiceClientSnippets
    {
        /// <summary>Snippet for DeleteUptimeCheckConfig</summary>
        /// <remarks>
        /// This snippet has been automatically generated for illustrative purposes only.
        /// It may require modifications to work in your environment.
        /// </remarks>
        public void DeleteUptimeCheckConfig()
        {
            // Create client
            UptimeCheckServiceClient uptimeCheckServiceClient = UptimeCheckServiceClient.Create();
            // Initialize request argument(s)
            string name = "projects/[PROJECT]/uptimeCheckConfigs/[UPTIME_CHECK_CONFIG]";
            // Make the request
            uptimeCheckServiceClient.DeleteUptimeCheckConfig(name);
        }
    }
    // [END monitoring_v3_generated_UptimeCheckService_DeleteUptimeCheckConfig_sync_flattened]
}


text:
<!DOCTYPE HTML>

        <meta charset="UTF-8">
        <title>Collections and Repetitions | Refresh-java</title>

        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="robots" content="index, follow">
        <meta name="author" content="chappers">
        <meta name="description" content="Book generated using GitBook">
        <meta name="keywords" content="gitbook,github" >
        <meta name="generator" content="www.gitbook.io">

        <link rel="next" href="../8-fixed-size-collections/chpt.html" />

        <link rel="prev" href="../6-Introduction-to-Program-Design/chpt.html" />

        <meta property="og:title" content="Collections and Repetitions | Refresh-java">
        <meta property="og:site_name" content="Refresh-java">
        <meta property="og:type" content="book">
        <meta property="og:locale" content="en_US">

        <meta property="book:author" content="https://github.com/chappers">
        <meta property="book:tag" content="GitBook">

        <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">

        <link rel="shortcut icon" href="../gitbook/images/favicon.ico" type="image/x-icon">

        <link rel="stylesheet" href="../gitbook/style.css">

     Star (-)
     Watch (-)

Refresh-java

            About the author

            Questions and Issues

            Edit and Contribute

             Introduction

                     1) Objects and Classes

                     2) A First look at Java Source Code

                     3) Class Definitions

                     4) Conditional Statements and Boolean Data Type

                     5) More About Data Types

                     6) Introduction to Program Design

                     7) Collections and Repetitions

                     8) Fixed Size Collections

                     9) Software Testing

                     10) Using the Java Library

                     11) Designing Classes

                     12) Introduction to Inheritance

                     13) Polymorphism

                     14) Abstract Classes and Interfaces

                     15) Handling Errors

                     16) Graphical User Interface

Collections

Collections are analogous to Python's list, tuples and dicts.
Collections include:

Strings

Arrays

Lists

Sets

Dictionaries or Maps

Iterators

These are reference types and are actually objects (at least
from my understanding). Which means they cannot be used in the
same way as the primitive types.

Strings

String is not the same as Python strings! Lets take a
quick look at something we would expect to work in Python
"translated" into Java.

public class wrongString {
    public static void main(String[] args) {
        String a = new String("test");
        String b = new String("test");

        if (a == b) {
            System.out.println("Equal!");
        }
        else {
            System.out.println("Not Equal!");
        }
    }
}

Why does this happen! Well the reason is simply because ==
tests for reference equality while what we want is value equality.

So lets look at the correct way:

//rightString.java is the right way to compare strings

public class rightString {
    public static void main(String[] args) {
        String a = new String("test");
        String b = new String("test");

        if (a.equals(b)) {
            System.out.println("Equal!");
        }
        else {
            System.out.println("Not Equal!");
        }
    }
}

We will use the .equals method in order to compare if strings
are the same.

What about comparing strings if they are "bigger" or "smaller"?
Simply use compareTo method.

// orderString shows a way to compare whether strings are "bigger"
// or "smaller"

public class orderString {
    public static void main(String[] args) {
        String a = new String("a");
        String b = new String("b");

        int compare = a.compareTo(b);

        if (compare < 0) {
            System.out.println(a + " comes before " + b);
        }
        else if (compare == 0) {
            System.out.println(a + " is equal to " + b);
        }
        else {
            System.out.println(a + " comes after " + b);
        }
    }
}

Arrays

You can declare an array of "things" quite easily in Java. There
really isn't a Python "version" of an array, though you can think of
an array as a list of fixed length and can only contain one variable
type.

public class intArray {
    public static void main(String[] args) {
        int[] numArr = {1,2,3,4};
        for (int i=0; i<4; i++) {
            System.out.println(numArr[i]);
        }
    }
}

You can also preallocate the array size and assign the values later.

public class intArrayFixed {
    public static void main(String[] args) {
        int[] numArr = new int[4];

        for (int i=0; i<4; i++) {
            numArr[i]=i+1; // indexing starts from 0
        }
        for (int i=0; i<4; i++) {
            System.out.println(numArr[i]);
        }
    }
}

Maps (Dictionary)

Python dictionaries are known as "maps" in Java. There are two
different maps that are in Java:

HashMap

TreeMap

Lets just look at the example below.

import java.util.HashMap;
import java.util.Map;
import java.lang.Math;

public class simpleMap {
    public static void main(String[] args) {
        Map<String, Integer> names = new HashMap<String, Integer>();

        //associate a random age with each name
        for (int i=1; i<=10; i++) {
            String name = "name"+i;
            names.put(name, (int)(Math.random() * 10+1));
        }

        //print them all out, the keys and the values
        for (String key : names.keySet()) {
            System.out.println(key + " " + names.get(key));
        }
    }
}

We can see here, there are some things that may look familiar to
Python programmers.

Firstly, we now have the import statement. This works much in the
same way as how Python has implemented it.

            Next


text:
package fr.paris.lutece.portal.web;

import fr.paris.lutece.portal.business.page.Page;
import fr.paris.lutece.portal.business.page.PageHome;
import fr.paris.lutece.portal.business.portlet.PortletHome;
import fr.paris.lutece.portal.business.right.Right;
import fr.paris.lutece.portal.business.right.RightHome;
import fr.paris.lutece.portal.business.user.AdminUser;
import fr.paris.lutece.portal.service.dashboard.DashboardComponent;
import fr.paris.lutece.portal.service.page.PageService;
import fr.paris.lutece.portal.service.spring.SpringContextService;
import fr.paris.lutece.portal.service.template.AppTemplateService;
import fr.paris.lutece.util.html.HtmlTemplate;

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

import javax.servlet.http.HttpServletRequest;

/**
 * SiteDashboardComponent
 */
public class SiteDashboardComponent extends DashboardComponent
{
    // CONSTANTS
    private static final String BEAN_PAGE_SERVICE = "pageService";

    // MARKS
    private static final String MARK_PAGES_COUNT = "pages_count";
    private static final String MARK_URL = "url";
    private static final String MARK_ICON = "icon";
    private static final String MARK_LAST_MODIFIED_PAGE = "last_modified_page";
    private static final String MARK_LAST_MODIFIED_PORTLET = "last_modified_portlet";
    private static final String MARK_IMAGE_THUMBNAIL_PAGE_URL = "image_thumbnail_page_url";

    // TEMPLATES
    private static final String TEMPLATE_DASHBOARD = "/admin/site/site_dashboard.html";

    /**
     * The HTML code of the component
     *
     * @param user
     *            The Admin User
     * @param request
     *            HttpServletRequest
     * @return The dashboard component
     */
    @Override
    public String getDashboardData( AdminUser user, HttpServletRequest request )
    {
        Right right = RightHome.findByPrimaryKey( getRight( ) );
        Map<String, Object> model = new HashMap<>( );
        model.put( MARK_URL, right.getUrl( ) );
        model.put( MARK_ICON, right.getIconUrl( ) );

        PageService pageService = SpringContextService.getBean( BEAN_PAGE_SERVICE );
        Page page = PageHome.getLastModifiedPage( );
        model.put( MARK_LAST_MODIFIED_PAGE, page );
        model.put( MARK_LAST_MODIFIED_PORTLET, PortletHome.getLastModifiedPortlet( ) );
        model.put( MARK_PAGES_COUNT, PageHome.getAllPages( ).size( ) );

        if ( page != null )
        {
            model.put( MARK_IMAGE_THUMBNAIL_PAGE_URL, pageService.getResourceImagePage( String.valueOf( page.getId( ) ) ) );
        }

        HtmlTemplate t = AppTemplateService.getTemplate( TEMPLATE_DASHBOARD, user.getLocale( ), model );

        return t.getHtml( );
    }
}


text:
function execute(whoami, done) {

  const fns = whoami.options.functions || {};
  const timeout = whoami.options.functionsTimeout;
  let finished = 0;
  let output = {};

  function checkFinalize() {
    if (finished >= Object.keys(fns).length) {
      whoami.store.set('functions', output);
      done();
    }
  }

  for (let k in fns) {
    output[k] = undefined;

    // async
    const val = fns[k]((v) => {
      output[k] = v;
      finished++;
      checkFinalize();
    });

    // sync
    if (!output[k] && val) {
      output[k] = val;
      finished++;
      checkFinalize();
    }

    setTimeout(() => {
      if (!output[k]) {
        finished++;
        checkFinalize();
      }
    }, timeout);
  }
}

export default { execute: execute }


text:
package org.opensingular.form.wicket.mapper;

import org.apache.commons.lang3.StringUtils;
import org.apache.wicket.Component;
import org.apache.wicket.behavior.AttributeAppender;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.model.IModel;
import org.opensingular.form.SInstance;
import org.opensingular.form.type.core.STypeTime;
import org.opensingular.form.view.date.ISViewTime;
import org.opensingular.form.view.date.SViewTime;
import org.opensingular.form.wicket.IAjaxUpdateListener;
import org.opensingular.form.wicket.WicketBuildContext;
import org.opensingular.form.wicket.behavior.AjaxUpdateInputBehavior;
import org.opensingular.form.wicket.behavior.InputMaskBehavior;
import org.opensingular.form.wicket.mapper.datetime.CreateTimePickerBehavior;
import org.opensingular.form.wicket.model.SIDateTimeModel;
import org.opensingular.form.wicket.model.SInstanceValueModel;
import org.opensingular.lib.wicket.util.bootstrap.layout.BSControls;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;

import static org.opensingular.form.wicket.mapper.SingularEventsHandlers.OPTS_ORIGINAL_PROCESS_EVENT;
import static org.opensingular.form.wicket.mapper.SingularEventsHandlers.OPTS_ORIGINAL_VALIDATE_EVENT;
import static org.opensingular.lib.wicket.util.util.Shortcuts.$b;

/**
 * Mapper for data type responsible for storing time (hour and minutes).
 */
public class TimeMapper extends AbstractControlsFieldComponentMapper {

    public static final String ON_VALIDATE_TIME = "onValidateTime";
    private static final String ON_PROCESS_TIME = "onProcessTime";
    private TextField<String> time;

    @Override
    public Component appendInput(WicketBuildContext ctx, BSControls formGroup, IModel<String> labelModel) {
        time = createTextFieldTime(ctx.getModel(), ctx.getViewSupplier(SViewTime.class).get());
        formGroup.appendInputText(time);
        return time;
    }

    public TextField<String> createTextFieldTime(IModel<? extends SInstance> model, ISViewTime viewTime) {
        time = new TextField<>("time", new SIDateTimeModel.TimeModel(new SInstanceValueModel<>(model)));
        if (checkModalTimerPickerWillShow(viewTime)) {
            time.add($b.classAppender(" sgl-timer-picker "));
            time.add(new CreateTimePickerBehavior(getParams(viewTime)));
        }

        time.add(new InputMaskBehavior(InputMaskBehavior.Masks.TIME))
                .add(AttributeAppender.append("autocomplete", "off"))
                .setOutputMarkupId(true);
        return time;
    }

    protected Map<String, Object> getParams(ISViewTime viewTime) {
        final Map<String, Object> params = new TreeMap<>();
        params.put("defaultTime", Boolean.FALSE);
        params.put("showMeridian", Boolean.FALSE);

        if (viewTime != null) {
            params.put("showMeridian", viewTime.isMode24hs());
            params.put("minuteStep", viewTime.getMinuteStep());
        }

        return params;
    }

    @Override
    public String getReadOnlyFormattedText(WicketBuildContext ctx, IModel<? extends SInstance> model) {
        final SimpleDateFormat format = new SimpleDateFormat(STypeTime.FORMAT);
        if (model.getObject().getValue() instanceof Date) {
            return format.format(model.getObject().getValue());
        }
        return StringUtils.EMPTY;
    }

    @Override
    public void addAjaxUpdate(WicketBuildContext ctx, Component component, IModel<SInstance> model, IAjaxUpdateListener listener) {
        addAjaxEvent(model, listener, time, ctx.getViewSupplier(SViewTime.class).get());
    }

    /**
     * Method to add AjaxEvent's to the Date Mapper. This event's should be add to works fine with dependsON.
     * If this ajaxEvent don't have, can have a error if have a dependsOn with exists = false.
     *
     * @param model     The model for process and validate.
     * @param listener  The listener for process and validate.
     * @param component The component that will be the ajax Event's adding.
     * @param viewTime  The view of the timer.
     */
    public static void addAjaxEvent(IModel<SInstance> model, IAjaxUpdateListener listener, TextField<String> component, ISViewTime viewTime) {
        SingularEventsHandlers eventsHandlers = new SingularEventsHandlers(SingularEventsHandlers.FUNCTION.ADD_TEXT_FIELD_HANDLERS);

        if (checkModalTimerPickerWillShow(viewTime)) {
            eventsHandlers.setOption(OPTS_ORIGINAL_PROCESS_EVENT, ON_PROCESS_TIME)
                    .setOption(OPTS_ORIGINAL_VALIDATE_EVENT, ON_VALIDATE_TIME);
        }

        component.add(eventsHandlers)
                .add(AjaxUpdateInputBehavior.forValidate(model, listener))
                .add(AjaxUpdateInputBehavior.forProcess(model, listener));

    }

    /**
     * Method responsible for containing the rules of the visible modal picker.
     *
     * @param viewTime The view that containing the logic.
     * @return True if the modal picker will show.
     */
    private static boolean checkModalTimerPickerWillShow(ISViewTime viewTime) {
        return viewTime == null || !viewTime.isModalTimerHide();
    }

}


text:
<?php

namespace Nz\CrawlerBundle\Client;

class ClientException extends \RuntimeException
{

}


text:
package com.querydsl.spatial;

import static org.junit.Assert.assertEquals;

import org.geolatte.geom.*;
import org.junit.Test;

public class GeometryPathTest {

    @Test
    public void convert() {
        GeometryPath<Geometry> geometry = new GeometryPath<Geometry>("geometry");
        assertEquals(new GeometryCollectionPath<GeometryCollection>("geometry"), geometry.asCollection());
        assertEquals(new LinearRingPath<LinearRing>("geometry"), geometry.asLinearRing());
        assertEquals(new LineStringPath<LineString>("geometry"), geometry.asLineString());
        assertEquals(new MultiLineStringPath<MultiLineString>("geometry"), geometry.asMultiLineString());
        assertEquals(new MultiPointPath<MultiPoint>("geometry"), geometry.asMultiPoint());
        assertEquals(new MultiPolygonPath<MultiPolygon>("geometry"), geometry.asMultiPolygon());
        assertEquals(new PointPath<Point>("geometry"), geometry.asPoint());
        assertEquals(new PolygonPath<Polygon>("geometry"), geometry.asPolygon());
    }
}


text:
/**
 * @module app.Geocoding
 */
/**
 * @fileoverview This file provides an Angular service for interacting
 * with the "geocoding" web service.
 */

import appModule from './module.js';
import {transform} from 'ol/proj.js';

/**
 * @constructor
 * @param {angular.$http} $http The Angular $http service.
 * @param {string} reverseGeocodingServiceUrl The url of the service.
 * @param {string} geocodingServiceUrl The url of the service.
 * @ngInject
 */
const exports = function($http, reverseGeocodingServiceUrl, geocodingServiceUrl) {
  /**
   * @type {angular.$http}
   * @private
   */
  this.$http_ = $http;

  /**
   * @type {string}
   * @private
   */
  this.reverseGeocodingServiceUrl_ = reverseGeocodingServiceUrl;

  /**
   * @type {string}
   * @private
   */
  this.geocodingServiceUrl_ = geocodingServiceUrl;
};

/**
 * @param {ol.Coordinate} coordinate The coordinate.
 * @return {!angular.$q.Promise} Promise providing the reverse geocode.
 */
exports.prototype.reverseGeocode = function(coordinate) {
  var lonlat = /** @type {ol.Coordinate} */
      (transform(coordinate,
      'EPSG:3857', 'EPSG:2169'));

  return this.$http_.get(this.reverseGeocodingServiceUrl_, {
    params: {
      'easting': lonlat[0],
      'northing': lonlat[1]
    }
  }).then(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {Object} The response
         */
          function(resp) {
            return resp['data'];
          });
};

/**
 * @param {string} address The address to geocode.
 * @return {!angular.$q.Promise} Promise providing the coordinates.
 */
exports.prototype.geocode = function(address) {

  return this.$http_.get(this.geocodingServiceUrl_, {
    params: {
      'queryString': address
    }
  }).then(
      /**
         * @param {angular.$http.Response} resp Ajax response.
         * @return {Object} The response
         */
          function(resp) {
            return resp['data'];
          });
};

appModule.service('appGeocoding', exports);

export default exports;


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#FFFFFF"
    android:orientation="vertical" >

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

    <ScrollView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:fillViewport="true" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:background="@drawable/hfb_info_bg"
                android:orientation="vertical"
                android:paddingLeft="5dp"
                android:paddingRight="5dp" >

                <TextView
                    android:id="@+id/tv_title"
                    style="@style/hfb_app_title_style"
                    android:layout_gravity="center_horizontal"
                    android:text="话费支付"
                    android:textColor="@color/hfb_black" />

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="商品名称:"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />

                    <TextView
                        android:id="@+id/tv_goodsName"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="电影票"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="订单价格:"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />

                    <TextView
                        android:id="@+id/tv_amount"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="1元(不含通信费)"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />
                </LinearLayout>

                <LinearLayout
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="客服电话:"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />

                    <TextView
                        android:id="@+id/tv_cusphone"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="4006125880"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/ll_phone"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginLeft="10dp"
                    android:layout_marginTop="5dp"
                    android:orientation="horizontal" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="支付手机:"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/et_phone"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginRight="10dp"
                        android:background="@drawable/hfb_ipt_bg"
                        android:inputType="phone"
                        android:singleLine="true"
                        android:text=""
                        android:textColor="#333333"
                        android:textSize="16sp" />
                </LinearLayout>

                <LinearLayout
                    android:id="@+id/ll_code"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="10dp"
                    android:layout_marginTop="5dp"
                    android:gravity="center_vertical"
                    android:orientation="horizontal" >

                    <TextView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:text="      验证码:"
                        android:textColor="@color/hfb_black"
                        android:textSize="16sp" />

                    <EditText
                        android:id="@+id/et_code"
                        android:layout_width="0dp"
                        android:layout_height="wrap_content"
                        android:background="@drawable/hfb_ipt_bg"
                        android:inputType="number"
                        android:layout_weight="1"
                        android:singleLine="true"
                        android:textColor="#333333"
                        android:textSize="16sp" />

                    <com.umpay.huafubao.view.CountDownButton
                        android:id="@+id/btn_code"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_marginLeft="15dp"
                        android:layout_marginRight="10dp"
                        android:background="@drawable/hfb_btn2"
                        android:text="获取验证码"
                        android:textColor="#007bb4"
                        android:textSize="12sp" />
                </LinearLayout>
            </LinearLayout>

            <TextView
                android:id="@+id/tv_goodsInfo"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:background="@drawable/hfb_merdesc_info_bg"
                android:textColor="@color/hfb_gray" />

            <TextView
                android:id="@+id/tv_smsInfo"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginTop="10dp"
                android:textColor="@color/hfb_gray" />

            <Button
                android:id="@+id/btn_pay"
                style="@style/hfb_txt_style"
                android:layout_gravity="center_horizontal"
                android:layout_marginBottom="20dp"
                android:layout_marginLeft="40dp"
                android:layout_marginRight="40dp"
                android:layout_marginTop="20dp"
                android:background="@drawable/hfb_red_btn"
                android:paddingBottom="10dp"
                android:paddingTop="10dp"
                android:text="确认支付" />

            <TextView
                android:id="@+id/tv_smsInfo2"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="10dp"
                android:layout_marginLeft="10dp"
                android:layout_marginRight="10dp"
                android:textColor="@color/hfb_gray" />
        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
package au.org.aurin.wif.executors.svc;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.Future;

import javax.annotation.Resource;

import org.geotools.filter.text.cql2.CQLException;
import org.opengis.geometry.MismatchedDimensionException;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import au.org.aurin.wif.exception.config.ParsingException;
import au.org.aurin.wif.exception.config.WifInvalidConfigException;
import au.org.aurin.wif.exception.validate.IncompleteDemandScenarioException;
import au.org.aurin.wif.exception.validate.SuitabilityAnalysisFailedException;
import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.impl.allocation.AllocationAnalyzer;
import au.org.aurin.wif.model.allocation.AllocationScenario;
import au.org.aurin.wif.model.demand.DemandOutcome;
import au.org.aurin.wif.model.demand.DemandScenario;
import au.org.aurin.wif.model.suitability.SuitabilityScenario;
import au.org.aurin.wif.repo.allocation.AllocationScenarioDao;
import au.org.aurin.wif.svc.allocation.AllocationScenarioService;
import au.org.aurin.wif.svc.demand.DemandOutcomeService;
import au.org.aurin.wif.svc.demand.DemandScenarioService;
import au.org.aurin.wif.svc.suitability.DemandConfigService;
import au.org.aurin.wif.svc.suitability.SuitabilityScenarioService;

import com.vividsolutions.jts.io.ParseException;

/**
 * Asynchronous service to perform lengthy allocation analysis.
 */
@Service
@Qualifier("asyncAllocationService")
public class AsyncAllocationService {

  /** The Constant LOGGER. */
  private static final Logger LOGGER = LoggerFactory
      .getLogger(AsyncAllocationService.class);

  /** The allocation analyzer. */
  @Autowired
  private AllocationAnalyzer allocationAnalyzer;

  /** The wif allocationScenario dao. */
  @Autowired
  private AllocationScenarioDao allocationScenarioDao;

  /** The allocation scenario service. */
  @Resource
  private AllocationScenarioService allocationScenarioService;

  /** The demand config service. */
  @Resource
  private DemandConfigService demandConfigService;

  /** The demand scenario service. */
  @Resource
  private DemandScenarioService demandScenarioService;

  /** The demand outcome service. */
  @Resource
  private DemandOutcomeService manualdemandScenarioService;

  /** The suitability scenario service. */
  @Resource
  private SuitabilityScenarioService suitabilityScenarioService;

  /**
   * Do allocation analysis async.
   *
   * @param id
   *          the id
   * @param areaAnalyzed
   *          the area analyzed
   * @param crsArea
   *          the crs area
   * @return the future
   * @throws WifInvalidConfigException
   *           the wif invalid config exception
   * @throws WifInvalidInputException
   *           the wif invalid input exception
   * @throws NoSuchAuthorityCodeException
   *           the no such authority code exception
   * @throws FactoryException
   *           the factory exception
   * @throws MismatchedDimensionException
   *           the mismatched dimension exception
   * @throws TransformException
   *           the transform exception
   * @throws ParseException
   *           the parse exception
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   * @throws SuitabilityAnalysisFailedException
   *           the wif analysis failed exception
   * @throws ParsingException
   *           the parsing exception
   * @throws CQLException
   * @throws IncompleteDemandScenarioException
   * @throws SQLException
   * @throws ClassNotFoundException
   */
  @Async
  // public Future<Boolean> doAllocationAnalysisAsync(final String id)
  public Future<String> doAllocationAnalysisAsync(final String id)
      throws WifInvalidConfigException, WifInvalidInputException,
      NoSuchAuthorityCodeException, FactoryException,
      MismatchedDimensionException, TransformException, ParseException,
      IOException, SuitabilityAnalysisFailedException, ParsingException,
      CQLException, IncompleteDemandScenarioException, ClassNotFoundException,
      SQLException {

    final AllocationScenario allocationScenario = allocationScenarioService
        .getAllocationScenario(id);

    LOGGER.debug(
        "doAllocationAnalysisAsync processing allocation analysis  for ={}",
        allocationScenario.getLabel());

    allocationScenario.setReady(false);
    allocationScenarioDao.updateAllocationScenario(allocationScenario);

    final String suitabilityScenarioId = allocationScenario
        .getSuitabilityScenarioId();
    final SuitabilityScenario suitabilityScenario = suitabilityScenarioService
        .getSuitabilityScenario(suitabilityScenarioId);

    allocationScenario.setSuitabilityScenario(suitabilityScenario);

    if (allocationScenario.isManual()) {
      final String manualdemandScenarioId = allocationScenario
          .getManualdemandScenarioId();

      final String projectId = suitabilityScenario.getWifProject().getId();
      final List<DemandScenario> listDemand = demandScenarioService
          .getDemandScenarios(projectId);
      Boolean lsw = false;
      for (final DemandScenario dsn : listDemand) {
        if (dsn.getId().equals(manualdemandScenarioId)) {
          lsw = true;
        }
      }
      if (lsw == false) {
        final DemandOutcome manualdemandScenario = manualdemandScenarioService
            .getDemandOutcome(manualdemandScenarioId, suitabilityScenario
                .getWifProject().getId());
        allocationScenario.setManualdemandScenario(manualdemandScenario);
      }

      // allocationScenario.setWifProject(manualdemandScenario.getWifProject());
      allocationScenario.setWifProject(suitabilityScenario.getWifProject());
    } else {
      final String demandScenarioId = allocationScenario.getDemandScenarioId();
      final DemandScenario demandScenario = demandScenarioService
          .getDemandScenario(demandScenarioId);
      allocationScenario.setDemandScenario(demandScenario);
      allocationScenario.setWifProject(demandScenario.getWifProject());
    }

    // return new AsyncResult<Boolean>(
    // allocationAnalyzer.doAllocationAnalysis(allocationScenario));

    return new AsyncResult<String>(
        allocationAnalyzer.doAllocationAnalysis(allocationScenario));
  }
}


text:
/*
 * This file is part of GreatFET
 *
 * Core verb defititions -- these provide solid implementations
 * of the Core Verbs, as provided by libgreat.
 */

#include <stddef.h>
#include <string.h>
#include <errno.h>

#include <config.h>
#include <greatfet_core.h>
#include <rom_iap.h>

#include <drivers/comms.h>
#include <drivers/reset.h>
#include <debug.h>

#define CLASS_NUMBER_CORE 0

char version_string[] = CONFIG_VERSION_STRING;

/**
 * Method that determines the board's ID.
 * Overrideable if derivative firmware wants to auto-detect which board it's running on.
 */
uint32_t ATTR_WEAK core_get_board_id()
{
	return CONFIG_BOARD_ID;
}

int core_verb_read_board_id(struct command_transaction *trans)
{
	comms_response_add_uint32_t(trans, core_get_board_id());
	return 0;
}

int core_verb_read_version_string(struct command_transaction *trans)
{
	comms_response_add_string(trans, version_string);
	return 0;
}

int core_verb_read_part_id(struct command_transaction *trans)
{
	iap_cmd_res_t iap_cmd_res;

	// Don't allow a read if we can't fit a full response.
	if (trans->data_out_max_length < 8)
		return EINVAL;

	// Read the IAP part number...
	iap_cmd_res.cmd_param.command_code = IAP_CMD_READ_PART_ID_NO;
	iap_cmd_call(&iap_cmd_res);

	// ... and build our response from it.
	for (int i = 0; i < 2; ++i)
		comms_response_add_uint32_t(trans, iap_cmd_res.status_res.iap_result[i]);

	// Return whether our data is valid.
	return iap_cmd_res.status_res.status_ret;
}

int core_verb_read_serial_number(struct command_transaction *trans)
{
	iap_cmd_res_t iap_cmd_res;

	// Don't allow reads if we can't fit a full response.
	if (trans->data_out_max_length < 16)
		return EINVAL;

	// Read the board's serial number.
	iap_cmd_res.cmd_param.command_code = IAP_CMD_READ_SERIAL_NO;
	iap_cmd_call(&iap_cmd_res);

	// Add in each of the blocks of the serial number.
	for (int i = 0; i < 4; ++i)
		comms_response_add_uint32_t(trans, iap_cmd_res.status_res.iap_result[i]);

	return iap_cmd_res.status_res.status_ret;
}

typedef enum  {

	//. Normal soft-reset. Resets everything.
	RESET_REQUEST_NORMAL = 0,

	// Request to switch to an external clock.
	RESET_REQUEST_SWITCH_TO_EXTCLOCK = 1,

	// Soft reset the entire device _minus_ the always-on power domain.
	RESET_REQUEST_MAINTAIN_ALWAYS_ON_DOMAIN = 2,

	// Normal reset request, but prints a message that we're rebooting into new firmware.
	RESET_REQUEST_POST_FIRMWARE_FLASH = 3,

} reset_request_commands_t;

/**
 * Arguments is a reset_request_commands_t.
 */
int core_verb_request_reset(struct command_transaction *trans)
{
	reset_request_commands_t reset_reason_command = comms_argument_parse_uint32_t(trans);
	reset_reason_t reset_reason;

	bool reset_always_on_domain = true;

	switch (reset_reason_command) {

		case RESET_REQUEST_SWITCH_TO_EXTCLOCK:
			pr_info("Performing soft reset and switching to external clock...\n");
			reset_reason = RESET_REASON_USE_EXTCLOCK;
			break;

		case RESET_REQUEST_MAINTAIN_ALWAYS_ON_DOMAIN:
			pr_info("Performing soft reset, but not resetting the always-on (RTC) power domain.\n");

			reset_reason = RESET_REASON_SOFT_RESET;
			reset_always_on_domain = false;
			break;

		case RESET_REQUEST_POST_FIRMWARE_FLASH:
			pr_info("Resetting device into newly-flashed firmware...\n");
			reset_reason = RESET_REASON_NEW_FIRMWARE;
			break;

		default:
			pr_info("Performing soft reset...\n");
			reset_reason = RESET_REASON_SOFT_RESET;
			break;
	}

	// Perform the actual reset. Should never return.
	system_reset(reset_reason, reset_always_on_domain);
	return 0;
}


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package lab4_progra2;

/**
 *
 * @author Franklin Garcia
 */
public class empleado_seguridad extends Empleado{

    public empleado_seguridad() {
        super();
    }

    public empleado_seguridad(String nombre, String id, int Edad, int altura, int peso, String residencia) {
        super(nombre, id, Edad, altura, peso, residencia);
    }

    @Override
    public String toString() {
        return "empleado_seguridad{" + '}';
    }

}


text:
colorize a stream with ansi colors

# example

Here we create 3 streams and interleave the colored chunks.

``` js
var through = require('through2');
var colorize = require('ansi-color-stream');

var a = through();
var b = through();
var c = through();

a.pipe(colorize('bg bright pink fg purple')).pipe(process.stdout);
b.pipe(colorize('purple')).pipe(process.stdout);
c.pipe(colorize('bg cyan fg blue')).pipe(process.stdout);

a.write('AAA');
b.write('BBB');
c.write('CCC\n');

b.write('bb');
c.write('ccc');
a.write('a\n');
```

# methods

``` js
var colorize = require('ansi-color-stream')
```

## var stream = colorize(color)

Return a transform stream that adds `color` to each of the chunks. `color`
is a
[fuzzy string name or array](https://npmjs.org/package/fuzzy-ansi-color)
that describes the color to use.

# install

With [npm](https://npmjs.org) do:

```
npm install ansi-color-stream
```

# license

MIT