text:
/* -*-  Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011, 2012 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Authors: Nicola Baldo <nbaldo@cttc.es>
 *          Marco Miozzo <mmiozzo@cttc.es>
 *          Manuel Requena <manuel.requena@cttc.es>
 */

#ifndef LTE_ENB_RRC_H
#define LTE_ENB_RRC_H

#include <ns3/nstime.h>
#include <ns3/object.h>
#include <ns3/packet.h>
#include <ns3/lte-enb-cmac-sap.h>
#include <ns3/lte-mac-sap.h>
#include <ns3/ff-mac-sched-sap.h>
#include <ns3/lte-pdcp-sap.h>
#include <ns3/epc-x2-sap.h>
#include <ns3/epc-enb-s1-sap.h>
#include <ns3/lte-enb-cphy-sap.h>
#include <ns3/lte-rrc-sap.h>
#include <ns3/traced-callback.h>
#include <ns3/event-id.h>

#include <map>
#include <set>

namespace ns3 {

class LteRadioBearerInfo;
class LteSignalingRadioBearerInfo;
class LteDataRadioBearerInfo;
class EpcEnbS1SapUser;
class EpcEnbS1SapProvider;
class LteUeRrc;
class LteEnbRrc;

/**
 * Manages all the radio bearer information possessed by the ENB RRC for a single UE
 *
 */
class UeManager : public Object
{
  friend class LtePdcpSpecificLtePdcpSapUser<UeManager>;

public:

  /**
   * The state of the UeManager at the eNB RRC
   *
   */
  enum State
    {
      INITIAL_RANDOM_ACCESS = 0,
      CONNECTION_SETUP,
      CONNECTION_REJECTED,
      CONNECTED_NORMALLY,
      CONNECTION_RECONFIGURATION,
      CONNECTION_REESTABLISHMENT,
      HANDOVER_PREPARATION,
      HANDOVER_JOINING,
      HANDOVER_PATH_SWITCH,
      HANDOVER_LEAVING,
      NUM_STATES
    };

  UeManager ();

  /**
   * UeManager constructor
   *
   * \param rrc pointer to the LteEnbRrc holding this UeManager
   * \param rnti RNTI of the UE
   * \param s initial state of the UeManager
   *
   * \return
   */
  UeManager (Ptr<LteEnbRrc> rrc, uint16_t rnti, State s);

  virtual ~UeManager (void);

  // inherited from Object
protected:
  virtual void DoInitialize ();
  virtual void DoDispose ();
public:
  static TypeId GetTypeId (void);

  /**
   * Set the identifiers of the source eNB for the case where a UE
   * joins the current eNB as part of a handover procedure
   *
   * \param sourceCellId
   * \param sourceX2apId
   */
  void SetSource (uint16_t sourceCellId, uint16_t sourceX2apId);

  /**
   * Set the IMSI
   *
   * \param imsi the IMSI
   */
  void SetImsi (uint64_t imsi);

  /**
   * Setup a new data radio bearer, including both the configuration
   * within the eNB and the necessary RRC signaling with the UE
   *
   * \param bearer the QoS characteristics of the bearer
   * \param bearerId the EPS bearer identifier
   * \param gtpTeid S1-bearer GTP tunnel endpoint identifier, see 36.423 9.2.1
   * \param transportLayerAddress  IP Address of the SGW, see 36.423 9.2.1
   *
   */
  void SetupDataRadioBearer (EpsBearer bearer, uint8_t bearerId, uint32_t gtpTeid, Ipv4Address transportLayerAddress);

  /**
   * Start all configured data radio bearers. It is safe to call this
   * method if any bearer had been already started previously.
   *
   */
  void RecordDataRadioBearersToBeStarted ();

  /**
   * Start the data radio bearers that have been previously recorded
   * to be started using RecordDataRadioBearersToBeStarted()
   *
   */
  void StartDataRadioBearers ();

  /**
   *
   * Release a given radio bearer
   *
   * \param drbid the data radio bearer id of the bearer to be released
   */
  void ReleaseDataRadioBearer (uint8_t drbid);

  /**
   * schedule an RRC Connection Reconfiguration procedure with the UE
   *
   */
  void ScheduleRrcConnectionReconfiguration ();

  /**
   * Start the handover preparation and send the handover request
   *
   * \param cellId id of the target cell
   */
  void PrepareHandover (uint16_t cellId);

  /**
   * take the necessary actions in response to the reception of an X2 HANDOVER REQUEST ACK message
   *
   * \param params
   */
  void RecvHandoverRequestAck (EpcX2SapUser::HandoverRequestAckParams params);

  /**
   *
   * \return the HandoverPreparationInfo sent by the source eNB to the
   * target eNB in the X2-based handover procedure
   */
  LteRrcSap::RadioResourceConfigDedicated GetRadioResourceConfigForHandoverPreparationInfo ();

  /**
   *
   * \return retrieve the data that the target eNB needs to send to the source
   * eNB as the Handover Command in the X2-based handover
   * procedure.
   *
   * \note mobility control info is not expected to be filled in
   * (shall be filled in by the caller).
   */
  LteRrcSap::RrcConnectionReconfiguration GetRrcConnectionReconfigurationForHandover ();

  /**
   * Send a data packet over the appropriate Data Radio Bearer
   *
   * \param bid the corresponding EPS Bearer ID
   * \param p the packet
   */
  void SendData (uint8_t bid, Ptr<Packet> p);

  /**
   *
   * \return a list of ERAB-to-be-setup items to be put in a X2 HO REQ message
   */
  std::vector<EpcX2Sap::ErabToBeSetupItem> GetErabList ();

  /**
   * send the UE CONTEXT RELEASE X2 message to the source eNB, thus
   * successfully terminating an X2 handover procedure
   *
   */
  void SendUeContextRelease ();

  /**
   * Take the necessary actions in response to the reception of an X2 HO preparation failure message
   *
   * \param cellId id of the target cell
   */
  void RecvHandoverPreparationFailure (uint16_t cellId);

  /**
   * Take the necessary actions in response to the reception of an X2 SN STATUS TRANSFER message
   *
   * \param params the SN STATUS
   */
  void RecvSnStatusTransfer (EpcX2SapUser::SnStatusTransferParams params);

  // methods forwarded from RRC SAP
  void CompleteSetupUe (LteEnbRrcSapProvider::CompleteSetupUeParameters params);
  void RecvRrcConnectionRequest (LteRrcSap::RrcConnectionRequest msg);
  void RecvRrcConnectionSetupCompleted (LteRrcSap::RrcConnectionSetupCompleted msg);
  void RecvRrcConnectionReconfigurationCompleted (LteRrcSap::RrcConnectionReconfigurationCompleted msg);
  void RecvRrcConnectionReestablishmentRequest (LteRrcSap::RrcConnectionReestablishmentRequest msg);
  void RecvRrcConnectionReestablishmentComplete (LteRrcSap::RrcConnectionReestablishmentComplete msg);
  void RecvMeasurementReport (LteRrcSap::MeasurementReport msg);

  // methods forwarded from CMAC SAP
  void CmacUeConfigUpdateInd (LteEnbCmacSapUser::UeConfig cmacParams);

  // methods forwarded from PDCP SAP
  void DoReceivePdcpSdu (LtePdcpSapUser::ReceivePdcpSduParameters params);

  /**
   *
   * \return the RNTI, i.e., an UE identifier that is unique within
   * the cell
   */
  uint16_t GetRnti (void);

  /**
   *
   * \return the IMSI, i.e., a globally unique UE identifier
   */
  uint64_t GetImsi (void);

  /**
   *
   * \return the SRS Configuration Index
   */
  uint16_t GetSrsConfigurationIndex (void);

  /**
   * Set the SRS configuration index and do the necessary reconfiguration
   *
   * \param srsConfIndex
   */
  void SetSrsConfigurationIndex (uint16_t srsConfIndex);

  /**
   *
   * \return the current state
   */
  State GetState ();

private:

  /**
   * Add a new LteDataRadioBearerInfo structure to the UeManager
   *
   * \param radioBearerInfo
   *
   * \return the id of the newly added data radio bearer structure
   */
  uint8_t AddDataRadioBearerInfo (Ptr<LteDataRadioBearerInfo> radioBearerInfo);

  /**
   * \param drbid the Data Radio Bearer id
   *
   * \return the corresponding LteDataRadioBearerInfo
   */
  Ptr<LteDataRadioBearerInfo> GetDataRadioBearerInfo (uint8_t drbid);

  /**
   * remove the LteDataRadioBearerInfo corresponding to a bearer being released
   *
   * \param drbid the Data Radio Bearer id
   */
  void RemoveDataRadioBearerInfo (uint8_t drbid);

  /**
   *
   * \return an RrcConnectionReconfiguration struct built based on the
   * current configuration
   */
  LteRrcSap::RrcConnectionReconfiguration BuildRrcConnectionReconfiguration ();

  /**
   *
   * \return a RadioResourceConfigDedicated struct built based on the
   * current configuration
   */
  LteRrcSap::RadioResourceConfigDedicated BuildRadioResourceConfigDedicated ();

  /**
   *
   * \return a newly allocated identifier for a new RRC transaction
   */
  uint8_t GetNewRrcTransactionIdentifier ();

  /**
   * \param lcid a Logical Channel Identifier
   *
   * \return the corresponding Data Radio Bearer Id
   */
  uint8_t Lcid2Drbid (uint8_t lcid);

  /**
   * \param drbid a Data Radio Bearer Id
   *
   * \return the corresponding  Logical Channel Identifier
   */
  uint8_t Drbid2Lcid (uint8_t drbid);

  /**
   * \param lcid a  Logical Channel Identifier
   *
   * \return the corresponding EPS Bearer Identifier
   */
  uint8_t Lcid2Bid (uint8_t lcid);

  /**
   * \param bid  an EPS Bearer Identifier
   *
   * \return the corresponding Logical Channel Identifier
   */
  uint8_t Bid2Lcid (uint8_t bid);

  /**
   * \param drbid Data Radio Bearer Id
   *
   * \return the corresponding EPS Bearer Identifier
   */
  uint8_t Drbid2Bid (uint8_t drbid);

  /**
   * \param bid an EPS Bearer Identifier
   *
   * \return the corresponding Data Radio Bearer Id
   */
  uint8_t Bid2Drbid (uint8_t bid);

  /**
   * Switch the UeManager to the given state
   *
   * \param s the given state
   */
  void SwitchToState (State s);

  std::map <uint8_t, Ptr<LteDataRadioBearerInfo> > m_drbMap;
  Ptr<LteSignalingRadioBearerInfo> m_srb0;
  Ptr<LteSignalingRadioBearerInfo> m_srb1;
  uint8_t m_lastAllocatedDrbid;
  uint16_t m_rnti;
  uint64_t m_imsi;
  uint8_t m_lastRrcTransactionIdentifier;
  LteRrcSap::PhysicalConfigDedicated m_physicalConfigDedicated;
  Ptr<LteEnbRrc> m_rrc;
  State m_state;
  LtePdcpSapUser* m_drbPdcpSapUser;
  bool m_pendingRrcConnectionReconfiguration;
  //             imsi      cellid    rnti      old    new
  TracedCallback<uint64_t, uint16_t, uint16_t, State, State> m_stateTransitionTrace;
  uint16_t m_sourceX2apId;
  uint16_t m_sourceCellId;
  uint16_t m_targetCellId;
  std::list<uint8_t> m_drbsToBeStarted;
  bool m_needTransmissionModeConfiguration;
  EventId m_connectionTimeout;
};

/**
 * \ingroup lte
 *
 * The LTE Radio Resource Control entity at the eNB
 */
class LteEnbRrc : public Object
{

  friend class EnbRrcMemberLteEnbCmacSapUser;
  friend class MemberLteEnbRrcSapProvider<LteEnbRrc>;
  friend class MemberEpcEnbS1SapUser<LteEnbRrc>;
  friend class EpcX2SpecificEpcX2SapUser<LteEnbRrc>;
  friend class UeManager;

public:
  /**
   * create an RRC instance for use within an eNB
   *
   */
  LteEnbRrc ();

  /**
   * Destructor
   */
  virtual ~LteEnbRrc ();

  // inherited from Object
protected:
  virtual void DoDispose (void);
public:
  static TypeId GetTypeId (void);

  /**
   * Set the X2 SAP this RRC should interact with
   * \param s the X2 SAP Provider to be used by this RRC entity
   */
  void SetEpcX2SapProvider (EpcX2SapProvider* s);

  /**
   * Get the X2 SAP offered by this RRC
   * \return s the X2 SAP User interface offered to the X2 entity by this RRC entity
   */
  EpcX2SapUser* GetEpcX2SapUser ();

  /**
   * set the CMAC SAP this RRC should interact with
   *
   * \param s the CMAC SAP Provider to be used by this RRC
   */
  void SetLteEnbCmacSapProvider (LteEnbCmacSapProvider * s);

  /**
   * Get the CMAC SAP offered by this RRC
   * \return s the CMAC SAP User interface offered to the MAC by this RRC
   */
  LteEnbCmacSapUser* GetLteEnbCmacSapUser ();

  /**
   * set the RRC SAP this RRC should interact with
   *
   * \param s the RRC SAP User to be used by this RRC
   */
  void SetLteEnbRrcSapUser (LteEnbRrcSapUser * s);

  /**
   *
   *
   * \return s the RRC SAP Provider interface offered to the MAC by this RRC
   */
  LteEnbRrcSapProvider* GetLteEnbRrcSapProvider ();

  /**
   * set the MAC SAP provider. The eNB RRC does not use this
   * directly, but it needs to provide it to newly created RLC instances.
   *
   * \param s the MAC SAP provider that will be used by all
   * newly created RLC instances
   */
  void SetLteMacSapProvider (LteMacSapProvider* s);

  /**
   * Set the S1 SAP Provider
   *
   * \param s the S1 SAP Provider
   */
  void SetS1SapProvider (EpcEnbS1SapProvider * s);

  /**
   *
   * \return the S1 SAP user
   */
  EpcEnbS1SapUser* GetS1SapUser ();

  /**
   * set the CPHY SAP this RRC should use to interact with the PHY
   *
   * \param s the CPHY SAP Provider
   */
  void SetLteEnbCphySapProvider (LteEnbCphySapProvider * s);

  /**
   *
   *
   * \return s the CPHY SAP User interface offered to the PHY by this RRC
   */
  LteEnbCphySapUser* GetLteEnbCphySapUser ();

  /**
   *
   *
   * \param rnti the identifier of an UE
   *
   * \return the corresponding UeManager instance
   */
  Ptr<UeManager> GetUeManager (uint16_t rnti);

  /**
   * configure cell-specific parameters
   *
   * \param ulBandwidth the uplink bandwidth in number of RB
   * \param dlBandwidth the downlink bandwidth in number of RB
   * \param ulEarfcn the UL EARFCN
   * \param dlEarfcn the DL EARFCN
   * \param cellId the ID of the cell
   */
  void ConfigureCell (uint8_t ulBandwidth,
                      uint8_t dlBandwidth,
                      uint16_t ulEarfcn,
                      uint16_t dlEarfcn,
                      uint16_t cellId);

  /**
   * set the cell id of this eNB
   *
   * \param m_cellId
   */
  void SetCellId (uint16_t m_cellId);

  /**
   * Enqueue an IP data packet on the proper bearer for downlink
   * transmission. Normally expected to be called by the NetDevice
   * forwarding a packet coming from the EpcEnbApplication
   *
   * \param p the packet
   *
   * \return true if successful, false if an error occurred
   */
  bool SendData (Ptr<Packet> p);

  /**
   * set the callback used to forward data packets up the stack
   *
   * \param void
   * \param cb
   */
  void SetForwardUpCallback (Callback <void, Ptr<Packet> > cb);

  /**
   * Method triggered when a UE is expected to get connected but does
   * not do so in a reasonable time
   *
   * \param rnti the T-C-RNTI whose timeout expired
   */
  void ConnectionTimeout (uint16_t rnti);

  /**
   * Send a HandoverRequest through the X2 SAP interface
   *
   * This method will trigger a handover which is started by the RRC
   * by sending a handover request to the target eNB over the X2
   * interface
   *
   * \param imsi the id of the UE to be handed over
   * \param cellId the id of the target eNB
   */
  void SendHandoverRequest (uint16_t rnti, uint16_t cellId);

  /**
   * Identifies how EPS Bearer parameters are mapped to different RLC types
   *
   */
  enum LteEpsBearerToRlcMapping_t {RLC_SM_ALWAYS = 1,
                                   RLC_UM_ALWAYS = 2,
                                   RLC_AM_ALWAYS = 3,
                                   PER_BASED = 4};

private:

  // methods forwarded from RRC SAP

  void DoCompleteSetupUe (uint16_t rnti, LteEnbRrcSapProvider::CompleteSetupUeParameters params);
  void DoRecvRrcConnectionRequest (uint16_t rnti, LteRrcSap::RrcConnectionRequest msg);
  void DoRecvRrcConnectionSetupCompleted (uint16_t rnti, LteRrcSap::RrcConnectionSetupCompleted msg);
  void DoRecvRrcConnectionReconfigurationCompleted (uint16_t rnti, LteRrcSap::RrcConnectionReconfigurationCompleted msg);
  void DoRecvRrcConnectionReestablishmentRequest (uint16_t rnti, LteRrcSap::RrcConnectionReestablishmentRequest msg);
  void DoRecvRrcConnectionReestablishmentComplete (uint16_t rnti, LteRrcSap::RrcConnectionReestablishmentComplete msg);
  void DoRecvMeasurementReport (uint16_t rnti, LteRrcSap::MeasurementReport msg);

  // S1 SAP methods
  void DoDataRadioBearerSetupRequest (EpcEnbS1SapUser::DataRadioBearerSetupRequestParameters params);
  void DoPathSwitchRequestAcknowledge (EpcEnbS1SapUser::PathSwitchRequestAcknowledgeParameters params);
  // X2 SAP methods
  void DoRecvHandoverRequest (EpcX2SapUser::HandoverRequestParams params);
  void DoRecvHandoverRequestAck (EpcX2SapUser::HandoverRequestAckParams params);
  void DoRecvHandoverPreparationFailure (EpcX2SapUser::HandoverPreparationFailureParams params);
  void DoRecvSnStatusTransfer (EpcX2SapUser::SnStatusTransferParams params);
  void DoRecvUeContextRelease (EpcX2SapUser::UeContextReleaseParams params);
  void DoRecvLoadInformation (EpcX2SapUser::LoadInformationParams params);
  void DoRecvResourceStatusUpdate (EpcX2SapUser::ResourceStatusUpdateParams params);
  void DoRecvUeData (EpcX2SapUser::UeDataParams params);

  // CMAC SAP methods
  uint16_t DoAllocateTemporaryCellRnti ();
  void DoNotifyLcConfigResult (uint16_t rnti, uint8_t lcid, bool success);
  void DoRrcConfigurationUpdateInd (LteEnbCmacSapUser::UeConfig params);

  // Internal methods

  /**
   * Allocate a new RNTI for a new UE. This is done in the following cases:
   *   * T-C-RNTI allocation upon contention-based MAC Random Access procedure
   *   * target cell RNTI allocation upon handover
   *
   * \param state the initial state of the UeManager
   *
   * \return the newly allocated RNTI
   */
  uint16_t AddUe (UeManager::State state);

  /**
   * remove a UE from the cell
   *
   * \param rnti the C-RNTI identiftying the user
   */
  void RemoveUe (uint16_t rnti);

  /**
   *
   * \param bearer the specification of an EPS bearer
   *
   * \return the type of RLC that is to be created for the given EPS bearer
   */
  TypeId GetRlcType (EpsBearer bearer);

public:

  /**
   *
   * \param p the SRS periodicity in num TTIs
   */
  void SetSrsPeriodicity (uint32_t p);

  /**
   *
   * \return the current SRS periodicity
   */
  uint32_t GetSrsPeriodicity () const;

private:

  /**
   * Allocate a new SRS configuration index for a new UE.
   *
   * \note this method can have the side effect of updating the SRS
   * configuration index of all UEs
   *
   * \return the newly allocated SRS configuration index
   */
  uint16_t GetNewSrsConfigurationIndex (void);

  /**
   * remove a previously allocated SRS configuration index
   *
   * \note this method can have the side effect of updating the SRS
   * configuration index of all UEs
   *
   * \param srcCi the indext to be removed
   */
  void RemoveSrsConfigurationIndex (uint16_t srcCi);

  /**
   *
   * \param bearer the characteristics of the bearer
   *
   * \return the Logical Channel Group in a bearer with these
   * characteristics is put. Used for MAC Buffer Status Reporting purposes.
   */
  uint8_t GetLogicalChannelGroup (EpsBearer bearer);

  /**
   *
   * \param bearer the characteristics of the bearer
   *
   * \return the priority level of a bearer with these
   * characteristics is put. Used for the part of UL MAC Scheduling
   * carried out by the UE
   */
  uint8_t GetLogicalChannelPriority (EpsBearer bearer);

  /**
   * method used to periodically send System Information
   *
   */
  void SendSystemInformation ();

  Callback <void, Ptr<Packet> > m_forwardUpCallback;

  EpcX2SapUser* m_x2SapUser;
  EpcX2SapProvider* m_x2SapProvider;

  LteEnbCmacSapUser* m_cmacSapUser;
  LteEnbCmacSapProvider* m_cmacSapProvider;

  LteEnbRrcSapUser* m_rrcSapUser;
  LteEnbRrcSapProvider* m_rrcSapProvider;

  LteMacSapProvider* m_macSapProvider;

  EpcEnbS1SapProvider* m_s1SapProvider;
  EpcEnbS1SapUser* m_s1SapUser;

  LteEnbCphySapUser* m_cphySapUser;
  LteEnbCphySapProvider* m_cphySapProvider;

  bool m_configured;
  uint16_t m_cellId;
  uint16_t m_dlEarfcn;
  uint16_t m_ulEarfcn;
  uint16_t m_dlBandwidth;
  uint16_t m_ulBandwidth;
  uint16_t m_lastAllocatedRnti;

  std::map<uint16_t, Ptr<UeManager> > m_ueMap;

  struct X2uTeidInfo
  {
    uint16_t rnti;
    uint8_t drbid;
  };

  //       TEID      RNTI, DRBID
  std::map<uint32_t, X2uTeidInfo> m_x2uTeidInfoMap;

  uint8_t m_defaultTransmissionMode;

  enum LteEpsBearerToRlcMapping_t m_epsBearerToRlcMapping;

  Time m_systemInformationPeriodicity;

  // SRS related attributes
  uint16_t m_srsCurrentPeriodicityId;
  std::set<uint16_t> m_ueSrsConfigurationIndexSet;
  uint16_t m_lastAllocatedConfigurationIndex;
  bool m_reconfigureUes;

  bool m_admitHandoverRequest;
  bool m_admitRrcConnectionRequest;

  //             cellid    rnti
  TracedCallback<uint16_t, uint16_t> m_newUeContextTrace;
  //             imsi      cellid    rnti
  TracedCallback<uint64_t, uint16_t, uint16_t> m_connectionEstablishedTrace;
  //             imsi      cellid    rnti
  TracedCallback<uint64_t, uint16_t, uint16_t> m_connectionReconfigurationTrace;
  //             imsi      cellid    rnti     targetCellId
  TracedCallback<uint64_t, uint16_t, uint16_t, uint16_t> m_handoverStartTrace;
  //             imsi      cellid    rnti
  TracedCallback<uint64_t, uint16_t, uint16_t> m_handoverEndOkTrace;

};

} // namespace ns3

#endif // LTE_ENB_RRC_H


text:
// Any copyright is dedicated to the Public Domain.
// http://creativecommons.org/publicdomain/zero/1.0/

/* eslint-disable no-shadow */

import path from 'path';
import childProcess from 'child_process';

import * as Const from '../utils/const';
import { dependencies } from '../../app/package.json';

export const nodeExternals = (context, request, cb) => {
  if (request.startsWith('.')) {
    cb(null, false);
    return;
  }

  for (const dependency of Object.keys(dependencies)) {
    if ((request === dependency) || request.startsWith(`${dependency}/`)) {
      cb(null, true);
      return;
    }
  }

  cb(null, false);
};

export const webpackBuild = (configPath, options) => new Promise((resolve, reject) => {
  const child = childProcess.fork(path.join(Const.BUILD_UTILS_PATH, 'webpack-process'));

  const once = expected => new Promise(resolve => {
    child.on('message', e => {
      if (e.message === expected) {
        resolve(e);
      }
    });
  });

  once('fatal-error', e => reject(e.err));
  once('build-error', e => reject(e.err));

  const build = () => {
    const finishedBuild = once('finished-build');
    child.send({ message: 'build', configPath, options });
    return finishedBuild;
  };

  const close = () => {
    const cleanedUp = once('cleaned-up');
    child.send({ message: 'will-close' });
    return cleanedUp.then(() => child.kill());
  };

  build().then(() => resolve({ close }));
});

redpajama_set_name: RedPajamaGithub


text:
/*
 * Licensed under MIT (https://github.com/ligoj/ligoj/blob/master/LICENSE)
 */
package org.ligoj.bootstrap.core.resource.mapper;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.ligoj.bootstrap.core.resource.AbstractMapper;
import org.ligoj.bootstrap.core.resource.ServerError;
import org.springframework.dao.DataIntegrityViolationException;

import lombok.extern.slf4j.Slf4j;

/**
 * Handles database integrity issue to a JSON string.
 */
@Provider
@Slf4j
public class DataIntegrityViolationExceptionMapper extends AbstractMapper implements ExceptionMapper<DataIntegrityViolationException> {

	/**
	 * Matcher for errors like : `assignment`, CONSTRAINT `FK3D2B86CDAF555D0B` FOREIGN KEY (`project`)
	 */
	private static final Pattern PATTERN_FOREIGN_KEY = Pattern.compile("`(\\w+)`, CONSTRAINT `.*` FOREIGN KEY \\(`(\\w+)`\\)");

	/**
	 * Matcher for errors like : Duplicate entry 'AA-EE' for key 'UniqueName'
	 */
	private static final Pattern PATTERN_UNICITY = Pattern.compile("Duplicate entry '([^']+)' for key '([^']+)'");

	@Override
	public Response toResponse(final DataIntegrityViolationException exception) {
		log.error("DataIntegrityViolationException exception", exception);
		final var root = ExceptionUtils.getRootCause(exception);
        var matcher = PATTERN_FOREIGN_KEY.matcher(StringUtils.trimToEmpty(root.getMessage()));
		final String code;
		if (matcher.find()) {
			// Foreign key
			code = "foreign";
		} else {
			matcher = PATTERN_UNICITY.matcher(root.getMessage());
			if (matcher.find()) {
				// Duplicate entry
				code = "unicity";
			} else {
				// Another SQL error
				code = "unknown";
				matcher = null;
			}
		}

		return toResponse(Status.PRECONDITION_FAILED, newServerError(exception, matcher, code));
	}

	/**
	 * Build the server error instance.
	 */
	private ServerError newServerError(final Throwable exception, final Matcher matcher, final String code) {
		final var serverError = new ServerError();
		serverError.setCode("integrity-" + code);
		serverError.setThrowable(exception.getCause());
		if (matcher != null) {
			serverError.setMessage(matcher.group(1) + "/" + matcher.group(2));
		}
		return serverError;
	}

}


text:
require 'spec_helper'

RSpec.describe "routes for root", :type => :routing do
  describe 'routes for login' do
    it 'routes /login to the user sessions controller' do
      expect(get: '/').to route_to('user_sessions#new')
    end
  end
end


text:
=head1 LICENSE

Copyright [2009-2014] EMBL-European Bioinformatics Institute

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.

=cut

package Bio::EnsEMBL::EGPipeline::Common::RunnableDB::Base;

use strict;
use Carp;

use base ('Bio::EnsEMBL::Hive::Process');

sub hive_dbc {
  my $self = shift;

  my $dbc = $self->dbc();
  confess('Type error!') unless($dbc->isa('Bio::EnsEMBL::DBSQL::DBConnection'));

  return $dbc;
}

sub hive_dbh {
  my $self = shift;

  my $dbh = $self->hive_dbc->db_handle();
  confess('Type error!') unless($dbh->isa('DBI::db'));

  return $dbh;
}

sub get_DBAdaptor {
  my ($self, $type) = @_;

  $type ||= 'core';
  my $species = ($type eq 'production') ? 'multi' : $self->param_required('species');

  return Bio::EnsEMBL::Registry->get_DBAdaptor($species, $type);
}

sub core_dba {
  my $self = shift;

  my $dba = $self->get_DBAdaptor('core');
  confess('Type error!') unless($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));

  return $dba;
}

sub core_dbc {
  my $self = shift;

  my $dbc = $self->core_dba()->dbc();
  confess('Type error!') unless($dbc->isa('Bio::EnsEMBL::DBSQL::DBConnection'));

  return $dbc;
}

sub core_dbh {
  my $self = shift;

  my $dbh = $self->core_dbc->db_handle();
  confess('Type error!') unless($dbh->isa('DBI::db'));

  return $dbh;
}

sub otherfeatures_dba {
  my $self = shift;

  my $dba = $self->get_DBAdaptor('otherfeatures');
  confess('Type error!') unless($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));

  return $dba;
}

sub otherfeatures_dbc {
  my $self = shift;

  my $dbc = $self->otherfeatures_dba()->dbc();
  confess('Type error!') unless($dbc->isa('Bio::EnsEMBL::DBSQL::DBConnection'));

  return $dbc;
}

sub otherfeatures_dbh {
  my $self = shift;

  my $dbh = $self->otherfeatures_dba()->dbc()->db_handle();
  confess('Type error!') unless($dbh->isa('DBI::db'));

  return $dbh;
}

sub production_dba {
  my $self = shift;

  my $dba = $self->get_DBAdaptor('production');
  if (!defined $dba) {
    my %production_db = %{$self->param('production_db')};
    $dba = Bio::EnsEMBL::DBSQL::DBAdaptor->new(%production_db);
  }
  confess('Type error!') unless($dba->isa('Bio::EnsEMBL::DBSQL::DBAdaptor'));

  return $dba;
}

sub production_dbc {
  my $self = shift;

  my $dbc = $self->production_dba()->dbc();
  confess('Type error!') unless($dbc->isa('Bio::EnsEMBL::DBSQL::DBConnection'));

  return $dbc;
}

sub production_dbh {
  my $self = shift;

  my $dbh = $self->production_dba()->dbc()->db_handle();
  confess('Type error!') unless($dbh->isa('DBI::db'));

  return $dbh;
}

=head2 hive_database_string_for_user

  Return the name and location of the database in a human readable way.

=cut
sub hive_database_string_for_user {
  my $self = shift;
  return $self->hive_dbc->dbname . " on " . $self->hive_dbc->host

}

=head2 core_database_string_for_user

	Return the name and location of the database in a human readable way.

=cut
sub core_database_string_for_user {
  my $self = shift;
  return $self->core_dbc->dbname . " on " . $self->core_dbc->host

}

=head2 otherfeatures_database_name

	Return the name of the otherfeatures db

=cut
sub otherfeatures_database_name {
  my $self = shift;
  return $self->otherfeatures_dbc->dbname;

}

=head2 mysql_command_line_connect
=cut
sub mysql_command_line_connect {
  my $self = shift;

  my $cmd =
      "mysql"
      . " --host ". $self->core_dbc->host
      . " --port ". $self->core_dbc->port
      . " --user ". $self->core_dbc->username
      . " --pass=". $self->core_dbc->password
  ;

  return $cmd;
}

=head2 mysql_command_line_connect_core_db
=cut
sub mysql_command_line_connect_core_db {

  my $self = shift;

  my $cmd =
      $self->mysql_command_line_connect
      . " ". $self->core_dbc->dbname
  ;

  return $cmd;
}

=head2 mysql_command_line_connect_otherfeatures_db
=cut
sub mysql_command_line_connect_otherfeatures_db {

  my $self = shift;

  my $cmd =
      "mysql"
      . " --host ". $self->otherfeatures_dbc->host
      . " --port ". $self->otherfeatures_dbc->port
      . " --user ". $self->otherfeatures_dbc->username
      . " --pass=". $self->otherfeatures_dbc->password
      . " ". $self->otherfeatures_dbc->dbname
  ;

  return $cmd;
}

=head2 mysql_command_line_connect_core_db
=cut
sub mysqldump_command_line_connect_core_db {

  my $self = shift;

  my $cmd =
      "mysqldump"
      . " --lock_table=FALSE --no-create-info"
      . " --host ". $self->core_dbc->host
      . " --port ". $self->core_dbc->port
      . " --user ". $self->core_dbc->username
      . " --pass=". $self->core_dbc->password
      . " ". $self->core_dbc->dbname
  ;

  return $cmd;
}

sub has_chromosomes {
  my ($self, $dba) = @_;
  my $helper = $dba->dbc->sql_helper();
  my $sql = q{
    SELECT COUNT(*) FROM
    coord_system cs INNER JOIN
    seq_region sr USING (coord_system_id) INNER JOIN
    seq_region_attrib sa USING (seq_region_id) INNER JOIN
    attrib_type at USING (attrib_type_id)
    WHERE cs.species_id = ?
    AND at.code = 'karyotype_rank'
  };
  my $count = $helper->execute_single_result(-SQL => $sql, -PARAMS => [$dba->species_id()]);

  $dba->dbc->disconnect_if_idle();

  return $count;
}

sub has_genes {
  my ($self, $dba) = @_;
  my $helper = $dba->dbc->sql_helper();
  my $sql = q{
    SELECT COUNT(*) FROM
    coord_system cs INNER JOIN
    seq_region sr USING (coord_system_id) INNER JOIN
    gene g USING (seq_region_id)
    WHERE cs.species_id = ?
  };
  my $count = $helper->execute_single_result(-SQL => $sql, -PARAMS => [$dba->species_id()]);

  $dba->dbc->disconnect_if_idle();

  return $count;
}

1;


text:
from urllib.parse import urljoin

from django.conf import settings
from django.urls import reverse

from orchestra.communication.mail import send_mail
from orchestra.communication.slack import OrchestraSlackService
from orchestra.models import CommunicationPreference
from orchestra.models import StaffingRequestInquiry
from orchestra.models import Task
from orchestra.models import Project
from orchestra.utils.decorators import run_if
from orchestra.utils.task_properties import assignment_history
from orchestra.utils.task_properties import current_assignment

# TODO(jrbotros): design HTML template
def notify_status_change(
        task, previous_status=None, staffing_request_inquiry=None):
    """
    Notify workers after task has changed state
    """
    task_assignments = assignment_history(task)
    current_task_assignment = current_assignment(task)
    current_worker = None
    if current_task_assignment:
        current_worker = current_task_assignment.worker
    message_info = None

    # Notify worker when task initially picked up
    if task.status == Task.Status.PROCESSING:
        message_info = {
            'subject': "You've been assigned to a new task!",
            'message': ("You've been assigned to a new task. We can't wait "
                        "to see the great things you'll do!"),
            'recipient_list': [current_worker.user.email]
        }
    # Notify worker when assignment selected for review
    elif task.status == Task.Status.PENDING_REVIEW:
        message_info = {
            'subject': 'Your task is under review!',
            'message': ('Thanks for all your hard work, {}! The following '
                        'task was randomly selected for review by another '
                        'expert; you should hear back soon!').format(
                            current_worker.user.username),
            'recipient_list': [current_worker.user.email]
        }
    # Notify worker when assignment rejected
    elif task.status == Task.Status.POST_REVIEW_PROCESSING:
        message_info = {
            'subject': 'Your task has been returned',
            'message': ('Your reviewer sent back your task for a bit more '
                        'polish. Check out the feedback as soon as you can!'),
            'recipient_list': [current_worker.user.email]
        }
    # Notify all workers on a task when it has been completed
    elif task.status == Task.Status.COMPLETE:
        message_info = {
            'subject': 'Task complete!',
            'message': 'Congratulations! The task you worked on is complete.',
            'recipient_list': [assignment.worker.user.email
                               for assignment in task_assignments
                               if assignment.worker and
                               assignment.worker.user.email]
        }
    # Notify reviewer when task pending update is ready for re-review, but not
    # for a task moving from PENDING_REVIEW to REVIEWING
    elif (task.status == Task.Status.REVIEWING and
          previous_status == Task.Status.POST_REVIEW_PROCESSING):
        message_info = {
            'subject': 'A task is ready for re-review!',
            'message': ('A task has been updated and is ready for '
                        're-review!'),
            'recipient_list': [current_worker.user.email]
        }

    # Notify all workers on a task when it has been aborted
    elif task.status == Task.Status.ABORTED:
        message_info = {
            'subject': 'A task you were working on has been ended',
            'message': ('Unfortunately, the task you were working on has '
                        'been ended. Please reach out to us if you think this '
                        'has been done in error.'),
            'recipient_list': [assignment.worker.user.email
                               for assignment in task_assignments
                               if assignment.worker and
                               assignment.worker.user.email]
        }

    _notify_internal_slack_status_change(
        task, current_worker,
        staffing_request_inquiry=staffing_request_inquiry)
    if task.project.slack_group_id:
        _notify_experts_slack_status_change(
            task, current_worker,
            staffing_request_inquiry=staffing_request_inquiry)

    if message_info is not None:
        message_info['message'] += _task_information(task)
        comm_type = (CommunicationPreference.CommunicationType
                     .TASK_STATUS_CHANGE.value)
        send_mail(from_email=settings.ORCHESTRA_NOTIFICATIONS_FROM_EMAIL,
                  communication_type=comm_type,
                  fail_silently=True,
                  **message_info)

def notify_project_status_change(project):
    extra_explanation = ''
    if project.status == Project.Status.PAUSED:
        status_text = 'paused'
        extra_explanation = (
            'All activities will be put on hold until '
            'the project is reactivated.')
    elif project.status == Project.Status.ACTIVE:
        status_text = 'reactivated'
    elif project.status == Project.Status.COMPLETED:
        status_text = 'completed'
    elif project.status == Project.Status.ABORTED:
        status_text = 'aborted'
    else:
        return
    slack_message = (
        '*Project {} | {} has been {}.*\n'
        '{}'
        ).format(
            project.workflow_version.slug,
            project.short_description,
            status_text,
            extra_explanation)
    message_internal_slack_group(
        settings.SLACK_INTERNAL_NOTIFICATION_CHANNEL, slack_message)
    if project.slack_group_id:
        message_experts_slack_group(project.slack_group_id, slack_message)

def _task_information(task, with_slack_link=True):
    # TODO(jrbotros): incorporate Django sites framework
    dashboard_link = urljoin(settings.ORCHESTRA_URL,
                             reverse('orchestra:index'))
    task_information = ('\n\n'
                        'Project: {} | {}\n'
                        'Task: {} {}\n\n'
                        'View dashboard: {}\n').format(
                            task.project.workflow_version.slug,
                            task.project.short_description,
                            task.step.slug,
                            task.id,
                            dashboard_link)

    if task.project.slack_group_id and with_slack_link:
        slack_link = urljoin(settings.SLACK_EXPERTS_BASE_URL,
                             task.project.slack_group_id)
        task_information += 'View Slack channel: {}'.format(slack_link)

    return task_information

def _notify_slack_status_change(task, current_worker, slack_api_key,
                                slack_channel, with_slack_link=True,
                                with_user_mention=False,
                                staffing_request_inquiry=None):
    slack = OrchestraSlackService(slack_api_key)
    auto_staff_method = (
        StaffingRequestInquiry.CommunicationMethod.PREVIOUSLY_OPTED_IN)
    is_auto_staffed = (staffing_request_inquiry
                       and staffing_request_inquiry.communication_method
                       == auto_staff_method.value)
    processing_status_message = (
        'Task has been auto-staffed to a worker.'
        if is_auto_staffed else
        'Task has been picked up by a worker.')
    slack_statuses = {
        Task.Status.PROCESSING: processing_status_message,
        Task.Status.PENDING_REVIEW: 'Task is awaiting review.',
        Task.Status.REVIEWING: 'Task is under review.',
        Task.Status.POST_REVIEW_PROCESSING: 'Task was returned by reviewer.',
        Task.Status.COMPLETE: 'Task has been completed.',
        Task.Status.ABORTED: 'Task has been aborted.',
    }
    worker_string = current_worker.user.username if current_worker else None
    slack_user_id = current_worker.slack_user_id if current_worker else None
    if slack_user_id and with_user_mention:
        worker_string += ' (<@{}>)'.format(slack_user_id)
    slack_message = ('*{}*\n'
                     '>>>'
                     'Current worker: {}'
                     '{}').format(slack_statuses[task.status],
                                  worker_string,
                                  _task_information(
                                      task, with_slack_link=with_slack_link))
    slack.chat.post_message(slack_channel, slack_message)

@run_if('ORCHESTRA_SLACK_INTERNAL_ENABLED')
def _notify_internal_slack_status_change(
        task, current_worker, staffing_request_inquiry=None):
    _notify_slack_status_change(
        task, current_worker,
        settings.SLACK_INTERNAL_API_KEY,
        settings.SLACK_INTERNAL_NOTIFICATION_CHANNEL,
        staffing_request_inquiry=staffing_request_inquiry)

@run_if('ORCHESTRA_SLACK_EXPERTS_ENABLED')
def _notify_experts_slack_status_change(
        task, current_worker, staffing_request_inquiry=None):
    _notify_slack_status_change(
        task, current_worker,
        settings.SLACK_EXPERTS_API_KEY,
        task.project.slack_group_id,
        with_slack_link=False,
        with_user_mention=True,
        staffing_request_inquiry=staffing_request_inquiry)

@run_if('ORCHESTRA_SLACK_EXPERTS_ENABLED')
def message_experts_slack_group(slack_channel, slack_message):
    slack = OrchestraSlackService(settings.SLACK_EXPERTS_API_KEY)
    slack.chat.post_message(slack_channel, slack_message)

@run_if('ORCHESTRA_SLACK_INTERNAL_ENABLED')
def message_internal_slack_group(slack_channel, slack_message):
    slack = OrchestraSlackService(settings.SLACK_INTERNAL_API_KEY)
    slack.chat.post_message(slack_channel, slack_message)


text:
/**
 * spring cloud config server
 * @author lzhoumail@126.com
 */
package com.haojiankang.framework.config.server;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.config.server.EnableConfigServer;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
@EnableDiscoveryClient
@EnableConfigServer
public class ConfigServerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServerApplication.class, args);
    }
}


text:
import React from 'react';
import { mount } from 'enzyme';
import toJson from 'enzyme-to-json';
import SVGSearch from '../SVGSearch';

it('should renders <SVGSearch> correctly', () => {
  const wrapper = mount(<SVGSearch />);

  expect(toJson(wrapper)).toMatchSnapshot();
});


text:
package com.galenframework.tests.runner;

import static java.util.Arrays.asList;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.LinkedList;
import java.util.List;

import com.galenframework.GalenMain;
import com.galenframework.components.DummyCompleteListener;
import com.galenframework.components.JsTestRegistry;
import com.galenframework.config.GalenProperty;
import com.galenframework.runner.CompleteListener;
import com.galenframework.tests.GalenTest;
import com.galenframework.config.GalenConfig;
import com.galenframework.specs.Spec;

import com.galenframework.validation.PageValidation;
import com.galenframework.validation.ValidationResult;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.Test;

import com.google.common.io.Files;

@Test(singleThreaded = true)
public class GalenMainTest {

    @AfterMethod
    public void resetConfigToDefaults() throws IOException {
        GalenConfig.getConfig().reset();
    }

    @Test
    public void shouldRun_javascriptTest_andGenerateReports() throws Exception {
        File reportsDir = Files.createTempDir();
        String htmlReportPath = reportsDir.getAbsolutePath();
        String testngReportPath = reportsDir.getAbsolutePath() + "/testng-report.html";
        String jsonReportPath = reportsDir.getAbsolutePath() + "/json-reports";

        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{"test",
                getClass().getResource("/js-tests/simple-with-error.test.js").getFile(),
                "--htmlreport", htmlReportPath,
                "--testngreport", testngReportPath,
                "--jsonreport", jsonReportPath
        });

        assertThat(JsTestRegistry.get().getEvents().size(), is(3));
        assertThat(JsTestRegistry.get().getEvents().get(0), is("Test #1 was invoked"));
        assertThat(JsTestRegistry.get().getEvents().get(1), is("Test #2 was invoked"));
        assertThat(JsTestRegistry.get().getEvents().get(2), is("Test #3 was invoked"));

        String testngReportContent = FileUtils.readFileToString(new File(testngReportPath));

        assertThat(testngReportContent, containsString("<test name=\"Test number 1\">"));
        assertThat(testngReportContent, containsString("<class name=\"Test number 1\">"));

        assertThat(testngReportContent, containsString("<test name=\"Test number 2\">"));
        assertThat(testngReportContent, containsString("<class name=\"Test number 2\">"));

        assertThat(testngReportContent, containsString("<test name=\"Test number 3\">"));
        assertThat(testngReportContent, containsString("<class name=\"Test number 3\">"));

        String htmlReportContent = FileUtils.readFileToString(new File(htmlReportPath + File.separator + "report.html"));

        assertThat(htmlReportContent, containsString("\"testId\" : \"1-test-number-1\""));
        assertThat(htmlReportContent, containsString("\"testId\" : \"2-test-number-2\""));
        assertThat(htmlReportContent, containsString("\"testId\" : \"3-test-number-3\""));

        File jsonReportDir = new File(jsonReportPath);
        assertThat("json-reports folder should be created", jsonReportDir.exists() && jsonReportDir.isDirectory(), is(true));

        assertThat("json-reports folder contains files", asList(jsonReportDir.list()), containsInAnyOrder(
                "1-test-number-1.json",
                "2-test-number-2.json",
                "3-test-number-3.json",
                "report.json"));
    }

    @Test
    public void shouldRun_javascriptTestWithEvents() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/with-events.test.js").getFile()
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Before test suite",
                "Before test: Test number 1",
                "Test #1 was invoked",
                "After test: Test number 1",
                "Before test: Test number 2",
                "Test #2 was invoked",
                "After test: Test number 2",
                "After test suite"));
    }

    @Test
    public void shouldRun_javascriptTest_regardlessOfItsSuffix() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/test-without-galen-suffix.js").getFile()
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Test #1 was invoked"));
    }

    @Test
    public void shouldFind_javascriptTests_basedOnConfigProperty() throws Exception {
        JsTestRegistry.get().clear();

        GalenConfig.getConfig().setProperty(GalenProperty.TEST_JS_SUFFIX, ".blahblah.js");

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/tests-with-custom-suffix").getFile()
        });

        assertThat(JsTestRegistry.get().getEvents(), containsInAnyOrder(
                "Test #1 was invoked",
                "Test #2 was invoked"
        ));

    }

    @Test
    public void shouldRunJavascriptTests_andFilterThem() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/testfilter.test.js").getFile()
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Test D invoked",
                "Test C invoked",
                "Test A invoked"
                ));
    }

    @Test
    public void shouldRunJavascriptTests_onlyForSpecifiedGroups_withTwoGroups() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                        "test",
                        getClass().getResource("/js-tests/testgroups.test.js").getFile(),
                        "--groups", "mobile,tablet"
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Test A invoked",
                "Test B invoked",
                "Test C invoked"
        ));
    }

    @Test
    public void shouldRunJavascriptTests_onlyForSpecifiedGroups_withOneGroup() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[] {
                        "test",
                        getClass().getResource("/js-tests/testgroups.test.js").getFile(),
                        "--groups", "tablet"
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Test B invoked",
                "Test C invoked"
        ));
    }

    @Test
    public void shouldRunJavascriptTests_withExcludedGroups() throws Exception {
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/testgroups.test.js").getFile(),
                "--excluded-groups", "tablet"
        });

        assertThat(JsTestRegistry.get().getEvents(), contains(
                "Test A invoked",
                "Test D invoked"
        ));
    }

    /**
     * Comes from https://github.com/galenframework/galen/issues/184
     * Test Retry Handler
     * @throws Exception
     */
    @Test
    public void shouldRunJavascriptTests_andRetryThem() throws Exception {
        File htmlReportDir = Files.createTempDir();
        JsTestRegistry.get().clear();

        new GalenMain().execute(new String[]{
                "test",
                getClass().getResource("/js-tests/testretry.test.js").getFile(),
                "--htmlreport", htmlReportDir.getAbsolutePath()
        });

        List<String> events = JsTestRegistry.get().getEvents();

        assertThat(events, contains(
                "Before test suite event",
                "Before test event for: Test A",
                "Test A invoked",
                "After test event for: Test A",
                "Retry handler invoked for test: Test A",
                "Before test event for: Test A",
                "Test A invoked",
                "After test event for: Test A",
                "Retry handler invoked for test: Test A",
                "Before test event for: Test A",
                "Test A invoked",
                "After test event for: Test A",
                "Retry handler invoked for test: Test A",
                "Before test event for: Test B",
                "Test B invoked",
                "After test event for: Test B",
                "Retry handler invoked for test: Test B",
                "Before test event for: Test B",
                "Test B invoked",
                "After test event for: Test B",
                "Retry handler invoked for test: Test B",
                "Before test event for: Test B",
                "Test B invoked",
                "After test event for: Test B",
                "Retry handler invoked for test: Test B",
                "Before test event for: Test C",
                "Test C invoked",
                "After test event for: Test C",
                "After test suite event"
        ));

        String htmlReportContent = FileUtils.readFileToString(new File(htmlReportDir.getAbsolutePath()
                + File.separator + "report.html"));

        int amountOfReportedTests = StringUtils.countMatches(htmlReportContent, "\"testId\"");
        assertThat("Amount of reported tests should be", amountOfReportedTests, is(3));
    }

    @Test
    public void shouldGenerate_configFile() throws Exception {
        new GalenMain().execute(new String[]{"config"});
        assertThat("config file should exist", new File("config").exists(), is(true));
        new File("config").delete();
    }

    @Test
    public void shouldNot_overrideExistingConfigFile() throws IOException {
        File file = new File("config");
        file.createNewFile();
        FileUtils.writeStringToFile(file, "someTestDate = qwertyuiop");

        new GalenMain().execute(new String[]{"config"});

        String data = FileUtils.readFileToString(file);
        assertThat(data, is("someTestDate = qwertyuiop"));

        file.delete();
    }

    @Test
    public void shouldRun_filteredTestInSuite() throws Exception {
        String testUrl = getClass().getResource("/suites/suite-for-filtering.test").getFile();
        GalenMain galen = new GalenMain();

        final List<String> executedSuites = new LinkedList<String>();

        CompleteListener listener = new DummyCompleteListener() {
            @Override
            public void onTestStarted(GalenTest test) {
                executedSuites.add(test.getName());
            }
        };
        galen.setListener(listener);

        galen.execute(new String[]{
                "test", testUrl,
                "--filter", "*with filter*"
        });

        assertThat("Amount of executed tests should be", executedSuites.size(), is(3));
        assertThat(executedSuites, hasItems(
                "Test 1 with filter one",
                "Test 1 with filter two",
                "Test 2 with filter"));
    }

    @Test
    public void shouldCheckLayout_inJsTests_andPassCustomJsVariables() throws Exception {
        String testUrl = getClass().getResource("/suites/custom-js-variables-for-checklayout/simple.test.js").getFile();

        GalenMain galen = new GalenMain();
        final List<String> errorMessages = new LinkedList<>();

        CompleteListener listener = new DummyCompleteListener() {
            @Override
            public void onSpecError(PageValidation pageValidation, String objectName, Spec spec, ValidationResult result) {
                errorMessages.addAll(result.getError().getMessages());
            }
        };
        galen.setListener(listener);
        galen.execute(new String[]{
                "test", testUrl
        });

        assertThat(errorMessages, hasItems("\"caption\" text is \"Hi my name is John\" but should be \"Hi my name is Jack\""));
    }

    @Test
    public void shouldPrintHelp() throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PrintStream ps = new PrintStream(baos);
        new GalenMain(ps, System.err).execute(new String[]{"help"});

        String realText = baos.toString("UTF-8");
        assertThat(realText, allOf(containsString("Galen Framework is an open-source tool for testing layout"),
                containsString("Apache License")));
    }
}


text:
@implementation ANExampleTableViewCell

- (void)updateWithModel:(NSString*)model
{
    self.textLabel.text = model;
}

@end


text:
<?php

namespace SmartCore\Module\Shop\Controller;

use Smart\CoreBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class AdminShippingController extends Controller
{
    public function indexAction(Request $request)
    {

        return $this->render('ShopModuleBundle:Admin:index.html.twig', []);
    }

    public function settingsAction(Request $request)
    {
        return $this->render('ShopModuleBundle:Admin:settings.html.twig', []);
    }

    public function shippingAction(Request $request)
    {
        return $this->render('ShopModuleBundle:Admin:shipping.html.twig', []);
    }

   public function shippingSettingsAction(Request $request)
    {
        return $this->render('ShopModuleBundle:Admin:shipping_settings.html.twig', []);
    }

}


text:
using namespace tinch_pp;
using namespace tinch_pp::erl;
using namespace boost::assign;

// The chat client is intended as a simple test-application when testing tinch++
// in a distributed environment.
//
// USAGE:
// ======
// 1. Start the included Erlang chat_server with the cookie abcdef.
// 2. Start this program: chat_client <client-name> <own-node-name> <chat-server-node-name>
//    Example: chat_client Adam zarathustra.mydomain server@lambda.mydomain
// 3. Connect yet another client, either locally or on another machine.
// 4. Chat 'til you drop.
//
// You leave the chat by entering an empty line (RETURN).

namespace {

// Blocks until a chat message is published from another client.
// The chat messages are sent as {chat_msg, From, Msg}
void receive_published_msg(mailbox_ptr mbox)
{
  while(1) {
    matchable_ptr msg = mbox->receive();

    std::string publisher;
    std::string message;

    if(msg->match(make_e_tuple(atom("chat_msg"), e_string(&publisher), e_string(&message))))
      std::cout << publisher << " says: " << message << std::endl;
    else
      std::cerr << "Received something I couldn't interpret - a possible error!" << std::endl;
  }
}

class chat_client : boost::noncopyable
{
  typedef std::list<erl::object_ptr> rpc_arg_type;

public:
  chat_client(const std::string& client_name,
              const std::string& own_node_name,
              const std::string& chat_server_node)
              : own_node(node::create(client_name + "@" + own_node_name, "abcdef")), // hardcoded cookie
      rpc_invoker(own_node),
      mbox(own_node->create_mailbox()),
      chat_server(chat_server_node),
      msg_receiver(receive_published_msg, mbox)
  {
    enter_chat(client_name);
  }

  ~chat_client()
  {
    leave_chat();

    msg_receiver.detach();
    msg_receiver.join();
  }

  void publish(const std::string& msg)
  {
    const rpc_arg_type publication = list_of(make_string(msg))(make_pid(mbox->self()));

    do_rpc("publish", publication);
  }

private:

  void enter_chat(const std::string& client_name)
  {
    const rpc_arg_type registration = list_of(make_string(client_name))(make_pid(mbox->self()));

    matchable_ptr reply = do_rpc("register_client", registration);

    if(!reply->match(atom("ok")))
      throw std::runtime_error("Failed to register at the chat_server - is it running on node " + chat_server + " ?");
  }

  void leave_chat()
  {
    const rpc_arg_type unregistration = list_of(make_pid(mbox->self()));

    do_rpc("unregister_client", unregistration);
  }

  matchable_ptr do_rpc(const std::string& remote_fun, const rpc_arg_type& rpc_args)
  {
    return rpc_invoker.blocking_rpc(chat_server,
                                    module_and_function_type("chat_server", remote_fun),
                                    make_list(rpc_args));
  }

private:

  node_ptr own_node;
  rpc rpc_invoker;

  mailbox_ptr mbox;
  std::string chat_server;

  std::thread msg_receiver;
};

std::string prompt_user(const std::string& user)
{
  std::cout << user << "> ";
  std::string msg;
  std::getline(std::cin, msg);

  return msg;
}

}

int main(int argc, char* argv[])
{
  if(argc < 4) {
    std::cerr << "Erroneous usage. Usage: chat_client <client-name> <own-node-name> <chat-server-node-name>" << std::endl;
    return -1;
  }

  const std::string client_name(argv[1]);
  const std::string own_node_name(argv[2]);
  const std::string server_node(argv[3]);

  chat_client client(client_name, own_node_name, server_node);

  bool chat_some_more = true;

  while(chat_some_more) {
    const std::string msg = prompt_user(client_name);

    if((chat_some_more = !msg.empty()))
      client.publish(msg);
  }
}


text:
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _Base = require('./Base');

var _Base2 = _interopRequireDefault(_Base);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }

/**
 * Unstyled display block link
 */

var LinkBlock = function LinkBlock(_ref, _ref2) {
  var rebass = _ref2.rebass;

  var _className = _ref._className,
      props = _objectWithoutProperties(_ref, ['_className']);

  var sx = {
    display: 'block',
    textDecoration: 'none',
    color: 'inherit'
  };

  return _react2.default.createElement(_Base2.default, _extends({}, props, {
    className: _className || 'LinkBlock',
    baseStyle: sx }));
};

LinkBlock.propTypes = {
  /** Root component - useful for use with react-router's Link component */
  is: _react2.default.PropTypes.oneOfType([_react2.default.PropTypes.string, _react2.default.PropTypes.object, _react2.default.PropTypes.func])
};

LinkBlock.defaultProps = {
  is: 'a'
};

LinkBlock.contextTypes = {
  rebass: _react2.default.PropTypes.object
};

exports.default = LinkBlock;


text:
module FileDb
  module Data
    def initialize params= {}
      before :initialize
      load_params_into_model params
      after :initialize
    end

    def delete
      before :delete
      table.delete(id)
      after :delete
    end

    def save
      before :save
      table.update_record self
      after :save
    end

    def persisted?
      table.hashed_by_id[id.to_s]
    end

    def table
      self.class.table
    end

private

    def load_params_into_model params
      params.each do |key, value|
        next unless self.class.columns_hash[key.to_sym]
        send("#{key}=", value)
      end
    end

  end
end


text:
<?php

namespace PhpGitHooks\Module\Git\Service;

use PhpGitHooks\Module\Git\Model\WriterInterface;

class GitIgnoreWriter
{
    /**
     * @var WriterInterface
     */
    private $gitIgnoreWriter;

    /**
     * GitIgnoreWriter constructor.
     *
     * @param WriterInterface $gitIgnoreWriter
     */
    public function __construct(WriterInterface $gitIgnoreWriter)
    {
        $this->gitIgnoreWriter = $gitIgnoreWriter;
    }

    /**
     * @param string $content
     */
    public function write($content)
    {
        $this->gitIgnoreWriter->write($content);
    }
}


text:
package net.adamcin.oakpal.core.jcrfacade.lock;

import static org.junit.Assert.assertSame;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import javax.jcr.Session;
import javax.jcr.lock.Lock;
import javax.jcr.lock.LockManager;

import net.adamcin.oakpal.core.ListenerReadOnlyException;
import net.adamcin.oakpal.core.jcrfacade.FacadeGetterMapping;
import net.adamcin.oakpal.core.jcrfacade.JcrSessionFacade;
import org.jetbrains.annotations.NotNull;
import org.junit.Test;

public class LockManagerFacadeTest {

    LockManagerFacade<Session> getFacade(final @NotNull LockManager mockLockManager) {
        return new LockManagerFacade<>(mockLockManager, new JcrSessionFacade(mock(Session.class), false));
    }

    @Test
    public void testGetLock() throws Exception {
        new FacadeGetterMapping.Tester<>(LockManager.class, this::getFacade)
                .testFacadeGetter(Lock.class, LockFacade.class, delegate -> delegate.getLock(""));
    }

    @Test
    public void testGetLockTokens() throws Exception {
        LockManager delegate = mock(LockManager.class);
        LockManagerFacade<Session> facade = getFacade(delegate);
        final String[] value = new String[0];
        when(delegate.getLockTokens()).thenReturn(value);
        assertSame("is same value", value, facade.getLockTokens());
    }

    @Test
    public void testHoldsLock() throws Exception {
        LockManager delegate = mock(LockManager.class);
        LockManagerFacade<Session> facade = getFacade(delegate);
        final String path = "/correct/path";
        when(delegate.holdsLock(path)).thenReturn(true);
        assertTrue("is true", facade.holdsLock(path));
    }

    @Test
    public void testIsLocked() throws Exception {
        LockManager delegate = mock(LockManager.class);
        LockManagerFacade<Session> facade = getFacade(delegate);
        final String path = "/correct/path";
        when(delegate.isLocked(path)).thenReturn(true);
        assertTrue("is true", facade.isLocked(path));
    }

    @Test(expected = ListenerReadOnlyException.class)
    public void testROAddLockToken() throws Exception {
        LockManagerFacade<Session> facade = getFacade(mock(LockManager.class));
        facade.addLockToken("");
    }

    @Test(expected = ListenerReadOnlyException.class)
    public void testRORemoveLockToken() throws Exception {
        LockManagerFacade<Session> facade = getFacade(mock(LockManager.class));
        facade.removeLockToken("");
    }

    @Test(expected = ListenerReadOnlyException.class)
    public void testROLock() throws Exception {
        LockManagerFacade<Session> facade = getFacade(mock(LockManager.class));
        facade.lock("", true, true, 0L, "");
    }

    @Test(expected = ListenerReadOnlyException.class)
    public void testROUnlock() throws Exception {
        LockManagerFacade<Session> facade = getFacade(mock(LockManager.class));
        facade.unlock("");
    }
}


text:
/**
 * This file is part of the CernVM File System.
 */

#include "cvmfs_config.h"
#include "quota_listener.h"

#include <poll.h>
#include <pthread.h>

#include <cstdlib>

#include "catalog_mgr.h"
#include "logging.h"
#include "quota.h"
#include "smalloc.h"
#include "util/posix.h"

using namespace std;  // NOLINT

namespace quota {

struct ListenerHandle {
  int pipe_backchannel[2];
  int pipe_terminate[2];
  QuotaManager *quota_manager;
  CatalogManager *catalog_manager;
  string repository_name;
  pthread_t thread_listener;
};

static void *MainUnpinListener(void *data) {
  ListenerHandle *handle = static_cast<ListenerHandle *>(data);
  LogCvmfs(kLogQuota, kLogDebug, "starting unpin listener for %s",
           handle->repository_name.c_str());

  struct pollfd *watch_fds =
    static_cast<struct pollfd *>(smalloc(2 * sizeof(struct pollfd)));
  watch_fds[0].fd = handle->pipe_terminate[0];
  watch_fds[0].events = POLLIN | POLLPRI;
  watch_fds[0].revents = 0;
  watch_fds[1].fd = handle->pipe_backchannel[0];
  watch_fds[1].events = POLLIN | POLLPRI;
  watch_fds[1].revents = 0;
  while (true) {
    int retval = poll(watch_fds, 2, -1);
    if (retval < 0) {
      continue;
    }

    // Terminate I/O thread
    if (watch_fds[0].revents)
      break;

    // Release pinned catalogs
    if (watch_fds[1].revents) {
      watch_fds[1].revents = 0;
      char cmd;
      ReadPipe(handle->pipe_backchannel[0], &cmd, sizeof(cmd));
      if (cmd == 'R') {
        handle->catalog_manager->DetachNested();
        LogCvmfs(kLogQuota, kLogDebug | kLogSyslog, "released nested catalogs");
      }
    }
  }
  free(watch_fds);

  LogCvmfs(kLogQuota, kLogDebug, "stopping unpin listener for %s",
           handle->repository_name.c_str());
  return NULL;
}

static void *MainWatchdogListener(void *data) {
  ListenerHandle *handle = static_cast<ListenerHandle *>(data);
  LogCvmfs(kLogQuota, kLogDebug, "starting cache manager watchdog for %s",
           handle->repository_name.c_str());

  struct pollfd *watch_fds =
  static_cast<struct pollfd *>(smalloc(2 * sizeof(struct pollfd)));
  watch_fds[0].fd = handle->pipe_terminate[0];
  watch_fds[0].events = POLLIN | POLLPRI;
  watch_fds[0].revents = 0;
  watch_fds[1].fd = handle->pipe_backchannel[0];
  watch_fds[1].events = POLLIN | POLLPRI;
  watch_fds[1].revents = 0;
  while (true) {
    int retval = poll(watch_fds, 2, -1);
    if (retval < 0) {
      continue;
    }

    // Terminate I/O thread
    if (watch_fds[0].revents)
      break;

    // Release pinned catalogs
    if (watch_fds[1].revents) {
      if ((watch_fds[1].revents & POLLERR) ||
          (watch_fds[1].revents & POLLHUP) ||
          (watch_fds[1].revents & POLLNVAL))
      {
        LogCvmfs(kLogQuota, kLogDebug | kLogSyslogErr,
                 "cache manager disappeared, aborting");
        abort();
      }
      // Clean the pipe
      watch_fds[1].revents = 0;
      char dummy;
      ReadPipe(handle->pipe_backchannel[0], &dummy, sizeof(dummy));
    }
  }
  free(watch_fds);

  LogCvmfs(kLogQuota, kLogDebug, "stopping cache manager watchdog for %s",
           handle->repository_name.c_str());
  return NULL;
}

/**
 * Registers a back channel that reacts on high watermark of pinned chunks
 */
ListenerHandle *
RegisterUnpinListener(QuotaManager *quota_manager,
                      CatalogManager *catalog_manager,
                      const string &repository_name)
{
  ListenerHandle *handle = new ListenerHandle();
  quota_manager->RegisterBackChannel(handle->pipe_backchannel, repository_name);
  MakePipe(handle->pipe_terminate);
  handle->quota_manager = quota_manager;
  handle->catalog_manager = catalog_manager;
  handle->repository_name = repository_name;
  int retval = pthread_create(&handle->thread_listener, NULL, MainUnpinListener,
                              static_cast<void *>(handle));
  assert(retval == 0);
  return handle;
}

/**
 * Registers a back channel that kills the fuse module if the cache manager
 * disappears
 */
ListenerHandle *
RegisterWatchdogListener(
  QuotaManager *quota_manager,
  const string &repository_name)
{
  ListenerHandle *handle = new ListenerHandle();
  quota_manager->RegisterBackChannel(handle->pipe_backchannel, repository_name);
  MakePipe(handle->pipe_terminate);
  handle->quota_manager = quota_manager;
  handle->catalog_manager = NULL;
  handle->repository_name = repository_name;
  int retval = pthread_create(&handle->thread_listener, NULL,
                              MainWatchdogListener,
                              static_cast<void *>(handle));
  assert(retval == 0);
  return handle;
}

void UnregisterListener(ListenerHandle *handle) {
  const char terminate = 'T';
  WritePipe(handle->pipe_terminate[1], &terminate, sizeof(terminate));
  pthread_join(handle->thread_listener, NULL);
  ClosePipe(handle->pipe_terminate);

  handle->quota_manager->UnregisterBackChannel(
    handle->pipe_backchannel, handle->repository_name);

  delete handle;
}

}  // namespace quota


text:
namespace SVPMigrator.Old
{
    using System;
    using System.Collections.Generic;

    public partial class evaluation
    {
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
        public evaluation()
        {
            this.prices = new HashSet<price>();
        }

        public int id { get; set; }
        public string name { get; set; }
        public string key { get; set; }

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
        public virtual ICollection<price> prices { get; set; }
    }
}


text:
cask :v1 => 'appcode-eap' do
  version '142.4859.15'
  sha256 '43094aa5c060e2e5731d1d9bd8ce3e8252e4c456e52431c50c482d6467056bc1'

  url "https://download.jetbrains.com/objc/AppCode-#{version}-custom-jdk-bundled.dmg"
  name 'AppCode'
  homepage 'https://confluence.jetbrains.com/display/OBJC/AppCode+EAP'
  license :commercial

  app 'AppCode EAP.app'

  zap :delete => [
                  '~/Library/Preferences/com.jetbrains.AppCode-EAP.plist',
                  '~/Library/Preferences/AppCode33',
                  '~/Library/Application Support/AppCode33',
                  '~/Library/Caches/AppCode33',
                  '~/Library/Logs/AppCode33',
                 ]
end


text:
package com.zimbra.cs.ldap;

public enum LdapConnType {
    PLAIN,
    LDAPS,
    STARTTLS,
    LDAPI;

    private static final String LDAPI_SCHEME = "ldapi";
    private static final String LDAPS_SCHEME = "ldaps";
    private static final String LDAPI_URL = LDAPI_SCHEME + "://";
    private static final String LDAPS_URL = LDAPS_SCHEME + "://";

    public static LdapConnType getConnType(String urls, boolean wantStartTLS) {
        if (urls.toLowerCase().contains(LDAPI_URL)) {
            return LDAPI;
        } else if (urls.toLowerCase().contains(LDAPS_URL)) {
            return LDAPS;
        } else if (wantStartTLS) {
            return STARTTLS;
        } else {
            return PLAIN;
        }
    }

    /*
     * for external LDAP, only called from legacy external GAL code
     */
    public static boolean requireStartTLS(String[] urls, boolean wantStartTLS) {
        if (wantStartTLS) {
            for (String url : urls) {
                if (url.toLowerCase().contains(LDAPS_URL))
                    return false;
            }
            return true;
        }
        return false;
    }

    public static boolean isLDAPI(String scheme) {
        return LDAPI_SCHEME.equalsIgnoreCase(scheme);
    }

}


text:
package lt.miliauskas.battlesats;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.view.WindowManager;

public class BattleSats extends Activity {

	/*
	 * Gameplay constants
	 */
	public static final float BOMB_HEALTH = 1.5f;
	public static final float BOMB_DAMAGE = 5.0f;
	public static final float BOMBER_HEALTH = 1000.0f;
	public static final float BOMBER_INTERVAL = 3000; // ms
	public static final float BOMBER_LASER_RANGE = 200.0f; // ms
	public static final float BOMBER_LASER_DAMAGE = 5.0f; // ms
	public static final float LASER_DAMAGE = 1.0f; // HP / ms
	public static final float LASER_RANGE = 100.0f;
	public static final float LASER_SENTINEL_HEALTH = 20.0f;
	public static final int EARTH_RADIUS = 30;
	public static final float EARTH_HEALTH = 100.0f;
	public static final int USER_SATELLITES = 5;

	/*
	 * Physics constants
	 */
	public static final float MASS_EARTH = 50000.0f;

	/*
	 * Constants for visuals
	 */
	public static final int LASER_BEAM_RADIUS = 2;
	public static final int BOMBER_LASER_BEAM_RADIUS = 5;
	public static final float BOMB_RADIUS = 5.0f;
	public static final float BOMBER_WIDTH = 25.0f;
	public static final float BOMBER_HEIGHT = 10.0f;
	public static final float HEALTH_BAR_HEIGHT = 10.0f;
	public static final float HEALTH_BAR_PADDING = 10.0f;
	public static final float SCALE_MIN = 0.2f;
	public static final float SCALE_MAX = 3.0f;

	/** How many pixels to drag onscreen to give a flier a velocity of 1 */
	public static final float DRAG_VELOCITY_RATIO = 5.0f;

	/*
     * State-tracking constants
     */
    public static final int STATE_LOSE = 1;
    public static final int STATE_PAUSE = 2;
    public static final int STATE_READY = 3;
    public static final int STATE_RUNNING = 4;
    public static final int STATE_WIN = 5;

	BattleView battleView;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // turn off the window's title bar
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        		WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.main);

        battleView = (BattleView)findViewById(R.id.battle);

        BattleThread thread = battleView.getThread();

        Log.i("BattleSats", "onCreate");
        if (savedInstanceState == null) {
            // we were just launched: set up a new game
            thread.setMode(BattleThread.STATE_READY);
        } else {
            // we are being restored: resume a previous game
            thread.restoreState(savedInstanceState);
            Log.w(this.getClass().getName(), "SIS is nonnull");
        }
    }

    /**
     * Invoked when the Activity loses user focus.
     */
    @Override
    protected void onPause() {
        super.onPause();
        battleView.getThread().pause(); // pause game when Activity pauses
        Log.i("BattleSats", "onPause");
    }

    /**
     * Notification that something is about to happen, to give the Activity a
     * chance to save state.
     *
     * @param outState a Bundle into which this Activity should save its state
     */
    @Override
    protected void onSaveInstanceState(Bundle outState) {
        // just have the View's thread save its state into our Bundle
        super.onSaveInstanceState(outState);
        battleView.getThread().saveState(outState);
        Log.w(this.getClass().getName(), "SIS called");
    }

}


text:
package org.mariotaku.restfu;

import org.jetbrains.annotations.NotNull;
import org.mariotaku.restfu.http.HttpResponse;
import org.mariotaku.restfu.http.mime.Body;
import org.mariotaku.restfu.http.mime.SimpleBody;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * Created by mariotaku on 15/2/6.
 */
public interface RestConverter<F, T, E extends Exception> {

    @NotNull
    T convert(@NotNull F from) throws ConvertException, IOException, E;

    interface Factory<E extends Exception> {

        @NotNull
        RestConverter<HttpResponse, ?, E> forResponse(@NotNull Type toType) throws ConvertException;

        @NotNull
        RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException;
    }

    abstract class SimpleFactory<E extends Exception> implements Factory<E> {
        @NotNull
        @Override
        public RestConverter<?, Body, E> forRequest(@NotNull Type fromType) throws ConvertException {
            if (!SimpleBody.supports(fromType)) throw new UnsupportedTypeException(fromType);
            return new SimpleBodyConverter<>(fromType);
        }

        public static class SimpleBodyConverter<E extends Exception> implements RestConverter<Object, Body, E> {
            private final Type fromType;

            public SimpleBodyConverter(Type fromType) {
                this.fromType = fromType;
            }

            @NotNull
            @Override
            public Body convert(@NotNull Object from) throws ConvertException, IOException {
                return SimpleBody.wrap(from);
            }
        }
    }

    class ConvertException extends Exception {
        public ConvertException() {
            super();
        }

        public ConvertException(String message) {
            super(message);
        }

        public ConvertException(String message, Throwable cause) {
            super(message, cause);
        }

        public ConvertException(Throwable cause) {
            super(cause);
        }

        protected ConvertException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
            super(message, cause, enableSuppression, writableStackTrace);
        }
    }

    class UnsupportedTypeException extends RuntimeException {
        public UnsupportedTypeException(Type type) {
            super(type.toString());
        }
    }
}


text:
"""
    flask_admin._compat
    ~~~~~~~~~~~~~~~~~~~~~~~

    Some py2/py3 compatibility support based on a stripped down
    version of six so we don't have to depend on a specific version
    of it.

    :copyright: (c) 2013 by Armin Ronacher.
    :license: BSD, see LICENSE for more details.
"""
import sys

PY2 = sys.version_info[0] == 2
VER = sys.version_info

if not PY2:
    text_type = str
    string_types = (str,)
    integer_types = (int, )

    iterkeys = lambda d: iter(d.keys())
    itervalues = lambda d: iter(d.values())
    iteritems = lambda d: iter(d.items())
    filter_list = lambda f, l: list(filter(f, l))

    def as_unicode(s):
        if isinstance(s, bytes):
            return s.decode('utf-8')

        return str(s)

    def csv_encode(s):
        ''' Returns unicode string expected by Python 3's csv module '''
        return as_unicode(s)

    # Various tools
    from functools import reduce
    from urllib.parse import urljoin, urlparse, quote
else:
    text_type = unicode
    string_types = (str, unicode)
    integer_types = (int, long)

    iterkeys = lambda d: d.iterkeys()
    itervalues = lambda d: d.itervalues()
    iteritems = lambda d: d.iteritems()
    filter_list = filter

    def as_unicode(s):
        if isinstance(s, str):
            return s.decode('utf-8')

        return unicode(s)

    def csv_encode(s):
        ''' Returns byte string expected by Python 2's csv module '''
        return as_unicode(s).encode('utf-8')

    # Helpers
    reduce = __builtins__['reduce'] if isinstance(__builtins__, dict) else __builtins__.reduce
    from urlparse import urljoin, urlparse
    from urllib import quote

def with_metaclass(meta, *bases):
    # This requires a bit of explanation: the basic idea is to make a
    # dummy metaclass for one level of class instantiation that replaces
    # itself with the actual metaclass.  Because of internal type checks
    # we also need to make sure that we downgrade the custom metaclass
    # for one level to something closer to type (that's why __call__ and
    # __init__ comes back from type etc.).
    #
    # This has the advantage over six.with_metaclass in that it does not
    # introduce dummy classes into the final MRO.
    class metaclass(meta):
        __call__ = type.__call__
        __init__ = type.__init__

        def __new__(cls, name, this_bases, d):
            if this_bases is None:
                return type.__new__(cls, name, (), d)
            return meta(name, bases, d)
    return metaclass('temporary_class', None, {})

try:
    from collections import OrderedDict
except ImportError:
    from ordereddict import OrderedDict

try:
    from jinja2 import pass_context
except ImportError:
    from jinja2 import contextfunction as pass_context


text:
package voldemort.server.rebalance.async;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import voldemort.client.protocol.admin.AdminClient;
import voldemort.client.rebalance.RebalanceTaskInfo;
import voldemort.server.VoldemortConfig;
import voldemort.server.rebalance.Rebalancer;
import voldemort.server.rebalance.VoldemortRebalancingException;
import voldemort.store.metadata.MetadataStore;
import voldemort.store.readonly.ReadOnlyStorageConfiguration;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;

/**
 * Individual rebalancing operation run on the server side as an async
 * operation. This is run on the stealer node
 */
public class StealerBasedRebalanceAsyncOperation extends RebalanceAsyncOperation {

    private List<Integer> rebalanceStatusList;

    private final RebalanceTaskInfo stealInfo;
    private final int partitionStoreCount;

    public StealerBasedRebalanceAsyncOperation(Rebalancer rebalancer,
                                               VoldemortConfig voldemortConfig,
                                               MetadataStore metadataStore,
                                               int requestId,
                                               RebalanceTaskInfo stealInfo) {
        super(rebalancer,
              voldemortConfig,
              metadataStore,
              requestId,
              "Stealer based rebalance of " + stealInfo.getPartitionStoreCount()
                      + " partition-stores.");
        this.rebalancer = rebalancer;
        this.stealInfo = stealInfo;
        this.rebalanceStatusList = new ArrayList<Integer>();
        this.partitionStoreCount = stealInfo.getPartitionStoreCount();
    }

    @Override
    public void operate() throws Exception {
        adminClient = AdminClient.createTempAdminClient(voldemortConfig,
                                                           metadataStore.getCluster(),
                                                           voldemortConfig.getMaxParallelStoresRebalancing());
        final List<Exception> failures = new ArrayList<Exception>();
        final ConcurrentLinkedQueue<String> storesRebalancing = new ConcurrentLinkedQueue<String>();
        final AtomicInteger completedStoresCount = new AtomicInteger(0);
        final int totalStoresCount = stealInfo.getPartitionStores().size();

        try {

            for (final String storeName : ImmutableList.copyOf(stealInfo.getPartitionStores())) {

                executors.submit(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            boolean isReadOnlyStore = metadataStore.getStoreDef(storeName)
                                                                   .getType()
                                                                   .compareTo(ReadOnlyStorageConfiguration.TYPE_NAME) == 0;

                            // Add the store to the rebalancing list
                            storesRebalancing.add(storeName);
                            updateStatus(getHeader(stealInfo) + "Completed working on "
                                         + completedStoresCount.get() + " out of "
                                         + totalStoresCount + " stores. Still rebalancing "
                                         + storesRebalancing);

                            // Start the rebalance..
                            rebalanceStore(storeName, adminClient, stealInfo, isReadOnlyStore);

                            // We finished the store, delete it
                            stealInfo.removeStore(storeName);
                            storesRebalancing.remove(storeName);

                            // Increment the store count
                            completedStoresCount.getAndIncrement();

                            updateStatus(getHeader(stealInfo) + "Completed working on "
                                         + completedStoresCount.get() + " out of "
                                         + totalStoresCount + " stores. Still rebalancing "
                                         + storesRebalancing);

                        } catch(Exception e) {
                            logger.error(getHeader(stealInfo)
                                         + "Error while rebalancing for store " + storeName + " - "
                                         + e.getMessage(), e);
                            failures.add(e);
                        }
                    }
                });

            }

            waitForShutdown();

            // If empty, clean state
            List<String> unbalancedStores = Lists.newArrayList(stealInfo.getPartitionStores());
            if(unbalancedStores.isEmpty()) {
                logger.info(getHeader(stealInfo) + "Rebalance of " + stealInfo
                            + " completed successfully for all " + totalStoresCount + " stores");
                updateStatus(getHeader(stealInfo) + "Rebalance of " + partitionStoreCount
                             + " partition-stores completed successfully for all "
                             + totalStoresCount + " stores");
                metadataStore.deleteRebalancingState(stealInfo);
            } else {
                throw new VoldemortRebalancingException(getHeader(stealInfo)
                                                        + "Failed to rebalance task " + stealInfo
                                                        + ". Could only complete "
                                                        + completedStoresCount.get() + " out of "
                                                        + totalStoresCount + " stores", failures);
            }

        } finally {
            // free the permit in all cases.
            logger.info(getHeader(stealInfo) + "Releasing permit for donor node "
                        + stealInfo.getDonorId());

            rebalancer.releaseRebalancingPermit(stealInfo.getDonorId());
            adminClient.close();
            adminClient = null;
        }
    }

    @Override
    public void stop() {
        updateStatus(getHeader(stealInfo) + "Stop called on rebalance operation");
        if(null != adminClient) {
            for(int asyncID: rebalanceStatusList) {
                adminClient.rpcOps.stopAsyncRequest(metadataStore.getNodeId(), asyncID);
            }
        }

        executors.shutdownNow();
    }

    private String getHeader(RebalanceTaskInfo stealInfo) {
        return "Stealer " + stealInfo.getStealerId() + ", Donor " + stealInfo.getDonorId() + "] ";
    }

    /**
     * Blocking function which completes the migration of one store
     *
     * @param storeName The name of the store
     * @param adminClient Admin client used to initiate the copying of data
     * @param stealInfo The steal information
     * @param isReadOnlyStore Boolean indicating that this is a read-only store
     */
    private void rebalanceStore(String storeName,
                                final AdminClient adminClient,
                                RebalanceTaskInfo stealInfo,
                                boolean isReadOnlyStore) {
        // Move partitions
        if (stealInfo.getPartitionIds(storeName) != null && stealInfo.getPartitionIds(storeName).size() > 0) {

            logger.info(getHeader(stealInfo) + "Starting partitions migration for store "
                        + storeName + " from donor node " + stealInfo.getDonorId());

            int asyncId = adminClient.storeMntOps.migratePartitions(stealInfo.getDonorId(),
                                                                    metadataStore.getNodeId(),
                                                                    storeName,
                                                                    stealInfo.getPartitionIds(storeName),
                                                                    null,
                                                                    stealInfo.getInitialCluster());
            rebalanceStatusList.add(asyncId);

            if(logger.isDebugEnabled()) {
                logger.debug(getHeader(stealInfo) + "Waiting for completion for " + storeName
                             + " with async id " + asyncId);
            }
            adminClient.rpcOps.waitForCompletion(metadataStore.getNodeId(),
                                                 asyncId,
                                                 voldemortConfig.getRebalancingTimeoutSec(),
                                                 TimeUnit.SECONDS,
                                                 getStatus());

            rebalanceStatusList.remove((Object) asyncId);

            logger.info(getHeader(stealInfo) + "Completed partition migration for store "
                        + storeName + " from donor node " + stealInfo.getDonorId());
        }

        logger.info(getHeader(stealInfo) + "Finished all migration for store " + storeName);
    }
}


text:
namespace base {
class DictionaryValue;
class ListValue;
}

namespace dbus {
class Bus;
class ObjectPath;
}

namespace chromeos {

// GsmSMSClient is used to communicate with the
// org.freedesktop.ModemManager.Modem.Gsm.SMS service.
// All methods should be called from the origin thread (UI thread) which
// initializes the DBusThreadManager instance.
class CHROMEOS_EXPORT GsmSMSClient {
 public:
  typedef base::Callback<void(uint32 index, bool complete)> SmsReceivedHandler;
  typedef base::Callback<void()> DeleteCallback;
  typedef base::Callback<void(const base::DictionaryValue& sms)> GetCallback;
  typedef base::Callback<void(const base::ListValue& result)> ListCallback;

  virtual ~GsmSMSClient();

  // Factory function, creates a new instance and returns ownership.
  // For normal usage, access the singleton via DBusThreadManager::Get().
  static GsmSMSClient* Create(DBusClientImplementationType type,
                              dbus::Bus* bus);

  // Sets SmsReceived signal handler.
  virtual void SetSmsReceivedHandler(const std::string& service_name,
                                     const dbus::ObjectPath& object_path,
                                     const SmsReceivedHandler& handler) = 0;

  // Resets SmsReceived signal handler.
  virtual void ResetSmsReceivedHandler(const std::string& service_name,
                                       const dbus::ObjectPath& object_path) = 0;

  // Calls Delete method.  |callback| is called after the method call succeeds.
  virtual void Delete(const std::string& service_name,
                      const dbus::ObjectPath& object_path,
                      uint32 index,
                      const DeleteCallback& callback) = 0;

  // Calls Get method.  |callback| is called after the method call succeeds.
  virtual void Get(const std::string& service_name,
                   const dbus::ObjectPath& object_path,
                   uint32 index,
                   const GetCallback& callback) = 0;

  // Calls List method.  |callback| is called after the method call succeeds.
  virtual void List(const std::string& service_name,
                    const dbus::ObjectPath& object_path,
                    const ListCallback& callback) = 0;

  // Requests a check for new messages. In shill this does nothing. The
  // stub implementation uses it to generate a sequence of test messages.
  virtual void RequestUpdate(const std::string& service_name,
                             const dbus::ObjectPath& object_path) = 0;

 protected:
  // Create() should be used instead.
  GsmSMSClient();

 private:
  DISALLOW_COPY_AND_ASSIGN(GsmSMSClient);
};

}  // namespace chromeos

#endif  // CHROMEOS_DBUS_GSM_SMS_CLIENT_H_


text:
package no.kantega.publishing.common;

import no.kantega.publishing.common.data.Content;
import no.kantega.publishing.topicmaps.data.Topic;

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

/**
 *
 */
public class ContentTopicsRelevanceComparator implements Comparator<Content> {

    Map<String, Topic> topics;

    public ContentTopicsRelevanceComparator(Content content) {
        if (content != null && content.getTopics() != null) {
            topics = new HashMap<String, Topic>();
            for (Topic topic : content.getTopics()) {
                topics.put(topic.getId(), topic);
            }
        }
    }

    public int compare(Content content1, Content content2) {
        int match1 = getSimilarTopicsCount(content1);
        int match2 = getSimilarTopicsCount(content2);
        if (match2 > match1) {
            return 1;
        } else if (match2 < match1) {
            return -1;
        }
        return 0;
    }

    private int getSimilarTopicsCount(Content content) {
        int match = 0;
        if (content != null && content.getTopics() != null && content.getTopics().size() > 0) {
            for (Topic topic : content.getTopics()) {
                if (topics.get(topic.getId()) != null) {
                    match++;
                }
            }
        }

        return match;
    }
}


text:
module.exports = {
    tags: ['news'],
    'mobile device visit': function(browser) {
        if(browser.globals.isMobile) {
            browser
                .page.news().mobileVisit()
                .end()
        } else {
            browser
                .page.news().desktopVisit()
                .end()
        }
    }

};