text:
#include "common_audio/vad/vad_core.h"

#include "rtc_base/sanitizer.h"
#include "common_audio/signal_processing/include/signal_processing_library.h"
#include "common_audio/vad/vad_filterbank.h"
#include "common_audio/vad/vad_gmm.h"
#include "common_audio/vad/vad_sp.h"

// Spectrum Weighting
static const int16_t kSpectrumWeight[kNumChannels] = { 6, 8, 10, 12, 14, 16 };
static const int16_t kNoiseUpdateConst = 655; // Q15
static const int16_t kSpeechUpdateConst = 6554; // Q15
static const int16_t kBackEta = 154; // Q8
// Minimum difference between the two models, Q5
static const int16_t kMinimumDifference[kNumChannels] = {
    544, 544, 576, 576, 576, 576 };
// Upper limit of mean value for speech model, Q7
static const int16_t kMaximumSpeech[kNumChannels] = {
    11392, 11392, 11520, 11520, 11520, 11520 };
// Minimum value for mean value
static const int16_t kMinimumMean[kNumGaussians] = { 640, 768 };
// Upper limit of mean value for noise model, Q7
static const int16_t kMaximumNoise[kNumChannels] = {
    9216, 9088, 8960, 8832, 8704, 8576 };
// Start values for the Gaussian models, Q7
// Weights for the two Gaussians for the six channels (noise)
static const int16_t kNoiseDataWeights[kTableSize] = {
    34, 62, 72, 66, 53, 25, 94, 66, 56, 62, 75, 103 };
// Weights for the two Gaussians for the six channels (speech)
static const int16_t kSpeechDataWeights[kTableSize] = {
    48, 82, 45, 87, 50, 47, 80, 46, 83, 41, 78, 81 };
// Means for the two Gaussians for the six channels (noise)
static const int16_t kNoiseDataMeans[kTableSize] = {
    6738, 4892, 7065, 6715, 6771, 3369, 7646, 3863, 7820, 7266, 5020, 4362 };
// Means for the two Gaussians for the six channels (speech)
static const int16_t kSpeechDataMeans[kTableSize] = {
    8306, 10085, 10078, 11823, 11843, 6309, 9473, 9571, 10879, 7581, 8180, 7483
};
// Stds for the two Gaussians for the six channels (noise)
static const int16_t kNoiseDataStds[kTableSize] = {
    378, 1064, 493, 582, 688, 593, 474, 697, 475, 688, 421, 455 };
// Stds for the two Gaussians for the six channels (speech)
static const int16_t kSpeechDataStds[kTableSize] = {
    555, 505, 567, 524, 585, 1231, 509, 828, 492, 1540, 1079, 850 };

// Constants used in GmmProbability().
//
// Maximum number of counted speech (VAD = 1) frames in a row.
static const int16_t kMaxSpeechFrames = 6;
// Minimum standard deviation for both speech and noise.
static const int16_t kMinStd = 384;

// Constants in WebRtcVad_InitCore().
// Default aggressiveness mode.
static const short kDefaultMode = 0;
static const int kInitCheck = 42;

// Constants used in WebRtcVad_set_mode_core().
//
// Thresholds for different frame lengths (10 ms, 20 ms and 30 ms).
//
// Mode 0, Quality.
static const int16_t kOverHangMax1Q[3] = { 8, 4, 3 };
static const int16_t kOverHangMax2Q[3] = { 14, 7, 5 };
static const int16_t kLocalThresholdQ[3] = { 24, 21, 24 };
static const int16_t kGlobalThresholdQ[3] = { 57, 48, 57 };
// Mode 1, Low bitrate.
static const int16_t kOverHangMax1LBR[3] = { 8, 4, 3 };
static const int16_t kOverHangMax2LBR[3] = { 14, 7, 5 };
static const int16_t kLocalThresholdLBR[3] = { 37, 32, 37 };
static const int16_t kGlobalThresholdLBR[3] = { 100, 80, 100 };
// Mode 2, Aggressive.
static const int16_t kOverHangMax1AGG[3] = { 6, 3, 2 };
static const int16_t kOverHangMax2AGG[3] = { 9, 5, 3 };
static const int16_t kLocalThresholdAGG[3] = { 82, 78, 82 };
static const int16_t kGlobalThresholdAGG[3] = { 285, 260, 285 };
// Mode 3, Very aggressive.
static const int16_t kOverHangMax1VAG[3] = { 6, 3, 2 };
static const int16_t kOverHangMax2VAG[3] = { 9, 5, 3 };
static const int16_t kLocalThresholdVAG[3] = { 94, 94, 94 };
static const int16_t kGlobalThresholdVAG[3] = { 1100, 1050, 1100 };

// Calculates the weighted average w.r.t. number of Gaussians. The |data| are
// updated with an |offset| before averaging.
//
// - data     [i/o] : Data to average.
// - offset   [i]   : An offset added to |data|.
// - weights  [i]   : Weights used for averaging.
//
// returns          : The weighted average.
static int32_t WeightedAverage(int16_t* data, int16_t offset,
                               const int16_t* weights) {
  int k;
  int32_t weighted_average = 0;

  for (k = 0; k < kNumGaussians; k++) {
    data[k * kNumChannels] += offset;
    weighted_average += data[k * kNumChannels] * weights[k * kNumChannels];
  }
  return weighted_average;
}

// An s16 x s32 -> s32 multiplication that's allowed to overflow. (It's still
// undefined behavior, so not a good idea; this just makes UBSan ignore the
// violation, so that our old code can continue to do what it's always been
// doing.)
static inline int32_t RTC_NO_SANITIZE("signed-integer-overflow")
    OverflowingMulS16ByS32ToS32(int16_t a, int32_t b) {
  return a * b;
}

// Calculates the probabilities for both speech and background noise using
// Gaussian Mixture Models (GMM). A hypothesis-test is performed to decide which
// type of signal is most probable.
//
// - self           [i/o] : Pointer to VAD instance
// - features       [i]   : Feature vector of length |kNumChannels|
//                          = log10(energy in frequency band)
// - total_power    [i]   : Total power in audio frame.
// - frame_length   [i]   : Number of input samples
//
// - returns              : the VAD decision (0 - noise, 1 - speech).
static int16_t GmmProbability(VadInstT* self, int16_t* features,
                              int16_t total_power, size_t frame_length) {
  int channel, k;
  int16_t feature_minimum;
  int16_t h0, h1;
  int16_t log_likelihood_ratio;
  int16_t vadflag = 0;
  int16_t shifts_h0, shifts_h1;
  int16_t tmp_s16, tmp1_s16, tmp2_s16;
  int16_t diff;
  int gaussian;
  int16_t nmk, nmk2, nmk3, smk, smk2, nsk, ssk;
  int16_t delt, ndelt;
  int16_t maxspe, maxmu;
  int16_t deltaN[kTableSize], deltaS[kTableSize];
  int16_t ngprvec[kTableSize] = { 0 };  // Conditional probability = 0.
  int16_t sgprvec[kTableSize] = { 0 };  // Conditional probability = 0.
  int32_t h0_test, h1_test;
  int32_t tmp1_s32, tmp2_s32;
  int32_t sum_log_likelihood_ratios = 0;
  int32_t noise_global_mean, speech_global_mean;
  int32_t noise_probability[kNumGaussians], speech_probability[kNumGaussians];
  int16_t overhead1, overhead2, individualTest, totalTest;

  // Set various thresholds based on frame lengths (80, 160 or 240 samples).
  if (frame_length == 80) {
    overhead1 = self->over_hang_max_1[0];
    overhead2 = self->over_hang_max_2[0];
    individualTest = self->individual[0];
    totalTest = self->total[0];
  } else if (frame_length == 160) {
    overhead1 = self->over_hang_max_1[1];
    overhead2 = self->over_hang_max_2[1];
    individualTest = self->individual[1];
    totalTest = self->total[1];
  } else {
    overhead1 = self->over_hang_max_1[2];
    overhead2 = self->over_hang_max_2[2];
    individualTest = self->individual[2];
    totalTest = self->total[2];
  }

  if (total_power > kMinEnergy) {
    // The signal power of current frame is large enough for processing. The
    // processing consists of two parts:
    // 1) Calculating the likelihood of speech and thereby a VAD decision.
    // 2) Updating the underlying model, w.r.t., the decision made.

    // The detection scheme is an LRT with hypothesis
    // H0: Noise
    // H1: Speech
    //
    // We combine a global LRT with local tests, for each frequency sub-band,
    // here defined as |channel|.
    for (channel = 0; channel < kNumChannels; channel++) {
      // For each channel we model the probability with a GMM consisting of
      // |kNumGaussians|, with different means and standard deviations depending
      // on H0 or H1.
      h0_test = 0;
      h1_test = 0;
      for (k = 0; k < kNumGaussians; k++) {
        gaussian = channel + k * kNumChannels;
        // Probability under H0, that is, probability of frame being noise.
        // Value given in Q27 = Q7 * Q20.
        tmp1_s32 = WebRtcVad_GaussianProbability(features[channel],
                                                 self->noise_means[gaussian],
                                                 self->noise_stds[gaussian],
                                                 &deltaN[gaussian]);
        noise_probability[k] = kNoiseDataWeights[gaussian] * tmp1_s32;
        h0_test += noise_probability[k];  // Q27

        // Probability under H1, that is, probability of frame being speech.
        // Value given in Q27 = Q7 * Q20.
        tmp1_s32 = WebRtcVad_GaussianProbability(features[channel],
                                                 self->speech_means[gaussian],
                                                 self->speech_stds[gaussian],
                                                 &deltaS[gaussian]);
        speech_probability[k] = kSpeechDataWeights[gaussian] * tmp1_s32;
        h1_test += speech_probability[k];  // Q27
      }

      // Calculate the log likelihood ratio: log2(Pr{X|H1} / Pr{X|H1}).
      // Approximation:
      // log2(Pr{X|H1} / Pr{X|H1}) = log2(Pr{X|H1}*2^Q) - log2(Pr{X|H1}*2^Q)
      //                           = log2(h1_test) - log2(h0_test)
      //                           = log2(2^(31-shifts_h1)*(1+b1))
      //                             - log2(2^(31-shifts_h0)*(1+b0))
      //                           = shifts_h0 - shifts_h1
      //                             + log2(1+b1) - log2(1+b0)
      //                          ~= shifts_h0 - shifts_h1
      //
      // Note that b0 and b1 are values less than 1, hence, 0 <= log2(1+b0) < 1.
      // Further, b0 and b1 are independent and on the average the two terms
      // cancel.
      shifts_h0 = WebRtcSpl_NormW32(h0_test);
      shifts_h1 = WebRtcSpl_NormW32(h1_test);
      if (h0_test == 0) {
        shifts_h0 = 31;
      }
      if (h1_test == 0) {
        shifts_h1 = 31;
      }
      log_likelihood_ratio = shifts_h0 - shifts_h1;

      // Update |sum_log_likelihood_ratios| with spectrum weighting. This is
      // used for the global VAD decision.
      sum_log_likelihood_ratios +=
          (int32_t) (log_likelihood_ratio * kSpectrumWeight[channel]);

      // Local VAD decision.
      if ((log_likelihood_ratio * 4) > individualTest) {
        vadflag = 1;
      }

      // TODO(bjornv): The conditional probabilities below are applied on the
      // hard coded number of Gaussians set to two. Find a way to generalize.
      // Calculate local noise probabilities used later when updating the GMM.
      h0 = (int16_t) (h0_test >> 12);  // Q15
      if (h0 > 0) {
        // High probability of noise. Assign conditional probabilities for each
        // Gaussian in the GMM.
        tmp1_s32 = (noise_probability[0] & 0xFFFFF000) << 2;  // Q29
        ngprvec[channel] = (int16_t) WebRtcSpl_DivW32W16(tmp1_s32, h0);  // Q14
        ngprvec[channel + kNumChannels] = 16384 - ngprvec[channel];
      } else {
        // Low noise probability. Assign conditional probability 1 to the first
        // Gaussian and 0 to the rest (which is already set at initialization).
        ngprvec[channel] = 16384;
      }

      // Calculate local speech probabilities used later when updating the GMM.
      h1 = (int16_t) (h1_test >> 12);  // Q15
      if (h1 > 0) {
        // High probability of speech. Assign conditional probabilities for each
        // Gaussian in the GMM. Otherwise use the initialized values, i.e., 0.
        tmp1_s32 = (speech_probability[0] & 0xFFFFF000) << 2;  // Q29
        sgprvec[channel] = (int16_t) WebRtcSpl_DivW32W16(tmp1_s32, h1);  // Q14
        sgprvec[channel + kNumChannels] = 16384 - sgprvec[channel];
      }
    }

    // Make a global VAD decision.
    vadflag |= (sum_log_likelihood_ratios >= totalTest);

    // Update the model parameters.
    maxspe = 12800;
    for (channel = 0; channel < kNumChannels; channel++) {

      // Get minimum value in past which is used for long term correction in Q4.
      feature_minimum = WebRtcVad_FindMinimum(self, features[channel], channel);

      // Compute the "global" mean, that is the sum of the two means weighted.
      noise_global_mean = WeightedAverage(&self->noise_means[channel], 0,
                                          &kNoiseDataWeights[channel]);
      tmp1_s16 = (int16_t) (noise_global_mean >> 6);  // Q8

      for (k = 0; k < kNumGaussians; k++) {
        gaussian = channel + k * kNumChannels;

        nmk = self->noise_means[gaussian];
        smk = self->speech_means[gaussian];
        nsk = self->noise_stds[gaussian];
        ssk = self->speech_stds[gaussian];

        // Update noise mean vector if the frame consists of noise only.
        nmk2 = nmk;
        if (!vadflag) {
          // deltaN = (x-mu)/sigma^2
          // ngprvec[k] = |noise_probability[k]| /
          //   (|noise_probability[0]| + |noise_probability[1]|)

          // (Q14 * Q11 >> 11) = Q14.
          delt = (int16_t)((ngprvec[gaussian] * deltaN[gaussian]) >> 11);
          // Q7 + (Q14 * Q15 >> 22) = Q7.
          nmk2 = nmk + (int16_t)((delt * kNoiseUpdateConst) >> 22);
        }

        // Long term correction of the noise mean.
        // Q8 - Q8 = Q8.
        ndelt = (feature_minimum << 4) - tmp1_s16;
        // Q7 + (Q8 * Q8) >> 9 = Q7.
        nmk3 = nmk2 + (int16_t)((ndelt * kBackEta) >> 9);

        // Control that the noise mean does not drift to much.
        tmp_s16 = (int16_t) ((k + 5) << 7);
        if (nmk3 < tmp_s16) {
          nmk3 = tmp_s16;
        }
        tmp_s16 = (int16_t) ((72 + k - channel) << 7);
        if (nmk3 > tmp_s16) {
          nmk3 = tmp_s16;
        }
        self->noise_means[gaussian] = nmk3;

        if (vadflag) {
          // Update speech mean vector:
          // |deltaS| = (x-mu)/sigma^2
          // sgprvec[k] = |speech_probability[k]| /
          //   (|speech_probability[0]| + |speech_probability[1]|)

          // (Q14 * Q11) >> 11 = Q14.
          delt = (int16_t)((sgprvec[gaussian] * deltaS[gaussian]) >> 11);
          // Q14 * Q15 >> 21 = Q8.
          tmp_s16 = (int16_t)((delt * kSpeechUpdateConst) >> 21);
          // Q7 + (Q8 >> 1) = Q7. With rounding.
          smk2 = smk + ((tmp_s16 + 1) >> 1);

          // Control that the speech mean does not drift to much.
          maxmu = maxspe + 640;
          if (smk2 < kMinimumMean[k]) {
            smk2 = kMinimumMean[k];
          }
          if (smk2 > maxmu) {
            smk2 = maxmu;
          }
          self->speech_means[gaussian] = smk2;  // Q7.

          // (Q7 >> 3) = Q4. With rounding.
          tmp_s16 = ((smk + 4) >> 3);

          tmp_s16 = features[channel] - tmp_s16;  // Q4
          // (Q11 * Q4 >> 3) = Q12.
          tmp1_s32 = (deltaS[gaussian] * tmp_s16) >> 3;
          tmp2_s32 = tmp1_s32 - 4096;
          tmp_s16 = sgprvec[gaussian] >> 2;
          // (Q14 >> 2) * Q12 = Q24.
          tmp1_s32 = tmp_s16 * tmp2_s32;

          tmp2_s32 = tmp1_s32 >> 4;  // Q20

          // 0.1 * Q20 / Q7 = Q13.
          if (tmp2_s32 > 0) {
            tmp_s16 = (int16_t) WebRtcSpl_DivW32W16(tmp2_s32, ssk * 10);
          } else {
            tmp_s16 = (int16_t) WebRtcSpl_DivW32W16(-tmp2_s32, ssk * 10);
            tmp_s16 = -tmp_s16;
          }
          // Divide by 4 giving an update factor of 0.025 (= 0.1 / 4).
          // Note that division by 4 equals shift by 2, hence,
          // (Q13 >> 8) = (Q13 >> 6) / 4 = Q7.
          tmp_s16 += 128;  // Rounding.
          ssk += (tmp_s16 >> 8);
          if (ssk < kMinStd) {
            ssk = kMinStd;
          }
          self->speech_stds[gaussian] = ssk;
        } else {
          // Update GMM variance vectors.
          // deltaN * (features[channel] - nmk) - 1
          // Q4 - (Q7 >> 3) = Q4.
          tmp_s16 = features[channel] - (nmk >> 3);
          // (Q11 * Q4 >> 3) = Q12.
          tmp1_s32 = (deltaN[gaussian] * tmp_s16) >> 3;
          tmp1_s32 -= 4096;

          // (Q14 >> 2) * Q12 = Q24.
          tmp_s16 = (ngprvec[gaussian] + 2) >> 2;
          tmp2_s32 = OverflowingMulS16ByS32ToS32(tmp_s16, tmp1_s32);
          // Q20  * approx 0.001 (2^-10=0.0009766), hence,
          // (Q24 >> 14) = (Q24 >> 4) / 2^10 = Q20.
          tmp1_s32 = tmp2_s32 >> 14;

          // Q20 / Q7 = Q13.
          if (tmp1_s32 > 0) {
            tmp_s16 = (int16_t) WebRtcSpl_DivW32W16(tmp1_s32, nsk);
          } else {
            tmp_s16 = (int16_t) WebRtcSpl_DivW32W16(-tmp1_s32, nsk);
            tmp_s16 = -tmp_s16;
          }
          tmp_s16 += 32;  // Rounding
          nsk += tmp_s16 >> 6;  // Q13 >> 6 = Q7.
          if (nsk < kMinStd) {
            nsk = kMinStd;
          }
          self->noise_stds[gaussian] = nsk;
        }
      }

      // Separate models if they are too close.
      // |noise_global_mean| in Q14 (= Q7 * Q7).
      noise_global_mean = WeightedAverage(&self->noise_means[channel], 0,
                                          &kNoiseDataWeights[channel]);

      // |speech_global_mean| in Q14 (= Q7 * Q7).
      speech_global_mean = WeightedAverage(&self->speech_means[channel], 0,
                                           &kSpeechDataWeights[channel]);

      // |diff| = "global" speech mean - "global" noise mean.
      // (Q14 >> 9) - (Q14 >> 9) = Q5.
      diff = (int16_t) (speech_global_mean >> 9) -
          (int16_t) (noise_global_mean >> 9);
      if (diff < kMinimumDifference[channel]) {
        tmp_s16 = kMinimumDifference[channel] - diff;

        // |tmp1_s16| = ~0.8 * (kMinimumDifference - diff) in Q7.
        // |tmp2_s16| = ~0.2 * (kMinimumDifference - diff) in Q7.
        tmp1_s16 = (int16_t)((13 * tmp_s16) >> 2);
        tmp2_s16 = (int16_t)((3 * tmp_s16) >> 2);

        // Move Gaussian means for speech model by |tmp1_s16| and update
        // |speech_global_mean|. Note that |self->speech_means[channel]| is
        // changed after the call.
        speech_global_mean = WeightedAverage(&self->speech_means[channel],
                                             tmp1_s16,
                                             &kSpeechDataWeights[channel]);

        // Move Gaussian means for noise model by -|tmp2_s16| and update
        // |noise_global_mean|. Note that |self->noise_means[channel]| is
        // changed after the call.
        noise_global_mean = WeightedAverage(&self->noise_means[channel],
                                            -tmp2_s16,
                                            &kNoiseDataWeights[channel]);
      }

      // Control that the speech & noise means do not drift to much.
      maxspe = kMaximumSpeech[channel];
      tmp2_s16 = (int16_t) (speech_global_mean >> 7);
      if (tmp2_s16 > maxspe) {
        // Upper limit of speech model.
        tmp2_s16 -= maxspe;

        for (k = 0; k < kNumGaussians; k++) {
          self->speech_means[channel + k * kNumChannels] -= tmp2_s16;
        }
      }

      tmp2_s16 = (int16_t) (noise_global_mean >> 7);
      if (tmp2_s16 > kMaximumNoise[channel]) {
        tmp2_s16 -= kMaximumNoise[channel];

        for (k = 0; k < kNumGaussians; k++) {
          self->noise_means[channel + k * kNumChannels] -= tmp2_s16;
        }
      }
    }
    self->frame_counter++;
  }

  // Smooth with respect to transition hysteresis.
  if (!vadflag) {
    if (self->over_hang > 0) {
      vadflag = 2 + self->over_hang;
      self->over_hang--;
    }
    self->num_of_speech = 0;
  } else {
    self->num_of_speech++;
    if (self->num_of_speech > kMaxSpeechFrames) {
      self->num_of_speech = kMaxSpeechFrames;
      self->over_hang = overhead2;
    } else {
      self->over_hang = overhead1;
    }
  }
  return vadflag;
}

// Initialize the VAD. Set aggressiveness mode to default value.
int WebRtcVad_InitCore(VadInstT* self) {
  int i;

  if (self == NULL) {
    return -1;
  }

  // Initialization of general struct variables.
  self->vad = 1;  // Speech active (=1).
  self->frame_counter = 0;
  self->over_hang = 0;
  self->num_of_speech = 0;

  // Initialization of downsampling filter state.
  memset(self->downsampling_filter_states, 0,
         sizeof(self->downsampling_filter_states));

  // Initialization of 48 to 8 kHz downsampling.
  WebRtcSpl_ResetResample48khzTo8khz(&self->state_48_to_8);

  // Read initial PDF parameters.
  for (i = 0; i < kTableSize; i++) {
    self->noise_means[i] = kNoiseDataMeans[i];
    self->speech_means[i] = kSpeechDataMeans[i];
    self->noise_stds[i] = kNoiseDataStds[i];
    self->speech_stds[i] = kSpeechDataStds[i];
  }

  // Initialize Index and Minimum value vectors.
  for (i = 0; i < 16 * kNumChannels; i++) {
    self->low_value_vector[i] = 10000;
    self->index_vector[i] = 0;
  }

  // Initialize splitting filter states.
  memset(self->upper_state, 0, sizeof(self->upper_state));
  memset(self->lower_state, 0, sizeof(self->lower_state));

  // Initialize high pass filter states.
  memset(self->hp_filter_state, 0, sizeof(self->hp_filter_state));

  // Initialize mean value memory, for WebRtcVad_FindMinimum().
  for (i = 0; i < kNumChannels; i++) {
    self->mean_value[i] = 1600;
  }

  // Set aggressiveness mode to default (=|kDefaultMode|).
  if (WebRtcVad_set_mode_core(self, kDefaultMode) != 0) {
    return -1;
  }

  self->init_flag = kInitCheck;

  return 0;
}

// Set aggressiveness mode
int WebRtcVad_set_mode_core(VadInstT* self, int mode) {
  int return_value = 0;

  switch (mode) {
    case 0:
      // Quality mode.
      memcpy(self->over_hang_max_1, kOverHangMax1Q,
             sizeof(self->over_hang_max_1));
      memcpy(self->over_hang_max_2, kOverHangMax2Q,
             sizeof(self->over_hang_max_2));
      memcpy(self->individual, kLocalThresholdQ,
             sizeof(self->individual));
      memcpy(self->total, kGlobalThresholdQ,
             sizeof(self->total));
      break;
    case 1:
      // Low bitrate mode.
      memcpy(self->over_hang_max_1, kOverHangMax1LBR,
             sizeof(self->over_hang_max_1));
      memcpy(self->over_hang_max_2, kOverHangMax2LBR,
             sizeof(self->over_hang_max_2));
      memcpy(self->individual, kLocalThresholdLBR,
             sizeof(self->individual));
      memcpy(self->total, kGlobalThresholdLBR,
             sizeof(self->total));
      break;
    case 2:
      // Aggressive mode.
      memcpy(self->over_hang_max_1, kOverHangMax1AGG,
             sizeof(self->over_hang_max_1));
      memcpy(self->over_hang_max_2, kOverHangMax2AGG,
             sizeof(self->over_hang_max_2));
      memcpy(self->individual, kLocalThresholdAGG,
             sizeof(self->individual));
      memcpy(self->total, kGlobalThresholdAGG,
             sizeof(self->total));
      break;
    case 3:
      // Very aggressive mode.
      memcpy(self->over_hang_max_1, kOverHangMax1VAG,
             sizeof(self->over_hang_max_1));
      memcpy(self->over_hang_max_2, kOverHangMax2VAG,
             sizeof(self->over_hang_max_2));
      memcpy(self->individual, kLocalThresholdVAG,
             sizeof(self->individual));
      memcpy(self->total, kGlobalThresholdVAG,
             sizeof(self->total));
      break;
    default:
      return_value = -1;
      break;
  }

  return return_value;
}

// Calculate VAD decision by first extracting feature values and then calculate
// probability for both speech and background noise.

int WebRtcVad_CalcVad48khz(VadInstT* inst, const int16_t* speech_frame,
                           size_t frame_length) {
  int vad;
  size_t i;
  int16_t speech_nb[240];  // 30 ms in 8 kHz.
  // |tmp_mem| is a temporary memory used by resample function, length is
  // frame length in 10 ms (480 samples) + 256 extra.
  int32_t tmp_mem[480 + 256] = { 0 };
  const size_t kFrameLen10ms48khz = 480;
  const size_t kFrameLen10ms8khz = 80;
  size_t num_10ms_frames = frame_length / kFrameLen10ms48khz;

  for (i = 0; i < num_10ms_frames; i++) {
    WebRtcSpl_Resample48khzTo8khz(speech_frame,
                                  &speech_nb[i * kFrameLen10ms8khz],
                                  &inst->state_48_to_8,
                                  tmp_mem);
  }

  // Do VAD on an 8 kHz signal
  vad = WebRtcVad_CalcVad8khz(inst, speech_nb, frame_length / 6);

  return vad;
}

int WebRtcVad_CalcVad32khz(VadInstT* inst, const int16_t* speech_frame,
                           size_t frame_length)
{
    size_t len;
    int vad;
    int16_t speechWB[480]; // Downsampled speech frame: 960 samples (30ms in SWB)
    int16_t speechNB[240]; // Downsampled speech frame: 480 samples (30ms in WB)

    // Downsample signal 32->16->8 before doing VAD
    WebRtcVad_Downsampling(speech_frame, speechWB, &(inst->downsampling_filter_states[2]),
                           frame_length);
    len = frame_length / 2;

    WebRtcVad_Downsampling(speechWB, speechNB, inst->downsampling_filter_states, len);
    len /= 2;

    // Do VAD on an 8 kHz signal
    vad = WebRtcVad_CalcVad8khz(inst, speechNB, len);

    return vad;
}

int WebRtcVad_CalcVad16khz(VadInstT* inst, const int16_t* speech_frame,
                           size_t frame_length)
{
    size_t len;
    int vad;
    int16_t speechNB[240]; // Downsampled speech frame: 480 samples (30ms in WB)

    // Wideband: Downsample signal before doing VAD
    WebRtcVad_Downsampling(speech_frame, speechNB, inst->downsampling_filter_states,
                           frame_length);

    len = frame_length / 2;
    vad = WebRtcVad_CalcVad8khz(inst, speechNB, len);

    return vad;
}

int WebRtcVad_CalcVad8khz(VadInstT* inst, const int16_t* speech_frame,
                          size_t frame_length)
{
    int16_t feature_vector[kNumChannels], total_power;

    // Get power in the bands
    total_power = WebRtcVad_CalculateFeatures(inst, speech_frame, frame_length,
                                              feature_vector);

    // Make a VAD
    inst->vad = GmmProbability(inst, feature_vector, total_power, frame_length);

    return inst->vad;
}


text:
git pull
npm run build
sudo docker-compose build
sudo docker-compose down
sudo docker-compose up -d

redpajama_set_name: RedPajamaGithub


text:
struct BlankAppWizard   : public NewProjectWizard
{
    BlankAppWizard()  {}

    String getName() const override         { return TRANS("Empty Application"); }
    String getDescription() const override  { return TRANS("Creates a blank JUCE GUI application."); }
    const char* getIcon() const override    { return BinaryData::wizard_GUI_svg; }

    bool initialiseProject (Project& project) override
    {
        createSourceFolder();
        project.getProjectTypeValue() = ProjectType::getGUIAppTypeName();
        Project::Item sourceGroup (createSourceGroup (project));
        setExecutableNameForAllTargets (project, File::createLegalFileName (appTitle));

        return true;
    }

    JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BlankAppWizard)
};


text:
require "active_record"
require "yaml"
config = YAML.load_file('config/database.yml')

ActiveRecord::Base.establish_connection(config["development"])
ActiveRecord::Migration.create_table :pages do |t|
  t.string :permalink
  t.timestamps

end


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

<title>Uses of Class org.drip.analytics.output.BondRVMeasures</title>
<meta name="date" content="2017-01-04">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.drip.analytics.output.BondRVMeasures

Packages that use BondRVMeasures

Package
Description

org.drip.product.credit

org.drip.product.definition

org.drip.service.product

Uses of BondRVMeasures in org.drip.product.credit

Methods in org.drip.product.credit that return BondRVMeasures

Modifier and Type
Method and Description

BondRVMeasures
BondComponent.standardMeasures(ValuationParams valParams,
                CreditPricerParams pricerParams,
                CurveSurfaceQuoteContainer csqs,
                ValuationCustomizationParams vcp,
                WorkoutInfo wi,
                double dblPrice)

Uses of BondRVMeasures in org.drip.product.definition

Methods in org.drip.product.definition that return BondRVMeasures

Modifier and Type
Method and Description

abstract BondRVMeasures
Bond.standardMeasures(ValuationParams valParams,
                CreditPricerParams pricerParams,
                CurveSurfaceQuoteContainer csqs,
                ValuationCustomizationParams vcp,
                WorkoutInfo wi,
                double dblPrice)

Calculate the full set of Bond RV Measures from the Price Input

Uses of BondRVMeasures in org.drip.service.product

Methods in org.drip.service.product that return BondRVMeasures

Modifier and Type
Method and Description

static BondRVMeasures
FixedBondAPI.RelativeValueMetrics(java.lang.String strIssuerName,
                    int iBondEffectiveDate,
                    int iBondMaturityDate,
                    double dblBondCoupon,
                    int iBondCouponFrequency,
                    java.lang.String strBondCouponDayCount,
                    java.lang.String strBondCouponCurrency,
                    int iSpotDate,
                    java.lang.String[] astrFundingCurveDepositTenor,
                    double[] adblFundingCurveDepositQuote,
                    java.lang.String strFundingCurveDepositMeasure,
                    double[] adblFundingCurveFuturesQuote,
                    java.lang.String strFundingCurveFuturesMeasure,
                    java.lang.String[] astrFundingCurveFixFloatTenor,
                    double[] adblFundingCurveFixFloatQuote,
                    java.lang.String strFundingFixFloatMeasure,
                    java.lang.String strGovvieCode,
                    int[] aiGovvieCurveTreasuryEffectiveDate,
                    int[] aiGovvieCurveTreasuryMaturityDate,
                    double[] adblGovvieCurveTreasuryCoupon,
                    double[] adblGovvieCurveTreasuryYield,
                    java.lang.String strGovvieCurveTreasuryMeasure,
                    java.lang.String strCreditCurveName,
                    java.lang.String[] astrCreditCurveCDSTenor,
                    double[] adblCreditCurveCDSCoupon,
                    double[] adblCreditCurveCDSQuote,
                    java.lang.String strCreditCurveCDSMeasure,
                    double dblBondMarketCleanPrice)

Generate the Relative Value Metrics for the Specified Bond

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes


text:
The XOS Tutorial demonstrates how to add a new subscriber-facing
service to CORD.

## Prepare the development POD

Follow steps 1-3 under the **How to Bring up CORD** heading in the
[README.md](./README.md) file.  For best results, use on a clean Ubuntu 14.04
LTS installation on a server with at least 48GB RAM and 12 CPU cores.

For step 1, use the single-node POD setup described at
https://github.com/open-cloud/openstack-cluster-setup.  If you like, you can run
[this script](https://github.com/open-cloud/openstack-cluster-setup/blob/master/scripts/single-node-pod.sh) to perform steps 1 and 2:

```
ubuntu@pod:~$ wget https://raw.githubusercontent.com/open-cloud/openstack-cluster-setup/master/scripts/single-node-pod.sh
ubuntu@pod:~$ bash single-node-pod.sh
```

For step 3, in place of the `compute-ext-net.sh` script, run
[this script](https://github.com/open-cloud/openstack-cluster-setup/blob/master/scripts/compute-ext-net-tutorial.sh)
inside the nova-compute VM.  It enables routing packets between the ExampleService and vSG subnets on a
single-node POD.

```
ubuntu@pod:~$ ssh ubuntu@nova-compute
ubuntu@nova-compute:~$ wget https://raw.githubusercontent.com/open-cloud/openstack-cluster-setup/master/scripts/compute-ext-net-tutorial.sh
ubuntu@nova-compute:~$ sudo bash compute-ext-net-tutorial.sh
```

## Include ExampleService in XOS

On the POD, SSH into the XOS VM: `$ ssh ubuntu@xos`.  You will see the XOS repository
checked out under `~/xos/`

Change the XOS code as described in the
[ExampleService Tutorial](http://guide.xosproject.org/devguide/exampleservice/)
under the **Install the Service in Django** heading, and rebuild the XOS containers as
described in that Tutorial:

```
ubuntu@xos:~$ cd xos/xos/configurations/devel
ubuntu@xos:~/xos/xos/configurations/devel$ make containers
```

Change directories to `../cord-pod`.
Modify the `docker-compose.yml` file in this directory to include the synchronizer
for ExampleService:

```yaml
xos_synchronizer_exampleservice:
    image: xosproject/xos-synchronizer-openstack
    command: bash -c "sleep 120; python /opt/xos/synchronizers/exampleservice/exampleservice-synchronizer.py -C /root/setup/files/exampleservice_config"
    labels:
        org.xosproject.kind: synchronizer
        org.xosproject.target: exampleservice
    links:
        - xos_db
    volumes:
        - .:/root/setup:ro
        - ../common/xos_common_config:/opt/xos/xos_configuration/xos_common_config:ro
        - ./id_rsa:/opt/xos/synchronizers/exampleservice/exampleservice_private_key:ro
```

Also, add ExampleService's public key to the `volumes` section of the `xos` docker container:

```
xos:
    ...
    volumes:
        ...
        - ./id_rsa.pub:/opt/xos/synchronizers/exampleservice/exampleservice_public_key:ro
```

## Bring up XOS

Run the `make` commands described in the [README.md](./README.md) file:

```
ubuntu@xos:~/xos/xos/configurations/cord-pod$ make
ubuntu@xos:~/xos/xos/configurations/cord-pod$ make vtn
ubuntu@xos:~/xos/xos/configurations/cord-pod$ make cord
```

The first `make` command initializes XOS and configures it to talk to OpenStack.
After running it you should be able to login to the XOS UI at http://xos
using credentials padmin@vicci.org/letmein.

The `make vtn` tells XOS to start and configure the ONOS VTN app.  The `make cord`
installs the CORD services in XOS and configures a sample subscriber; the end
result is that XOS will spin up the subscriber's vSG.

## Configure ExampleService in XOS

The TOSCA file `pod-exampleservice.yaml` contains the service declaration.
Tell XOS to process it by running:

```
ubuntu@xos:~/xos/xos/configurations/cord-pod$ make exampleservice
```

In the XOS UI, create an ExampleTenant. Go to *http://xos/admin/exampleservice*
and add / save an Example Tenant (when creating the tenant, fill in a message that
this tenant should display).  This will cause an Instance to be created
in the the *mysite_exampleservice* slice.

## Set up a Subscriber Device

The single-node POD does not include a virtual OLT, but a device at the
subscriber's premises can be simulated by an LXC container running on the
nova-compute node.

In the nova-compute VM:

```
ubuntu@nova-compute:~$ sudo apt-get install lxc
```

Next edit `/etc/lxc/default.conf` and change the default bridge name to `databr`:

```
  lxc.network.link = databr
```

Create the client container and attach to it:

```
ubuntu@nova-compute:~$ sudo lxc-create -t ubuntu -n testclient
ubuntu@nova-compute:~$ sudo lxc-start -n testclient
ubuntu@nova-compute:~$ sudo lxc-attach -n testclient
```

(The lxc-start command may throw an error but it seems to be unimportant.)

Finally, inside the container set up an interface so that outgoing traffic
is tagged with the s-tag (222) and c-tag (111) configured for the
sample subscriber:

```
root@testclient:~# ip link add link eth0 name eth0.222 type vlan id 222
root@testclient:~# ip link add link eth0.222 name eth0.222.111 type vlan id 111
root@testclient:~# ifconfig eth0.222 up
root@testclient:~# ifconfig eth0.222.111 up
root@testclient:~# dhclient eth0.222.111
```

If the vSG is up and everything is working correctly, the eth0.222.111
interface should acquire an IP address via DHCP and have external connectivity.

## Access ExampleService from the Subscriber Device

To test that the subscriber device can access the ExampleService, find the IP
address of the ExampleService Instance in the XOS GUI, and then curl this
address from inside the testclient container:

```
root@testclient:~# sudo apt-get install curl
root@testclient:~# curl 10.168.1.3
ExampleService
 Service Message: "service_message"
 Tenant Message: "tenant_message"
```

Hooray!  This shows that the subscriber (1) has external connectivity, and
(2) can access the new service via the vSG.


text:
import sinon from 'sinon';

export default function stub(objectPath, propertyName, ignoreIndex) {
	let ignoreRegExp;
	let ignored = [];

	const original = objectPath[propertyName];

	function stub(...args) {
		if (ignoreIndex !== undefined) {
			const ignoreArgument = args.slice(ignoreIndex, ignoreIndex + 1)[0];
			if (ignoreRegExp && ignoreRegExp.test(ignoreArgument)) {
				ignored.push(ignoreArgument);
				throw new Error('Ignored by mock');
			}
		}

		return original.bind(this)(...args);
	}

	sinon.stub(objectPath, propertyName).callsFake(stub);

	return {
		ignore(_ignoreRegExp) {
			ignoreRegExp = _ignoreRegExp;
		},
		ignored: () => ignored.length,
		called: () => objectPath[propertyName].callCount,
		restore() {
			ignoreRegExp = undefined;
			ignored = [];
			objectPath[propertyName].resetHistory();
		},
	};
}


text:
"""Functional tests for Concat Op."""

import numpy as np

from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.python.framework import errors_impl
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_array_ops
from tensorflow.python.ops import gradient_checker
from tensorflow.python.ops import gradients_impl
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import nn_ops
from tensorflow.python.ops import variables
from tensorflow.python.platform import test

class ConcatOpTest(test.TestCase):

  @test_util.run_deprecated_v1
  def testHStack(self):
    with self.session():
      p1 = array_ops.placeholder(dtypes.float32, shape=[4, 4])
      p2 = array_ops.placeholder(dtypes.float32, shape=[4, 4])
      c = array_ops.concat([p1, p2], 0)
      params = {
          p1: np.random.rand(4, 4).astype("f"),
          p2: np.random.rand(4, 4).astype("f")
      }
      result = c.eval(feed_dict=params)

    self.assertEqual(result.shape, c.get_shape())
    self.assertAllEqual(result[:4, :], params[p1])
    self.assertAllEqual(result[4:, :], params[p2])

  @test_util.run_deprecated_v1
  def testVStack(self):
    with self.session():
      p1 = array_ops.placeholder(dtypes.float32, shape=[4, 4])
      p2 = array_ops.placeholder(dtypes.float32, shape=[4, 4])
      c = array_ops.concat([p1, p2], 1)
      params = {
          p1: np.random.rand(4, 4).astype("f"),
          p2: np.random.rand(4, 4).astype("f")
      }
      result = c.eval(feed_dict=params)

    self.assertEqual(result.shape, c.get_shape())
    self.assertAllEqual(result[:, :4], params[p1])
    self.assertAllEqual(result[:, 4:], params[p2])

  @test_util.run_deprecated_v1
  def test4DStack(self):
    with self.session():
      p1 = array_ops.placeholder(dtypes.float32, shape=[2, 3, 1, 1])
      p2 = array_ops.placeholder(dtypes.float32, shape=[2, 3, 4, 1])
      c = array_ops.concat([p1, p2], 2)
      params = {
          p1: np.random.rand(2, 3, 1, 1).astype("f"),
          p2: np.random.rand(2, 3, 4, 1).astype("f")
      }
      result = c.eval(feed_dict=params)

    self.assertEqual(result.shape, c.get_shape())
    self.assertAllEqual(result[:, :, :1, :], params[p1])
    self.assertAllEqual(result[:, :, 1:, :], params[p2])

  def testInt32GPU(self):
    with test_util.use_gpu():
      p1 = np.random.rand(2, 3).astype("i")
      p2 = np.random.rand(2, 3).astype("i")
      x1 = constant_op.constant(p1)
      x2 = constant_op.constant(p2)
      c = array_ops.concat([x1, x2], 0)
      result = self.evaluate(c)
    self.assertAllEqual(result[:2, :], p1)
    self.assertAllEqual(result[2:, :], p2)

  def testRefType(self):
    with test_util.use_gpu():
      p1 = np.random.rand(4, 4).astype("f")
      p2 = np.random.rand(4, 4).astype("f")
      v1 = variables.Variable(p1)
      v2 = variables.Variable(p2)
      c = array_ops.concat([v1, v2], 0)
      self.evaluate(variables.global_variables_initializer())
      result = self.evaluate(c)

    self.assertEqual(result.shape, c.get_shape())
    self.assertAllEqual(result[:4, :], p1)
    self.assertAllEqual(result[4:, :], p2)

  def _testRandom(self, dtype):
    # Random dims of rank 5
    shape = np.random.randint(1, 5, size=5)
    # Random number of tensors, but always > 1.
    num_tensors = np.random.randint(2, 10)
    # Random dim to concat on
    concat_dim = np.random.randint(5)
    params = {}
    if dtype == dtypes.bfloat16:
      dtype_feed = dtypes.float32
    else:
      dtype_feed = dtype
    with self.session():
      p = []
      for i in np.arange(num_tensors):
        input_shape = shape
        input_shape[concat_dim] = np.random.randint(1, 5)
        placeholder = array_ops.placeholder(dtype_feed, shape=input_shape)
        p.append(placeholder)

        t = dtype_feed.as_numpy_dtype
        params[placeholder] = np.random.rand(*input_shape).astype(t)

      if dtype != dtype_feed:
        concat_inputs = [math_ops.cast(p_i, dtype) for p_i in p]
      else:
        concat_inputs = p
      c = array_ops.concat(concat_inputs, concat_dim)
      if dtype != dtype_feed:
        c = math_ops.cast(c, dtype_feed)
      result = c.eval(feed_dict=params)

    self.assertEqual(result.shape, c.get_shape())
    cur_offset = 0

    for i in np.arange(num_tensors):
      # The index into the result is the ':' along all dimensions
      # except the concat_dim. slice(0, size) is used for ':', and
      # a list of slices is used to index into result.
      ind = [slice(0, params[p[i]].shape[j]) for j in np.arange(5)]
      ind[concat_dim] = slice(cur_offset,
                              cur_offset + params[p[i]].shape[concat_dim])
      cur_offset += params[p[i]].shape[concat_dim]
      if dtype == dtype_feed:
        self.assertAllEqual(result[ind], params[p[i]])
      else:
        self.assertAllClose(result[ind], params[p[i]], 0.01)

  @test_util.run_deprecated_v1
  def testRandom(self):
    self._testRandom(dtypes.bool)
    self._testRandom(dtypes.float32)
    self._testRandom(dtypes.int16)
    self._testRandom(dtypes.int32)
    self._testRandom(dtypes.int64)
    self._testRandom(dtypes.bfloat16)
    self._testRandom(dtypes.complex64)
    self._testRandom(dtypes.complex128)

  @test_util.run_deprecated_v1
  def testInvalidConcatDimTypeAndShape(self):
    a = variables.Variable(constant_op.constant(1.0, shape=[1]))
    b = variables.Variable(constant_op.constant(2.0, shape=[1]))
    with self.assertRaises(ValueError):
      array_ops.concat(b, a)
    with self.assertRaises(TypeError):
      array_ops.concat(1, 4.2)
    with self.assertRaises(ValueError):
      array_ops.concat(1, a)
    with self.assertRaises(TypeError):
      array_ops.concat([a, b], a)
    with self.assertRaises(ValueError):
      array_ops.concat([a, b], [3])
    with self.assertRaises(ValueError):
      array_ops.concat([], 0)
    # An integer tensor for shape dim should throw no error.
    array_ops.concat(1, constant_op.constant(0, shape=[]))
    # A non-scalar tensor for shape should throw ValueError.
    with self.assertRaises(ValueError):
      array_ops.concat(1, constant_op.constant(0, shape=[1]))

  def _testGradientsSimple(self, dtype):
    # Test both positive and negative concat axis.
    # -2 and 1 correspond to the same axis for 3-dimensional tensors.
    for axis in [-2, 1]:
      with test_util.use_gpu():
        inp = []
        inp_tensors = []
        for x in [1, 2, 6]:
          shape = [10, x, 2]
          t = np.random.rand(*shape).astype(dtype.as_numpy_dtype)
          if dtype.is_complex:
            t += -1j * t
          inp.append(t)
          inp_tensors.append(
              constant_op.constant(
                  t.flatten(),
                  shape=shape,
                  dtype=dtype))
        c = array_ops.concat(inp_tensors, axis)
        output_shape = [10, 9, 2]
        grad_inp = np.random.rand(*output_shape).astype(dtype.as_numpy_dtype)
        if dtype.is_complex:
          grad_inp += -1j * grad_inp
        grad_tensor = constant_op.constant(
            grad_inp.flatten(), shape=output_shape)
        grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
        concated_grad = array_ops.concat(grad, axis)
        result = self.evaluate(concated_grad)
    self.assertAllEqual(result, grad_inp)

  @test_util.run_deprecated_v1
  def testGradientsSimple(self):
    self._testGradientsSimple(dtypes.float32)
    self._testGradientsSimple(dtypes.complex64)

  @test_util.run_deprecated_v1
  def testGradientsFirstDim(self):
    with test_util.use_gpu():
      inp = []
      inp_tensors = []
      for x in [1, 2, 6]:
        shape = [x, 10, 2]
        t = np.random.rand(*shape).astype("f")
        inp.append(t)
        inp_tensors.append(
            constant_op.constant(
                t.flatten(),
                shape=shape,
                dtype=dtypes.float32))
      c = array_ops.concat(inp_tensors, 0)
      output_shape = [9, 10, 2]
      grad_inp = np.random.rand(*output_shape).astype("f")
      grad_tensor = constant_op.constant(
          grad_inp.flatten(), shape=output_shape)
      grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
      concated_grad = array_ops.concat(grad, 0)
      result = self.evaluate(concated_grad)

    self.assertAllEqual(result, grad_inp)

  @test_util.run_deprecated_v1
  def testGradientsLastDim(self):
    # Test both positive and negative concat axis.
    # -1 and 2 correspond to the same axis for 3-dimensional tensors.
    for axis in [-1, 2]:
      with test_util.use_gpu():
        inp = []
        inp_tensors = []
        for x in [1, 2, 6]:
          shape = [10, 2, x]
          t = np.random.rand(*shape).astype("f")
          inp.append(t)
          inp_tensors.append(
              constant_op.constant(
                  t.flatten(),
                  shape=shape,
                  dtype=dtypes.float32))
        c = array_ops.concat(inp_tensors, 2)
        output_shape = [10, 2, 9]
        grad_inp = np.random.rand(*output_shape).astype("f")
        grad_tensor = constant_op.constant(
            grad_inp.flatten(), shape=output_shape)
        grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
        concated_grad = array_ops.concat(grad, axis)
        result = self.evaluate(concated_grad)

    self.assertAllEqual(result, grad_inp)

  def _RunAndVerifyGradientsRandom(self):
    # Random dims of rank 5
    input_shape = np.random.randint(1, 5, size=5)
    # Random number of tensors
    num_tensors = np.random.randint(12, 20)
    # Random dim to concat on
    concat_dim = np.random.randint(5)
    concat_dim_sizes = np.random.randint(1, 5, size=num_tensors)
    with test_util.use_gpu():
      inp = []
      inp_tensors = []
      for x in concat_dim_sizes:
        shape = input_shape
        shape[concat_dim] = x
        t = np.random.rand(*shape).astype("f")
        inp.append(t)
        inp_tensors.append(
            constant_op.constant(t.flatten(), shape=shape,
                                 dtype=dtypes.float32))
      c = array_ops.concat(inp_tensors, concat_dim)
      output_shape = input_shape
      output_shape[concat_dim] = concat_dim_sizes.sum()
      grad_inp = np.random.rand(*output_shape).astype("f")
      grad_tensor = constant_op.constant(grad_inp.flatten(), shape=output_shape)
      grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
      concated_grad = array_ops.concat(grad, concat_dim)
      result = self.evaluate(concated_grad)

    self.assertAllEqual(result, grad_inp)

  @test_util.run_deprecated_v1
  def testGradientsRandom(self):
    for _ in range(5):
      self._RunAndVerifyGradientsRandom()

  @test_util.run_deprecated_v1
  def testGradientWithUnknownInputDim(self):
    with self.session():
      x = array_ops.placeholder(dtypes.float32)
      y = array_ops.placeholder(dtypes.float32)
      c = array_ops.concat([x, y], 2)

      output_shape = [10, 2, 9]
      grad_inp = np.random.rand(*output_shape).astype("f")
      grad_tensor = constant_op.constant(
          grad_inp.flatten(), shape=output_shape)

      grad = gradients_impl.gradients([c], [x, y], [grad_tensor])
      concated_grad = array_ops.concat(grad, 2)
      params = {
          x: np.random.rand(10, 2, 3).astype("f"),
          y: np.random.rand(10, 2, 6).astype("f")
      }
      result = concated_grad.eval(feed_dict=params)

      self.assertAllEqual(result, grad_inp)

  @test_util.run_deprecated_v1
  def testShapeError(self):
    # Rank doesn't match.
    with self.assertRaises(ValueError):
      array_ops.concat(
          [constant_op.constant(10.0, shape=[4, 4, 4, 4]),
           constant_op.constant(20.0, shape=[4, 4, 4])
          ], 1)

    # Dimensions don't match in a non-concat dim.
    with self.assertRaises(ValueError):
      array_ops.concat(
          [constant_op.constant(10.0, shape=[1, 2, 1]),
           constant_op.constant(20.0, shape=[3, 2, 1])
          ], 1)

    # concat_dim out of range.
    with self.assertRaises(ValueError):
      array_ops.concat(
          [constant_op.constant(10.0, shape=[4, 4, 4]),
           constant_op.constant(20.0, shape=[4, 4, 4])
          ], 3)

    # concat_dim out of range
    with self.assertRaises(ValueError):
      array_ops.concat(
          [constant_op.constant(10.0, shape=[4, 4, 4]),
           constant_op.constant(20.0, shape=[4, 4, 4])
          ], -4)

  @test_util.run_deprecated_v1
  def testShapeWithUnknownConcatDim(self):
    p1 = array_ops.placeholder(dtypes.float32)
    c1 = constant_op.constant(10.0, shape=[4, 4, 4, 4])
    p2 = array_ops.placeholder(dtypes.float32)
    c2 = constant_op.constant(20.0, shape=[4, 4, 4, 4])
    dim = array_ops.placeholder(dtypes.int32)
    concat = array_ops.concat([p1, c1, p2, c2], dim)
    self.assertEqual(4, concat.get_shape().ndims)

    # All dimensions unknown.
    concat2 = array_ops.concat([p1, p2], dim)
    self.assertEqual(None, concat2.get_shape())

    # Rank doesn't match.
    c3 = constant_op.constant(30.0, shape=[4, 4, 4])
    with self.assertRaises(ValueError):
      array_ops.concat([p1, c1, p2, c3], dim)

  @test_util.run_deprecated_v1
  def testZeroSize(self):
    # Verify that concat doesn't crash and burn for zero size inputs
    np.random.seed(7)
    with test_util.use_gpu():
      for shape0 in (), (2,):
        axis = len(shape0)
        for shape1 in (), (3,):
          for n0 in 0, 1, 2:
            for n1 in 0, 1, 2:
              x0 = np.random.randn(*(shape0 + (n0,) + shape1))
              x1 = np.random.randn(*(shape0 + (n1,) + shape1))
              correct = np.concatenate([x0, x1], axis=axis)
              # TODO(irving): Make tf.concat handle map, then drop list().
              xs = list(map(constant_op.constant, [x0, x1]))
              c = array_ops.concat(xs, axis)
              self.assertAllEqual(self.evaluate(c), correct)
              # Check gradients
              dc = np.random.randn(*c.get_shape().as_list())
              dxs = self.evaluate(gradients_impl.gradients(c, xs, dc))
              self.assertAllEqual(dc, np.concatenate(dxs, axis=axis))

  @test_util.run_deprecated_v1
  def testTensorConcatDim0Grad(self):
    x_shapes = [[20, 7, 3], [10, 7, 3], [14, 7, 3]]
    output_shape = [44, 7, 3]
    x_vals = [
        np.random.random_sample(x_shape).astype(np.float64)
        for x_shape in x_shapes
    ]
    with self.cached_session():
      xs = [constant_op.constant(x_val) for x_val in x_vals]
      output = array_ops.concat(xs, 0)
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape)
    self.assertLess(err, 1e-11)

  @test_util.run_deprecated_v1
  def testTensorConcatDim1Grad(self):
    x_shapes = [[20, 7, 3], [20, 3, 3], [20, 1, 3]]
    output_shape = [20, 11, 3]
    x_vals = [
        np.random.random_sample(x_shape).astype(np.float64)
        for x_shape in x_shapes
    ]
    with self.cached_session():
      xs = [constant_op.constant(x_val) for x_val in x_vals]
      output = array_ops.concat(xs, 1)
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape)
    self.assertLess(err, 1e-11)

  @test_util.run_deprecated_v1
  def testIndexedSlicesConcatDim0Grad(self):
    x_shapes = [[20, 7, 3], [10, 7, 3], [14, 7, 3]]
    output_shape = [4, 7, 3]
    x_vals = [
        np.random.random_sample(x_shape).astype(np.float64)
        for x_shape in x_shapes
    ]
    with self.cached_session():
      xs = [constant_op.constant(x_val) for x_val in x_vals]
      x_concat = array_ops.concat(xs, 0)
      output = array_ops.gather(x_concat, [1, 2, 0, 5])
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape)
    self.assertLess(err, 1e-11)

  @test_util.run_deprecated_v1
  def testIndexedSlicesConcatDim1Grad(self):
    x_shapes = [[20, 7, 3], [20, 3, 3], [20, 1, 3]]
    output_shape = [4, 11, 3]
    x_vals = [
        np.random.random_sample(x_shape).astype(np.float64)
        for x_shape in x_shapes
    ]
    with self.cached_session():
      xs = [constant_op.constant(x_val) for x_val in x_vals]
      x_concat = array_ops.concat(xs, 1)
      output = array_ops.gather(x_concat, [1, 2, 0, 5])
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape)
    self.assertLess(err, 1e-11)

  @test_util.run_deprecated_v1
  def testIndexedSlicesConcatDim2Grad(self):
    x_shapes = [[20, 7, 3], [20, 7, 1], [20, 7, 2]]
    output_shape = [4, 7, 6]
    x_vals = [
        np.random.random_sample(x_shape).astype(np.float64)
        for x_shape in x_shapes
    ]
    with self.cached_session():
      xs = [constant_op.constant(x_val) for x_val in x_vals]
      x_concat = array_ops.concat(xs, 2)
      output = array_ops.gather(x_concat, [1, 2, 0, 5])
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape)
    self.assertLess(err, 1e-11)

  @test_util.run_deprecated_v1
  def testIndexedSlicesConcatDim1Grad_UnknownInputDim(self):
    x_shapes = [[20, 7, 3], [20, 3, 3], [20, 1, 3]]
    output_shape = [4, 11, 3]
    with self.cached_session():
      x_1 = array_ops.placeholder(dtypes.float64)
      x_2 = array_ops.placeholder(dtypes.float64)
      x_3 = array_ops.placeholder(dtypes.float64)
      xs = [x_1, x_2, x_3]

      x_concat = array_ops.concat(xs, 1)
      output = array_ops.gather(x_concat, [1, 2, 0, 5])
      params = {
          x_1: np.random.random_sample(x_shapes[0]).astype(np.float64),
          x_2: np.random.random_sample(x_shapes[1]).astype(np.float64),
          x_3: np.random.random_sample(x_shapes[2]).astype(np.float64)
      }
      err = gradient_checker.compute_gradient_error(xs, x_shapes, output,
                                                    output_shape,
                                                    extra_feed_dict=params)
    self.assertLess(err, 1e-11)

  def testConcatTuple(self):
    c1 = np.random.rand(4, 4)
    c2 = np.random.rand(4, 4)
    concat_list_t = array_ops.concat([c1, c2], 0)
    concat_tuple_t = array_ops.concat((c1, c2), 0)
    self.assertAllEqual(
        self.evaluate(concat_list_t), self.evaluate(concat_tuple_t))

  @test_util.run_deprecated_v1
  def testConcatNoScalars(self):
    scalar = constant_op.constant(7)
    dim = array_ops.placeholder(dtypes.int32)
    with self.assertRaisesRegex(
        ValueError, r"Can't concatenate scalars \(use tf\.stack instead\)"):
      array_ops.concat([scalar, scalar, scalar], dim)

  # important as gpu implementation could fail if
  # shared memory is not large for all the inputs
  @test_util.run_deprecated_v1
  def testConcatLargeNumberOfTensors(self):
    with self.session():
      for concat_dim in range(2):
        params = {}
        p = []
        shape = np.array([7, 13])
        if test.is_gpu_available():
          num_tensors = 5000
        else:
          num_tensors = 500
        for i in np.arange(num_tensors):
          input_shape = shape
          placeholder = array_ops.placeholder(dtypes.float32, shape=input_shape)
          p.append(placeholder)

          params[placeholder] = np.random.rand(*input_shape).astype(np.float32)

        concat_inputs = p
        c = array_ops.concat(concat_inputs, concat_dim)
        result = c.eval(feed_dict=params)

        self.assertEqual(result.shape, c.get_shape())
        cur_offset = 0

        for i in np.arange(num_tensors):
          # The index into the result is the ':' along all dimensions
          # except the concat_dim. slice(0, size) is used for ':', and
          # a list of slices is used to index into result.
          index = [slice(0, params[p[i]].shape[j]) for j in np.arange(2)]
          index[concat_dim] = slice(cur_offset,
                                    cur_offset + params[p[i]].shape[concat_dim])
          cur_offset += params[p[i]].shape[concat_dim]
          self.assertAllEqual(result[index], params[p[i]])

  def testConcatEmpty(self):
    with test_util.use_gpu():
      t1 = []
      t2 = []
      output = gen_array_ops.concat_v2([t1, t2], 0)
      self.assertFalse(self.evaluate(output))  # Checks that output is empty

  @test_util.run_deprecated_v1
  def testConcatInvalidAxis(self):
    with self.assertRaises(ValueError):
      with test_util.use_gpu():
        t1 = [1]
        t2 = [2]
        gen_array_ops.concat_v2([t1, t2], 1).eval()

  def testConcatInvalidAxisInTfFunction(self):

    @def_function.function
    def concat_wrapper():
      y = gen_array_ops.concat_v2(
          values=[[1, 2, 3], [4, 5, 6]], axis=0xb500005b)
      return y

    with self.assertRaises(ValueError):
      concat_wrapper()

  def testConcatNegativeAxis(self):
    with test_util.use_gpu():
      t1 = [[1, 2, 3], [4, 5, 6]]
      t2 = [[7, 8, 9], [10, 11, 12]]

      c = gen_array_ops.concat_v2([t1, t2], -2)
      self.assertEqual([4, 3], c.get_shape().as_list())
      output = self.evaluate(c)
      self.assertAllEqual([[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]],
                          output)

      c = gen_array_ops.concat_v2([t1, t2], -1)
      self.assertEqual([2, 6], c.get_shape().as_list())
      output = self.evaluate(c)
      self.assertAllEqual([[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]], output)

  def _testGradientsForAxis(
      self, inp_tensors, axis, output_shape, feed_dict=None):
    with self.cached_session():
      c = array_ops.concat(inp_tensors, axis)
      grad_inp = np.random.rand(*output_shape).astype("f")
      grad_tensor = constant_op.constant(
          grad_inp.flatten(), shape=output_shape)
      grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
      concated_grad = array_ops.concat(grad, axis)
      result = concated_grad.eval(feed_dict=feed_dict)
      self.assertAllEqual(result, grad_inp)

  def _testIndexedSlicesGradientsForAxis(
      self, inp_tensors, axis, output_shape, gather_indexes, feed_dict=None):
    with self.cached_session():
      c = array_ops.gather(
          array_ops.concat(inp_tensors, axis), gather_indexes)
      grad_inp = np.random.rand(*output_shape).astype("f")
      grad_tensor = constant_op.constant(
          grad_inp.flatten(), shape=output_shape)
      grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor])
      concated_grad = array_ops.gather(
          array_ops.concat(grad, axis), gather_indexes)
      result = concated_grad.eval(feed_dict=feed_dict)
      self.assertAllEqual(result, grad_inp)

  @test_util.run_deprecated_v1
  def testGradientsNegativeAxis(self):
    x1 = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]]
    x2 = [[7.0, 8.0, 9.0], [10.0, 11.0, 12.0]]
    inp_tensors = [constant_op.constant(x1, shape=(2, 3), dtype=dtypes.float32),
                   constant_op.constant(x2, shape=(2, 3), dtype=dtypes.float32)]

    # Test concat gradient with axis == -2
    self._testGradientsForAxis(inp_tensors, -2, output_shape=[4, 3])

    # Test concat gradient with unknown-shape tensors.
    x1_placeholder = array_ops.placeholder(dtypes.float32)
    x2_placeholder = array_ops.placeholder(dtypes.float32)
    inp_tensors_placeholders = [x1_placeholder, x2_placeholder]
    feed_dict = {x1_placeholder: x1, x2_placeholder: x2}
    self._testGradientsForAxis(
        inp_tensors_placeholders, -1, output_shape=[2, 6], feed_dict=feed_dict)

    # Test IndexedSlices concat gradient.
    self._testIndexedSlicesGradientsForAxis(
        inp_tensors, -2, output_shape=[2, 3], gather_indexes=[2, 0])

    # We don't support calculating IndexedSlices concat gradient for
    # negative indexes when rank is not known.
    with self.assertRaises(ValueError):
      self._testIndexedSlicesGradientsForAxis(
          inp_tensors_placeholders, -2, output_shape=[2, 3],
          gather_indexes=[2, 0], feed_dict=feed_dict)

  def testConcatDtype(self):
    for dtype in [dtypes.int32, dtypes.int64, dtypes.uint32, dtypes.uint64]:
      with test_util.use_gpu():
        t1 = constant_op.constant([[1, 2, 3], [4, 5, 6]], dtype=dtype)
        t2 = constant_op.constant([[7, 8, 9], [10, 11, 12]], dtype=dtype)

        c = gen_array_ops.concat_v2([t1, t2], 1)
        self.assertEqual([2, 6], c.get_shape().as_list())
        output = self.evaluate(c)
        self.assertAllEqual([[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]], output)

  def testConcatAxisType(self):
    for dtype in [dtypes.int32, dtypes.int64]:
      with test_util.use_gpu():
        t1 = [[1, 2, 3], [4, 5, 6]]
        t2 = [[7, 8, 9], [10, 11, 12]]

        c = gen_array_ops.concat_v2([t1, t2],
                                    constant_op.constant(1, dtype=dtype))
        self.assertEqual([2, 6], c.get_shape().as_list())
        output = self.evaluate(c)
        self.assertAllEqual([[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]], output)

class ConcatOffsetTest(test.TestCase):

  def testBasic(self):
    with test_util.use_gpu():
      cdim = constant_op.constant(1, dtypes.int32)
      s0 = constant_op.constant([2, 3, 5], dtypes.int32)
      s1 = constant_op.constant([2, 7, 5], dtypes.int32)
      s2 = constant_op.constant([2, 20, 5], dtypes.int32)
      off = gen_array_ops.concat_offset(cdim, [s0, s1, s2])
      ans = self.evaluate(off)
      self.assertAllEqual(ans, [[0, 0, 0], [0, 3, 0], [0, 10, 0]])

  @test_util.run_deprecated_v1
  def testNotVector(self):
    cdim = constant_op.constant(1, dtypes.int32)
    s0 = constant_op.constant([[2, 3, 5]], dtypes.int32)
    s1 = constant_op.constant([[2, 7, 5]], dtypes.int32)
    off = gen_array_ops.concat_offset(cdim, [s0, s1])
    with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
                                r"should be a vector"):
      self.evaluate(off)

  @test_util.run_deprecated_v1
  def testConcatDimOutOfRange(self):
    cdim = constant_op.constant(4, dtypes.int32)
    s0 = constant_op.constant([2, 3, 5], dtypes.int32)
    s1 = constant_op.constant([2, 7, 5], dtypes.int32)
    off = gen_array_ops.concat_offset(cdim, [s0, s1])
    with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
                                r"Concat dim is out of range: 4 vs. 3"):
      self.evaluate(off)

  @test_util.run_deprecated_v1
  def testDimMismatch(self):
    cdim = constant_op.constant(1, dtypes.int32)
    s0 = constant_op.constant([2, 3, 5], dtypes.int32)
    s1 = constant_op.constant([2, 7, 5, 10], dtypes.int32)
    off = gen_array_ops.concat_offset(cdim, [s0, s1])
    with self.assertRaisesRegex(errors_impl.InvalidArgumentError,
                                r"should contain 3 elem"):
      self.evaluate(off)

  @test_util.run_deprecated_v1
  def testSizeMismatch(self):
    cdim = constant_op.constant(1, dtypes.int32)
    s0 = constant_op.constant([2, 3, 5], dtypes.int32)
    s1 = constant_op.constant([2, 7, 10], dtypes.int32)
    off = gen_array_ops.concat_offset(cdim, [s0, s1])
    with self.assertRaisesRegex(
        errors_impl.InvalidArgumentError,
        r"All dimensions except 1 must match. Input 1 has shape \[2 7 10\] "
        r"and doesn't match input 0 with shape \[2 3 5\]."):
      self.evaluate(off)

  def testNegativeDim(self):
    with test_util.use_gpu():
      cdim = constant_op.constant(-2, dtypes.int32)
      s0 = constant_op.constant([2, 3, 5], dtypes.int32)
      s1 = constant_op.constant([2, 7, 5], dtypes.int32)
      s2 = constant_op.constant([2, 20, 5], dtypes.int32)
      off = gen_array_ops.concat_offset(cdim, [s0, s1, s2])
      ans = self.evaluate(off)
      self.assertAllEqual(ans, [[0, 0, 0], [0, 3, 0], [0, 10, 0]])

      cdim = constant_op.constant(-3, dtypes.int32)
      s0 = constant_op.constant([2, 3, 5], dtypes.int32)
      s1 = constant_op.constant([1, 3, 5], dtypes.int32)
      s2 = constant_op.constant([3, 3, 5], dtypes.int32)
      off = gen_array_ops.concat_offset(cdim, [s0, s1, s2])
      ans = self.evaluate(off)
      self.assertAllEqual(ans, [[0, 0, 0], [2, 0, 0], [3, 0, 0]])

  def testCreateMemDecBlockedFormat(self):
    """Try to create the mkl concat operation

    when one of the input's memory descriptor is in blocked format
    """
    if test_util.IsMklEnabled():
      s0 = np.ones((1, 8188, 4092, 1), dtype=np.uint8).astype(np.float32)
      s1 = array_ops.strided_slice(
          s0, [0, 1, 1, 0], [0, -1, -1, 0], [1, 1, 1, 1],
          begin_mask=9,
          end_mask=9)
      s2 = array_ops.slice(s1, [0, 0, 0, 0], [-1, -1, -1, 1])
      s3_1 = array_ops.slice(s2, [0, 4, 4, 0], [-1, 8178, 4082, 1])
      s3_2 = array_ops.slice(s2, [0, 4, 4, 0], [-1, 8178, 4082, 1])
      filter4_1 = constant_op.constant([[[[1.18, -0.51]]]])
      s4_1 = nn_ops.conv2d(
          s3_1, filter4_1, strides=[1, 1, 1, 1], padding="VALID")
      filter4_2 = constant_op.constant([[[[1.38, -0.11]]]])
      s4_2 = nn_ops.conv2d(
          s3_2, filter4_2, strides=[1, 1, 1, 1], padding="VALID")
      s5_1 = array_ops.slice(s4_1, [0, 6, 6, 0], [-1, 1, 1, -1])
      s5_2 = array_ops.slice(s4_2, [0, 6, 6, 0], [-1, 1, 1, -1])
      x_concat = array_ops.concat([s5_1, s5_2], 3)
      self.evaluate(
          x_concat
      )  # This test is only meant to check the creation is not crashed

if __name__ == "__main__":
  test.main()


text: home


text:
class SessionsController < ApplicationController
  skip_before_filter :require_login

  def new
  end

  def create
    user = User.authenticate(params[:email], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to root_url, :notice => "Logged in!"
    else
      flash[:error] = "Invalid Username or Password"
      redirect_to log_in_path
    end
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end
end


text:
Cidade-Roleplay
===============

Cidade:RP ( Open Source )


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.

using System;
using Microsoft.Azure.Management.SecurityInsights.Models;
using Microsoft.Azure.Management.SecurityInsights.Tests.Helpers;
using Microsoft.Azure.Test.HttpRecorder;
using Microsoft.Rest.Azure;
using Microsoft.Rest.ClientRuntime.Azure.TestFramework;
using Xunit;

namespace Microsoft.Azure.Management.SecurityInsights.Tests
{
    public class BookmarksTests : TestBase
    {
        #region Test setup

        #endregion

        #region Bookmarks

        [Fact]
        public void Bookmarks_List()
        {
            using (var context = MockContext.Start(this.GetType()))
            {
                var SecurityInsightsClient = TestHelper.GetSecurityInsightsClient(context);
                var BookmarkId = Guid.NewGuid().ToString();
                var BookmarkBody = BookmarksUtils.GetDefaultBookmarkProperties();
                var Bookmark = SecurityInsightsClient.Bookmarks.CreateOrUpdate(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId, BookmarkBody);

                var Bookmarks = SecurityInsightsClient.Bookmarks.List(TestHelper.ResourceGroup, TestHelper.WorkspaceName);
                ValidateBookmarks(Bookmarks);

                SecurityInsightsClient.Bookmarks.Delete(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId);
            }
        }

        [Fact]
        public void Bookmarks_CreateorUpdate()
        {

            using (var context = MockContext.Start(this.GetType()))
            {
                var SecurityInsightsClient = TestHelper.GetSecurityInsightsClient(context);
                var BookmarkId = Guid.NewGuid().ToString();
                var BookmarkBody = BookmarksUtils.GetDefaultBookmarkProperties();
                var Bookmark = SecurityInsightsClient.Bookmarks.CreateOrUpdate(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId, BookmarkBody);
                ValidateBookmark(Bookmark);
                SecurityInsightsClient.Bookmarks.Delete(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId);
            }
        }

        [Fact]
        public void Bookmarks_Get()
        {
            using (var context = MockContext.Start(this.GetType()))
            {
                var SecurityInsightsClient = TestHelper.GetSecurityInsightsClient(context);
                var BookmarkId = Guid.NewGuid().ToString();
                var BookmarkBody = BookmarksUtils.GetDefaultBookmarkProperties();
                SecurityInsightsClient.Bookmarks.CreateOrUpdate(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId, BookmarkBody);
                var Bookmark = SecurityInsightsClient.Bookmarks.Get(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId);
                ValidateBookmark(Bookmark);

            }
        }

        [Fact]
        public void Bookmarks_Delete()
        {
            using (var context = MockContext.Start(this.GetType()))
            {
                var SecurityInsightsClient = TestHelper.GetSecurityInsightsClient(context);
                var BookmarkId = Guid.NewGuid().ToString();
                var BookmarkBody = BookmarksUtils.GetDefaultBookmarkProperties();
                SecurityInsightsClient.Bookmarks.CreateOrUpdate(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId, BookmarkBody);
                SecurityInsightsClient.Bookmarks.Delete(TestHelper.ResourceGroup, TestHelper.WorkspaceName, BookmarkId);
            }
        }

        #endregion

        #region Validations

        private void ValidateBookmarks(IPage<Bookmark> Bookmarkpage)
        {
            Assert.True(Bookmarkpage.IsAny());

            Bookmarkpage.ForEach(ValidateBookmark);
        }

        private void ValidateBookmark(Bookmark Bookmark)
        {
            Assert.NotNull(Bookmark);
        }

        private void ValidateBookmarkExpand(BookmarkExpandResponse BookmarkExpand)
        {
            Assert.NotNull(BookmarkExpand);
        }

        #endregion
    }
}


text:
import React from 'react'

export default class Page500 extends React.Component{
    render() {
        return (

                {/* row */}

 Error 500

Oooops, Something went wrong!

                                        You have experienced a technical error. We apologize.

                                            We are working hard to correct this issue. Please wait a few moments and try your search again.
 In the meantime, check out whats new on SmartAdmin:

Go to My Dashboard

Contact SmartAdmin IT Staff

Report error!

Go back

                {/* end row */}

        )
    }
}


text:
void __cxa_free_exception(void * thrown_exception) throw(){

}


text:
#pragma once
#include <aws/codedeploy/CodeDeploy_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace CodeDeploy
{
namespace Model
{
  enum class ComputePlatform
  {
    NOT_SET,
    Server,
    Lambda
  };

namespace ComputePlatformMapper
{
AWS_CODEDEPLOY_API ComputePlatform GetComputePlatformForName(const Aws::String& name);

AWS_CODEDEPLOY_API Aws::String GetNameForComputePlatform(ComputePlatform value);
} // namespace ComputePlatformMapper
} // namespace Model
} // namespace CodeDeploy
} // namespace Aws


text:
var path = require('path');
var fs = require('fs');

var falafel = require('falafel');
var glob = require('glob');

var constants = require('../tasks/util/constants');

// check for for focus and exclude jasmine blocks

var BLACK_LIST = ['fdescribe', 'fit', 'xdescribe', 'xit'];
var testGlob = path.join(constants.pathToJasmineTests, '**/*.js');
var bundleTestGlob = path.join(constants.pathToJasmineBundleTests, '**/*.js');

var logsJasmine = [];
glob('{' + testGlob + ',' + bundleTestGlob + '}', function(err, files) {
    files.forEach(function(file) {
        var code = fs.readFileSync(file, 'utf-8');

        falafel(code, {locations: true}, function(node) {
            if(node.type === 'Identifier' && BLACK_LIST.indexOf(node.name) !== -1) {
                logsJasmine.push([
                    path.basename(file),
                    '[line ' + node.loc.start.line + '] :',
                    'contains either a *fdescribe*, *fit*,',
                    '*xdescribe* or *xit* block.'
                ].join(' '));
            }
        });

    });

    if(logsJasmine.length) {
        throw new Error('\n' + logsJasmine.join('\n') + '\n');
    }
});

// check for header in src and lib files

var licenseSrc = constants.licenseSrc;
var licenseStr = licenseSrc.substring(2, licenseSrc.length - 2);
var srcGlob = path.join(constants.pathToSrc, '**/*.js');
var libGlob = path.join(constants.pathToLib, '**/*.js');

var logsHeader = [];
glob('{' + srcGlob + ',' + libGlob + '}', function(err, files) {
    files.forEach(function(file) {
        var code = fs.readFileSync(file, 'utf-8');

        // parse through code string while keeping track of comments
        var comments = [];
        falafel(code, {onComment: comments, locations: true}, function() {});

        var header = comments[0];

        if(!header || header.loc.start.line > 1) {
            logsHeader.push(file + ' : has no header information.');
            return;
        }

        if(header.value !== licenseStr) {
            logsHeader.push(file + ' : has incorrect header information.');
        }
    });

    if(logsHeader.length) {
        throw new Error('\n' + logsHeader.join('\n') + '\n');
    }
});


text:
#pragma once
#include <memory>
#include <Windows.h>
#include <D3D11.h>

#include "DirectXDefs.hpp"
#include "IDirectX.hpp"

class IShader
{
protected:
  void LoadShaderFromFile(CHAR * shaderName, CHAR * shaderType, TCHAR * fileName);

  virtual void BuildShader(ID3D10Blob * shaderBlob) = 0;

  D3D11Instance mDxgiInstance;
  BlobPtr mShaderBlob;

public:
  template <typename T>
  void QueryType(T ** type)
  {
    if (type)
      *type = dynamic_cast<T *>((IShader *)this);
  }

  IShader() : mDxgiInstance(IDirectX::GetDirectXInstance()) {}
};

/*
class IShader
{
protected:
  IShader() = delete;
  IShader(D3D11Instance instance) : mDxgiInstance(instance) {}

  D3D11Instance mDxgiInstance;

  InputLayoutPtr mInputLayout;
  D3DBufferPtr mConstantBuffer;

  virtual void BuildShader(ID3D10Blob * shaderBlob) = 0;
  virtual void BuildConstantBuffer() = 0;
  virtual void BuildInputLayout(std::vector<D3D11_INPUT_ELEMENT_DESC> &) = 0;

public:
  template <typename Tcb>
  void UpdateShaderResource(Tcb & data);

  void SetInputAssemblerLayout();

  virtual void SetShader() = 0;

  void LoadShaderFromFile(CHAR * shaderName, CHAR * shaderType, TCHAR * fileName, D3D11InputDescVector & inputLayoutDesc);

  virtual ~IShader() {}
};

template <typename Tcb>
void IShader::UpdateShaderResource(Tcb & resource)
{
  //mDxgiInstance->mDevContext->UpdateSubresource(mConstantBuffer.Get(), 0, NULL, &resource, 0, 0);
  D3D11_MAPPED_SUBRESOURCE mapped;

  mDxgiInstance->mDevContext->Map(mConstantBuffer.Get(), 0, D3D11_MAP::D3D11_MAP_WRITE_DISCARD, 0, &mapped);

  memcpy(mapped.pData, &resource, sizeof(Tcb));

  mDxgiInstance->mDevContext->Unmap(mConstantBuffer.Get(), 0);
}
*/


text:
uint8_t fault_status = FAULT_STATUS_NONE;
uint32_t faults = 0U;

void fault_occurred(uint32_t fault) {
  faults |= fault;
  if((PERMANENT_FAULTS & fault) != 0U){
    puts("Permanent fault occurred: 0x"); puth(fault); puts("\n");
    fault_status = FAULT_STATUS_PERMANENT;
  } else {
    puts("Temporary fault occurred: 0x"); puth(fault); puts("\n");
    fault_status = FAULT_STATUS_TEMPORARY;
  }
}

void fault_recovered(uint32_t fault) {
  if((PERMANENT_FAULTS & fault) == 0U){
    faults &= ~fault;
  } else {
    puts("Cannot recover from a permanent fault!\n");
  }
}


text:
#include <yara/modules.h>

#define MODULE_NAME tests

define_function(fsum_2)
{
  double a = float_argument(1);
  double b = float_argument(2);

  return_float(a + b);
}

define_function(fsum_3)
{
  double a = float_argument(1);
  double b = float_argument(2);
  double c = float_argument(3);

  return_float(a + b + c);
}

define_function(isum_2)
{
  int64_t a = integer_argument(1);
  int64_t b = integer_argument(2);

  return_integer(a + b);
}

define_function(isum_3)
{
  int64_t a = integer_argument(1);
  int64_t b = integer_argument(2);
  int64_t c = integer_argument(3);

  return_integer(a + b + c);
}

define_function(length)
{
  char* s = string_argument(1);

  return_integer(strlen(s));
}

define_function(empty)
{
  return_string("");
}

define_function(match)
{
  return_integer(
      yr_re_match(scan_context(), regexp_argument(1), string_argument(2)));
}

define_function(foobar)
{
  int64_t arg = integer_argument(1);

  switch (arg)
  {
  case 1:
    return_string("foo");
    break;
  case 2:
    return_string("bar");
    break;
  }

  return_string("oops")
}

begin_declarations
  begin_struct("constants")
    declare_integer("one");
    declare_integer("two");
    declare_string("foo");
    declare_string("empty");
  end_struct("constants")

  begin_struct("undefined")
    declare_integer("i");
    declare_float("f");
  end_struct("undefined")

  declare_string("module_data");
  declare_integer_array("integer_array");
  declare_string_array("string_array");

  declare_integer_dictionary("integer_dict");
  declare_string_dictionary("string_dict");

  begin_struct_array("struct_array")
    declare_integer("i");
    declare_string("s");
  end_struct_array("struct_array")

  begin_struct_dictionary("struct_dict")
    declare_integer("i");
    declare_string("s");
  end_struct_dictionary("struct_dict");

  begin_struct_dictionary("empty_struct_dict")
    declare_integer("unused");
  end_struct_dictionary("empty_struct_dict")

  begin_struct_array("empty_struct_array")
    begin_struct_array("struct_array")
      declare_string("unused");
    end_struct_array("struct_array");
    begin_struct_dictionary("struct_dict")
      declare_string("unused");
    end_struct_dictionary("struct_dict");
  end_struct_array("empty_struct_array");

  declare_function("match", "rs", "i", match);
  declare_function("isum", "ii", "i", isum_2);
  declare_function("isum", "iii", "i", isum_3);
  declare_function("fsum", "ff", "f", fsum_2);
  declare_function("fsum", "fff", "f", fsum_3);
  declare_function("length", "s", "i", length);
  declare_function("empty", "", "s", empty);
  declare_function("foobar", "i", "s", foobar);
end_declarations

int module_initialize(YR_MODULE* module)
{
  return ERROR_SUCCESS;
}

int module_finalize(YR_MODULE* module)
{
  return ERROR_SUCCESS;
}

int module_load(
    YR_SCAN_CONTEXT* context,
    YR_OBJECT* module_object,
    void* module_data,
    size_t module_data_size)
{
  set_integer(1, module_object, "constants.one");
  set_integer(2, module_object, "constants.two");
  set_string("foo", module_object, "constants.foo");
  set_string("", module_object, "constants.empty");

  set_integer(1, module_object, "struct_array[1].i");

  set_integer(0, module_object, "integer_array[%i]", 0);
  set_integer(1, module_object, "integer_array[%i]", 1);
  set_integer(2, module_object, "integer_array[%i]", 2);
  set_integer(256, module_object, "integer_array[%i]", 256);

  set_string("foo", module_object, "string_array[%i]", 0);
  set_string("bar", module_object, "string_array[%i]", 1);
  set_string("baz", module_object, "string_array[%i]", 2);

  set_sized_string("foo\0bar", 7, module_object, "string_array[%i]", 3);

  set_string("foo", module_object, "string_dict[%s]", "foo");
  set_string("bar", module_object, "string_dict[\"bar\"]");

  set_string("foo", module_object, "struct_dict[%s].s", "foo");
  set_integer(1, module_object, "struct_dict[%s].i", "foo");

  if (module_data_size > 0 && module_data != NULL)
  {
    set_sized_string(
        (const char*) module_data,
        module_data_size,
        module_object,
        "module_data");
  }

  return ERROR_SUCCESS;
}

int module_unload(YR_OBJECT* module_object)
{
  // Fail if module_unload is called twice with the same module_object
  if (module_object->data == (void*) 0xFABADA)
    assert(false);

  module_object->data = (void*) 0xFABADA;
  return ERROR_SUCCESS;
}


text:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>The Equinox Project by EduardoPires</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" href="stylesheets/normalize.css" media="screen">
    <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" type="text/css" href="stylesheets/stylesheet.css" media="screen">
    <link rel="stylesheet" type="text/css" href="stylesheets/github-light.css" media="screen">

The Equinox Project

Full ASP.NET Core application with DDD, CQRS and Event Sourcing

      View on GitHub
      Download .zip
      Download .tar.gz

What is the Equinox Project?

The Equinox Project is a open-source project written in .NET Core

The goal of this project is implement the most common used technologies and share with the technical community the best way to develop great applications with .NET

Technologies implemented:

ASP.NET Core 1.1 (with .NET Core)

ASP.NET MVC Core

ASP.NET Identity Core

Entity Framework Core

Dapper

AutoMapper

.NET Core Native DI

Unit of Work

Repository and Generic Repository

FluentValidator

Architecture:

Full architecture with responsibility separation concerns, SOLID and Clean Code

Domain Driven Design (Layers and Domain Model Pattern)

Domain Events

Domain Notification

CQRS (Imediate Consistency)

Event Sourcing

Disclaimer:

This is a sample application using some beta/pre-release versions (including ASP.NET Core 1.1)

NOT intended to be a definitive solution

Beware to use in production way

Maybe you don't need a lot of implementations that is included, try avoid the over engineering

About the next versions

Watch your RoadMap to know the new changes

Pull-Requests are welcome!

Why Equinox?

The Equinox is an astronomical event in which the plane of Earth's equator passes through the center of the Sun, which occurs twice each year, around 20 March and 23 September. Wikipedia

Equinox is also a series of publications (subtitle: "The Review of Scientific Illuminism") in book form that serves as the official organ of the A∴A∴, a magical order founded by Aleister Crowley :) Wikipedia

We are Online:

See the project running on Azure

The Equinox Project was developed by Eduardo Pires under the MIT license.

        The Equinox Project is maintained by EduardoPires.

        This page was generated by GitHub Pages using the Cayman theme by Jason Long.


text:
<TimeML
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="../../dtd/timeml_1.2.1.xsd">

<DOCNO> WSJ891027-0089 </DOCNO>
<DD> = 891027 </DD>
<AN> 891027-0089. </AN>
<HL> Financing Business:
@  Healthdyne Inc. </HL>
<DD> 10/27/89 </DD>
<SO> WALL STREET JOURNAL (J) </SO>
<CO> HDYN </CO>
<IN> STOCK MARKET, OFFERINGS (STK)
INITIAL STOCK OFFERINGS (INI) </IN>
<TEXT>
   HEALTHDYNE Inc., Atlanta, said its subsidiary, Home Nutritional Services Inc., registered with the Securities and Exchange Commission an initial public offering of four million shares of common.
The in-home health care services provider said it will sell 1.8 million of the new shares, while Home Nutritional Services will sell the remaining 2.2 million.
The company estimates the offering price at between $14 and $16 a share.
The company said it expects to use the proceeds to repay certain bank debt and for general corporate purposes, including establishing new operating centers and possible acquisitions.
Home Nutritional currently has 10 million shares outstanding.
It will have 11.8 million shares outstanding after the offering, with Healthdyne owning about 65% of the total.

</TEXT>

</TimeML>