text:
namespace {
// During playback of protected content, we need to request the keys at an
// interval no greater than this. This allows updating of key usage data.
constexpr base::TimeDelta kKeyRetrievalMaxPeriod = base::Minutes(1);
// This increments the lower 64 bit counter of an 128 bit IV.
void ctr128_inc64(uint8_t* counter) {
  uint32_t n = 16;
  do {
    if (++counter[--n] != 0)
      return;
  } while (n > 8);
}

}  // namespace
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)

namespace media {

VaapiVideoDecoderDelegate::VaapiVideoDecoderDelegate(
    DecodeSurfaceHandler<VASurface>* const vaapi_dec,
    scoped_refptr<VaapiWrapper> vaapi_wrapper,
    ProtectedSessionUpdateCB on_protected_session_update_cb,
    CdmContext* cdm_context,
    EncryptionScheme encryption_scheme)
    : vaapi_dec_(vaapi_dec),
      vaapi_wrapper_(std::move(vaapi_wrapper)),
      on_protected_session_update_cb_(
          std::move(on_protected_session_update_cb)),
      encryption_scheme_(encryption_scheme),
      protected_session_state_(ProtectedSessionState::kNotCreated),
      performing_recovery_(false) {
  DCHECK(vaapi_wrapper_);
  DCHECK(vaapi_dec_);
  DETACH_FROM_SEQUENCE(sequence_checker_);
#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (cdm_context)
    chromeos_cdm_context_ = cdm_context->GetChromeOsCdmContext();
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
  transcryption_ = cdm_context && VaapiWrapper::GetImplementationType() ==
                                      VAImplementation::kMesaGallium;
}

VaapiVideoDecoderDelegate::~VaapiVideoDecoderDelegate() {
  // TODO(mcasas): consider enabling the checker, https://crbug.com/789160
  // DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // Also destroy the protected session on destruction of the accelerator
  // delegate. That way if a new delegate is created, when it tries to create a
  // new protected session it won't overwrite the existing one.
  vaapi_wrapper_->DestroyProtectedSession();
}

void VaapiVideoDecoderDelegate::set_vaapi_wrapper(
    scoped_refptr<VaapiWrapper> vaapi_wrapper) {
  DETACH_FROM_SEQUENCE(sequence_checker_);
  vaapi_wrapper_ = std::move(vaapi_wrapper);
  protected_session_state_ = ProtectedSessionState::kNotCreated;
  hw_identifier_.clear();
  hw_key_data_map_.clear();
}

void VaapiVideoDecoderDelegate::OnVAContextDestructionSoon() {}

bool VaapiVideoDecoderDelegate::HasInitiatedProtectedRecovery() {
  if (protected_session_state_ != ProtectedSessionState::kNeedsRecovery)
    return false;

  performing_recovery_ = true;
  protected_session_state_ = ProtectedSessionState::kNotCreated;
  return true;
}

bool VaapiVideoDecoderDelegate::SetDecryptConfig(
    std::unique_ptr<DecryptConfig> decrypt_config) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // It is possible to switch between clear and encrypted (and vice versa).
  if (!decrypt_config)
    return true;
  decrypt_config_ = std::move(decrypt_config);
  encryption_scheme_ = decrypt_config_->encryption_scheme();
  return true;
}

#if BUILDFLAG(IS_CHROMEOS_ASH)
VaapiVideoDecoderDelegate::ProtectedSessionState
VaapiVideoDecoderDelegate::SetupDecryptDecode(
    bool full_sample,
    size_t size,
    VAEncryptionParameters* crypto_params,
    std::vector<VAEncryptionSegmentInfo>* segments,
    const std::vector<SubsampleEntry>& subsamples) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  DCHECK(crypto_params);
  DCHECK(segments);
  if (protected_session_state_ == ProtectedSessionState::kInProcess ||
      protected_session_state_ == ProtectedSessionState::kFailed) {
    return protected_session_state_;
  }
  if (protected_session_state_ == ProtectedSessionState::kNotCreated) {
    if (!chromeos_cdm_context_) {
      LOG(ERROR) << "Cannot create protected session w/out ChromeOsCdmContext";
      protected_session_state_ = ProtectedSessionState::kFailed;
      return protected_session_state_;
    }
    // We need to start the creation of this, first part requires getting the
    // hw config data from the daemon.
    chromeos_cdm_context_->GetHwConfigData(BindToCurrentLoop(
        base::BindOnce(&VaapiVideoDecoderDelegate::OnGetHwConfigData,
                       weak_factory_.GetWeakPtr())));
    protected_session_state_ = ProtectedSessionState::kInProcess;
    return protected_session_state_;
  }

  DCHECK_EQ(protected_session_state_, ProtectedSessionState::kCreated);

  const bool ctr = (encryption_scheme_ == EncryptionScheme::kCenc);
  if (ctr) {
    crypto_params->encryption_type = full_sample
                                         ? VA_ENCRYPTION_TYPE_FULLSAMPLE_CTR
                                         : VA_ENCRYPTION_TYPE_SUBSAMPLE_CTR;
  } else {
    crypto_params->encryption_type = full_sample
                                         ? VA_ENCRYPTION_TYPE_FULLSAMPLE_CBC
                                         : VA_ENCRYPTION_TYPE_SUBSAMPLE_CBC;
  }

  // For multi-slice we may already have segment information in here, so
  // calculate the current offset.
  size_t offset = 0;
  for (const auto& segment : *segments)
    offset += segment.segment_length;

  if (subsamples.empty() ||
      (subsamples.size() == 1 && subsamples[0].cypher_bytes == 0)) {
    // We still need to specify the crypto params to the driver for some reason
    // and indicate the entire content is clear.
    VAEncryptionSegmentInfo segment_info = {};
    segment_info.segment_start_offset = offset;
    segment_info.segment_length = segment_info.init_byte_length = size;
    if (decrypt_config_) {
      // We need to specify the IV even if the segment is clear.
      memcpy(segment_info.aes_cbc_iv_or_ctr, decrypt_config_->iv().data(),
             DecryptConfig::kDecryptionKeySize);
    }
    segments->emplace_back(std::move(segment_info));
    crypto_params->num_segments++;
    crypto_params->segment_info = &segments->front();
    return protected_session_state_;
  }

  // On Intel if we change encryption modes after we have started decrypting
  // then we need to rebuild the protected session.
  if (!IsTranscrypted() &&
      last_used_encryption_scheme_ != EncryptionScheme::kUnencrypted &&
      last_used_encryption_scheme_ != encryption_scheme_) {
    LOG(WARNING) << "Forcing rebuild since encryption mode changed midstream";
    RecoverProtectedSession();
    last_used_encryption_scheme_ = EncryptionScheme::kUnencrypted;
    return protected_session_state_;
  }

  last_used_encryption_scheme_ = encryption_scheme_;
  DCHECK(decrypt_config_);
  // We also need to make sure we have the key data for the active
  // DecryptConfig now that the protected session exists.
  if (!base::Contains(hw_key_data_map_, decrypt_config_->key_id())) {
    DVLOG(1) << "Looking up the key data for: " << decrypt_config_->key_id();
    chromeos_cdm_context_->GetHwKeyData(
        decrypt_config_.get(), hw_identifier_,
        BindToCurrentLoop(base::BindOnce(
            &VaapiVideoDecoderDelegate::OnGetHwKeyData,
            weak_factory_.GetWeakPtr(), decrypt_config_->key_id())));
    last_key_retrieval_time_ =
        base::DefaultTickClock::GetInstance()->NowTicks();
    // Don't change our state here because we are created, but we just return
    // kInProcess for now to trigger a wait/retry state.
    return ProtectedSessionState::kInProcess;
  }

  // We may also need to request the key in order to update key usage times in
  // OEMCrypto. We do care about the return value, because it will indicate key
  // validity for us.
  if (base::DefaultTickClock::GetInstance()->NowTicks() -
          last_key_retrieval_time_ >
      kKeyRetrievalMaxPeriod) {
    chromeos_cdm_context_->GetHwKeyData(
        decrypt_config_.get(), hw_identifier_,
        BindToCurrentLoop(base::BindOnce(
            &VaapiVideoDecoderDelegate::OnGetHwKeyData,
            weak_factory_.GetWeakPtr(), decrypt_config_->key_id())));

    last_key_retrieval_time_ =
        base::DefaultTickClock::GetInstance()->NowTicks();
  }

  crypto_params->num_segments += subsamples.size();
  // If the pattern has no skip blocks, which means the entire thing is
  // encrypted, then don't specify a pattern at all as Intel's implementation
  // does not expect that.
  if (decrypt_config_->HasPattern() &&
      decrypt_config_->encryption_pattern()->skip_byte_block()) {
    crypto_params->blocks_stripe_encrypted =
        decrypt_config_->encryption_pattern()->crypt_byte_block();
    crypto_params->blocks_stripe_clear =
        decrypt_config_->encryption_pattern()->skip_byte_block();
  }
  size_t total_cypher_size = 0;
  std::vector<uint8_t> iv(DecryptConfig::kDecryptionKeySize);
  iv.assign(decrypt_config_->iv().begin(), decrypt_config_->iv().end());
  for (const auto& entry : subsamples) {
    VAEncryptionSegmentInfo segment_info = {};
    segment_info.segment_start_offset = offset;
    segment_info.segment_length = entry.clear_bytes + entry.cypher_bytes;
    memcpy(segment_info.aes_cbc_iv_or_ctr, iv.data(),
           DecryptConfig::kDecryptionKeySize);
    if (ctr) {
      size_t partial_block_size =
          (DecryptConfig::kDecryptionKeySize -
           (total_cypher_size % DecryptConfig::kDecryptionKeySize)) %
          DecryptConfig::kDecryptionKeySize;
      segment_info.partial_aes_block_size = partial_block_size;
      if (entry.cypher_bytes > partial_block_size) {
        // If we are finishing a block, increment the counter.
        if (partial_block_size)
          ctr128_inc64(iv.data());
        // Increment the counter for every complete block we are adding.
        for (size_t block = 0;
             block < (entry.cypher_bytes - partial_block_size) /
                         DecryptConfig::kDecryptionKeySize;
             ++block)
          ctr128_inc64(iv.data());
      }
      total_cypher_size += entry.cypher_bytes;
    }
    segment_info.init_byte_length = entry.clear_bytes;
    offset += entry.clear_bytes + entry.cypher_bytes;
    segments->emplace_back(std::move(segment_info));
  }
  memcpy(crypto_params->wrapped_decrypt_blob,
         hw_key_data_map_[decrypt_config_->key_id()].data(),
         DecryptConfig::kDecryptionKeySize);
  crypto_params->key_blob_size = DecryptConfig::kDecryptionKeySize;
  crypto_params->segment_info = &segments->front();
  return protected_session_state_;
}
#endif  // if BUILDFLAG(IS_CHROMEOS_ASH)

bool VaapiVideoDecoderDelegate::NeedsProtectedSessionRecovery() {
  if (!IsEncryptedSession() || !vaapi_wrapper_->IsProtectedSessionDead() ||
      performing_recovery_) {
    return false;
  }

  RecoverProtectedSession();
  return true;
}

void VaapiVideoDecoderDelegate::ProtectedDecodedSucceeded() {
  performing_recovery_ = false;
}

std::string VaapiVideoDecoderDelegate::GetDecryptKeyId() const {
  DCHECK(decrypt_config_);
  return decrypt_config_->key_id();
}

void VaapiVideoDecoderDelegate::OnGetHwConfigData(
    bool success,
    const std::vector<uint8_t>& config_data) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  if (!success) {
    protected_session_state_ = ProtectedSessionState::kFailed;
    on_protected_session_update_cb_.Run(false);
    return;
  }

  hw_identifier_.clear();
  if (!vaapi_wrapper_->CreateProtectedSession(encryption_scheme_, config_data,
                                              &hw_identifier_)) {
    LOG(ERROR) << "Failed to setup protected session";
    protected_session_state_ = ProtectedSessionState::kFailed;
    on_protected_session_update_cb_.Run(false);
    return;
  }

  protected_session_state_ = ProtectedSessionState::kCreated;
  on_protected_session_update_cb_.Run(true);
}

void VaapiVideoDecoderDelegate::OnGetHwKeyData(
    const std::string& key_id,
    Decryptor::Status status,
    const std::vector<uint8_t>& key_data) {
  DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
  // There's a special case here where we are updating usage times/checking on
  // key validity, and in that case the key is already in the map.
  if (base::Contains(hw_key_data_map_, key_id)) {
    if (status == Decryptor::Status::kSuccess)
      return;
    // This key is no longer valid, decryption will fail, so stop playback
    // now. This key should have been renewed by the CDM instead.
    LOG(ERROR) << "CDM has lost key information, stopping playback";
    protected_session_state_ = ProtectedSessionState::kFailed;
    on_protected_session_update_cb_.Run(false);
    return;
  }
  if (status != Decryptor::Status::kSuccess) {
    // If it's a failure, then indicate so, otherwise if it's waiting for a key,
    // then we don't do anything since we will get called again when there's a
    // message about key availability changing.
    if (status == Decryptor::Status::kNoKey) {
      DVLOG(1) << "HW did not have key information, keep waiting for it";
      return;
    }
    LOG(ERROR) << "Failure getting the key data, fail overall";
    protected_session_state_ = ProtectedSessionState::kFailed;
    on_protected_session_update_cb_.Run(false);
    return;
  }
  if (key_data.size() != DecryptConfig::kDecryptionKeySize) {
    LOG(ERROR) << "Invalid key size returned of: " << key_data.size();
    protected_session_state_ = ProtectedSessionState::kFailed;
    on_protected_session_update_cb_.Run(false);
    return;
  }
  hw_key_data_map_[key_id] = key_data;
  on_protected_session_update_cb_.Run(true);
}

void VaapiVideoDecoderDelegate::RecoverProtectedSession() {
  LOG(WARNING) << "Protected session loss detected, initiating recovery";
  protected_session_state_ = ProtectedSessionState::kNeedsRecovery;
  hw_key_data_map_.clear();
  hw_identifier_.clear();
  vaapi_wrapper_->DestroyProtectedSession();
#if BUILDFLAG(IS_CHROMEOS_ASH)
  if (chromeos_cdm_context_ && chromeos_cdm_context_->UsingArcCdm()) {
    // The ARC decoder doesn't handle the WaitingCB that'll get invoked so we
    // need to trigger a protected update ourselves in order to get decoding
    // running again.
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE, base::BindRepeating(on_protected_session_update_cb_, true));
  }
#endif  // BUILDFLAG(IS_CHROMEOS_ASH)
}

}  // namespace media


text:
'use strict';

function _log(debug) {
  if (debug) {
    var args = Array.prototype.slice.call(arguments);
    args.shift();
    args.unshift("[le/lib/core.js]");
    console.log.apply(console, args);
  }
}

module.exports.create = function (le) {
  var PromiseA = require('bluebird');
  var utils = require('./utils');
  var RSA = PromiseA.promisifyAll(require('rsa-compat').RSA);
  var log = le.log || _log; // allow custom log
  var pendingRegistrations = {};

  var core = {
    //
    // Helpers
    //
    getAcmeUrlsAsync: function (args) {
      var now = Date.now();

      // TODO check response header on request for cache time
      if ((now - le._ipc.acmeUrlsUpdatedAt) < 10 * 60 * 1000) {
        return PromiseA.resolve(le._ipc.acmeUrls);
      }

      return le.acme.getAcmeUrlsAsync(args.server).then(function (data) {
        le._ipc.acmeUrlsUpdatedAt = Date.now();
        le._ipc.acmeUrls = data;

        return le._ipc.acmeUrls;
      });
    }

    //
    // The Main Enchilada
    //

    //
    // Accounts
    //
  , accounts: {
      // Accounts
      registerAsync: function (args) {
        var err;
        var copy = utils.merge(args, le);
        var disagreeTos;
        args = utils.tplCopy(copy);

        disagreeTos = (!args.agreeTos && 'undefined' !== typeof args.agreeTos);
        if (!args.email || disagreeTos || (parseInt(args.rsaKeySize, 10) < 2048)) {
          err = new Error(
            "In order to register an account both 'email' and 'agreeTos' must be present"
              + " and 'rsaKeySize' must be 2048 or greater."
          );
          err.code = 'E_ARGS';
          return PromiseA.reject(err);
        }

        return utils.testEmail(args.email).then(function () {
          var keypairOpts = { public: true, pem: true };

          var promise = le.store.accounts.checkKeypairAsync(args).then(function (keypair) {
            if (keypair) {
              return RSA.import(keypair);
            }

            if (args.accountKeypair) {
              return le.store.accounts.setKeypairAsync(args, RSA.import(args.accountKeypair));
            }

            return RSA.generateKeypairAsync(args.rsaKeySize, 65537, keypairOpts).then(function (keypair) {
              keypair.privateKeyPem = RSA.exportPrivatePem(keypair);
              keypair.publicKeyPem = RSA.exportPublicPem(keypair);
              keypair.privateKeyJwk = RSA.exportPrivateJwk(keypair);
              return le.store.accounts.setKeypairAsync(args, keypair);
            });
          });

          return promise.then(function (keypair) {
            // Note: the ACME urls are always fetched fresh on purpose
            // TODO is this the right place for this?
            return core.getAcmeUrlsAsync(args).then(function (urls) {
              args._acmeUrls = urls;

              return le.acme.registerNewAccountAsync({
                email: args.email
              , newRegUrl: args._acmeUrls.newReg
              , agreeToTerms: function (tosUrl, agreeCb) {
                  if (true === args.agreeTos || tosUrl === args.agreeTos || tosUrl === le.agreeToTerms) {
                    agreeCb(null, tosUrl);
                    return;
                  }

                  // args.email = email;      // already there
                  // args.domains = domains   // already there
                  args.tosUrl = tosUrl;
                  le.agreeToTerms(args, agreeCb);
                }
              , accountKeypair: keypair

              , debug: le.debug || args.debug
              }).then(function (receipt) {
                var reg = {
                  keypair: keypair
                , receipt: receipt
                , email: args.email
                };

                // TODO move templating of arguments to right here?
                return le.store.accounts.setAsync(args, reg).then(function (account) {
                  // should now have account.id and account.accountId
                  args.account = account;
                  args.accountId = account.id;
                  return account;
                });
              });
            });
          });
        });
      }

      // Accounts
    , getAsync: function (args) {
        return core.accounts.checkAsync(args).then(function (account) {
          if (account) {
            return account;
          } else {
            return core.accounts.registerAsync(args);
          }
        });
      }

      // Accounts
    , checkAsync: function (args) {
        var requiredArgs = ['accountId', 'email', 'domains', 'domain'];
        if (!requiredArgs.some(function (key) { return -1 !== Object.keys(args).indexOf(key); })) {
          return PromiseA.reject(new Error(
            "In order to register or retrieve an account one of '" + requiredArgs.join("', '") + "' must be present"
          ));
        }

        var copy = utils.merge(args, le);
        args = utils.tplCopy(copy);

        return le.store.accounts.checkAsync(args).then(function (account) {

          if (!account) {
            return null;
          }

          args.account = account;
          args.accountId = account.id;

          return account;
        });
      }
    }

  , certificates: {
      // Certificates
      registerAsync: function (args) {
        var err;
        var challengeDefaults = le['_challengeOpts_' + (args.challengeType || le.challengeType)] || {};
        var copy = utils.merge(args, challengeDefaults || {});
        copy = utils.merge(copy, le);
        args = utils.tplCopy(copy);

        if (!Array.isArray(args.domains)) {
          return PromiseA.reject(new Error('args.domains should be an array of domains'));
        }

        if (!(args.domains.length && args.domains.every(utils.isValidDomain))) {
          // NOTE: this library can't assume to handle the http loopback
          // (or dns-01 validation may be used)
          // so we do not check dns records or attempt a loopback here
          err = new Error("invalid domain name(s): '" + args.domains + "'");
          err.code = "INVALID_DOMAIN";
          return PromiseA.reject(err);
        }

        // If a previous request to (re)register a certificate is already underway we need
        // to return the same promise created before rather than registering things twice.
        // I'm not 100% sure how to properly handle the case where someone registers domain
        // lists with some but not all elements common, nor am I sure that's even a case that
        // is allowed to happen anyway. But for now we act like the list is completely the
        // same if any elements are the same.
        var promise;
        args.domains.some(function (name) {
          if (pendingRegistrations.hasOwnProperty(name)) {
            promise = pendingRegistrations[name];
            return true;
          }
        });
        if (promise) {
          return promise;
        }

        promise = core.certificates._runRegistration(args);

        // Now that the registration is actually underway we need to make sure any subsequent
        // registration attempts return the same promise until it is completed (but not after
        // it is completed).
        args.domains.forEach(function (name) {
          pendingRegistrations[name] = promise;
        });
        function clearPending() {
          args.domains.forEach(function (name) {
            delete pendingRegistrations[name];
          });
        }
        promise.then(clearPending, clearPending);

        return promise;
      }
    , _runRegistration: function (args) {
        // TODO renewal cb
        // accountId and or email
        return core.accounts.getAsync(args).then(function (account) {
          args.account = account;

          var promise = le.store.certificates.checkKeypairAsync(args).then(function (keypair) {
            if (keypair) {
              return RSA.import(keypair);
            }

            if (args.domainKeypair) {
              return le.store.certificates.setKeypairAsync(args, RSA.import(args.domainKeypair));
            }

            var keypairOpts = { public: true, pem: true };
            return RSA.generateKeypairAsync(args.rsaKeySize, 65537, keypairOpts).then(function (keypair) {
              keypair.privateKeyPem = RSA.exportPrivatePem(keypair);
              keypair.publicKeyPem = RSA.exportPublicPem(keypair);
              keypair.privateKeyJwk = RSA.exportPrivateJwk(keypair);
              return le.store.certificates.setKeypairAsync(args, keypair);
            });
          });

          return promise.then(function (domainKeypair) {
            args.domainKeypair = domainKeypair;
            //args.registration = domainKey;

            // Note: the ACME urls are always fetched fresh on purpose
            // TODO is this the right place for this?
            return core.getAcmeUrlsAsync(args).then(function (urls) {
              args._acmeUrls = urls;

              var certReq = {
                debug: args.debug || le.debug

              , newAuthzUrl: args._acmeUrls.newAuthz
              , newCertUrl: args._acmeUrls.newCert

              , accountKeypair: RSA.import(account.keypair)
              , domainKeypair: domainKeypair
              , domains: args.domains
              , challengeType: args.challengeType
              };

              //
              // IMPORTANT
              //
              // setChallenge and removeChallenge are handed defaults
              // instead of args because getChallenge does not have
              // access to args
              // (args is per-request, defaults is per instance)
              //
              // Each of these fires individually for each domain,
              // even though the certificate on the whole may have many domains
              //
              certReq.setChallenge = function (domain, key, value, done) {
                log(args.debug, "setChallenge called for '" + domain + "'");
                var copy = utils.merge({ domains: [domain] }, args);
                copy = utils.merge(copy, le);
                utils.tplCopy(copy);

                // TODO need to save challengeType
                le.challenges[args.challengeType].set(copy, domain, key, value, done);
              };
              certReq.removeChallenge = function (domain, key, done) {
                log(args.debug, "removeChallenge called for '" + domain + "'");
                var copy = utils.merge({ domains: [domain] }, le);
                utils.tplCopy(copy);

                le.challenges[args.challengeType].remove(copy, domain, key, done);
              };

              log(args.debug, 'calling le.acme.getCertificateAsync', certReq.domains);

              return le.acme.getCertificateAsync(certReq).then(utils.attachCertInfo);
            });
          }).then(function (results) {
            // { cert, chain, privkey /*TODO, subject, altnames, issuedAt, expiresAt */ }

            args.certs = results;
            // args.pems is deprecated
            args.pems = results;
            return le.store.certificates.setAsync(args).then(function () {
              return results;
            });
          });
        });
      }
      // Certificates
    , renewAsync: function (args, certs) {
        var renewableAt = core.certificates._getRenewableAt(args, certs);
        var err;
        //var halfLife = (certs.expiresAt - certs.issuedAt) / 2;
        //var renewable = (Date.now() - certs.issuedAt) > halfLife;

        log(args.debug, "(Renew) Expires At", new Date(certs.expiresAt).toISOString());
        log(args.debug, "(Renew) Renewable At", new Date(renewableAt).toISOString());

        if (!args.duplicate && Date.now() < renewableAt) {
          err = new Error(
              "[ERROR] Certificate issued at '"
            + new Date(certs.issuedAt).toISOString() + "' and expires at '"
            + new Date(certs.expiresAt).toISOString() + "'. Ignoring renewal attempt until '"
            + new Date(renewableAt).toISOString() + "'. Set { duplicate: true } to force."
          );
          err.code = 'E_NOT_RENEWABLE';
          return PromiseA.reject(err);
        }

        // Either the cert has entered its renewal period
        // or we're forcing a refresh via 'dupliate: true'
        log(args.debug, "Renewing!");

        // TODO fetch email address / accountId (accountBydomain) if not present
        // store.config.getAsync(args.domains).then(function (config) { /*...*/ });
        if (!args.domains || (args.domains.length || 0) <= 2) {
          // this is a renewal, therefore we should renewal ALL of the domains
          // associated with this certificate, unless args.domains is a list larger
          // than example.com,www.example.com
          // TODO check www. prefix
          args.domains = certs.altnames;
          if (Array.isArray(certs.domains) && certs.domains.length) {
            args.domains = certs.domains;
          }
        }

        return core.certificates.registerAsync(args);
      }
      // Certificates
    , _isRenewable: function (args, certs) {
        var renewableAt = core.certificates._getRenewableAt(args, certs);

        log(args.debug, "Check Expires At", new Date(certs.expiresAt).toISOString());
        log(args.debug, "Check Renewable At", new Date(renewableAt).toISOString());

        if (args.duplicate || Date.now() >= renewableAt) {
          log(args.debug, "certificates are renewable");
          return true;
        }

        return false;
      }
    , _getRenewableAt: function (args, certs) {
        return certs.expiresAt - (args.renewWithin || le.renewWithin);
      }
    , checkAsync: function (args) {
        var copy = utils.merge(args, le);
        utils.tplCopy(copy);

        // returns pems
        return le.store.certificates.checkAsync(copy).then(function (cert) {
          if (cert) {
            log(args.debug, 'checkAsync found existing certificates');
            return utils.attachCertInfo(cert);
          }

          log(args.debug, 'checkAsync failed to find certificates');
          return null;
        });
      }
      // Certificates
    , getAsync: function (args) {
        var copy = utils.merge(args, le);
        args = utils.tplCopy(copy);

        return core.certificates.checkAsync(args).then(function (certs) {
          if (!certs) {
            // There is no cert available
            return core.certificates.registerAsync(args);
          }

          if (core.certificates._isRenewable(args, certs)) {
            // it's time to renew the available cert
            certs.renewing = core.certificates.renewAsync(args, certs);
            if (args.waitForRenewal) {
              return certs.renewing;
            }
          }

          // return existing unexpired (although potentially stale) certificates when available
          // there will be an additional .renewing property if the certs are being asynchronously renewed
          return certs;
        }).then(function (results) {
          // returns pems
          return results;
        });
      }
    }

  };

  return core;
};

redpajama_set_name: RedPajamaGithub


text:
interface Iconfig {
    logging?: boolean;
    smartConvert?: boolean;
    searchId?: string;
    recordType?: string;
    filterExpression?: any;
    columns?: string;
    start?: number;
    end?: number;
    maxUnitsUsage?: number;
}
declare module jSuite {
    function getVersion(): string;
    function setLogging(toggle: boolean): void;
    function getRoleCenter(): any;
    function getUser(): any;
    function getScriptParameter(paramName: string): any;
    function getDeploymentId(): any;
    function getScriptId(): any;
    function isProduction(): any;
    function clearSublist(transaction: nlobjRecord, listType: string): void;
    function getCompanyPreference(paramName: string): any;
    function roundNum(num: number, length: number): number;
    function isNumber(n: any): boolean;
    function runSearch(config?: Iconfig): any;
    function lookupField(dataIn: any): string;
    function submitField(dataIn: any): any;
    function asyncLookupField(config: any, callback: any): void;
    function asyncSubmitField(config: any): JQueryXHR;
    function audit(title: string, message: string): void;
    function debug(title: string, message: string): void;
    function error(title: string, message: string): void;
    function emergency(title: string, message: string): void;
}


text:
<?php
	class Controller_spritecomics_delete_comment extends Controller_main
	{
		public function delete_index($id = null)
		{
			$redirect_url = $this->request->getBaseURL().'spritecomics/gallery/';

			if( ! $this->_current_member->isConnected())
			{
				$this->response->error(Library_i18n::get('errors.global.need_connection'), 401);
				return;
			}

			$comment = Model_Comments::getById($id);

			if(empty($comment))
			{
				$this->response->error(Library_i18n::get('spritecomics.delete.comment.errors.not_found_in_db'), 404);
				return;
			}

			$file = $comment->getFile();

			$owner						=	$comment->getUser();

			$can_remove_other_comments	=	$this->_current_member->can(Model_UsersGroups::PERM_REMOVE_OTHERS_COMMENTS);

			if( ! $this->_current_member->equals($owner) && ! $can_remove_other_comments)
			{
				$this->response->error(Library_i18n::get('spritecomics.delete.comment.errors.forbidden'), 403);
				return;
			}

			//Not forget to update the feed for followers
            $feed = Model_Feed::getGalleryFeed($this->_current_member->getId(), $file->getId(), Model_Feed::OBJECT_IS_A_COMMENTARY);
            Model_Feed::delete($feed);

			Model_Comments::delete($comment);

			$redirect_url .= 'details/'.$file->getId();

			Library_Messages::store(Library_i18n::get('spritecomics.delete.comment.success'), Library_Messages::TYPE_SUCCESS);
			$this->response->redirect($redirect_url, 200);
		}
	}


text:
require 'spec_helper'

RSpec.describe SessionsHelper, type: :helper do
  pending "add some examples to (or delete) #{__FILE__}"
end


text:
package org.araneaframework.http.filter;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.araneaframework.InputData;
import org.araneaframework.OutputData;
import org.araneaframework.Path;
import org.araneaframework.core.Assert;
import org.araneaframework.framework.core.BaseFilterService;
import org.araneaframework.http.HttpInputData;
import org.araneaframework.http.extension.ExternalResource;
import org.araneaframework.http.extension.ExternalResourceInitializer;
import org.araneaframework.http.util.ServletUtil;
import org.araneaframework.http.util.URLUtil;

/**
 * @author "Toomas Römer" <toomas@webmedia.ee>
 * @author Jevgeni Kabanov (ekabanov@araneaframework.org)
 */
public class StandardFileImportFilterService extends BaseFilterService {

  private static final Log LOG = LogFactory.getLog(StandardFileImportFilterService.class);

  private static boolean isInitialized = false;

  private static ExternalResource resources;

  public static final String OVERRIDE_PREFIX = "override";

  public static final String FILE_IMPORTER_NAME = "fileimporter";

  protected long cacheHoldingTime = 3600000;

  private synchronized void initialize() {
    if (!isInitialized) {
      initialize(getEnvironment().requireEntry(ServletConfig.class).getServletContext());
    }
  }

  private synchronized static void initialize(ServletContext context) {
    if (!isInitialized) {
      resources = new ExternalResourceInitializer().getResources(context);
      isInitialized = true;
    }
  }

  public void setCacheHoldingTime(Long cacheHoldingTime) {
    Assert.notNullParam(this, cacheHoldingTime, "cacheHoldingTime");
    this.cacheHoldingTime = cacheHoldingTime;
  }

  @Override
  protected void action(Path path, InputData input, OutputData output) throws Exception {
    initialize();

    HttpInputData input2 = (HttpInputData) input;
    String uri = URLUtil.normalizeURI(input2.getPath());

    if (uri == null || !uri.startsWith(FILE_IMPORTER_NAME)) {
      this.childService._getService().action(path, input2, output);
      return;
    }

    input2.pushPathPrefix(FILE_IMPORTER_NAME);

    String target = input2.getSimplePath();

    boolean isGroup = target != null && resources.getGroupByName(target) != null;

    HttpServletResponse response = ServletUtil.getResponse(output);
    List<String> filesToLoad = new ArrayList<String>();

    try {
      if (target != null) {
        if (!isGroup && resources.isAllowedFile(target)) {
          setHeaders(response, resources.getContentType(target));
          filesToLoad.add(target);

        } else if (isGroup) {
          Map<String, String> group = resources.getGroupByName(target);

          if (group != null && !group.isEmpty()) {
            Map.Entry<String, String> entry = group.entrySet().iterator().next();
            setHeaders(response, entry.getValue());
            filesToLoad.addAll(group.keySet());
          } else {
            LOG.warn("Unexistent group specified for file importing, " + target);
            throw new FileNotFoundException();
          }
        }

        loadFiles(filesToLoad, response.getOutputStream());
      }
    } catch (FileNotFoundException e) {
      response.sendError(HttpServletResponse.SC_NOT_FOUND, "Imported file or group '" + target + "' not found.");
    }
  }

  private void setHeaders(HttpServletResponse response, String contentType) {
    response.setHeader("Cache-Control", "max-age=" + (cacheHoldingTime / 1000));
    response.setDateHeader("Expires", System.currentTimeMillis() + cacheHoldingTime);
    response.setContentType(contentType);
  }

  private void loadFiles(List<String> files, OutputStream out) throws Exception {
    ServletContext context = getEnvironment().requireEntry(ServletContext.class);

    for (String fileName : files) {
      // first we try load an override
      URL fileURL = resolveFileURL(context, fileName);
      InputStream fileInputStream = URLUtil.getFileStream(fileURL, fileName);

      if (fileInputStream == null) {
        if (LOG.isWarnEnabled()) {
          LOG.warn("Unable to locate resource '" + fileName + "'");
        }
        throw new FileNotFoundException("Unable to locate resource '" + fileName + "'");
      }

      try {
        IOUtils.copy(fileInputStream, out);
      } finally {
        IOUtils.closeQuietly(fileInputStream);
      }
    }
  }

  protected URL resolveFileURL(ServletContext context, String fileName) throws MalformedURLException {
    // first we try load an override
    URL fileURL = context.getResource("/" + OVERRIDE_PREFIX + "/" + fileName);
    if (fileURL == null) {
      fileURL = context.getResource("/" + fileName);
    }

    if (fileURL == null) { // fall-back to the original
      fileURL = getClass().getClassLoader().getResource(fileName);
    } else if (LOG.isDebugEnabled()) {
      LOG.debug("Serving override of file '" + fileName + "'" + " from context path resource '" + fileURL.getFile()
          + "'.");
    }

    return fileURL;
  }
}


text:
@interface GJGCChatFriendDataSourceManager : GJGCChatDetailDataSourceManager

@end


text:
import requests
import data_model as dm

def query_list(queries, tax_id='9606', fields='sym'):
    results = []
    for q in queries:
        results.append(query(q, tax_id))
    return results

def query_batch(query_string, tax_id='9606', scopes="symbol, entrezgene, alias, uniprot", fields="symbol, entrezgene"):
    data = {'species': tax_id,
            'scopes': scopes,
            'fields': fields,
            'q': query_string}
    r = requests.post('http://mygene.info/v3/query', data)
    json = r.json()
    return json

def query(q, tax_id='9606', entrezonly=True):
    if entrezonly:
        r = requests.get('http://mygene.info/v3/query?q='+q+'&species='+tax_id+'&entrezonly=true')
    else:
        r = requests.get('http://mygene.info/v3/query?q='+q+'&species='+tax_id)
    result = r.json()
    result['query'] = q
    return result

def query_symbol(q, tax_id='9606'):
    return query_to_gene("symbol:" + q, tax_id)

def query_uniprot(q, tax_id='9606'):
    return query_to_gene("uniprot:" + q, tax_id)

def query_entrez_gene(q, tax_id='9606'):
    return query_to_gene("entrezgene:" + q, tax_id)

def query_ensemble(q, tax_id='9606'):
    return query_to_gene("ensemblgene:" + q, tax_id)

def query_alias(q, tax_id='9606'):
    return query_to_gene("alias:" + q, tax_id)

def query_to_gene(q, tax_id='9606'):
    hits = query(q, tax_id).get("hits")
    if hits and len(hits) > 0:
        hit = hits[0]
        gene = dm.Gene(hit.get('symbol'), hit.get('entrezgene'))
        return gene
    return False

def query_to_gene_all(q, tax_id='9606'):
    #r = requests.get('http://mygene.info/v3/query?q='+q+'&fields=symbol%2Centrezgene%2Censemblgene%2Cuniprot%2Calias&species='+tax_id+'&entrezonly=true')
    r = requests.get('http://mygene.info/v3/query?q='+q+'&species='+tax_id)
    r.raise_for_status()
    result = r.json()
    hits = result.get("hits")
    if hits and len(hits) > 0:
        hit = hits[0]
        gene = dm.Gene(hit.get('symbol'), hit.get('entrezgene'))
        print gene.symbol
        return gene
    return False

def query_standard_to_gene(q, tax_id='9606'):
    return query_symbol(q, tax_id) or query_entrez_gene(q, tax_id) or query_uniprot(q, tax_id) or query_ensemble(q, tax_id) or query_alias(q,tax_id)

def query_standard_to_gene_quick(q, tax_id='9606'):
    return query_to_gene_all(q,tax_id)

# returns a standardized gene symbol if found, otherwise returns None
def query_term_to_gene(q, tax_id='9606'):
    gene = query_to_gene_all(q,tax_id)
    #query_symbol(q, tax_id) or query_entrez_gene(q, tax_id) or query_uniprot(q, tax_id) or query_ensemble(q, tax_id) or query_alias(q,tax_id)
    if gene :
        return gene.symbol
    else :
        return None

def get_gene_symbol(q, node_id, taxon_id = '9606'):
    gene = query_standard_to_gene_quick(q, taxon_id)
      #  query_standard_to_gene(q, taxon_id)
    if gene :
        return dm.GeneNodeRelation(gene.symbol,gene.id, node_id)
    return False

#print query_list(['symbol:brca1','symbol:brca2'])


text:
This log4j2 appender plugin uses [AsyncHttpClient](https://github.com/AsyncHttpClient/async-http-client) to push logs in batches to Elasticsearch clusters.

Netty buffer based API guarantees lower memory allocation than [log4j2-elasticsearch-jest](https://github.com/rfoltyns/log4j2-elasticsearch/tree/master/log4j2-elasticsearch-jest).

Output is generated with FasterXML Jackson based [JacksonJsonLayout](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/JacksonJsonLayout.java).

## Maven

```xml
<dependency>
    <groupId>org.appenders.log4j</groupId>
    <artifactId>log4j2-elasticsearch-ahc</artifactId>
    <version>1.6.0-SNAPSHOT</version>
</dependency>
```
## Usage

Add `AHCHttp` to
* [`logj2.xml`](#example)
* or [log4j2.properties](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/test/resources/log4j2.properties)
* or [configure programmatically](#programmatic-config)

It's highly recommended to put this plugin behind `AsyncLogger`. See [log4j2.xml](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/test/resources/log4j2.xml) example.

##### Example
```xml
<Appenders>
    <Elasticsearch name="elasticsearchAsyncBatch">
        <IndexName indexName="log4j2"/>
        <JacksonJsonLayout>
            <PooledItemSourceFactory poolName="itemPool" itemSizeInBytes="1024" initialPoolSize="3000"/>
        </JacksonJsonLayout>
        <AsyncBatchDelivery batchSize="1000" deliveryInterval="10000" >
            <IndexTemplate name="log4j2" path="classpath:indexTemplate-7.json" />
            <AHCHttp serverUris="http://localhost:9200">
                <PooledItemSourceFactory poolName="batchPool" itemSizeInBytes="1024000" initialPoolSize="3"/>
            </AHCHttp>
        </AsyncBatchDelivery>
    </Elasticsearch>
</Appenders>
```

### AHCHttp Properties
| Name                | Type      | Required                                                         | Default                     | Description                                                                                |
|---------------------|-----------|------------------------------------------------------------------|-----------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| serverUris          | Attribute | no (MUST be specified by either `AHCHttp` or `ServiceDiscovery`) | None                        | List of semicolon-separated `http[s]://host:[port]` addresses of Elasticsearch nodes to connect with.                                                                                |
| connTimeout         | Attribute | no                                                               | 1000                        | Number of milliseconds before ConnectException is thrown while attempting to connect.                                                                                |
| readTimeout         | Attribute | no                                                               | 0                           | Number of milliseconds before SocketTimeoutException is thrown while waiting for response bytes.                                                                                |
| maxTotalConnections | Attribute | no                                                               | 8                           | Number of connections available.                                                                                |
| ioThreadCount       | Attribute | no                                                               | No. of available processors | Number of Netty `EventLoop`s.                                                                                |
| gzipCompression     | Attribute | no                                                               | False                       | If `true`, force GZIP.                                                                                |
| itemSourceFactory   | Element   | yes                                                              | None                        | `ItemSourceFactory` used to create wrappers for batch requests. `PooledItemSourceFactory` and it's extensions can be used.                                                                                |
| auth                | Element   | no                                                               | None                        | Security config. [Security](#pem-cert-config)                                                                                |
| serviceDiscovery    | Element   | no                                                               | None                        | Service discovery config. [ServiceDiscovery](#service-discovery)                                                                                |
| clientAPIFactory    | Element   | no                                                               | `ElasticsearchBulk`         | Batch API factory. [ElasticsearchBulk](#elasticsearchbulk)                                                                                |
| name                | Attribute | No                                                               | `AHCHttp`                   | Metric component name                                                                                |
| metricConfig        | Element[] | No                                                               | Disabled `MetricConfig`(s)  | `Metrics` supported by this component:
- `serverTookMs`
- `itemsSent`
- `itemsDelivered`
- `itemsFailed`
- `backoffApplied`
- `batchesFailed`
-`failoverTookMs`
-`responseBytes`
 - `initial`
- `total`
- `available`
- `noSuchElementCaught`
- `resizeAttempts`
See `Metrics` docs below for more info |

### Service Discovery

Since 1.5, service discovery can be configured using `ServiceDiscovery` tag. Once defined, batches and setup operations will be executed against addresses retrieved from [Nodes API](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster-nodes-info.html).

Supported across all versions of Elasticsearch.

Custom [`ServiceDiscoveryFactory`](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/discovery/ServiceDiscoveryFactory.java) can be defined to integrate with other address sources.

| Name            | Type      | Required | Default                | Description                                                                                |
|-----------------|-----------|----------|------------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| nodesFilter     | Attribute | no       | `_all`                 | Nodes filter as defined in [Elasticsearch 7.x documentation](https://www.elastic.co/guide/en/elasticsearch/reference/7.x/cluster.html#cluster-nodes) (`_nodes/<nodesFilter>/http`).                                                                              |
| serverUris      | Attribute | no       | inherited from AHCHttp | List of semicolon-separated address sources.                                                                                |
| connTimeout     | Attribute | no       | 500                    | Number of milliseconds before ConnectException is thrown while attempting to connect.                                                                                |
| readTimeout     | Attribute | no       | 1000                   | Number of milliseconds before SocketTimeoutException is thrown while waiting for response bytes.                                                                                |
| targetScheme    | Attribute | no       | http                   | Scheme of resolved addresses passed to AHCHttp client.                                                                                |
| refreshInterval | Attribute | no       | 30000                  | Number of milliseconds between the end of previous request and start of new one.                                                                                |
| configPolicies  | Attribute | no       | serverList,security    | List of comma-separated config policies to apply. Available policies: `shared`, `none`, `serverList`, `security`. See [Config Policies](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc#config-policies) for more details. |

Example:
```xml
<Elasticsearch>
    <AsyncBatchDelivery>
        <AHCHttp>
            <ServiceDiscovery serverUris="http://localhost:9250"
                              refreshInterval="10000"
                              nodesFilter="ingest:true" />
        </AHCHttp>
    </AsyncBatchDelivery>
</Elasticsearch>
```

#### Config policies

`ServiceDiscovery` can inherit parts of AHCHttp client config or even reuse whole client. By default, `AHCHttp.serverUris` and `Security` settings are reused during creation of new `ServiceDiscovery` HTTP client. Following policies are available:
* `serverList` - create a new client, inherit `AHCHttp.serverUris`
* `security` - create a new client, inherit `AHCHttp.auth`
* `shared` - reuse AHCHttp batch client (ensure enough connections!)
* `none` - create a new client, don't inherit anything

`serverList` and `security` can be used together. New client will inherit both config elements.

`shared` and `none` can only be used individually. They can't be mixed with other policies.

Example:
```xml
<Elasticsearch>
    <AsyncBatchDelivery>
        <AHCHttp>
            <Security/>
            <ServiceDiscovery serverUris="https://localhost:9200"
                              refreshInterval="10000"
                              targetScheme="https"
                              configPolicies="security" />
        </AHCHttp>
    </AsyncBatchDelivery>
</Elasticsearch>
```

NOTE: Config policies were added for convenience. Recommended configuration should contain `configPolices=none`, `serverUris` configured ONLY for `ServiceDiscovery` and separate `Security` configs if needed.

### Client API Factory

Since 1.6, [ClientAPIFactory](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/ClientAPIFactory.java) can be configured to further customize the output and runtime capabilities of batches and batch items. [ElasticsearchBulk](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/ElasticsearchBulkPlugin.java) is used by default.

#### ElasticsearchBulk

Default.

Configures builders and serializers for:
* [BatchRequest](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/BatchRequest.java) - `/_bulk` request (batch)
* [IndexRequest](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/IndexRequest.java) - document (batch item)

```xml
<AHCHttp>
    <ElasticsearchBulk/>
</AHCHttp>
```

#### ElasticsearchBulk Properties
| Name        | Type      | Required | Default          | Description                                                                                |
|-------------|-----------|----------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| mappingType | Attribute | no       | `null` since 1.6 | Name of index mapping type to use. Applicable to Elasticsearch <8.x. See [removal of types](https://www.elastic.co/guide/en/elasticsearch/reference/7.17/removal-of-types.html).                                            |
| filterPath  | Attribute | no       | `null`           | If not empty, `filter_path` query param will be added to Bulk API requests. See [Response Filtering](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#common-options-response-filtering) |

### ElasticsearchDataStream

Since 1.6, [Data streams](https://www.elastic.co/guide/en/elasticsearch/reference/current/data-streams.html) are supported with `DataStream` setup operation.

Configures `BatchOperations`-level builders and serializers for:
* [DataStreamBatchRequest](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/DataStreamBatchRequest.java) - `/<indexName>/_bulk` request (batch)
* [DataStreamItem](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/DataStreamItem.java) - document (batch item)

#### ElasticsearchDataStream Properties
| Name        | Type      | Required | Default          | Description                                                                                |
|-------------|-----------|----------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| filterPath  | Attribute | no       | `null`           | If not empty, `filter_path` query param will be added to Bulk API requests. See [Response Filtering](https://www.elastic.co/guide/en/elasticsearch/reference/current/common-options.html#common-options-response-filtering) |

If `ILMPolicy` is used, `ILMPolicy.createBootstrapIndex` MUST be set to `false`. This behaviour will be changed in future releases - bootstrap index will be created separately, similar to other setup operations.

With `JacksonJsonLayout`, use [LogEventDataStreamMixIn](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/json/jackson/LogEventDataStreamMixIn.java) or equivalent to serialize `LogEvent.timeMillis` as `@timestamp`.

```xml
<Elasticsearch>
    <JacksonJsonLayout>
        <JacksonMixIn targetClass="org.apache.logging.log4j.core.LogEvent"
                      mixInClass="org.appenders.log4j2.elasticsearch.json.jackson.LogEventDataStreamMixIn" />
    </JacksonJsonLayout>
    <AsyncBatchDelivery>
        <ILMPolicy createBootstrapIndex="false" />
        <AHCHttp>
            <ElasticsearchDataStream />
        </AHCHttp>
    </AsyncBatchDelivery>
</Elasticsearch>
```

### Programmatic config
See [programmatic config example](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/test/java/org/appenders/log4j2/elasticsearch/hc/smoke/SmokeTest.java).

### Delivery frequency
See [delivery frequency](../log4j2-elasticsearch-core#delivery-frequency)

### Message output
See [available output configuration methods](../log4j2-elasticsearch-core#message-output)

### Failover
See [failover options](../log4j2-elasticsearch-core#failover)

### Backoff
Since 1.4, `BackoffPolicy` can provide additional fail-safe during delivery.
In the event of cluster failure or slowdown, when policy gets triggered, batch will be automatically redirected to configured `FailoverPolicy` (see [failover options](../log4j2-elasticsearch-core#failover)).

#### BatchLimitBackoffPolicy

`BatchLimitBackoffPolicy` is a simple `BackoffPolicy` based on a number of currently processed batches (batches that arrived at the `AHCHttp` batch listener). Every arriving batch will increase the "in-flight count" by 1 if `maxBatchesInFlight` is not exceeded. Every response to a batch request decreases "in-flight count" by 1. Every batch that arrives when `maxBatchesInFlight` limit is met is redirected to configured `FailoverPolicy`.

:warning: **See [failover options](../log4j2-elasticsearch-core#failover) for available `FailoverPolicy` implementations. If no `FailoverPolicy` is configured, batch will be lost!**

| Name               | Type      | Required | Default | Description                                                                                |
|--------------------|-----------|----------|---------|-------------------------------------------------------------------------------------------------|
| maxBatchesInFlight | Attribute | no       | 8       | Maximum number of batches delivered simultaneously (including the ones waiting for a response). |

Example:
``` xml
<Elasticsearch ...>
    <AsyncBatchDelivery ... >
        ...
        <AHCHttp ...>
            ...
            <BatchLimitBackoffPolicy maxBatchesInFlight="4" />
            ...
        </AHCHttp>
    </AsyncBatchDelivery>
</Elasticsearch>
```

### Index name
See [index name](../log4j2-elasticsearch-core#index-name) or [index rollover](../log4j2-elasticsearch-core#index-rollover)

### Index template

Since 1.6, this module is compatible with Elasticsearch 8.x by default. Use `apiVersion` for older clusters.

See [index template docs](../log4j2-elasticsearch-core#index-template)

### SSL/TLS
Can be configured using `Security` tag:

#### PEM cert config
```xml
<AHCHttp serverUris="https://localhost:9200" >
    <Security>
        <BasicCredentials username="admin" password="changeme" />
        <PEM keyPath="${sys:pemCertInfo.keyPath}"
             keyPassphrase="${sys:pemCertInfo.keyPassphrase}"
             clientCertPath="${sys:pemCertInfo.clientCertPath}"
             caPath="${sys:pemCertInfo.caPath}" />
    </Security>
</AHCHttp>
```

#### JKS cert config
```xml
<AHCHttp serverUris="https://localhost:9200" >
    <Security>
        <BasicCredentials username="admin" password="changeme" />
        <JKS keystorePath="${sys:jksCertInfo.keystorePath}"
             keystorePassword="${sys:jksCertInfo.keystorePassword}"
             truststorePath="${sys:jksCertInfo.truststorePath}"
             truststorePassword="${sys:jksCertInfo.truststorePassword}" />
    </Security>
</AHCHttp>
```

### Compatibility matrix

| Feature/Version  | 2.x        | 5.x        | 6.x        | 7.x        | 8.x        |
|------------------|------------|------------|------------|------------|------------|
| IndexTemplate    | Yes        | Yes        | Yes        | Yes        | Yes        |
| BasicCredentials | Yes        | Yes        | Yes        | Yes        | Yes        |
| JKS              | Yes        | Not tested | Not tested | Not tested | Not tested |
| PEM              | Not tested | Yes        | Yes        | Yes        | Yes        |

## Pluggable JCTools

See [Pluggable JCTools](../log4j2-elasticsearch-core#pluggable-jctools)

JVM params:

| Param                                    | Type    | Default |
|------------------------------------------|---------|---------|
| -Dappenders.BatchRequest.jctools.enabled | boolean | true    |
| -Dappenders.BatchRequest.initialSize     | int     | 10000   |

## Metrics

See [Core Metrics](../log4j2-elasticsearch-core#metrics) for detailed documentation.

### Measured HC components

All [Measured Core components](../log4j2-elasticsearch-core#measured-core-components) and:

[AHCHttp](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/AHCHttp.java):
* itemsSent `Count`: number of items sent to cluster
* itemsDelivered `Count`: number of items successfully delivered to cluster
* itemsFailed `Count`: number of items received by failure handler as a result of cluster response or cluster unavailability
* backoffApplied `Count`: number of items dropped due to back-off policy kicking in (still delivered to `FailoverPolicy` and counted as `itemsFailed`)
* batchesFailed `Count`: number of batches received by failure handler as a result of cluster response or cluster unavailability
* serverTookMs `Max`: maximum time spent on cluster side
* failoverTookMs `Max`: maximum time spent handling failover as a result of cluster response, cluster unavailability or back-off policy
* all [GenericItemSourcePool](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/GenericItemSourcePool.java) metrics
* all [HttpClient](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/HttpClient.java) metrics

Example:
```xml
<AHCHttp name="some-sensible-name" serverUris="https://localhost:9200" >
    <Metrics>
        <Count name="itemsSent" />
        <Count name="itemsDelivered" />
        <Count name="itemsFailed" />
        <Count name="backoffApplied" />
        <Count name="batchesFailed" />
        <Max name="serverTookMs" />
        <Max name="failoverTookMs" />
    </Metrics>
</AHCHttp>
```

[ServiceDiscovery](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/ahc/discovery/AHCServiceDiscovery.java):
* all [GenericItemSourcePool](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-core/src/main/java/org/appenders/log4j2/elasticsearch/GenericItemSourcePool.java) metrics
* all [HttpClient](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/HttpClient.java) metrics

Example:
```xml
<AHCHttp name="some-sensible-name" serverUris="https://localhost:9200" >
    <ServiceDiscovery name="another-sensible-name"
                      serverUris="https://localhost:9200"
                      targetScheme="https"
                      refreshInterval="10000"
                      nodesFilter="ingest:true"
                      policies="none">
        <Count name="available" />
        <Count name="connectionsActive" />
    </ServiceDiscovery>
</AHCHttp>
```

[HttpClient](https://github.com/rfoltyns/log4j2-elasticsearch/blob/master/log4j2-elasticsearch-ahc/src/main/java/org/appenders/log4j2/elasticsearch/hc/HttpClient.java). Actually, `HttpClient` metrics at respective level (`AHCHttp` or `ServiceDiscovery`):
* connectionsActive `Count`- number of active connections
* connectionsIdle `Count`- number of idle connections
* connectionsTotal `Count`- number of total connections

Example:
```xml
<AHCHttp name="some-sensible-name" serverUris="https://localhost:9200" >
    <Metrics>
        <Count name="connectionsIdle" />
        <Count name="connectionsTotal" />
    </Metrics>
</AHCHttp>
```

More metrics will become available in future releases. [![contributions welcome](https://img.shields.io/badge/contributions-welcome-brightgreen.svg?style=flat)](https://github.com/rfoltyns/log4j2-elasticsearch)

## Dependencies

Be aware that following jars may have to be provided by user for this library to work:

* Netty: `io.netty:netty-buffer`
* Jackson FasterXML: `com.fasterxml.jackson.core:jackson-core,jackson-databind,jackson-annotations`
* Jackson FasterXML Afterburner module if `JacksonJsonLayout:afterburner=true`: `com.fasterxml.jackson.module:jackson-module-afterburner`
* Log4j2: `org.apache.logging.log4j:log4-api,log4j-core`
* Disruptor (if using `AsyncLogger`): `com.lmax:disruptor`
* Bouncy Castle (if using `Security`): `org.bouncycastle:bcprov-jdk15on,bcpkix-jdk15on`

Visit `pom.xml` for a full list of dependencies.


text:
/**
 * Internal function used by the Tween Builder to create a function that will return
 * the given value from the source.
 *
 * @function Phaser.Tweens.Builders.GetNewValue
 * @since 3.0.0
 *
 * @param {any} source - The source object to get the value from.
 * @param {string} key - The property to get from the source.
 * @param {any} defaultValue - A default value to return should the source not have the property set.
 *
 * @return {function} A function which when called will return the property value from the source.
 */
var GetNewValue = function (source, key, defaultValue)
{
    var valueCallback;

    if (source.hasOwnProperty(key))
    {
        var t = typeof(source[key]);

        if (t === 'function')
        {
            valueCallback = function (target, targetKey, value, targetIndex, totalTargets, tween)
            {
                return source[key](target, targetKey, value, targetIndex, totalTargets, tween);
            };
        }
        else
        {
            valueCallback = function ()
            {
                return source[key];
            };
        }
    }
    else if (typeof defaultValue === 'function')
    {
        valueCallback = defaultValue;
    }
    else
    {
        valueCallback = function ()
        {
            return defaultValue;
        };
    }

    return valueCallback;
};

module.exports = GetNewValue;


text:
<?php

namespace Mcevent\Service\Accounts;

use Contentinum\Service\WebsiteServiceFactory;
use ContentinumComponents\Mapper\Worker;
use Zend\Config\Config;

class LocationServiceFactory extends WebsiteServiceFactory
{

    /**
     * Cache key page table
     *
     * @var string
     */
    const CONTENTINUM_DATABASE = 'mcevent_location';

    /**
     * Name cache factory
     *
     * @var string
     */
    const CONTENTINUM_CACHE = 'mcwork_cache_data';

    protected function queryDbCacheResult($config, $sl)
    {
        $result = array();
        $cache = $sl->get(static::CONTENTINUM_CACHE);
        $key = $config['cache'];
        if (! ($result = $cache->getItem($key))) {
            $worker = new Worker($sl->get($config['entitymanager']));

            $entries = $worker->getStorage()
                ->getRepository($config['entity'])
                ->findBy(array(
                'eventLocation' => 1
            ), array(
                'organisation' => 'ASC'
            ));

            $tmp = array();
            foreach ($entries as $entry) {
                $str = '';
                if (strlen($entry->organisationExt) > 1){
                    $str = ' (' . $entry->organisationExt . ')';
                }
                $tmp[$entry->id] = array(
                    'name' => $entry->organisation . $str
                );
            }
            $result = new Config($tmp);
            if (isset($config['savecache']) && true === $config['savecache']) {
                $cache->setItem($key, $result);
            }
        }
        return $result;
    }
}


text:
{% extends "admin.html" %}

{% block style %}

{% endblock %}

{%- macro eventName(event) %}
    {% if '.' in event.name %}
        {{ _('trigger.' + event.name.split('.')[0]+'_sub', sub=event.name.split('.')[-1]) }}
    {% else %}
        {{ _('trigger.' + event.name) }}
    {% endif %}
{%- endmacro %}

{% block content %}

{{ _('events.listtitle') }}

{{ _('events.info') }}

    {%- if definitions==0 %}

{{ _('events.nodefinitionfound') }}

    {%- endif %}
    <form method="post" action="">

{{ _('events.name') }}

{{ _('events.possible') }}

            {%- for event in events %}

{{ eventName(event) }}

{{ event.getHandlers()|count}} / {{ event.getHandlerList()|count }}

{{ _('event.handler') }}

{{ _('event.parameters') }}

                    {%- if event.getHandlerList()|count>0 %}
                    <button class="add" type="submit" name="action" value="createhandler_{{ event.name }}" title="{{ _('event.addtitle') }}"></button>
                    {%- endif %}

                    {%- for handler in event.getHandlers() %}

{{ loop.index }}.

{{ _(handler.handler) }}

{{ handler.parameters|replace('\n', '
')|safe }}

                        <button type="submit" name="action" value="deletehandler_{{ handler.id }}" title="{{ _('event.deletetitle') }}" onclick="return questionDel()"></button>
                        <button type="submit" name="action" value="edithandler_{{ handler.id }}" title="{{ _('handler.edittitle') }}"></button>
                        <input type="hidden" value="{{ handler.id }} " name="position_{{ event.name }}"/>

                    {%- endfor %}

                    {%- if events|count==0 %}

{{ _('handler.notdefined') }}

                    {%- endif %}

            {%- endfor %}

            <button type="submit" name="action" value="updateorder" id="orderchange" class="save" style="display:none"> {{ _('events.updateorder') }}</button>

        <input type="hidden" name="form_id" value="admin.events.overview"/>
    </form>
{% endblock %}

{% block script_end %}
    {{ super() }}
    function questionDel(){
        return confirm('{{ _('events.delete') }}');
    }
    $(function() {$('div[id^="sortable_"]').sortable({update: function(event, ui){$('#orderchange').show()}});});

    function details(id, obj){
        $('#details_'+id).toggle();
        if ($(obj).hasClass('expanded')){
            $(obj).removeClass('expanded');
        }else{
            $(obj).addClass('expanded');
        }
        return false;
    }
{% endblock %}


text:
import * as Client from "bitcoin-core";

export function connectToBC(): any {
  return new Client(
    {
      network: "regtest",
      username: "username",
      password: "password",
      port: 16593
    }
  );
}


text:
package onlythree.imanager.logic.commands;

import java.util.List;

import onlythree.imanager.commons.core.Messages;
import onlythree.imanager.commons.exceptions.IllegalValueException;
import onlythree.imanager.logic.commands.exceptions.CommandException;
import onlythree.imanager.model.task.ReadOnlyTask;
import onlythree.imanager.model.task.Task;

//@@author A0135998H
/**
 * Mark an existing task in the task list as "done".
 */
public class DoneCommand extends Command {

    public static final String COMMAND_WORD = "done";

    public static final String MESSAGE_USAGE = COMMAND_WORD + ": Marks an existing task "
            + "by the index number used in the last task listing.\n"
            + "Parameters: INDEX (must be a positive integer)\n"
            + "Example: " + COMMAND_WORD + " 1";

    public static final String MESSAGE_MARK_TASK_SUCCESS = "Marked Task: %1$s";

    private final int filteredTaskListIndex;

    /**
     * @param filteredTaskListIndex the index of the task in the filtered task list to edit
     */
    public DoneCommand(int filteredTaskListIndex) {
        assert filteredTaskListIndex > 0;

        // converts filteredTaskListIndex from one-based to zero-based.
        this.filteredTaskListIndex = filteredTaskListIndex - 1;
    }

    @Override
    public CommandResult execute() throws CommandException {
        List<ReadOnlyTask> lastShownList = model.getFilteredTaskList();

        if (filteredTaskListIndex >= lastShownList.size()) {
            throw new CommandException(Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX);
        }
        ReadOnlyTask taskToEdit = lastShownList.get(filteredTaskListIndex);

        Task editedTask;
        try {
            editedTask = new Task(taskToEdit);
        } catch (IllegalValueException e) {
            throw new AssertionError("Copying a valid task should always result in a valid task");
        }
        /* switch status of task */
        editedTask.setComplete(!(taskToEdit.isComplete()));

        model.updateTask(filteredTaskListIndex, editedTask);

        model.updateFilteredListToShowDone();
        return new CommandResult(String.format(MESSAGE_MARK_TASK_SUCCESS, taskToEdit));
    }

}


text:
import argparse
import os

import numpy as np
import torch as t

from utils.batch_loader import BatchLoader
from utils.parameters import Parameters
from model.rvae import RVAE

if __name__ == '__main__':

    assert os.path.exists('trained_RVAE'), \
        'trained model not found'

    parser = argparse.ArgumentParser(description='Sampler')
    parser.add_argument('--use-cuda', type=bool, default=True, metavar='CUDA',
                        help='use cuda (default: True)')
    parser.add_argument('--num-sample', type=int, default=10, metavar='NS',
                        help='num samplings (default: 10)')

    args = parser.parse_args()

    batch_loader = BatchLoader('')
    parameters = Parameters(batch_loader.max_word_len,
                            batch_loader.max_seq_len,
                            batch_loader.words_vocab_size,
                            batch_loader.chars_vocab_size)

    rvae = RVAE(parameters)
    rvae.load_state_dict(t.load('trained_RVAE'))
    if args.use_cuda:
        rvae = rvae.cuda()

    for iteration in range(args.num_sample):
        seed = np.random.normal(size=[1, parameters.latent_variable_size])
        result = rvae.sample(batch_loader, 50, seed, args.use_cuda)
        print(result)
        print()


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>User</title>
<meta name="date" content="2015-04-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD

com.CMPUT301W15T02.teamtoapp.Model

Class User

java.lang.Object

com.CMPUT301W15T02.teamtoapp.Model.User

public class User
extends java.lang.Object

User class consists of the name of the user, the type of user
 (claimant or approver), and a personal list of tags.

Method Summary

Methods

Modifier and Type
Method and Description

void
addListener(Listener listener)

Add listener

void
addTag(Tag tag)

Adds a tag to the users personal list of tags only if it is unique to avoid duplicates

double
getHomeLatitude()

double
getHomeLongitude()

static User
getInstance()

Ensure singleton is initialized

java.lang.String
getName()

Tag
getTagByID(java.lang.String tagID)

java.util.ArrayList<Tag>
getTags()

boolean
getType()

void
notifyListeners()

Notify listeners when need to update any changes made to user

void
removeListener(Listener listener)

Remove listener

void
removeTag(Tag tag)

Removes a tag from the users personal list of tags only if it exists

void
renameTag(Tag tag,
         java.lang.String newText)

Renames a tag

void
setHomeLatitude(double homeLatitude)

void
setHomeLongitude(double homeLongitude)

void
setName(java.lang.String name)

void
setTags(java.util.ArrayList<Tag> tags)

void
setType(boolean type)

Sets the type of user, false is approver mode, true for claimant

static void
setUser(User user)

static void
tearDownForTesting()

Methods inherited from class java.lang.Object

equals, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Method Detail

getInstance

public static User getInstance()

Ensure singleton is initialized

Returns:

instance

setUser

public static void setUser(User user)

getName

public java.lang.String getName()

setName

public void setName(java.lang.String name)

getType

public boolean getType()

setType

public void setType(boolean type)

Sets the type of user, false is approver mode, true for claimant

Parameters:

type -

getTags

public java.util.ArrayList<Tag> getTags()

getTagByID

public Tag getTagByID(java.lang.String tagID)

setTags

public void setTags(java.util.ArrayList<Tag> tags)

addTag

public void addTag(Tag tag)

Adds a tag to the users personal list of tags only if it is unique to avoid duplicates

Parameters:

tag -

removeTag

public void removeTag(Tag tag)

Removes a tag from the users personal list of tags only if it exists

Parameters:

tag -

renameTag

public void renameTag(Tag tag,
             java.lang.String newText)

Renames a tag

Parameters:

tag - The tag to be renamed

newText - The new name for the tag

getHomeLatitude

public double getHomeLatitude()

setHomeLatitude

public void setHomeLatitude(double homeLatitude)

getHomeLongitude

public double getHomeLongitude()

setHomeLongitude

public void setHomeLongitude(double homeLongitude)

notifyListeners

public void notifyListeners()

Notify listeners when need to update any changes made to user

addListener

public void addListener(Listener listener)

Add listener

Parameters:

listener -

removeListener

public void removeListener(Listener listener)

Remove listener

Parameters:

listener -

tearDownForTesting

public static void tearDownForTesting()

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV CLASS

NEXT CLASS

FRAMES

NO FRAMES

All Classes

SUMMARY:

NESTED |

FIELD |

CONSTR |

METHOD

DETAIL:

FIELD |

CONSTR |

METHOD


text:
<?php

namespace Fantoine\TranslationExtractorBundle\Translation\Factory\Handler;

use Fantoine\TranslationExtractorBundle\Translation\Factory\FactoryInterface;
use Fantoine\TranslationExtractorBundle\Translation\Factory\NamespaceFactory;

/**
 * Description of NamespaceHandler
 *
 * @author Fabien Antoine <fabien@fantoine.fr>
 */
class NamespaceHandler extends AbstractHandler
{
    /**
     * @param FactoryInterface $factory
     * @return string
     */
    public function getAstClass(FactoryInterface $factory) {
        return '\PHPParser_Node_Stmt_Namespace';
    }

    /**
     * @param FactoryInterface $factory
     * @param string $nodeAlias
     * @return \PHPParser_Node_Stmt|array|null
     */
    public function createExtractionValidation(FactoryInterface $factory, $nodeAlias)
    {
        if (! $factory instanceof NamespaceFactory) {
            return null;
        }
        return $this->parseCode(
            $this->getCode($factory, $nodeAlias)
        );
    }

    /**
     * @param NamespaceFactory $factory
     * @param string $nodeAlias
     * @return string
     */
    protected function getCode(NamespaceFactory $factory, $nodeAlias)
    {
        $code = '';

        $namespaces = $factory->getNamespaces();
        if (count($namespaces) > 0) {
            $code .= sprintf('
                // Check namespace
                $namespace = implode("\\\\", %s->name->parts);
                if (!preg_match(%s, $namespace)) {
                    return false;
                }
                ',
                $nodeAlias,
                implode(', $namespace) && !preg_match(', $this->escapeStringArray($namespaces))
            );
        }

        // Final return
        $code .= 'return true;';

        return $code;
    }
}


text:
var session = require('express-session')
var RedisStore = require('connect-redis')(session)
var logger = require('./log-manager')
var config = require('./config-manager').getConfig()

module.exports.initSession = initSession

function initSession(app) {
  // ttl: default to cookie maxAge or one day.  Unit is second.
  app.use(session({
    resave: false,
    saveUninitialized: false,
    store: new RedisStore({
      host: config.base.redis.host,
      port: config.base.redis.port
    }),
    secret: config.base.sessionSecret,
    logErrors: logger.error.bind(logger)
  }))
}


text:
silverstripe-piwik - SilverStripe Add-on for Piwik web analytics integration
==================

This SilverStripe Add-on integrates Piwik into the SilverStripe CMS.

Piwik is the leading open source web analytics platform. It's goal is to liberate web analytics. This Add-on does it's share on this great target.


text:
package org.semanticweb.elk.owl.predefined;

import org.semanticweb.elk.owl.interfaces.ElkClass;

/**
 * Factory for creating
 * <a href= "http://www.w3.org/TR/owl2-syntax/#Classes">built-in classes<a> in
 * the OWL 2 specification, such as {@code owl:Thing} and {@code owl:Nothing}.
 *
 * @author "Yevgeny Kazakov"
 *
 */
public interface PredefinedElkClassFactory {

	/**
	 * @return the {@link ElkClass} corresponding to {@code owl:Thing}
	 */
	ElkClass getOwlThing();

	/**
	 * @return the {@link ElkClass} corresponding to {@code owl:Nothing}
	 */
	ElkClass getOwlNothing();

}


text:
<?php
namespace LaravelRocket\Foundation\Repositories;

interface SingleKeyModelRepositoryInterface extends BaseRepositoryInterface
{
    /**
     * @return array
     */
    public function getPrimaryKey();

    /**
     * @param int $id
     *
     * @return \LaravelRocket\Foundation\Models\Base|null
     */
    public function find($id);

    /**
     * @param array       $ids
     * @param string|null $order
     * @param string|null $direction
     * @param bool        $reorder
     *
     * @return \LaravelRocket\Foundation\Models\Base[]|\Illuminate\Database\Eloquent\Collection
     */
    public function allByIds($ids, $order = null, $direction = null, $reorder = false);

    /**
     * @param array $ids
     *
     * @return int
     */
    public function countByIds($ids);

    /**
     * @param array       $ids
     * @param string|null $order
     * @param string|null $direction
     * @param int|null    $offset
     * @param int|null    $limit
     *
     * @return \LaravelRocket\Foundation\Models\Base[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByIds($ids, $order = null, $direction = null, $offset = null, $limit = null);

    /**
     * @param array $input
     *
     * @return \LaravelRocket\Foundation\Models\Base
     */
    public function create($input);

    /**
     * @param \LaravelRocket\Foundation\Models\Base $model
     * @param array                                 $input
     *
     * @return \LaravelRocket\Foundation\Models\Base
     */
    public function dryUpdate($model, $input);

    /**
     * @param \LaravelRocket\Foundation\Models\Base $model
     * @param array                                 $input
     *
     * @return \LaravelRocket\Foundation\Models\Base
     */
    public function update($model, $input);

    /**
     * @param \LaravelRocket\Foundation\Models\Base $model
     *
     * @return \LaravelRocket\Foundation\Models\Base
     */
    public function save($model);

    /**
     * @param \LaravelRocket\Foundation\Models\Base $model
     *
     * @return bool
     */
    public function delete($model);

    /**
     * @param int    $id
     * @param string $parentColumnName
     * @param string $targetColumnName
     * @param array  $list
     *
     * @return bool
     */
    public function updateMultipleEntries(int $id, string $parentColumnName, string $targetColumnName, array $list);

    /**
     * @param array  $filter
     * @param string $targetColumnName
     * @param array  $list
     *
     * @return bool
     */
    public function updateMultipleEntriesWithFilter(array $filter, string $targetColumnName, array $list);
}


text:
__version__ = 0.1

try:
    from bandsintown import Client
except:
    pass


text:
<?php

include_once('BCGColor.php');
include_once('BCGLabel.php');
include_once('BCGArgumentException.php');
include_once('BCGDrawException.php');

abstract class BCGBarcode {
    const COLOR_BG = 0;
    const COLOR_FG = 1;

    protected $colorFg, $colorBg;       // Color Foreground, Barckground
    protected $scale;                   // Scale of the graphic, default: 1
    protected $offsetX, $offsetY;       // Position where to start the drawing
    protected $labels = array();        // Array of BCGLabel
    protected $pushLabel = array(0, 0); // Push for the label, left and top

    /**
     * Constructor.
     */
    protected function __construct() {
        $this->setOffsetX(0);
        $this->setOffsetY(0);
        $this->setForegroundColor(0x000000);
        $this->setBackgroundColor(0xffffff);
        $this->setScale(1);
    }

    /**
     * Parses the text before displaying it.
     *
     * @param mixed $text
     */
    public function parse($text) {
    }

    /**
     * Gets the foreground color of the barcode.
     *
     * @return BCGColor
     */
    public function getForegroundColor() {
        return $this->colorFg;
    }

    /**
     * Sets the foreground color of the barcode. It could be a BCGColor
     * value or simply a language code (white, black, yellow...) or hex value.
     *
     * @param mixed $code
     */
    public function setForegroundColor($code) {
        if ($code instanceof BCGColor) {
            $this->colorFg = $code;
        } else {
            $this->colorFg = new BCGColor($code);
        }
    }

    /**
     * Gets the background color of the barcode.
     *
     * @return BCGColor
     */
    public function getBackgroundColor() {
        return $this->colorBg;
    }

    /**
     * Sets the background color of the barcode. It could be a BCGColor
     * value or simply a language code (white, black, yellow...) or hex value.
     *
     * @param mixed $code
     */
    public function setBackgroundColor($code) {
        if ($code instanceof BCGColor) {
            $this->colorBg = $code;
        } else {
            $this->colorBg = new BCGColor($code);
        }

        foreach ($this->labels as $label) {
            $label->setBackgroundColor($this->colorBg);
        }
    }

    /**
     * Sets the color.
     *
     * @param mixed $fg
     * @param mixed $bg
     */
    public function setColor($fg, $bg) {
        $this->setForegroundColor($fg);
        $this->setBackgroundColor($bg);
    }

    /**
     * Gets the scale of the barcode.
     *
     * @return int
     */
    public function getScale() {
        return $this->scale;
    }

    /**
     * Sets the scale of the barcode in pixel.
     * If the scale is lower than 1, an exception is raised.
     *
     * @param int $scale
     */
    public function setScale($scale) {
        $scale = intval($scale);
        if ($scale <= 0) {
            throw new BCGArgumentException('The scale must be larger than 0.', 'scale');
        }

        $this->scale = $scale;
    }

    /**
     * Abstract method that draws the barcode on the resource.
     *
     * @param resource $im
     */
    public abstract function draw($im);

    /**
     * Returns the maximal size of a barcode.
     * [0]->width
     * [1]->height
     *
     * @param int $w
     * @param int $h
     * @return int[]
     */
    public function getDimension($w, $h) {
        $labels = $this->getBiggestLabels(false);
        $pixelsAround = array(0, 0, 0, 0); // TRBL
        if (isset($labels[BCGLabel::POSITION_TOP])) {
            $dimension = $labels[BCGLabel::POSITION_TOP]->getDimension();
            $pixelsAround[0] += $dimension[1];
        }

        if (isset($labels[BCGLabel::POSITION_RIGHT])) {
            $dimension = $labels[BCGLabel::POSITION_RIGHT]->getDimension();
            $pixelsAround[1] += $dimension[0];
        }

        if (isset($labels[BCGLabel::POSITION_BOTTOM])) {
            $dimension = $labels[BCGLabel::POSITION_BOTTOM]->getDimension();
            $pixelsAround[2] += $dimension[1];
        }

        if (isset($labels[BCGLabel::POSITION_LEFT])) {
            $dimension = $labels[BCGLabel::POSITION_LEFT]->getDimension();
            $pixelsAround[3] += $dimension[0];
        }

        $finalW = ($w + $this->offsetX) * $this->scale;
        $finalH = ($h + $this->offsetY) * $this->scale;

        // This section will check if a top/bottom label is too big for its width and left/right too big for its height
        $reversedLabels = $this->getBiggestLabels(true);
        foreach ($reversedLabels as $label) {
            $dimension = $label->getDimension();
            $alignment = $label->getAlignment();
            if ($label->getPosition() === BCGLabel::POSITION_LEFT || $label->getPosition() === BCGLabel::POSITION_RIGHT) {
                if ($alignment === BCGLabel::ALIGN_TOP) {
                    $pixelsAround[2] = max($pixelsAround[2], $dimension[1] - $finalH);
                } elseif ($alignment === BCGLabel::ALIGN_CENTER) {
                    $temp = ceil(($dimension[1] - $finalH) / 2);
                    $pixelsAround[0] = max($pixelsAround[0], $temp);
                    $pixelsAround[2] = max($pixelsAround[2], $temp);
                } elseif ($alignment === BCGLabel::ALIGN_BOTTOM) {
                    $pixelsAround[0] = max($pixelsAround[0], $dimension[1] - $finalH);
                }
            } else {
                if ($alignment === BCGLabel::ALIGN_LEFT) {
                    $pixelsAround[1] = max($pixelsAround[1], $dimension[0] - $finalW);
                } elseif ($alignment === BCGLabel::ALIGN_CENTER) {
                    $temp = ceil(($dimension[0] - $finalW) / 2);
                    $pixelsAround[1] = max($pixelsAround[1], $temp);
                    $pixelsAround[3] = max($pixelsAround[3], $temp);
                } elseif ($alignment === BCGLabel::ALIGN_RIGHT) {
                    $pixelsAround[3] = max($pixelsAround[3], $dimension[0] - $finalW);
                }
            }
        }

        $this->pushLabel[0] = $pixelsAround[3];
        $this->pushLabel[1] = $pixelsAround[0];

        $finalW = ($w + $this->offsetX) * $this->scale + $pixelsAround[1] + $pixelsAround[3];
        $finalH = ($h + $this->offsetY) * $this->scale + $pixelsAround[0] + $pixelsAround[2];

        return array($finalW, $finalH);
    }

    /**
     * Gets the X offset.
     *
     * @return int
     */
    public function getOffsetX() {
        return $this->offsetX;
    }

    /**
     * Sets the X offset.
     *
     * @param int $offsetX
     */
    public function setOffsetX($offsetX) {
        $offsetX = intval($offsetX);
        if ($offsetX < 0) {
            throw new BCGArgumentException('The offset X must be 0 or larger.', 'offsetX');
        }

        $this->offsetX = $offsetX;
    }

    /**
     * Gets the Y offset.
     *
     * @return int
     */
    public function getOffsetY() {
        return $this->offsetY;
    }

    /**
     * Sets the Y offset.
     *
     * @param int $offsetY
     */
    public function setOffsetY($offsetY) {
        $offsetY = intval($offsetY);
        if ($offsetY < 0) {
            throw new BCGArgumentException('The offset Y must be 0 or larger.', 'offsetY');
        }

        $this->offsetY = $offsetY;
    }

    /**
     * Adds the label to the drawing.
     *
     * @param BCGLabel $label
     */
    public function addLabel(BCGLabel $label) {
        $label->setBackgroundColor($this->colorBg);
        $this->labels[] = $label;
    }

    /**
     * Removes the label from the drawing.
     *
     * @param BCGLabel $label
     */
    public function removeLabel(BCGLabel $label) {
        $remove = -1;
        $c = count($this->labels);
        for ($i = 0; $i < $c; $i++) {
            if ($this->labels[$i] === $label) {
                $remove = $i;
                break;
            }
        }

        if ($remove > -1) {
            array_splice($this->labels, $remove, 1);
        }
    }

    /**
     * Clears the labels.
     */
    public function clearLabels() {
        $this->labels = array();
    }

    /**
     * Draws the text.
     * The coordinate passed are the positions of the barcode.
     * $x1 and $y1 represent the top left corner.
     * $x2 and $y2 represent the bottom right corner.
     *
     * @param resource $im
     * @param int $x1
     * @param int $y1
     * @param int $x2
     * @param int $y2
     */
    protected function drawText($im, $x1, $y1, $x2, $y2) {
        foreach ($this->labels as $label) {
            $label->draw($im,
                ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0],
                ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1],
                ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0],
                ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1]);
        }
    }

    /**
     * Draws 1 pixel on the resource at a specific position with a determined color.
     *
     * @param resource $im
     * @param int $x
     * @param int $y
     * @param int $color
     */
    protected function drawPixel($im, $x, $y, $color = self::COLOR_FG) {
        $xR = ($x + $this->offsetX) * $this->scale + $this->pushLabel[0];
        $yR = ($y + $this->offsetY) * $this->scale + $this->pushLabel[1];

        // We always draw a rectangle
        imagefilledrectangle($im,
            $xR,
            $yR,
            $xR + $this->scale - 1,
            $yR + $this->scale - 1,
            $this->getColor($im, $color));
    }

    /**
     * Draws an empty rectangle on the resource at a specific position with a determined color.
     *
     * @param resource $im
     * @param int $x1
     * @param int $y1
     * @param int $x2
     * @param int $y2
     * @param int $color
     */
    protected function drawRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) {
        if ($this->scale === 1) {
            imagefilledrectangle($im,
                ($x1 + $this->offsetX) + $this->pushLabel[0],
                ($y1 + $this->offsetY) + $this->pushLabel[1],
                ($x2 + $this->offsetX) + $this->pushLabel[0],
                ($y2 + $this->offsetY) + $this->pushLabel[1],
                $this->getColor($im, $color));
        } else {
            imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color));
            imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color));
            imagefilledrectangle($im, ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color));
            imagefilledrectangle($im, ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0], ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1], ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1, ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1, $this->getColor($im, $color));
        }
    }

    /**
     * Draws a filled rectangle on the resource at a specific position with a determined color.
     *
     * @param resource $im
     * @param int $x1
     * @param int $y1
     * @param int $x2
     * @param int $y2
     * @param int $color
     */
    protected function drawFilledRectangle($im, $x1, $y1, $x2, $y2, $color = self::COLOR_FG) {
        if ($x1 > $x2) { // Swap
            $x1 ^= $x2 ^= $x1 ^= $x2;
        }

        if ($y1 > $y2) { // Swap
            $y1 ^= $y2 ^= $y1 ^= $y2;
        }

        imagefilledrectangle($im,
            ($x1 + $this->offsetX) * $this->scale + $this->pushLabel[0],
            ($y1 + $this->offsetY) * $this->scale + $this->pushLabel[1],
            ($x2 + $this->offsetX) * $this->scale + $this->pushLabel[0] + $this->scale - 1,
            ($y2 + $this->offsetY) * $this->scale + $this->pushLabel[1] + $this->scale - 1,
            $this->getColor($im, $color));
    }

    /**
     * Allocates the color based on the integer.
     *
     * @param resource $im
     * @param int $color
     * @return resource
     */
    protected function getColor($im, $color) {
        if ($color === self::COLOR_BG) {
            return $this->colorBg->allocate($im);
        } else {
            return $this->colorFg->allocate($im);
        }
    }

    /**
     * Returning the biggest label widths for LEFT/RIGHT and heights for TOP/BOTTOM.
     *
     * @param bool $reversed
     * @return BCGLabel[]
     */
    private function getBiggestLabels($reversed = false) {
        $searchLR = $reversed ? 1 : 0;
        $searchTB = $reversed ? 0 : 1;

        $labels = array();
        foreach ($this->labels as $label) {
            $position = $label->getPosition();
            if (isset($labels[$position])) {
                $savedDimension = $labels[$position]->getDimension();
                $dimension = $label->getDimension();
                if ($position === BCGLabel::POSITION_LEFT || $position === BCGLabel::POSITION_RIGHT) {
                    if ($dimension[$searchLR] > $savedDimension[$searchLR]) {
                        $labels[$position] = $label;
                    }
                } else {
                    if ($dimension[$searchTB] > $savedDimension[$searchTB]) {
                        $labels[$position] = $label;
                    }
                }
            } else {
                $labels[$position] = $label;
            }
        }

        return $labels;
    }
}
?>


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>standard file</title>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">