text:
<?php

namespace PCI\Http\Middleware;

use Closure;
use Illuminate\Contracts\Auth\Guard;
use PCI\Models\User;

/**
 * Class RedirectIfNotVerified
 * @package PCI\Http\Middleware
 * @author Alejandro Granadillo <slayerfat@gmail.com>
 * @link https://github.com/slayerfat/sistemaPCI Repositorio en linea.
 */
class RedirectIfNotVerified
{

    /**
     * The Guard implementation.
     *
     * @var Guard
     */
    protected $auth;

    /**
     * @var User|null
     */
    protected $user;

    /**
     * Create a new filter instance.
     *
     * @param  Guard  $auth
     */
    public function __construct(Guard $auth)
    {
        $this->auth = $auth;

        $this->user = $auth->user();
    }

    /**
     * Handle an incoming request.
     * Basicamente lo mismo que admin pero para verficado.
     * @see \PCI\Http\Middleware\RedirectIfNotAdmin
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if ($this->user && $this->user->isVerified()) {
            return redirect()->route('index');
        }

        return $next($request);
    }
}


text:
package com.mossle.bpm.support;

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

import javax.annotation.Resource;

import com.mossle.api.form.FormDTO;

import com.mossle.bpm.cmd.CompleteTaskWithCommentCmd;
import com.mossle.bpm.cmd.DeleteTaskWithCommentCmd;
import com.mossle.bpm.cmd.FindTaskDefinitionsCmd;
import com.mossle.bpm.cmd.RollbackTaskCmd;
import com.mossle.bpm.cmd.SignalStartEventCmd;
import com.mossle.bpm.cmd.WithdrawTaskCmd;
import com.mossle.bpm.persistence.domain.BpmConfForm;
import com.mossle.bpm.persistence.domain.BpmConfOperation;
import com.mossle.bpm.persistence.domain.BpmConfUser;
import com.mossle.bpm.persistence.domain.BpmTaskConf;
import com.mossle.bpm.persistence.manager.BpmConfFormManager;
import com.mossle.bpm.persistence.manager.BpmConfOperationManager;
import com.mossle.bpm.persistence.manager.BpmConfUserManager;
import com.mossle.bpm.persistence.manager.BpmTaskConfManager;

import com.mossle.spi.process.InternalProcessConnector;
import com.mossle.spi.process.ProcessTaskDefinition;

import org.activiti.engine.IdentityService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.cmd.GetDeploymentProcessDefinitionCmd;
import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.el.ExpressionManager;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.task.TaskDefinition;
import org.activiti.engine.task.Task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.jdbc.core.JdbcTemplate;

/**
 * 这是一个spi接口,因为HumanTask的配置还没有完全从bpm里抽象出去,所以还有不少配置需要从bpm里读取.
 */
public class ActivitiInternalProcessConnector implements
        InternalProcessConnector {
    /** logger. */
    private static Logger logger = LoggerFactory
            .getLogger(ActivitiInternalProcessConnector.class);
    private ProcessEngine processEngine;
    private BpmConfOperationManager bpmConfOperationManager;
    private BpmConfFormManager bpmConfFormManager;
    private BpmTaskConfManager bpmTaskConfManager;
    private BpmConfUserManager bpmConfUserManager;
    private JdbcTemplate jdbcTemplate;

    /**
     * 获得任务表单,不包含表单内容.
     */
    public FormDTO findTaskForm(String taskId) {
        Task task = processEngine.getTaskService().createTaskQuery()
                .taskId(taskId).singleResult();
        String processDefinitionId = task.getProcessDefinitionId();
        String activityId = task.getTaskDefinitionKey();
        FormDTO formDto = new FormDTO();
        formDto.setTaskId(taskId);

        List<BpmConfOperation> bpmConfOperations = bpmConfOperationManager
                .find("from BpmConfOperation where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        processDefinitionId, activityId);

        for (BpmConfOperation bpmConfOperation : bpmConfOperations) {
            formDto.getButtons().add(bpmConfOperation.getValue());
        }

        formDto.setProcessDefinitionId(processDefinitionId);
        formDto.setActivityId(activityId);

        List<BpmConfForm> bpmConfForms = bpmConfFormManager
                .find("from BpmConfForm where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        processDefinitionId, activityId);

        if (!bpmConfForms.isEmpty()) {
            BpmConfForm bpmConfForm = bpmConfForms.get(0);

            if (!Integer.valueOf(2).equals(bpmConfForm.getStatus())) {
                // 外部表单
                if (Integer.valueOf(1).equals(bpmConfForm.getType())) {
                    formDto.setRedirect(true);
                    formDto.setUrl(bpmConfForm.getValue());
                } else {
                    formDto.setCode(bpmConfForm.getValue());
                }
            }
        }

        return formDto;
    }

    /**
     * 获得任务定义.
     */
    public List<ProcessTaskDefinition> findTaskDefinitions(
            String processDefinitionId) {
        List<ProcessTaskDefinition> processTaskDefinitions = new ArrayList<ProcessTaskDefinition>();
        FindTaskDefinitionsCmd cmd = new FindTaskDefinitionsCmd(
                processDefinitionId);
        List<TaskDefinition> taskDefinitions = processEngine
                .getManagementService().executeCommand(cmd);

        for (TaskDefinition taskDefinition : taskDefinitions) {
            ProcessTaskDefinition processTaskDefinition = new ProcessTaskDefinition();
            processTaskDefinition.setKey(taskDefinition.getKey());

            if (taskDefinition.getNameExpression() != null) {
                processTaskDefinition.setName(taskDefinition
                        .getNameExpression().getExpressionText());
            }

            if (taskDefinition.getAssigneeExpression() != null) {
                processTaskDefinition.setAssignee(taskDefinition
                        .getAssigneeExpression().getExpressionText());
            }

            processTaskDefinitions.add(processTaskDefinition);
        }

        return processTaskDefinitions;
    }

    /**
     * 完成任务.
     */
    public void completeTask(String taskId, String userId,
            Map<String, Object> variables) {
        TaskService taskService = processEngine.getTaskService();
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if (task == null) {
            throw new IllegalStateException("任务不存在");
        }

        // 先设置登录用户
        IdentityService identityService = processEngine.getIdentityService();
        identityService.setAuthenticatedUserId(userId);

        // 处理子任务
        if ("subtask".equals(task.getCategory())) {
            processEngine.getManagementService().executeCommand(
                    new DeleteTaskWithCommentCmd(taskId, "完成"));

            int count = jdbcTemplate.queryForObject(
                    "select count(*) from ACT_RU_TASK where PARENT_TASK_ID_=?",
                    Integer.class, task.getParentTaskId());

            if (count > 1) {
                return;
            }

            taskId = task.getParentTaskId();
        }

        processEngine.getManagementService().executeCommand(
                new CompleteTaskWithCommentCmd(taskId, variables, "完成"));
    }

    /**
     * 转发任务.
     */
    public void transfer(String taskId, String assignee, String owner) {
        processEngine.getTaskService().setAssignee(taskId, assignee);
        processEngine.getTaskService().setOwner(taskId, owner);
    }

    /**
     * 撤销任务.
     */
    public void withdrawTask(String taskId) {
        Command<Integer> cmd = new WithdrawTaskCmd(taskId);

        processEngine.getManagementService().executeCommand(cmd);
    }

    /**
     * 回退指定节点,指定负责人. 如果activityId为null,就自动查询上一个节点.
     */
    public void rollback(String taskId, String activityId, String userId) {
        Command<Object> cmd = new RollbackTaskCmd(taskId, activityId, userId);

        processEngine.getManagementService().executeCommand(cmd);
    }

    /**
     * 回退自定节点,使用最后的负责人. 如果activityId为null,就自动查询上一个节点.
     */
    public void rollbackAuto(String taskId, String activityId) {
        Command<Object> cmd = new RollbackTaskCmd(taskId, activityId);
        processEngine.getManagementService().executeCommand(cmd);
    }

    /**
     * 协办任务.
     */
    public void delegateTask(String taskId, String userId) {
        processEngine.getTaskService().delegateTask(taskId, userId);
    }

    /**
     * 完成协办.
     */
    public void resolveTask(String taskId) {
        processEngine.getTaskService().resolveTask(taskId);
    }

    /**
     * 根据activityId找到任务定义.
     *
     * TODO: 支持ExpressionManager,支持Expr
     */
    public ProcessTaskDefinition findTaskDefinition(String processDefinitionId,
            String taskDefinitionKey, String businessKey) {
        // 先从流程定义里读取设计配置的负责人
        List<BpmConfUser> bpmConfUsers = bpmConfUserManager
                .find("from BpmConfUser where bpmConfNode.bpmConfBase.processDefinitionId=? and bpmConfNode.code=?",
                        processDefinitionId, taskDefinitionKey);
        logger.debug("{}", bpmConfUsers);

        ProcessTaskDefinition processTaskDefinition = new ProcessTaskDefinition();

        try {
            for (BpmConfUser bpmConfUser : bpmConfUsers) {
                logger.debug("status : {}, type: {}", bpmConfUser.getStatus(),
                        bpmConfUser.getType());
                logger.debug("value : {}", bpmConfUser.getValue());

                String value = bpmConfUser.getValue();

                if (bpmConfUser.getStatus() == 1) {
                    if (bpmConfUser.getType() == 0) {
                        logger.debug("add assignee : {}", value);
                        processTaskDefinition.setAssignee(value);
                    } else if (bpmConfUser.getType() == 1) {
                        logger.debug("add candidate user : {}", value);
                        processTaskDefinition.addParticipantDefinition("user",
                                value, "add");
                    } else if (bpmConfUser.getType() == 2) {
                        logger.debug("add candidate group : {}", value);
                        processTaskDefinition.addParticipantDefinition("group",
                                value, "add");
                    }
                } else if (bpmConfUser.getStatus() == 2) {
                    if (bpmConfUser.getType() == 0) {
                        logger.debug("delete assignee : {}", value);
                        processTaskDefinition.setAssignee(null);
                    } else if (bpmConfUser.getType() == 1) {
                        logger.debug("delete candidate user : {}", value);
                        processTaskDefinition.addParticipantDefinition("user",
                                value, "delete");
                    } else if (bpmConfUser.getType() == 2) {
                        logger.debug("delete candidate group : {}", value);
                        processTaskDefinition.addParticipantDefinition("group",
                                value, "delete");
                    }
                }
            }
        } catch (Exception ex) {
            logger.info(ex.getMessage(), ex);
        }

        try {
            String hql = "from BpmTaskConf where businessKey=? and taskDefinitionKey=?";
            BpmTaskConf bpmTaskConf = bpmTaskConfManager.findUnique(hql,
                    businessKey, taskDefinitionKey);
            String assignee = bpmTaskConf.getAssignee();

            if ((assignee != null) && (!"".equals(assignee))) {
                logger.debug("add assignee : {}", assignee);
                processTaskDefinition.setAssignee(assignee);
            }
        } catch (Exception ex) {
            logger.info(ex.getMessage(), ex);
        }

        return processTaskDefinition;
    }

    /**
     * 获得流程发起人.
     */
    public String findInitiator(String processInstanceId) {
        String initiator = null;

        if (Context.getCommandContext() == null) {
            initiator = processEngine.getHistoryService()
                    .createHistoricProcessInstanceQuery()
                    .processInstanceId(processInstanceId).singleResult()
                    .getStartUserId();
        } else {
            initiator = Context.getCommandContext()
                    .getHistoricProcessInstanceEntityManager()
                    .findHistoricProcessInstance(processInstanceId)
                    .getStartUserId();
        }

        return initiator;
    }

    /**
     * 获得某个节点的历史负责人.
     */
    public String findAssigneeByActivityId(String processInstanceId,
            String activityId) {
        return null;
    }

    /**
     * 解析表达式.
     */
    public Object executeExpression(String taskId, String expressionText) {
        TaskEntity taskEntity = Context.getCommandContext()
                .getTaskEntityManager().findTaskById(taskId);
        ExpressionManager expressionManager = Context
                .getProcessEngineConfiguration().getExpressionManager();

        return expressionManager.createExpression(expressionText).getValue(
                taskEntity);
    }

    /**
     * 获得开始事件id.
     */
    public String findInitialActivityId(String processDefinitionId) {
        GetDeploymentProcessDefinitionCmd getDeploymentProcessDefinitionCmd = new GetDeploymentProcessDefinitionCmd(
                processDefinitionId);
        ProcessDefinitionEntity processDefinition = processEngine
                .getManagementService().executeCommand(
                        getDeploymentProcessDefinitionCmd);

        return processDefinition.getInitial().getId();
    }

    /**
     * 触发execution继续执行.
     */
    public void signalExecution(String executionId) {
        // processEngine.getRuntimeService().signal(executionId);
        processEngine.getManagementService().executeCommand(
                new SignalStartEventCmd(executionId));
    }

    // ~ ==================================================
    @Resource
    public void setProcessEngine(ProcessEngine processEngine) {
        this.processEngine = processEngine;
    }

    @Resource
    public void setBpmConfOperationManager(
            BpmConfOperationManager bpmConfOperationManager) {
        this.bpmConfOperationManager = bpmConfOperationManager;
    }

    @Resource
    public void setBpmConfFormManager(BpmConfFormManager bpmConfFormManager) {
        this.bpmConfFormManager = bpmConfFormManager;
    }

    @Resource
    public void setBpmTaskConfManager(BpmTaskConfManager bpmTaskConfManager) {
        this.bpmTaskConfManager = bpmTaskConfManager;
    }

    @Resource
    public void setBpmConfUserManager(BpmConfUserManager bpmConfUserManager) {
        this.bpmConfUserManager = bpmConfUserManager;
    }

    @Resource
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Messenger\Test;

abstract class Database extends \PHPUnit_Extensions_Database_TestCase
{
    protected $connection = null;

    public function getConnection()
    {
        $databasePath = __DIR__ . "/../../../resources/messenger_test.db";
        $config = new \Doctrine\DBAL\Configuration();

        $connectionParams = array(
            'path' => $databasePath,
            'driver' => 'pdo_sqlite',
        );

        $this->connection = \Doctrine\DBAL\DriverManager::getConnection($connectionParams, $config);

        return $this->createDefaultDBConnection($this->connection->getWrappedConnection(), "messenger_test");
    }
}


text:
package io.github.ageofwar.telejam.messages;

import com.google.gson.annotations.SerializedName;
import io.github.ageofwar.telejam.chats.Chat;
import io.github.ageofwar.telejam.payments.SuccessfulPayment;
import io.github.ageofwar.telejam.replymarkups.InlineKeyboardMarkup;
import io.github.ageofwar.telejam.users.User;

import java.util.Objects;

/**
 * This object represents a successful payment message.
 *
 * @author Michi Palazzo
 */
public class SuccessfulPaymentMessage extends Message {

  static final String SUCCESSFUL_PAYMENT_FIELD = "successful_payment";

  /**
   * Information about the payment.
   */
  @SerializedName(SUCCESSFUL_PAYMENT_FIELD)
  private final SuccessfulPayment successfulPayment;

  public SuccessfulPaymentMessage(long id,
                                  User sender,
                                  long date,
                                  Chat chat,
                                  Message replyToMessage,
                                  Long editDate,
                                  String authorSignature,
                                  SuccessfulPayment successfulPayment,
                                  InlineKeyboardMarkup replyMarkup) {
    super(id, sender, date, chat, replyToMessage, editDate, authorSignature, replyMarkup);
    this.successfulPayment = Objects.requireNonNull(successfulPayment);
  }

  /**
   * Getter for property {@link #successfulPayment}.
   *
   * @return value for property {@link #successfulPayment}
   */
  public SuccessfulPayment getSuccessfulPayment() {
    return successfulPayment;
  }

}


text:
namespace Crowdin.CSharp
{
    public interface IProjectGroupedClient
    {
        IProjectEndpoint Project { get; }

        IDirectoryEndpoint Directory { get; }
    }
}


text:
@(startForm:Form[String])(implicit request: RequestHeader, lang: Lang, env: securesocial.core.RuntimeEnvironment[_])
@import helper._
@import securesocial.core.IdentityProvider
@implicitFieldConstructor = @{ FieldConstructor(securesocial.views.html.inputFieldConstructor.f) }
@main( Messages("securesocial.password.title") ) {

@Messages("securesocial.password.title")

  @request.flash.get("error").map { msg =>

      @Messages(msg)

  }
  <form action="@env.routes.handleStartResetPasswordUrl"
  class="form-horizontal"
  autocomplete="off"
  method="POST"
  >
    <fieldset>
      @CSRF.formField
      @helper.inputText(
        startForm("email"),
        '_label -> Messages("securesocial.signup.email1"),
        'class -> "form-input-default form-control",
        'placeholder -> Messages("securesocial.signup.email1")
      )

        <button type="submit" class="btn btn-primary">@Messages("securesocial.password.reset")</button>
        @Messages("securesocial.signup.cancel")

    </fieldset>
  </form>
}


text:
#ifndef _IAS_AS_Lang_Printer_Expr_RelationalIsInstanceNodeHandler_H_
#define _IAS_AS_Lang_Printer_Expr_RelationalIsInstanceNodeHandler_H_

#include "RelationalBinaryOperNodeHandler.h"

namespace IAS {
namespace Lang {
namespace Printer {
namespace Expr {

/*************************************************************************/
/** The class. */
 class RelationalIsInstanceNodeHandler : public RelationalBinaryOperNodeHandler {
public:

	virtual ~RelationalIsInstanceNodeHandler() throw();

	virtual void call(const Model::Node* pNode, CallbackCtx *pCtx, std::ostream& os);

protected:
	RelationalIsInstanceNodeHandler();

	friend class ::IAS::Factory<RelationalIsInstanceNodeHandler>;
};

/*************************************************************************/
}
}
}
}

#endif /* _IAS_AS_Lang_Printer_Expr_RelationalEqNODEHANDLER_H_ */


text:
import { Map } from 'immutable';

import {
  InitialNetworksState,
  Network
} from '../../js/immutableRecords/networks';
import { getNetworks } from '../../js/selectors/networks';

describe('networks selectors', () => {
  describe('getNetworks()', () => {
    const state = {
      networks: new InitialNetworksState({
        loaded: false,
        isFetching: false,
        networks: Map({
          aNetwork1: new Network({
            name: 'aNetwork1'
          }),
          bNetwork2: new Network({
            name: 'bNetwork2'
          })
        })
      })
    };

    it('gets all networks', () => {
      expect(getNetworks(state).size).toEqual(2);
      expect(getNetworks(state).first().name).toEqual('aNetwork1');
    });
  });
});


text:
package org.ovirt.engine.ui.userportal.widget.tab;

import org.ovirt.engine.ui.common.widget.tab.AbstractHeadlessTabPanel;
import org.ovirt.engine.ui.common.widget.tab.TabDefinition;

import com.google.gwt.core.client.GWT;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.user.client.ui.Widget;
import com.gwtplatform.mvp.client.TabData;

public class HeadlessTabPanel extends AbstractHeadlessTabPanel {

    interface WidgetUiBinder extends UiBinder<Widget, HeadlessTabPanel> {
        WidgetUiBinder uiBinder = GWT.create(WidgetUiBinder.class);
    }

    public HeadlessTabPanel() {
        initWidget(WidgetUiBinder.uiBinder.createAndBindUi(this));
    }

    @Override
    protected TabDefinition createNewTab(TabData tabData) {
        return new UserPortalMainTab(tabData, this);
    }

}


text:
- - -

##HowTo:

###### The application need a server (es. Apache) to run. The easiest way to use the app is:
-  download and install xampp
-  put code in xampp/htdocs/
-  run xampp controll and start apache
-  from browser (firefox) 127.0.0.1

### The project aims to
1. Upload and view stack of images dicom
2. Manipulate images dicom
3. Extraction of areas of interest
4. Geometric simplification of the areas of interest
5. Build 3d models from a stack of images dicom

This guide help the user to use the web-application

- - -

### Upload and view stack of images dicom :

####- This is the index page of the project

####- From this page, using the botton open you can load one or more image dicom.

![image](1_bio.jpg)

#### - The slide_files botton is usefull for show all image that you load

#### - The scroll bar gives you the possibility to choose between the images loaded

![image](2_bio.jpg)

- - -

### Manipulate images dicom :

#### - Moving the mouse on the canvas, initially white, you can choose the bone density of the image

![image](3_bio.jpg)

- - -

#### - An example is given by the two underlying images that represent the same image at different densities

![image](4_load_img_1.jpg)

![image](5_load_img_2.jpg)

- - -

### Extraction of areas of interest :

#### -Once you have chosen the density region the button "Region Selection" will open the page for the selection of the region of interest :

![image](7_region_screen_1.jpg)

- - -
#### - Using the scrool bar you can choose the border approximation of the segmentation

#### - Clicking the area of interest will be colored blue

#### - The selection extracted from the image is displayed in a new canvas

#### - At the end of this process with the "Send to Segmenter" botton you can load the segmenter page

![image](6_region_screen.jpg)

- - -

### Geometric simplification of the areas of interest:

#### - The algorithm use a square that navigate the image to finf edge
#### - Using the scrool bar you can choose the square width of the algorithm

![image](7_segmenter_screen_2.jpg)

- - -

#### - The segment from the image are displayed in a new canvas

![image](7_segmenter_screen_1.jpg)


text:
using System;
using Ads.Client.Helpers;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using Ads.Client.Common;
using System.Diagnostics;

namespace Ads.Client
{
    public abstract class AmsSocketBase : IAmsSocket
    {
		public AmsSocketBase(string ipTarget, int portTarget = 48898)
        {
            Subscribers = 0;
            CreateSocket();
			this.IpTarget = ipTarget;
			this.PortTarget = portTarget;
            this.synchronizationContext = SynchronizationContext.Current;
        }

        public abstract void CreateSocket();

        protected SynchronizationContext synchronizationContext;

		public string IpTarget { get; set;}
		public int PortTarget { get; set;}

        public int Subscribers { get; set; }

        public event AmsSocketResponseDelegate OnReadCallBack;

        public bool ConnectedAsync { get; set; }

        public abstract bool IsConnected { get; }

        public abstract void ListenForHeader(byte[] amsheader, Action<byte[], SynchronizationContext> lambda);

        public void Listen()
        {
            if (IsConnected)
            {
                try
                {
                    //First wait for the Ams header (starts new thread)
                    byte[] amsheader = new byte[AmsHeaderHelper.AmsTcpHeaderSize];

                    ListenForHeader(amsheader, (buffer, usertoken) =>
                    {
                        //If a ams header is received, then read the rest (this is the new thread)
                        try
                        {
                            byte[] response = GetAmsMessage(buffer);

#if DEBUG_AMS
                            Debug.WriteLine("Received bytes: " +
                                    ByteArrayHelper.ByteArrayToTestString(buffer) + ',' +
                                    ByteArrayHelper.ByteArrayToTestString(response));
#endif

                            SynchronizationContext syncContext = usertoken != null ? usertoken : synchronizationContext;

                            var callbackArgs = new AmsSocketResponseArgs() {
                                Response = response,
                                Context = syncContext };
                            OnReadCallBack(this, callbackArgs);
                            Listen();
                        }
                        catch (Exception ex)
                        {
                            var callbackArgs = new AmsSocketResponseArgs() { Error = ex };
                            OnReadCallBack(this, callbackArgs);
                        }
                    });
                }
                catch (Exception ex)
                {
                    if (!Object.ReferenceEquals(ex.GetType(), typeof(ObjectDisposedException))) throw;
                }
            }
        }

        private byte[] GetAmsMessage(byte[] tcpHeader)
        {
            uint responseLength = AmsHeaderHelper.GetResponseLength(tcpHeader);
            byte[] response = new byte[responseLength];
            GetMessage(response);
            return response;
        }

        private void GetMessage(byte[] response)
        {
            if (ConnectedAsync)
                Async.ReceiveAsync(response).Wait();
            else
                Sync.Receive(response);

        }

        protected abstract void CloseConnection();

        protected virtual void Dispose(bool managed)
        {
            CloseConnection();
        }

        public void Dispose()
        {
            Dispose(true);
        }

        public virtual IAmsSocketSync Sync { get; set; }
        public virtual IAmsSocketAsync Async { get; set; }
    }
}


text:
=========
mtoatools
=========

.. image:: https://img.shields.io/pypi/v/mtoatools.svg
        :target: https://pypi.python.org/pypi/mtoatools

MtoAtools is a set of production tools for use with Arnold for Maya. This package will grow over time.

mtoatools.mattes
================
UI for managing Matte AOVs.

|mattesui|

Table of Contents
=================

.. toctree::
   :maxdepth: 2

   installation
   mattes
   history

Indices and tables
==================

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

.. |mattesui| image:: images/mtoatools_mattes_ui.png


text: Graphs and Data from LRAUVs (Long Range Autonomous Underwater Vehicles)


text:
package com.landoop.streamreactor.connect.hive.orc.vectors

import org.apache.hadoop.hive.ql.exec.vector.LongColumnVector

object LongVectorWriter extends OrcVectorWriter[LongColumnVector, Long] {
  override def write(vector: LongColumnVector, offset: Int, value: Option[Long]): Unit = {
    value match {
      case None =>
        vector.isNull(offset) = true
        vector.noNulls = false
      case Some(long) => vector.vector(offset) = long
    }
  }
}


text:
<?php //-->

namespace Cradle\Sql\MySql;

use Cradle\Sql\AbstractQuery;

/**
 * Generates alter query string syntax
 *
 * @vendor   Cradle
 * @package  Sql
 * @author   Christian Blanquera <cblanquera@openovate.com>
 * @standard PSR-2
 */
class QueryAlter extends AbstractQuery
{
    /**
     * @var string|null $name Name of table
     */
    protected $name = null;

    /**
     * @var array $changeFields List of fields to change
     */
    protected $changeFields = [];

    /**
     * @var array $addFields List of fields to add
     */
    protected $addFields = [];

    /**
     * @var array $removeFields List of fields to remove
     */
    protected $removeFields = [];

    /**
     * @var array $addKeys List of keys to add
     */
    protected $addKeys = [];

    /**
     * @var array $removeKeys List of keys to remove
     */
    protected $removeKeys = [];

    /**
     * @var array $addUniqueKeys List of unique keys to add
     */
    protected $addUniqueKeys = [];

    /**
     * @var array $removeUniqueKeys List of unique keys to remove
     */
    protected $removeUniqueKeys = [];

    /**
     * @var array $addPrimaryKeys List of primary keys to add
     */
    protected $addPrimaryKeys = [];

    /**
     * @var array $removePrimaryKeys List of primary keys to remove
     */
    protected $removePrimaryKeys = [];

    /**
     * Construct: Set the table, if any
     *
     * @param string|null $name Table name
     */
    public function __construct($name = null)
    {
        if (is_string($name)) {
            $this->setName($name);
        }
    }

    /**
     * Adds a field in the table
     *
     * @param *string $name       Column name
     * @param *array  $attributes Column attributes
     *
     * @return QueryAlter
     */
    public function addField($name, array $attributes)
    {
        $this->addFields[$name] = $attributes;
        return $this;
    }

    /**
     * Adds an index key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function addKey($name)
    {
        $this->addKeys[] = '`'.$name.'`';
        return $this;
    }

    /**
     * Adds a primary key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function addPrimaryKey($name)
    {
        $this->addPrimaryKeys[] = '`'.$name.'`';
        return $this;
    }

    /**
     * Adds a unique key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function addUniqueKey($name)
    {
        $this->addUniqueKeys[] = '`'.$name.'`';
        return $this;
    }

    /**
     * Changes attributes of the table given
     * the field name
     *
     * @param *string $name       Column name
     * @param *array  $attributes Column attributes
     *
     * @return QueryAlter
     */
    public function changeField($name, array $attributes)
    {
        $this->changeFields[$name] = $attributes;
        return $this;
    }

    /**
     * Returns the string version of the query
     *
     * @param bool $unbind Whether to unbind variables
     *
     * @return string
     */
    public function getQuery($unbind = false)
    {
        $fields = [];
        $table = '`'.$this->name.'`';

        foreach ($this->removeFields as $name) {
            $fields[] = 'DROP `'.$name.'`';
        }

        foreach ($this->addFields as $name => $attr) {
            $field = ['ADD `'.$name.'`'];
            if (isset($attr['type'])) {
                $field[] = isset($attr['length']) ?
                    $attr['type'] . '('.$attr['length'].')' :
                    $attr['type'];
            }

            if (isset($attr['attribute'])) {
                $field[] = $attr['attribute'];
            }

            if (isset($attr['null'])) {
                if ($attr['null'] == false) {
                    $field[] = 'NOT NULL';
                } else {
                    $field[] = 'DEFAULT NULL';
                }
            }

            if (isset($attr['default'])&& $attr['default'] !== false) {
                if (!isset($attr['null']) || $attr['null'] == false) {
                    if (is_string($attr['default'])) {
                        $field[] = 'DEFAULT \''.$attr['default'] . '\'';
                    } else if (is_numeric($attr['default'])) {
                        $field[] = 'DEFAULT '.$attr['default'];
                    }
                }
            }

            if (isset($attr['auto_increment']) && $attr['auto_increment'] == true) {
                $field[] = 'auto_increment';
            }

            $fields[] = implode(' ', $field);
        }

        foreach ($this->changeFields as $name => $attr) {
            $field = ['CHANGE `'.$name.'`  `'.$name.'`'];

            if (isset($attr['name'])) {
                $field = ['CHANGE `'.$name.'`  `'.$attr['name'].'`'];
            }

            if (isset($attr['type'])) {
                $field[] = isset($attr['length']) ? $attr['type'] . '('.$attr['length'].')' : $attr['type'];
            }

            if (isset($attr['attribute'])) {
                $field[] = $attr['attribute'];
            }

            if (isset($attr['null'])) {
                if ($attr['null'] == false) {
                    $field[] = 'NOT NULL';
                } else {
                    $field[] = 'DEFAULT NULL';
                }
            }

            if (isset($attr['default'])&& $attr['default'] !== false) {
                if (!isset($attr['null']) || $attr['null'] == false) {
                    if (is_string($attr['default'])) {
                        $field[] = 'DEFAULT \''.$attr['default'] . '\'';
                    } else if (is_numeric($attr['default'])) {
                        $field[] = 'DEFAULT '.$attr['default'];
                    }
                }
            }

            if (isset($attr['auto_increment']) && $attr['auto_increment'] == true) {
                $field[] = 'auto_increment';
            }

            $fields[] = implode(' ', $field);
        }

        foreach ($this->removeKeys as $key) {
            $fields[] = 'DROP INDEX `'.$key.'`';
        }

        if (!empty($this->addKeys)) {
            $fields[] = 'ADD INDEX ('.implode(', ', $this->addKeys).')';
        }

        foreach ($this->removeUniqueKeys as $key) {
            $fields[] = 'DROP INDEX `'.$key.'`';
        }

        if (!empty($this->addUniqueKeys)) {
            $fields[] = 'ADD UNIQUE ('.implode(', ', $this->addUniqueKeys).')';
        }

        foreach ($this->removePrimaryKeys as $key) {
            $fields[] = 'DROP PRIMARY KEY `'.$key.'`';
        }

        if (!empty($this->addPrimaryKeys)) {
            $fields[] = 'ADD PRIMARY KEY ('.implode(', ', $this->addPrimaryKeys).')';
        }

        $fields = implode(", \n", $fields);

        return sprintf(
            'ALTER TABLE %s %s;',
            $table,
            $fields
        );
    }

    /**
     * Removes a field
     *
     * @param *string $name Column name
     *
     * @return QueryAlter
     */
    public function removeField($name)
    {
        $this->removeFields[] = $name;
        return $this;
    }

    /**
     * Removes an index key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function removeKey($name)
    {
        $this->removeKeys[] = $name;
        return $this;
    }

    /**
     * Removes a primary key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function removePrimaryKey($name)
    {
        $this->removePrimaryKeys[] = $name;
        return $this;
    }

    /**
     * Removes a unique key
     *
     * @param *string $name Name of key
     *
     * @return QueryAlter
     */
    public function removeUniqueKey($name)
    {
        $this->removeUniqueKeys[] = $name;
        return $this;
    }

    /**
     * Sets the name of the table you wish to create
     *
     * @param *string $name Table name
     *
     * @return QueryAlter
     */
    public function setName($name)
    {
        $this->name = $name;
        return $this;
    }
}


text:
package test.models;

import models.Day;
import models.Show;
import org.junit.Test;

import static org.fest.assertions.Assertions.assertThat;
import static play.test.Helpers.*;

public class Test_Model_Show {

    private Show createShow() {

        Show show = new Show();
        show.setTitle("Duck Tales Test 02");
        show.setDescription("Description Of Duck Tales");
        show.setAirday(Day.SATURDAY);
        show.save();

        return show;

    }

    @Test
    public void selectShowById() {
        running(fakeApplication(inMemoryDatabase()), new Runnable() {
            public void run() {

                Show savedShow = createShow();

                Show show = Show.find.byId(savedShow.getId());
                assertThat(show.getId()).isEqualTo(savedShow.getId());
                assertThat(show.getTitle()).isEqualTo(savedShow.getTitle());
                assertThat(show.getDescription()).isEqualTo(savedShow.getDescription());
                assertThat(show.getAirday()).isEqualTo(savedShow.getAirday());

            }
        });
    }

    @Test
    public void selectShowByTitle() {
        running(fakeApplication(inMemoryDatabase()), new Runnable() {
            public void run() {

                Show savedShow = createShow();
                String title = savedShow.getTitle();
                Show show = Show.find.where().eq("title", savedShow.getTitle()).findUnique();

                assertThat(show.getId()).isEqualTo(savedShow.getId());
                assertThat(show.getTitle()).isEqualTo(savedShow.getTitle());
                assertThat(show.getDescription()).isEqualTo(savedShow.getDescription());

            }
        });
    }

    @Test
    public void updateShow() {
        running(fakeApplication(inMemoryDatabase()), new Runnable() {
            public void run() {

                String newTitle = "Duck Tales - Neues aus Entenhausen";
                String newDescription = "Duck Tales - Neues aus Entenhausen";

                Show savedShow = createShow();
                Long id = savedShow.getId();
                savedShow.setTitle(newTitle);
                savedShow.setDescription(newDescription);
                savedShow.save();

                Show updatedShow = Show.find.byId(id);

                assertThat(savedShow.getTitle()).isEqualTo(newTitle);
                assertThat(savedShow.getDescription()).isEqualTo(newDescription);

            }
        });
    }

    @Test
    public void deleteShow() {
        running(fakeApplication(inMemoryDatabase()), new Runnable() {
            public void run() {

                Show show = createShow();
                Long id = show.getId();
                show.delete();

                Show deletedShow = Show.find.byId(id);

                assertThat(deletedShow).isNull();

            }
        });
    }

}


text:
package com.albedinsky.android.intent;

import android.app.Activity;
import android.app.Fragment;
import android.test.ActivityInstrumentationTestCase2;
import android.util.AndroidRuntimeException;

import com.albedinsky.android.intent.inner.TestActivity;
import com.albedinsky.android.intent.inner.TestFragment;
import com.albedinsky.android.intent.internal.IntentActivityWrapper;
import com.albedinsky.android.intent.internal.IntentFragmentWrapper;

/**
 * @author Martin Albedinsky
 */
public abstract class IntentBaseTest<I extends BaseIntent> extends ActivityInstrumentationTestCase2<TestActivity> {

	@SuppressWarnings("unused")
	private static final String TAG = "IntentBaseTest";

	private final Class<I> mIntentClass;
	Activity mActivity;
	I mIntent;

	public IntentBaseTest(Class<I> classOfIntent) {
		super(TestActivity.class);
		this.mIntentClass = classOfIntent;
	}

	@Override
	public void setUp() throws Exception {
		super.setUp();
		this.mActivity = getActivity();
		this.createIntent();
	}

	public void testInstantiationWithActivity() {
		if (mIntentClass != null) {
			try {
				final BaseIntent intent = mIntentClass.getConstructor(Activity.class).newInstance(mActivity);
				assertTrue(intent.mContextWrapper instanceof IntentActivityWrapper);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void testInstantiationWithFragment() {
		if (mIntentClass != null) {
			try {
				final BaseIntent intent = mIntentClass.getConstructor(Fragment.class).newInstance(new TestFragment());
				assertTrue(intent.mContextWrapper instanceof IntentFragmentWrapper);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	private void createIntent() {
		if (mIntentClass != null) {
			try {
				this.mIntent = mIntentClass.getConstructor(Activity.class).newInstance(mActivity);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	String getString(int resId) {
		return mActivity.getString(resId);
	}

	CharSequence getText(int resId) {
		return mActivity.getText(resId);
	}

	static void assertBuildThrowsExceptionWithCause(BaseIntent intent, String cause) {
		try {
			intent.build();
		} catch (AndroidRuntimeException e) {
			final String message = "Cannot build " + intent.getClass().getSimpleName() + ". " + cause;
			final String eMessage = e.getMessage();
			if (!message.contentEquals(eMessage)) {
				throw new AssertionError(
						"Expected exception with message <" + message + "> but message was <" + eMessage + ">"
				);
			}
			return;
		}
		final String intentName = intent.getClass().getSimpleName();
		throw new AssertionError("No exception has been thrown while building intent(" + intentName + ").");
	}
}


text:
"""API to record and track seconds since last request"""
from flask import current_app
import redis

def _connection():
    # Documented to be pooled at the library level
    return redis.Redis.from_url(current_app.config['REDIS_URL'])

KEY = 'Usage Tracker'

def mark_usage():
    conn = _connection()
    conn.set(name=KEY, value="ping")

def last_usage():
    conn = _connection()
    return conn.object(key=KEY, infotype='idletime')


text:
package com.intellij.execution;

import com.intellij.execution.configurations.GeneralCommandLine;
import com.intellij.execution.configurations.PtyCommandLine;
import com.intellij.openapi.util.SystemInfo;

import static org.junit.Assume.assumeFalse;

public class PtyCommandLineTest extends GeneralCommandLineTest {
  @Override
  protected GeneralCommandLine createCommandLine(String... command) {
    PtyCommandLine cmd = new PtyCommandLine();

    if (command.length > 0) {
      cmd.setExePath(command[0]);

      for (int i = 1; i < command.length; i++) {
        cmd.addParameter(command[i]);
      }
    }

    return cmd;
  }
}


text:
package com.sissi.protocol.error.detail;

import javax.xml.bind.annotation.XmlRootElement;

import com.sissi.protocol.error.ServerErrorDetail;

/**
 * @author kim 2014年1月6日
 */
@XmlRootElement(name = MalformedRequest.NAME)
public class MalformedRequest extends ServerErrorDetail {

	public final static MalformedRequest DETAIL = new MalformedRequest();

	public final static String NAME = "malformed-request";

	private MalformedRequest() {
		super(XMLNS_ELEMENT);
	}
}


text:
<?php

namespace PaynetEasy\PaynetEasyApi\Query;

use PaynetEasy\PaynetEasyApi\PaymentData\Payment;

/**
 * @see http://wiki.payneteasy.com/index.php/PnE:Preauth/Capture_Transactions#Process_Preauth_transaction
 */
class PreauthQuery extends SaleQuery
{
    /**
     * {@inheritdoc}
     */
    static protected $paymentStatus = Payment::STATUS_PREAUTH;
}


text:
package reswing

import scala.swing.{Color, Component, Dimension, Font, Graphics2D}
import scala.swing.event._

abstract class ReComponent(
    val background: ReSwingValue[Color] = (),
    val foreground: ReSwingValue[Color] = (),
    val font: ReSwingValue[Font] = (),
    val enabled: ReSwingValue[Boolean] = (),
    minimumSize: ReSwingValue[Dimension] = (),
    maximumSize: ReSwingValue[Dimension] = (),
    preferredSize: ReSwingValue[Dimension] = ()
) extends ReUIElement(minimumSize, maximumSize, preferredSize) {

  override protected lazy val peer = new Component with ComponentMixin

  val hasFocus = ReSwingValue.using({ () => peer.hasFocus }, classOf[FocusGained], classOf[FocusLost])

  background.using({ () => peer.background }, peer.background_= _, "background")
  foreground.using({ () => peer.foreground }, peer.foreground_= _, "foreground")
  font.using({ () => peer.font }, peer.font_= _, "font")
  enabled.using({ () => peer.enabled }, peer.enabled_= _, "enabled")

  object mouse {
    object clicks {
      val clicked  = ReSwingEvent.using(peer.mouse.clicks, classOf[MouseClicked])
      val pressed  = ReSwingEvent.using(peer.mouse.clicks, classOf[MousePressed])
      val released = ReSwingEvent.using(peer.mouse.clicks, classOf[MouseReleased])
    }

    object moves {
      val dragged = ReSwingEvent.using(peer.mouse.moves, classOf[MouseDragged])
      val entered = ReSwingEvent.using(peer.mouse.moves, classOf[MouseEntered])
      val exited  = ReSwingEvent.using(peer.mouse.moves, classOf[MouseExited])
      val moved   = ReSwingEvent.using(peer.mouse.moves, classOf[MouseMoved])
    }

    object wheel {
      val moved = ReSwingEvent.using(peer.mouse.wheel, classOf[MouseWheelMoved])
    }
  }

  object keys {
    val pressed  = ReSwingEvent.using(peer.keys, classOf[KeyPressed])
    val released = ReSwingEvent.using(peer.keys, classOf[KeyReleased])
    val typed    = ReSwingEvent.using(peer.keys, classOf[KeyTyped])
  }

  protected trait ComponentMixin extends Component {
    override def paintComponent(g: Graphics2D) = ReComponent.this.paintComponent(g)
    def __super__paintComponent(g: Graphics2D) = super.paintComponent(g)
    override def paintBorder(g: Graphics2D)    = ReComponent.this.paintBorder(g)
    def __super__paintBorder(g: Graphics2D)    = super.paintBorder(g)
    override def paintChildren(g: Graphics2D)  = ReComponent.this.paintChildren(g)
    def __super__paintChildren(g: Graphics2D)  = super.paintChildren(g)
    override def paint(g: Graphics2D) = {
      ReComponent.this.location() = location
      ReComponent.this.bounds() = bounds
      ReComponent.this.size() = size
      ReComponent.this.paint(g)
    }
    def __super__paint(g: Graphics2D) = super.paint(g)
  }

  protected def paintComponent(g: Graphics2D) = peer.__super__paintComponent(g)
  protected def paintBorder(g: Graphics2D)    = peer.__super__paintBorder(g)
  protected def paintChildren(g: Graphics2D)  = peer.__super__paintChildren(g)
  def paint(g: Graphics2D)                    = peer.__super__paint(g)
}

object ReComponent {
  implicit def toComponent(component: ReComponent): Component = component.peer
}


text:
package db2ea;

import db2ea.utils.StrUtils;

import java.io.BufferedWriter;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;

/**
 * Created by user on 2017/9/23.
 */
public class EAWriter {
    private String fileName;
    private BufferedWriter fileWriter;
    private EAItem pack;
    private IdChecker idChecker;

    public static String Field_Marker = "\"";
    public static String Field_Marker_Replace = "'";
    public static String Field_Separator = ",";
    public static String Field_Header = "Alias,Name,Type,Stereotype,Phase,CSV_KEY,CSV_PARENT_KEY";

    public EAWriter(String fileName) {
        if (!StrUtils.isEmpty(fileName) && fileName.toLowerCase().endsWith(SqlParser.File_SQL_Ext)) {
            fileName = fileName.substring(0, fileName.length() - SqlParser.File_SQL_Ext.length());
        }
        this.fileName = String.format("%s%s", fileName == null ? "file" : fileName, SqlParser.File_EA_Ext);
    }

    public boolean isOpen() {
        return fileWriter != null;
    }

    public EAItem getPack() {
        return pack;
    }

    /**
     * open, write header, create root package which will be the first level elements' parent
     * @return
     */
    public EAItem open() {
        if (fileWriter != null) {
            close();
        }

        pack = null;
        idChecker = new IdChecker();

        try {
            fileWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));

            // headers
            fileWriter.write(Field_Header);
            fileWriter.newLine();

            // package
            // pack = new EAItem("EA包", EAType.Package, EAStereotype.None, null);
            write(pack);
        } catch (IOException e) {
            fileWriter = null;
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

        return pack;
    }

    public void close() {
        if (fileWriter == null) {
            return;
        }

        pack = null;
        idChecker = null;

        try {
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        } finally {
            fileWriter = null;
        }
        System.out.printf("EAWrite saves successfully: %s\n", fileName);
    }

    public void write(EAItem item) {
        if (item == null) {
            return;
        }

        if (idChecker != null && idChecker.isDuplicated(item.getId())) {
            System.out.printf("Duplicated id: %s, %s\n", item.getId(), item.toString());
            return;
        }

        if (fileWriter == null) {
            System.out.println("Please call open() firstly.");
            return;
        }

        try {
            fileWriter.write(item.toString());
            fileWriter.write("\n");
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }
    }
}


text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.Docs.MarkdownLite.Matchers
{
    internal sealed class ReverseMatcher : Matcher
    {
        private readonly Matcher _inner;

        public ReverseMatcher(Matcher inner)
        {
            _inner = inner;
        }

        public override int Match(MatchContent content)
        {
            return _inner.Match(content.Reverse());
        }

        public override string ToString()
        {
            return "(Reverse:" + _inner + ")";
        }
    }
}


text:
define([
    'underscore',
    'jquery',
    'backbone',
    'find/app/model/geography-model',
    'find/app/page/search/abstract-section-view',
    'find/app/page/search/filters/date/dates-filter-view',
    'find/app/page/search/filters/geography/geography-view',
    'find/app/page/search/filters/documentselection/document-selection-view',
    'find/app/page/search/filters/parametric/filtered-parametric-fields-collection',
    'find/app/page/search/filters/parametric/parametric-view',
    'find/app/page/search/filters/parametric/numeric-parametric-field-view',
    'find/app/util/text-input',
    'find/app/util/collapsible',
    'find/app/util/filtering-collection',
    'find/app/configuration',
    'i18n!find/nls/bundle',
    'i18n!find/nls/indexes',
    'text!find/templates/app/page/search/filters/filter-separator.html'
], function(_, $, Backbone, GeographyModel, AbstractSectionView, DateView, GeographyView, DocumentSelectionFilterView, FilteredParametricFieldsCollection,
            ParametricView, NumericParametricFieldView, TextInput, Collapsible, FilteringCollection,
            configuration, i18n, i18nIndexes, filterSeparator) {
    'use strict';

    const datesTitle = i18n['search.dates'];
    const geographyTitle = i18n['search.geography'];
    const LIST_RESULTS_VIEW_ID = 'list';

    function searchMatches(text, search) {
        return text.toLowerCase().indexOf(search.toLowerCase()) > -1;
    }

    const showGeographyFilter = GeographyModel.LocationFields.length > 0;

    return AbstractSectionView.extend({
        initialize: function(options) {
            AbstractSectionView.prototype.initialize.apply(this, arguments);

            const IndexesView = options.IndexesView;
            this.collapsed = {};

            const config = configuration();

            const views = [{
                id: 'metaFilter',
                shown: config.enableMetaFilter,
                initialize: function() {
                    //Initializing the text with empty string to stop IE11 issue with triggering input event on render
                    this.filterModel = new Backbone.Model({text: ''});

                    this.filterInput = new TextInput({
                        model: this.filterModel,
                        modelAttribute: 'text',
                        templateOptions: {
                            placeholder: i18n['search.filters.filter']
                        }
                    });

                    this.$emptyMessage = $('
' + i18n['search.filters.empty'] + '
');

                    this.listenTo(this.filterModel, 'change', function() {
                        this.updateDatesVisibility();
                        this.updateGeographyVisibility();
                        this.updateParametricVisibility();
                        this.updateEmptyMessage();
                    });
                }.bind(this),
                get$els: function() {
                    return [this.filterInput.$el, this.$emptyMessage];
                }.bind(this),
                render: function() {
                    this.filterInput.render();
                }.bind(this),
                postRender: function() {
                    this.updateParametricVisibility();
                    this.updateDatesVisibility();
                    this.updateGeographyVisibility();
                    this.updateIndexesVisibility();
                    this.updateEmptyMessage();
                }.bind(this),
                remove: function() {
                    this.filterInput.remove();
                }.bind(this)
            }, {
                id: 'indexesFilter',
                shown: true,
                initialize: function() {
                    this.indexesEmpty = false;
                    this.collapsed.indexes = true;

                    const indexesView = new IndexesView({
                        delayedSelection: options.delayedIndexesSelection,
                        filterModel: this.filterModel,
                        indexesCollection: options.indexesCollection,
                        queryModel: options.queryModel,
                        selectedDatabasesCollection: options.queryState.selectedIndexes,
                        visibleIndexesCallback: _.bind(function(indexes) {
                            this.indexesEmpty = indexes.length === 0;
                            this.updateIndexesVisibility();
                            this.updateEmptyMessage();
                        }, this)
                    });

                    this.indexesViewWrapper = new Collapsible({
                        view: indexesView,
                        collapseModel: new Backbone.Model({collapsed: this.collapsed.indexes}),
                        title: i18nIndexes['search.indexes']
                    });

                    // only track user triggered changes, not automatic ones
                    this.listenTo(this.indexesViewWrapper, 'toggle', function(newState) {
                        this.collapsed.indexes = newState;
                    });
                }.bind(this),
                get$els: function() {
                    return [this.indexesViewWrapper.$el];
                }.bind(this),
                render: function() {
                    this.indexesViewWrapper.render();
                }.bind(this),
                postRender: function() {
                    this.updateIndexesVisibility();
                }.bind(this),
                remove: function() {
                    this.indexesViewWrapper.remove();
                }.bind(this)
            }, {
                id: 'datesFilter',
                shown: config.enableDatesFilter,
                initialize: function() {
                    this.collapsed.dates = true;

                    const dateView = new DateView({
                        datesFilterModel: options.queryState.datesFilterModel,
                        savedSearchModel: options.savedSearchModel
                    });

                    this.dateViewWrapper = new Collapsible({
                        view: dateView,
                        collapseModel: new Backbone.Model({collapsed: this.collapsed.dates}),
                        title: datesTitle
                    });

                    this.listenTo(this.dateViewWrapper, 'toggle', function(newState) {
                        this.collapsed.dates = newState;
                    });

                }.bind(this),
                get$els: function() {
                    return [this.dateViewWrapper.$el];
                }.bind(this),
                render: function() {
                    this.dateViewWrapper.render();
                }.bind(this),
                postRender: function() {
                    this.updateDatesVisibility();
                }.bind(this),
                remove: function() {
                    this.dateViewWrapper.remove();
                }.bind(this)
            }, {
                id: 'geographyFilter',
                shown: config.enableGeographyFilter && showGeographyFilter,
                initialize: function() {
                    const geographyModel = options.queryState.geographyModel;
                    this.collapsed.geography = !_.find(_.map(geographyModel.attributes, function(v){ return v && v.length }));

                    const geographyView = new GeographyView({
                        geographyModel: geographyModel,
                        savedSearchModel: options.savedSearchModel
                    })

                    this.geographyViewWrapper = new Collapsible({
                        view: geographyView,
                        collapseModel: new Backbone.Model({collapsed: this.collapsed.geography}),
                        title: geographyTitle
                    })

                    this.listenTo(this.geographyViewWrapper, 'toggle', function(newState) {
                        this.collapsed.geography = newState;
                    });
                }.bind(this),
                get$els: function() {
                    return [this.geographyViewWrapper.$el];
                }.bind(this),
                render: function() {
                    this.geographyViewWrapper.render();
                }.bind(this),
                postRender: function() {
                    this.updateGeographyVisibility();
                }.bind(this),
                remove: function() {
                    this.geographyViewWrapper.remove();
                }.bind(this)
            }, {

                id: 'documentSelectionFilter',
                shown: config.enableDocumentSelectionFilter &&
                    _.contains(config.resultViewOrder, LIST_RESULTS_VIEW_ID),
                initialize: function() {
                    const documentSelectionView = new DocumentSelectionFilterView({
                        documentSelectionModel: options.queryState.documentSelectionModel,
                        savedSearchModel: options.savedSearchModel
                    });
                    const viewWrapper = this.documentSelectionViewWrapper = new Collapsible({
                        view: documentSelectionView,
                        collapseModel: new Backbone.Model({ collapsed: true }),
                        title: i18n['search.documentSelection.title']
                    });

                    // keep queryModel and wrapper toggled state synchronised
                    this.listenTo(this.documentSelectionViewWrapper, 'toggle',
                        function (collapsed) {
                            if (collapsed) {
                                options.queryModel.set('editingDocumentSelection', false);
                            } else {
                                options.queryModel.set('editingDocumentSelection', true);
                            }
                        });
                    this.listenTo(options.queryModel, 'change:editingDocumentSelection',
                        function () {
                            if (options.queryModel.get('editingDocumentSelection')) {
                                viewWrapper.show();
                            } else {
                                viewWrapper.hide();
                            }
                        });
                }.bind(this),

                get$els: function() {
                    return [this.documentSelectionViewWrapper.$el];
                }.bind(this),
                render: function() {
                    this.documentSelectionViewWrapper.render();
                }.bind(this),
                postRender: _.noop,
                remove: function() {
                    this.documentSelectionViewWrapper.remove();
                }.bind(this)

            }, {
                id: 'parametricFilter',
                shown: true,
                initialize: function() {
                    this.parametricFieldsCollection = options.parametricFieldsCollection;
                    const filteredParametricCollection = new FilteringCollection([], {
                        collection: options.parametricCollection,
                        predicate: _.constant(true)
                    });
                    this.filteredParametricFieldsCollection = new FilteredParametricFieldsCollection([], {
                        collection: this.parametricFieldsCollection,
                        filterModel: this.filterModel,
                        queryModel: options.queryModel,
                        parametricCollection: options.parametricCollection,
                        filteredParametricCollection: filteredParametricCollection
                    });

                    if(this.filterModel) {
                        this.listenTo(this.filteredParametricFieldsCollection, 'update reset', function() {
                            this.updateParametricVisibility();
                            this.updateEmptyMessage();
                        });
                    }

                    const parametricValuesSort = config && config.uiCustomization && config.uiCustomization.parametricValuesSort || undefined;

                    this.parametricView = new ParametricView({
                        filterModel: this.filterModel,
                        queryModel: options.queryModel,
                        queryState: options.queryState,
                        timeBarModel: options.timeBarModel,
                        collection: this.filteredParametricFieldsCollection,
                        parametricFieldsCollection: this.parametricFieldsCollection,
                        parametricValuesSort: parametricValuesSort,
                        inputTemplate: NumericParametricFieldView.dateInputTemplate,
                        formatting: NumericParametricFieldView.dateFormatting,
                        indexesCollection: options.indexesCollection,
                        filteredParametricCollection: filteredParametricCollection
                    });
                }.bind(this),
                get$els: function() {
                    return [this.parametricView.$el];
                }.bind(this),
                render: function() {
                    this.parametricView.render();
                }.bind(this),
                postRender: _.noop,
                remove: function() {
                    this.parametricView.remove();
                }.bind(this)
            }];

            if (config && config.uiCustomization && config.uiCustomization.filterOrder) {
                const unused = views.splice(0);

                _.each(config.uiCustomization.filterOrder, function(id){
                    if (id === '-') {
                        const $el = $(filterSeparator);
                        views.push({
                            shown: true,
                            initialize: _.noop,
                            get$els: function() {
                                return [$el];
                            }.bind(this),
                            render: _.noop,
                            postRender: _.noop,
                            remove: function() {
                                $el.remove();
                            }.bind(this)
                        })
                    }
                    else {
                        const viewIdx = _.findIndex(unused, function(view){ return view.id === id });
                        if (viewIdx >= 0) {
                            views.push(unused.splice(viewIdx, 1)[0]);
                        }
                    }
                });

                views.push.apply(views, unused);
            }

            this.views = _.where(views, {shown: true});
            _.invoke(this.views, 'initialize');
        },

        render: function() {
            AbstractSectionView.prototype.render.apply(this);

            this.getViewContainer().empty();
            this.views.forEach(function(view) {
                view.get$els().forEach(function($el) {
                    this.getViewContainer().append($el);
                }.bind(this));
            }.bind(this));

            _.invoke(this.views, 'render');
            _.invoke(this.views, 'postRender');

            return this;
        },

        remove: function() {
            _.invoke(this.views, 'remove');

            AbstractSectionView.prototype.remove.call(this);
        },

        updateEmptyMessage: function() {
            const noFiltersMatched = !(
                this.indexesEmpty &&
                this.hideDates &&
                this.parametricFieldsEmpty()
            );

            this.$emptyMessage.toggleClass('hide', noFiltersMatched);
        },

        updateParametricVisibility: function() {
            this.parametricView.$el.toggleClass('hide',
                this.parametricFieldsEmpty() && !!(this.filterModel && this.filterModel.get('text')));
        },

        updateDatesVisibility: function() {
            if (!this.dateViewWrapper) {
                return;
            }

            const search = this.filterModel && this.filterModel.get('text');
            this.hideDates = !(!search || searchMatches(datesTitle, search));

            this.dateViewWrapper.$el.toggleClass('hide', this.hideDates);
            this.dateViewWrapper.toggle(search || !this.collapsed.dates);
        },

        updateGeographyVisibility: function() {
            if (!this.geographyViewWrapper) {
                return;
            }

            const search = this.filterModel && this.filterModel.get('text');
            this.hideGeography = !(!search || searchMatches(geographyTitle, search));

            this.geographyViewWrapper.$el.toggleClass('hide', this.hideGeography);
            this.geographyViewWrapper.toggle(search || !this.collapsed.geography);
        },

        updateIndexesVisibility: function() {
            if (configuration().enableIndexesFilter) {
                this.indexesViewWrapper.$el.toggleClass('hide', this.indexesEmpty);
                this.indexesViewWrapper.toggle((this.filterModel && this.filterModel.get('text')) || !this.collapsed.indexes);
            } else {
                this.indexesViewWrapper.$el.toggleClass('hide', true);
            }
        },

        parametricFieldsEmpty: function() {
            return !this.filteredParametricFieldsCollection || this.filteredParametricFieldsCollection.isEmpty();
        }
    });
});


text:
"""This module represents the Azerbaijani language.

.. seealso:: http://en.wikipedia.org/wiki/Azerbaijani_language
"""

from translate.lang import common

class az(common.Common):
    """This class represents Azerbaijani."""

    mozilla_nplurals = 1
    mozilla_pluralequation = "0"


text:
/*
	MIT License http://www.opensource.org/licenses/mit-license.php
	Author Tobias Koppers @sokra
*/
"use strict";

const RequireResolveDependency = require("./RequireResolveDependency");
const RequireResolveContextDependency = require("./RequireResolveContextDependency");
const RequireResolveHeaderDependency = require("./RequireResolveHeaderDependency");
const ContextDependencyHelpers = require("./ContextDependencyHelpers");

class RequireResolveDependencyParserPlugin {
	constructor(options) {
		this.options = options;
	}

	apply(parser) {
		const options = this.options;

		const process = (expr, weak) => {
			if (expr.arguments.length !== 1) return;
			const param = parser.evaluateExpression(expr.arguments[0]);
			if (param.isConditional()) {
				for (const option of param.options) {
					const result = processItem(expr, option, weak);
					if (result === undefined) {
						processContext(expr, option, weak);
					}
				}
				const dep = new RequireResolveHeaderDependency(expr.callee.range);
				dep.loc = expr.loc;
				parser.state.current.addDependency(dep);
				return true;
			} else {
				const result = processItem(expr, param, weak);
				if (result === undefined) {
					processContext(expr, param, weak);
				}
				const dep = new RequireResolveHeaderDependency(expr.callee.range);
				dep.loc = expr.loc;
				parser.state.current.addDependency(dep);
				return true;
			}
		};
		const processItem = (expr, param, weak) => {
			if (param.isString()) {
				const dep = new RequireResolveDependency(param.string, param.range);
				dep.loc = expr.loc;
				dep.optional = !!parser.scope.inTry;
				dep.weak = weak;
				parser.state.current.addDependency(dep);
				return true;
			}
		};
		const processContext = (expr, param, weak) => {
			const dep = ContextDependencyHelpers.create(
				RequireResolveContextDependency,
				param.range,
				param,
				expr,
				options,
				{
					mode: weak ? "weak" : "sync"
				},
				parser
			);
			if (!dep) return;
			dep.loc = expr.loc;
			dep.optional = !!parser.scope.inTry;
			parser.state.current.addDependency(dep);
			return true;
		};

		parser.hooks.call
			.for("require.resolve")
			.tap("RequireResolveDependencyParserPlugin", expr => {
				return process(expr, false);
			});
		parser.hooks.call
			.for("require.resolveWeak")
			.tap("RequireResolveDependencyParserPlugin", expr => {
				return process(expr, true);
			});
	}
}
module.exports = RequireResolveDependencyParserPlugin;


text:
package org.apache.beam.fn.harness;

import static org.apache.beam.sdk.util.WindowedValue.timestampedValueInGlobalWindow;
import static org.apache.beam.sdk.util.WindowedValue.valueInGlobalWindow;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.anyOf;
import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.empty;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.in;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import org.apache.beam.fn.harness.PrecombineGroupingTable.SamplingSizeEstimator;
import org.apache.beam.fn.harness.PrecombineGroupingTable.SizeEstimator;
import org.apache.beam.runners.core.GlobalCombineFnRunner;
import org.apache.beam.runners.core.GlobalCombineFnRunners;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.apache.beam.sdk.coders.VarLongCoder;
import org.apache.beam.sdk.fn.data.FnDataReceiver;
import org.apache.beam.sdk.fn.test.TestExecutors;
import org.apache.beam.sdk.fn.test.TestExecutors.TestExecutorService;
import org.apache.beam.sdk.options.PipelineOptions;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.transforms.Combine.CombineFn;
import org.apache.beam.sdk.util.WindowedValue;
import org.apache.beam.sdk.values.KV;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ArrayListMultimap;
import org.hamcrest.Description;
import org.hamcrest.TypeSafeDiagnosingMatcher;
import org.joda.time.Instant;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Unit tests for {@link PrecombineGroupingTable}. */
@RunWith(JUnit4.class)
public class PrecombineGroupingTableTest {

  @Rule
  public TestExecutorService executorService = TestExecutors.from(Executors.newCachedThreadPool());

  private static class TestOutputReceiver<T> implements FnDataReceiver<T> {
    final List<T> outputElems = new ArrayList<>();

    @Override
    public void accept(T elem) {
      outputElems.add(elem);
    }
  }

  private static final CombineFn<Integer, Long, Long> COMBINE_FN =
      new CombineFn<Integer, Long, Long>() {

        @Override
        public Long createAccumulator() {
          return 0L;
        }

        @Override
        public Long addInput(Long accumulator, Integer value) {
          return accumulator + value;
        }

        @Override
        public Long mergeAccumulators(Iterable<Long> accumulators) {
          long sum = 0;
          for (Long part : accumulators) {
            sum += part;
          }
          return sum;
        }

        @Override
        public Long compact(Long accumulator) {
          if (accumulator % 2 == 0) {
            return accumulator / 4;
          }
          return accumulator;
        }

        @Override
        public Long extractOutput(Long accumulator) {
          return accumulator;
        }
      };

  @Test
  public void testCombiningInheritsOneOfTheValuesTimestamps() throws Exception {
    PrecombineGroupingTable<String, Integer, Long> table =
        new PrecombineGroupingTable<>(
            PipelineOptionsFactory.create(),
            Caches.forMaximumBytes(2500L),
            StringUtf8Coder.of(),
            GlobalCombineFnRunners.create(COMBINE_FN),
            new StringPowerSizeEstimator(),
            new IdentitySizeEstimator(),
            false);

    TestOutputReceiver<WindowedValue<KV<String, Long>>> receiver = new TestOutputReceiver<>();

    table.put(timestampedValueInGlobalWindow(KV.of("A", 1), new Instant(1)), receiver);
    table.put(timestampedValueInGlobalWindow(KV.of("B", 9), new Instant(21)), receiver);
    table.put(timestampedValueInGlobalWindow(KV.of("A", 2), new Instant(1)), receiver);
    table.put(timestampedValueInGlobalWindow(KV.of("B", 2), new Instant(20)), receiver);
    table.put(timestampedValueInGlobalWindow(KV.of("A", 4), new Instant(1)), receiver);
    table.flush(receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            timestampedValueInGlobalWindow(KV.of("A", 1L + 2 + 4), new Instant(1)),
            timestampedValueInGlobalWindow(KV.of("B", 9L + 2), new Instant(21))));
  }

  @Test
  public void testCombiningGroupingTableHonorsKeyWeights() throws Exception {
    PrecombineGroupingTable<String, Integer, Long> table =
        new PrecombineGroupingTable<>(
            PipelineOptionsFactory.create(),
            Caches.forMaximumBytes(2500L),
            StringUtf8Coder.of(),
            GlobalCombineFnRunners.create(COMBINE_FN),
            new StringPowerSizeEstimator(),
            new IdentitySizeEstimator(),
            false);

    TestOutputReceiver<WindowedValue<KV<String, Long>>> receiver = new TestOutputReceiver<>();

    // Putting the same 1000 weight key in should not cause any eviction.
    table.put(valueInGlobalWindow(KV.of("AAA", 1)), receiver);
    table.put(valueInGlobalWindow(KV.of("AAA", 2)), receiver);
    table.put(valueInGlobalWindow(KV.of("AAA", 4)), receiver);
    assertThat(receiver.outputElems, empty());

    // Putting in other large keys should cause eviction.
    table.put(valueInGlobalWindow(KV.of("BBB", 9)), receiver);
    table.put(valueInGlobalWindow(KV.of("CCC", 11)), receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("AAA", 1L + 2 + 4)), valueInGlobalWindow(KV.of("BBB", 9L))));

    table.flush(receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("AAA", 1L + 2 + 4)),
            valueInGlobalWindow(KV.of("BBB", 9L)),
            valueInGlobalWindow(KV.of("CCC", 11L))));
  }

  @Test
  public void testCombiningGroupingTableEvictsAllOnLargeEntry() throws Exception {
    PrecombineGroupingTable<String, Integer, Long> table =
        new PrecombineGroupingTable<>(
            PipelineOptionsFactory.create(),
            Caches.forMaximumBytes(2500L),
            StringUtf8Coder.of(),
            GlobalCombineFnRunners.create(COMBINE_FN),
            new StringPowerSizeEstimator(),
            new IdentitySizeEstimator(),
            false);

    TestOutputReceiver<WindowedValue<KV<String, Long>>> receiver = new TestOutputReceiver<>();

    table.put(valueInGlobalWindow(KV.of("A", 1)), receiver);
    table.put(valueInGlobalWindow(KV.of("B", 3)), receiver);
    table.put(valueInGlobalWindow(KV.of("B", 6)), receiver);
    table.put(valueInGlobalWindow(KV.of("C", 7)), receiver);
    assertThat(receiver.outputElems, empty());

    // Add beyond the size which causes compaction which still leads to evicting all since the
    // largest is most recent.
    table.put(valueInGlobalWindow(KV.of("C", 9999)), receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("A", 1L)),
            valueInGlobalWindow(KV.of("B", 9L)),
            valueInGlobalWindow(KV.of("C", (9999L + 7) / 4))));

    table.flush(receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("A", 1L)),
            valueInGlobalWindow(KV.of("B", 3L + 6)),
            valueInGlobalWindow(KV.of("C", (9999L + 7) / 4))));
  }

  @Test
  public void testCombiningGroupingTableCompactionSaves() throws Exception {
    PrecombineGroupingTable<String, Integer, Long> table =
        new PrecombineGroupingTable<>(
            PipelineOptionsFactory.create(),
            Caches.forMaximumBytes(2500L),
            StringUtf8Coder.of(),
            GlobalCombineFnRunners.create(COMBINE_FN),
            new StringPowerSizeEstimator(),
            new IdentitySizeEstimator(),
            false);

    TestOutputReceiver<WindowedValue<KV<String, Long>>> receiver = new TestOutputReceiver<>();

    // Insert three compactable values which shouldn't lead to eviction even though we are over
    // the maximum size.
    table.put(valueInGlobalWindow(KV.of("A", 1004)), receiver);
    table.put(valueInGlobalWindow(KV.of("B", 1004)), receiver);
    table.put(valueInGlobalWindow(KV.of("C", 1004)), receiver);
    assertThat(receiver.outputElems, empty());

    table.flush(receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("A", 1004L / 4)),
            valueInGlobalWindow(KV.of("B", 1004L / 4)),
            valueInGlobalWindow(KV.of("C", 1004L / 4))));
  }

  @Test
  public void testCombiningGroupingTablePartialEviction() throws Exception {
    PrecombineGroupingTable<String, Integer, Long> table =
        new PrecombineGroupingTable<>(
            PipelineOptionsFactory.create(),
            Caches.forMaximumBytes(2500L),
            StringUtf8Coder.of(),
            GlobalCombineFnRunners.create(COMBINE_FN),
            new StringPowerSizeEstimator(),
            new IdentitySizeEstimator(),
            false);

    TestOutputReceiver<WindowedValue<KV<String, Long>>> receiver = new TestOutputReceiver<>();

    // Insert three values which even with compaction isn't enough so we evict A & B to get
    // under the max weight.
    table.put(valueInGlobalWindow(KV.of("A", 1001)), receiver);
    table.put(valueInGlobalWindow(KV.of("B", 1001)), receiver);
    table.put(valueInGlobalWindow(KV.of("C", 1001)), receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("A", 1001L)), valueInGlobalWindow(KV.of("B", 1001L))));

    table.flush(receiver);
    assertThat(
        receiver.outputElems,
        containsInAnyOrder(
            valueInGlobalWindow(KV.of("A", 1001L)),
            valueInGlobalWindow(KV.of("B", 1001L)),
            valueInGlobalWindow(KV.of("C", 1001L))));
  }

  @Test
  public void testCombiningGroupingTableEmitsCorrectValuesUnderHighCacheContention()
      throws Exception {
    Long[] expectedKeys = new Long[1000];
    for (int j = 1; j <= 1000; ++j) {
      expectedKeys[j - 1] = (long) j;
    }

    int numThreads = 1000;
    List<Future<?>> futures = new ArrayList<>(numThreads);
    PipelineOptions options = PipelineOptionsFactory.create();
    GlobalCombineFnRunner<Integer, Long, Long> combineFnRunner =
        GlobalCombineFnRunners.create(COMBINE_FN);
    Cache<Object, Object> cache = Caches.forMaximumBytes(numThreads * 50000);
    for (int i = 0; i < numThreads; ++i) {
      final int currentI = i;
      futures.add(
          executorService.submit(
              () -> {
                ArrayListMultimap<Long, Long> values = ArrayListMultimap.create();
                PrecombineGroupingTable<Long, Integer, Long> table =
                    new PrecombineGroupingTable<>(
                        options,
                        Caches.subCache(cache, currentI),
                        VarLongCoder.of(),
                        combineFnRunner,
                        new IdentitySizeEstimator(),
                        new IdentitySizeEstimator(),
                        false);
                for (int j = 1; j <= 1000; ++j) {
                  table.put(
                      valueInGlobalWindow(KV.of((long) j, j)),
                      (input) ->
                          values.put(input.getValue().getKey(), input.getValue().getValue()));
                }
                for (int j = 1; j <= 1000; ++j) {
                  table.flush(
                      (input) ->
                          values.put(input.getValue().getKey(), input.getValue().getValue()));
                }

                assertThat(values.keySet(), containsInAnyOrder(expectedKeys));
                for (Map.Entry<Long, Long> value : values.entries()) {
                  if (value.getKey() % 2 == 0) {
                    assertThat(value.getValue(), equalTo(value.getKey() / 4));
                  } else {
                    assertThat(value.getValue(), equalTo(value.getKey()));
                  }
                }
                return null;
              }));
    }
    for (Future<?> future : futures) {
      future.get();
    }
  }

  ////////////////////////////////////////////////////////////////////////////
  // Tests for the sampling size estimator.

  @Test
  public void testSampleFlatSizes() throws Exception {
    IdentitySizeEstimator underlying = new IdentitySizeEstimator();
    SizeEstimator<Long> estimator =
        new SamplingSizeEstimator<>(underlying, 0.05, 1.0, 10, new Random(1));
    // First 10 elements are always sampled.
    for (int k = 0; k < 10; k++) {
      assertEquals(100, estimator.estimateSize(100L));
      assertEquals(k + 1, underlying.calls);
    }
    // Next 10 are sometimes sampled.
    for (int k = 10; k < 20; k++) {
      assertEquals(100, estimator.estimateSize(100L));
    }
    assertThat(underlying.calls, between(11, 19));
    int initialCalls = underlying.calls;
    // Next 1000 are sampled at about 5%.
    for (int k = 20; k < 1020; k++) {
      assertEquals(100, estimator.estimateSize(100L));
    }
    assertThat(underlying.calls - initialCalls, between(40, 60));
  }

  @Test
  public void testSampleBoringSizes() throws Exception {
    IdentitySizeEstimator underlying = new IdentitySizeEstimator();
    SizeEstimator<Long> estimator =
        new SamplingSizeEstimator<>(underlying, 0.05, 1.0, 10, new Random(1));
    // First 10 elements are always sampled.
    for (int k = 0; k < 10; k += 2) {
      assertEquals(100, estimator.estimateSize(100L));
      assertEquals(102, estimator.estimateSize(102L));
      assertEquals(k + 2, underlying.calls);
    }
    // Next 10 are sometimes sampled.
    for (int k = 10; k < 20; k += 2) {
      assertThat(estimator.estimateSize(100L), between(100L, 102L));
      assertThat(estimator.estimateSize(102L), between(100L, 102L));
    }
    assertThat(underlying.calls, between(11, 19));
    int initialCalls = underlying.calls;
    // Next 1000 are sampled at about 5%.
    for (int k = 20; k < 1020; k += 2) {
      assertThat(estimator.estimateSize(100L), between(100L, 102L));
      assertThat(estimator.estimateSize(102L), between(100L, 102L));
    }
    assertThat(underlying.calls - initialCalls, between(40, 60));
  }

  @Test
  public void testSampleHighVarianceSizes() throws Exception {
    // The largest element is much larger than the average.
    List<Long> sizes = Arrays.asList(1L, 10L, 100L, 1000L);
    IdentitySizeEstimator underlying = new IdentitySizeEstimator();
    SizeEstimator<Long> estimator =
        new SamplingSizeEstimator<>(underlying, 0.1, 0.2, 10, new Random(1));
    // First 10 elements are always sampled.
    for (int k = 0; k < 10; k++) {
      long size = sizes.get(k % sizes.size());
      assertEquals(size, estimator.estimateSize(size));
      assertEquals(k + 1, underlying.calls);
    }
    // We're still not out of the woods; sample every element.
    for (int k = 10; k < 20; k++) {
      long size = sizes.get(k % sizes.size());
      assertEquals(size, estimator.estimateSize(size));
      assertEquals(k + 1, underlying.calls);
    }
    // Sample some more to let things settle down.
    for (int k = 20; k < 500; k++) {
      estimator.estimateSize(sizes.get(k % sizes.size()));
    }
    // Next 1000 are sampled at about 20% (maxSampleRate).
    int initialCalls = underlying.calls;
    for (int k = 500; k < 1500; k++) {
      long size = sizes.get(k % sizes.size());
      assertThat(estimator.estimateSize(size), anyOf(is(in(sizes)), between(250L, 350L)));
    }
    assertThat(underlying.calls - initialCalls, between(180, 220));
    // Sample some more to let things settle down.
    for (int k = 1500; k < 3000; k++) {
      estimator.estimateSize(sizes.get(k % sizes.size()));
    }
    // Next 1000 are sampled at about 10% (minSampleRate).
    initialCalls = underlying.calls;
    for (int k = 3000; k < 4000; k++) {
      long size = sizes.get(k % sizes.size());
      assertThat(estimator.estimateSize(size), anyOf(is(in(sizes)), between(250L, 350L)));
    }
    assertThat(underlying.calls - initialCalls, between(90, 110));
  }

  @Test
  public void testSampleChangingSizes() throws Exception {
    IdentitySizeEstimator underlying = new IdentitySizeEstimator();
    SizeEstimator<Long> estimator =
        new SamplingSizeEstimator<>(underlying, 0.05, 1.0, 10, new Random(1));
    // First 10 elements are always sampled.
    for (int k = 0; k < 10; k++) {
      assertEquals(100, estimator.estimateSize(100L));
      assertEquals(k + 1, underlying.calls);
    }
    // Next 10 are sometimes sampled.
    for (int k = 10; k < 20; k++) {
      assertEquals(100, estimator.estimateSize(100L));
    }
    assertThat(underlying.calls, between(11, 19));
    int initialCalls = underlying.calls;
    // Next 1000 are sampled at about 5%.
    for (int k = 20; k < 1020; k++) {
      assertEquals(100, estimator.estimateSize(100L));
    }
    assertThat(underlying.calls - initialCalls, between(40, 60));
    // Inject a big element until it is sampled.
    while (estimator.estimateSize(1000000L) == 100) {}
    // Check that we have started sampling more regularly again.
    assertEquals(99, estimator.estimateSize(99L));
  }

  private static <T extends Comparable<T>> TypeSafeDiagnosingMatcher<T> between(
      final T min, final T max) {
    return new TypeSafeDiagnosingMatcher<T>() {
      @Override
      public void describeTo(Description description) {
        description.appendText("is between " + min + " and " + max);
      }

      @Override
      protected boolean matchesSafely(T item, Description mismatchDescription) {
        return min.compareTo(item) <= 0 && item.compareTo(max) <= 0;
      }
    };
  }

  /** "Estimate" the size of longs by looking at their value. */
  private static class IdentitySizeEstimator implements SizeEstimator<Long> {
    int calls = 0;

    @Override
    public long estimateSize(Long element) {
      calls++;
      return element;
    }
  }

  /** "Estimate" the size of strings by taking the tenth power of their length. */
  private static class StringPowerSizeEstimator implements SizeEstimator<String> {
    @Override
    public long estimateSize(String element) {
      return (long) Math.pow(10, element.length());
    }
  }
}


text:
<?php
/**
 * Module Name: Ads
 * Module Description: Earn income by allowing Jetpack to display high quality ads.
 * Sort Order: 1
 * First Introduced: 4.5.0
 * Requires Connection: Yes
 * Auto Activate: No
 * Module Tags: Traffic, Appearance
 * Additional Search Queries: advertising, ad codes, ads
 * Plans: premium, business, security, complete
 *
 * @package Jetpack
 */

/**
 * Load WordAds.
 */
function jetpack_load_wordads() {
	Jetpack::enable_module_configurable( __FILE__ );
	require_once dirname( __FILE__ ) . '/wordads/class-wordads.php';
}

jetpack_load_wordads();


text:
void  TURB_Init( float *table, int sr );

float TURB_Turbulence2d( float *table, float x, float y, long octaves );
float TURB_Turbulence4d( float *table, float x, float y, float z, float w, long octaves );

#endif


text:
// Copyright 2007-2016 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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.
namespace MassTransit.AutomatonymousIntegration.Tests
{
    using System;
    using System.Threading.Tasks;
    using Automatonymous;
    using NUnit.Framework;
    using Saga;
    using TestFramework;

    [TestFixture]
    public class When_an_exception_is_filtered :
        InMemoryTestFixture
    {
        [Test]
        public async Task Should_be_able_to_observe_its_own_event_fault()
        {
            Task<ConsumeContext<Fault<Start>>> faulted = SubscribeHandler<Fault<Start>>();

            var message = new Initialize();
            await InputQueueSendEndpoint.Send(message);

            Guid? saga = await _repository.ShouldContainSaga(x => x.CorrelationId == message.CorrelationId
                && GetCurrentState(x) == _machine.WaitingToStart, TestTimeout);
            Assert.IsTrue(saga.HasValue);

            await InputQueueSendEndpoint.Send(new Start(message.CorrelationId));

            await faulted;

            saga = await _repository.ShouldContainSaga(x => x.CorrelationId == message.CorrelationId
                && GetCurrentState(x) == _machine.WaitingToStart && x.StartAttempts == 1, TestTimeout);
            Assert.IsTrue(saga.HasValue);

        }

        protected override void ConfigureInputQueueEndpoint(IInMemoryReceiveEndpointConfigurator configurator)
        {
            _machine = new TestStateMachine();
            _repository = new InMemorySagaRepository<Instance>();

            configurator.UseRetry(Retry.Except<NotSupportedException>().Immediate(2));

            configurator.StateMachineSaga(_machine, _repository);
        }

        State GetCurrentState(Instance state)
        {
            return _machine.GetState(state).Result;
        }

        TestStateMachine _machine;
        InMemorySagaRepository<Instance> _repository;

        class Instance :
            SagaStateMachineInstance
        {
            public Instance(Guid correlationId)
            {
                CorrelationId = correlationId;
            }

            protected Instance()
            {
            }

            public int StartAttempts { get; set; }
            public State CurrentState { get; set; }
            public Guid CorrelationId { get; set; }
        }

        class TestStateMachine :
            MassTransitStateMachine<Instance>
        {
            public TestStateMachine()
            {
                InstanceState(x => x.CurrentState);

                Initially(
                    When(Started)
                        .Then(context =>
                        {
                            context.Instance.StartAttempts++;
                            throw new NotSupportedException("This is expected, but nonetheless exceptional");
                        })
                        .TransitionTo(Running),
                    When(Initialized)
                        .TransitionTo(WaitingToStart));

                During(WaitingToStart,
                    When(Started)
                        .Then(instance =>
                        {
                            instance.Instance.StartAttempts++;
                            throw new NotSupportedException("This is expected, but nonetheless exceptional");
                        })
                        .TransitionTo(Running));

                During(Running,
                    When(Stopped)
                        .TransitionTo(Complete));
            }

            public State WaitingToStart { get; private set; }
            public State Running { get; private set; }
            public State Complete { get; private set; }

            public Event<Start> Started { get; private set; }
            public Event<Initialize> Initialized { get; private set; }
            public Event<Stop> Stopped { get; private set; }
        }

        public class Start :
            CorrelatedBy<Guid>
        {
            public Start()
            {
                CorrelationId = NewId.NextGuid();
            }

            public Start(Guid correlationId)
            {
                CorrelationId = correlationId;
            }

            public Guid CorrelationId { get; set; }
        }

        public class Stop :
            CorrelatedBy<Guid>
        {
            public Stop()
            {
                CorrelationId = NewId.NextGuid();
            }

            public Stop(Guid correlationId)
            {
                CorrelationId = correlationId;
            }

            public Guid CorrelationId { get; set; }
        }

        public class Initialize :
            CorrelatedBy<Guid>
        {
            public Initialize()
            {
                CorrelationId = NewId.NextGuid();
            }

            public Guid CorrelationId { get; set; }
        }
    }
}


text:
class LogDockWidget : public QDockWidget
{
    Q_OBJECT
private:
    QTextEdit *textEdit;
public:
    explicit LogDockWidget(QWidget *parent = 0);

    void addLine(const QString &line);

signals:

public slots:
};

#endif // LOGVIEW_H


text:
package equipo.once.elizabeth.richard.wilson.controllers.view.tecnico;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class IndexTecnicoController extends TecnicoController{

  @RequestMapping(value = {"/","","/index", "home"}, method = RequestMethod.GET)
  public ModelAndView tecnicoIndexGet(){
    ModelAndView modelAndView = new ModelAndView(TECNICO_INDEX_VIEW);

    return modelAndView;
  }
}


text:
<?php

namespace Bolt\Extension\BoltAuth\Auth\Form\Type;

use Bolt\Extension\BoltAuth\Auth\Form\AuthForms;
use Symfony\Component\OptionsResolver\OptionsResolver;

class ProfileViewType extends AbstractProfileType
{
    /** @var boolean */
    protected $requirePassword = false;

    /**
     * {@inheritdoc}
     */
    public function getName()
    {
        return AuthForms::PROFILE_VIEW;
    }

    /**
     * {@inheritdoc}
     */
    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefault('read_only', true);
    }
}