text:
require_relative 'util'

module BigML

 PLURALITY = 'plurality'
 CONFIDENCE = 'confidence weighted'
 PROBABILITY = 'probability weighted'
 THRESHOLD = 'threshold'
 BOOSTING = 'boosting'
 PLURALITY_CODE = 0
 CONFIDENCE_CODE = 1
 PROBABILITY_CODE = 2
 THRESHOLD_CODE = 3
 BOOSTING_CODE = -1
 # COMBINATION = -2
 # AGGREGATION = -3

 PREDICTION_HEADERS = ['prediction', 'confidence', 'order', 'distribution',
                      'count']
 COMBINATION_WEIGHTS = {
    PLURALITY => nil,
    CONFIDENCE => 'confidence',
    PROBABILITY => 'probability',
    THRESHOLD => nil,
    BOOSTING => 'weight'}
 COMBINER_MAP = {
    PLURALITY_CODE => PLURALITY,
    CONFIDENCE_CODE => CONFIDENCE,
    PROBABILITY_CODE => PROBABILITY,
    THRESHOLD_CODE => THRESHOLD,
    BOOSTING_CODE => BOOSTING}
 WEIGHT_KEYS = {
    PLURALITY => nil,
    CONFIDENCE => ['confidence'],
    PROBABILITY => ['distribution', 'count'],
    THRESHOLD => nil,
    BOOSTING => ['weight']}

 BOOSTING_CLASS = 'class'
 CONFIDENCE_W = COMBINATION_WEIGHTS[CONFIDENCE]

 DEFAULT_METHOD = 0
 BINS_LIMIT = 32

 NUMERICAL_COMBINATION_METHODS = {
    PLURALITY => "avg",
    CONFIDENCE => "error_weighted",
    PROBABILITY => "avg"}

  def self.weighted_sum(predictions, weight=nil)
   # Returns a weighted sum of the predictions
     return predictions.collect {|prediction| prediction["prediction"] * prediction[weight] }.inject(0){|sum,x| sum + x }
  end

  def self.softmax(predictions)
   # Returns the softmax values from a distribution given as a dictionary
   # like:
   #     {"category" => {"probability" => probability, "order" => order}}
   total = 0.0
   normalized = {}
   predictions.each do |category, cat_info|
      normalized[category] = {"probability" => Math.exp(cat_info["probability"]),
                             "order" => cat_info["order"]}
      total += normalized[category]["probability"]
   end

   if total == 0
      return Float::NAN
   else
     result = {}
     normalized.each do |category, cat_info|
       result[category] = {"probability" => cat_info["probability"] / total,
                           "order" => cat_info["order"]}
     end

     return result
   end
  end

  def self.ws_confidence(prediction, distribution, ws_z=1.96, ws_n=nil)
    # Wilson score interval computation of the distribution for the prediction

    #   expected arguments:
    #        prediction: the value of the prediction for which confidence is
    #                    computed
    #        distribution: a distribution-like structure of predictions and
    #                      the associated weights. (e.g.
    #                      [['Iris-setosa', 10], ['Iris-versicolor', 5]])
    #        ws_z: percentile of the standard normal distribution
    #        ws_n: total number of instances in the distribution. If absent,
    #              the number is computed as the sum of weights in the
    #              provided distribution
    if distribution.is_a?(Array)
        new_distribution = {}
        distribution.each do |it|
           new_distribution[it[0]] = it[1]
        end
        distribution = new_distribution
    end

    ws_p = distribution[prediction]
    if ws_p < 0
        raise ArgumentError, "The distribution weight must be a positive value"
    end

    ws_norm = distribution.values.inject(:+).to_f

    if ws_norm != 1.0
        ws_p = ws_p / ws_norm
    end

    if ws_n.nil?
        ws_n = ws_norm
    else
        ws_n = ws_n.to_f
    end

    if ws_n < 1
        raise ArgumentError, "The total of instances in the distribution must be a positive integer"
    end
    ws_z = ws_z.to_f
    ws_z2 = ws_z * ws_z
    ws_factor = ws_z2 / ws_n
    ws_sqrt = Math.sqrt((ws_p * (1 - ws_p) + ws_factor / 4) / ws_n)

    result=(ws_p + ws_factor / 2 - ws_z * ws_sqrt) / (1 + ws_factor).round(BigML::Util::PRECISION)

    return result

  end

  def self.merge_distributions(distribution, new_distribution)
    # Adds up a new distribution structure to a map formatted distribution

    new_distribution.each do |value, instances|
       if !distribution.key?(value)
          distribution[value] = 0
       end
       distribution[value] += instances
    end

    return  distribution

  end

  def self.merge_bins(distribution, limit)
    # Merges the bins of a regression distribution to the given limit number

    length = distribution.size
    if limit < 1 or length <= limit or length < 2
        return distribution
    end

    index_to_merge = 2
    shortest = Float::INFINITY

    (1..(length-1)).each do |index|
      distance = distribution[index][0] - distribution[index - 1][0]
      if distance < shortest
         shortest = distance
         index_to_merge = index
      end
    end

    new_distribution = distribution[0..(index_to_merge - 2)]
    left = distribution[index_to_merge - 1]
    right = distribution[index_to_merge]
    new_bin = [(left[0] * left[1] + right[0] * right[1]) /
               (left[1] + right[1]), left[1] + right[1]]
    new_distribution << new_bin
    if index_to_merge < (length - 1)
        new_distribution.concat(distribution[(index_to_merge + 1)..-1])
    end

    return merge_bins(new_distribution, limit)

  end

  class MultiVote
     # A multiple vote prediction
     # Uses a number of predictions to generate a combined prediction.
     #
     attr_accessor :predictions, :boosting, :boosting_offsets
     def initialize(predictions, boosting_offsets=nil)
       # Init method, builds a MultiVote with a list of predictions

       # The constuctor expects a list of well formed predictions like:
       #      {'prediction' => 'Iris-setosa', 'confidence' => 0.7}
       #  Each prediction can also contain an 'order' key that is used
       #   to break even in votations. The list order is used by default.
       #   The second argument will be true if the predictions belong to
       #   boosting models.

       @predictions = []
       @boosting = !boosting_offsets.nil?
       @boosting_offsets = boosting_offsets
       if predictions.is_a?(Array)
          @predictions.concat(predictions)
       else
          @predictions << predictions
       end

       if !predictions.collect {|prediction| prediction.key?('order') }.all?
          (0..(@predictions.size-1)).each do |i|
             @predictions[i]["order"] = i
          end
       end

     end

     def self.grouped_distribution(instance)
        # Returns a distribution formed by grouping the distributions of
        # each predicted node.

        joined_distribution = {}
        distribution_unit = 'counts'
        distribution=[]
        instance.predictions.each do |prediction|
           joined_distribution=BigML::merge_distributions(joined_distribution,
                                                   { prediction['distribution'][0][0] =>
                                                     prediction['distribution'][0][1] })
           # when there's more instances, sort elements by their mean
           distribution = joined_distribution.sort_by {|x| x[0]}.collect {|k, v| [k,v]}
           if distribution_unit == 'counts'
              distribution_unit = distribution.size > BINS_LIMIT ? 'bins' : 'counts'
           end
           distribution = BigML::merge_bins(distribution, BINS_LIMIT)
        end

        return {'distribution' => distribution,
                'distribution_unit' => distribution_unit}
     end

     def self.avg(instance, full=false)
        if !instance.predictions.empty? and full and
            !instance.predictions.collect{|prediction| prediction.key?(CONFIDENCE_W)}.all?
            raise Exception, "Not enough data to use the selected prediction method. Try creating your model anew."
        end
        total = instance.predictions.size
        result = 0.0
        median_result = 0.0
        confidence = 0.0
        instances = 0
        missing_confidence = 0
        d_min = Float::INFINITY
        d_max = -Float::INFINITY

        instance.predictions.each do |prediction|
            result += prediction['prediction']
            if full
              if prediction.key?("median")
                median_result += prediction['median']
              end

              if !prediction[CONFIDENCE_W].nil? and
                  prediction[CONFIDENCE_W] > 0
                 confidence += prediction[CONFIDENCE_W]
              else
                missing_confidence += 1
              end

              instances += prediction['count']

              if prediction.key?("min") and prediction['min'] < d_min
                d_min = prediction['min']
              end

              if prediction.key?("max") and prediction['max'] > d_max
                d_max = prediction['max']
              end

            end
        end

        if full
          output = {'prediction' => total > 0 ? result/total :  Float::INFINITY}
          # some strange models have no confidence
          output['confidence'] = total > 0 ?  (confidence /(total-missing_confidence)).round(BigML::Util::PRECISION) : 0
          output.merge!(grouped_distribution(instance))
          output['count'] = instances
          if median_result > 0
            output['median'] = total > 0 ? median_result/total : Float::NAN
          end
          if d_min < Float::INFINITY
             output['min'] = d_min
          end

          if d_max > -Float::INFINITY
             output['max'] = d_max
          end

          return output
        end

        return total > 0 ?  result / total : Float::INFINITY

     end

     def self.error_weighted(instance, full=false)
        #  Returns the prediction combining votes using error to compute weight

        #   If with_confidences is true, the combined confidence (as the
        #   error weighted average of the confidences of the multivote
        #   predictions) is also returned
        #

        if !instance.predictions.empty? and full and !instance.predictions.collect{|prediction| prediction.key?(CONFIDENCE_W)}.all?
            raise Exception, "Not enough data to use the selected prediction method. Try creating your model anew."
        end

        top_range = 10
        result = 0.0
        median_result = 0.0
        instances = 0
        d_min = Float::INFINITY
        d_max = -Float::INFINITY

        normalization_factor = MultiVote.normalize_error(instance, top_range)
        if normalization_factor == 0
            if with_confidence
               return [Float::INFINITY, 0]
            else
               return Float::INFINITY
            end
        end

        if full
          combined_error = 0.0
        end

        instance.predictions.each do |prediction|
          result += prediction['prediction'] * prediction['_error_weight']
          if full

            if prediction.key?("median")
              median_result += (prediction['median'] *
                                prediction['_error_weight'])
            end

            instances += prediction['count']

            if prediction.key?("min") && prediction['min'] < d_min
              d_min = prediction['min']
            end

            if prediction.key?("max") && prediction['max'] > d_max
              d_max = prediction['max']
            end

            # some buggy models don't produce a valid confidence value
            if !prediction[CONFIDENCE_W].nil?
                combined_error += (prediction[CONFIDENCE_W] *
                                   prediction['_error_weight'])
            end

            prediction.delete('_error_weight')

          end
        end

        if full
          output = {'prediction' => result / normalization_factor}
          output['confidence'] =  (combined_error / normalization_factor).round(BigML::Util::PRECISION)
          output.merge!(grouped_distribution(instance))
          output['count'] = instances

          if median_result > 0
            output['median'] = median_result / normalization_factor
          end

          if d_min < Float::INFINITY
             output['min'] = d_min
          end

          if d_max < -Float::INFINITY
             output['max'] = d_max
          end

          return output
        end

        return result / normalization_factor

     end

     def self.normalize_error(instance, top_range)
        # Normalizes error to a [0, top_range] and builds probabilities

        if !instance.predictions.empty? and
             !instance.predictions..collect {|prediction| prediction.key?(CONFIDENCE_W) }.all?
            raise Exception , "Not enough data to use the selected prediction method. Try creating your model anew."
        end
        error_values=[]
        instance.predictions.each do |prediction|
          unless prediction[CONFIDENCE_W].nil?
            error_values.append(prediction[CONFIDENCE_W])
          end
        end

        max_error = error_values.max
        min_error = error_values.min
        error_range = 1.0 * (max_error - min_error)
        normalize_factor = 0
        if error_range > 0
            # Shifts and scales predictions errors to [0, top_range].
            # Then builds e^-[scaled error] and returns the normalization
            # factor to fit them between [0, 1]
            instance.predictions.each do |prediction|
                delta = (min_error - prediction[CONFIDENCE_W])
                prediction['_error_weight'] = Math.exp(delta / error_range *
                                                       top_range)
                normalize_factor += prediction['_error_weight']
            end
        else
            instance.predictions.each do |prediction|
                prediction['_error_weight'] = 1
            end
            normalize_factor = error_values.size
        end
        return normalize_factor

     end

     def is_regression()
        # Returns True if all the predictions are numbers

        if !@boosting.nil? && @boosting
           return @predictions.collect{|prediction| prediction.fetch("class", nil).nil? }.any?
        end

        return @predictions.collect{|prediction| prediction["prediction"].is_a?(Numeric) }.all?
     end

     def next_order()
        # Return the next order to be assigned to a prediction

        #    Predictions in MultiVote are ordered in arrival sequence when
        #   added using the constructor or the append and extend methods.
        #   This order is used to break even cases in combination
        #   methods for classifications.

        if !@predictions.empty?
            return @predictions[-1]['order'] + 1
        end
        return 0
     end

     def combine(method=DEFAULT_METHOD, options=nil, full=false)
        #  "Reduces a number of predictions voting for classification and
        #   averaging predictions for regression.

        #   method will determine the voting method (plurality, confidence
        #   weighted, probability weighted or threshold).
        #   If with_confidence is true, the combined confidence (as a weighted
        #   average of the confidences of votes for the combined prediction)
        #   will also be given.
        #
        # there must be at least one prediction to be combined
        if @predictions.empty?
            raise Exception, "No predictions to be combined."
        end

        method = COMBINER_MAP.fetch(method, COMBINER_MAP[DEFAULT_METHOD])
        keys = WEIGHT_KEYS.fetch(method, nil)
        # and all predictions should have the weight-related keys

        if !keys.nil?
            keys.each do |key|
	       if !@predictions.collect{|prediction| prediction.key?(key) }.all?
                 raise Exception, "Not enough data to use the selected prediction method. Try creating your model anew."
               end
            end
        end

        if !@boosting.nil? and @boosting
            @predictions.each do |prediction|
              if prediction[COMBINATION_WEIGHTS[BOOSTING]].nil?
                 prediction[COMBINATION_WEIGHTS[BOOSTING]] = 0
              end
            end

            if is_regression()
               # sum all gradients weighted by their "weight"
               return BigML::weighted_sum(@predictions, "weight")+self.boosting_offsets
            else
               return classification_boosting_combiner(options, full)
            end

        elsif is_regression()
            @predictions.each do |prediction|
              if prediction[CONFIDENCE_W].nil?
                 prediction[CONFIDENCE_W] = 0
              end
            end

            function = MultiVote.method(NUMERICAL_COMBINATION_METHODS.fetch(method, "avg"))
            return function.call(self, full)
        else
            if method == THRESHOLD
                if options.nil?
                    options = {}
                end
                predictions = single_out_category(options)
            elsif method == PROBABILITY
                predictions = MultiVote.new([])
                predictions.predictions = probability_weight()
            else
                predictions = self
            end

            return predictions.combine_categorical(
                COMBINATION_WEIGHTS.fetch(method, nil),
                full)
        end

     end

     def probability_weight()
        # Reorganizes predictions depending on training data probability
        predictions = []
        @predictions.each do |prediction|
           if !prediction.include?('distribution') or !prediction.include?('count')
              raise Exception, "Probability weighting is not available because distribution information is missing."
           end

           total = prediction['count']
           if total < 1 or !total.is_a?(Integer)
              raise Exception, "Probability weighting is not available
                                because distribution seems to have %s as number
                                of instances in a node" % [total]
           end
           order = prediction['order']
           prediction['distribution'].each do |prediction,instances|
             predictions << {'prediction' => prediction,
                             'probability' => (instances.to_f/total).round(BigML::Util::PRECISION),
                             'count' => instances, 'order' =>  order}
           end

        end

        return predictions
     end

     def combine_distribution(weight_label='probability')
        # Builds a distribution based on the predictions of the MultiVote

        #   Given the array of predictions, we build a set of predictions with
        #   them and associate the sum of weights (the weight being the
        #   contents of the weight_label field of each prediction)

        if !@predictions.collect {|prediction| prediction.include?(weight_label)}.all?
           Exception "Not enough data to use the selected  prediction method. Try creating your model anew."
        end

        distribution = {}
        total = 0
        @predictions.each do |prediction|
            if !distribution.include?(prediction["prediction"])
               distribution[prediction['prediction']] = 0.0
            end
            distribution[prediction['prediction']] += prediction[weight_label]
            total += prediction['count']
        end

        if total > 0
           distribution = distribution.collect{ |key, value| [key, value]}
        else
           distribution = []
        end

        return [distribution, total]
     end

     def combine_categorical(weight_label=nil, full=false)
        # Returns the prediction combining votes by using the given weight:

        #    weight_label can be set as:
        #    nil:          plurality (1 vote per prediction)
        #    'confidence':  confidence weighted (confidence as a vote value)
        #    'probability': probability weighted (probability as a vote value)

        #    If with_confidence is true, the combined confidence (as a weighted
        #    average of the confidences of the votes for the combined
        #    prediction) will also be given.
        #
        mode = {}
        instances = 0
        if weight_label.nil?
            weight = 1
        end

        @predictions.each do |prediction|
            if !weight_label.nil?
               if !COMBINATION_WEIGHTS.values.include?(weight_label)
                   raise Exception, "Wrong weight_label value."
               end
               if !prediction.include?(weight_label)
                   raise Exception, "Not enough data to use the selected prediction method. Try creating your model anew."
               else
                   weight = prediction[weight_label]
               end
            end
            category = prediction['prediction']
            if full
               instances += prediction['count']
            end
            if mode.include?(category)
                mode[category] = {"count" => mode[category]["count"] + weight,
                                 "order" => mode[category]["order"]}
            else
                mode[category] = {"count"=> weight,
                                  "order"=> prediction['order']}
            end
        end

        prediction = mode.sort_by {|key, x| [x["count"], -x["order"], key]}.collect {|key,value|
                     [key, value]}.reverse[0][0]

        if full
          output = {'prediction' => prediction}
          if self.predictions[0].key?("confidence")
            data = weighted_confidence(prediction, weight_label)
            prediction = data[0]
            combined_confidence = data[1]
          else
            if self.predictions[0].key?("probability")
              combined_distribution = combine_distribution()
              distribution = combined_distribution[0]
              count = combined_distribution[1]
              combined_confidence = BigML::ws_confidence(prediction, distribution, 1.96 , count)
            end
          end
          output['confidence']=combined_confidence.round(BigML::Util::PRECISION)

          if self.predictions[0].key?("probability")
            self.predictions.each do|prediction|
              if prediction['prediction'] == output['prediction']
                output['probability'] = prediction['probability']
              end
            end
          end

          if self.predictions[0].key?("distribution")
            grouped_dis = self.class.grouped_distribution(self)
            output["distribution"] = grouped_dis["distribution"]
            output["distribution_unit"] = grouped_dis["distribution_unit"]
          end

          output['count'] = instances
          return output
        end

        return prediction

     end

     def weighted_confidence(combined_prediction, weight_label)
        #Compute the combined weighted confidence from a list of predictions

        predictions = []
        @predictions.each do |prediction|
          if prediction['prediction'] == combined_prediction
              predictions << prediction
          end
        end

        if (!weight_label.nil? and (!weight_label.is_a?(String) or
                                    predictions.any?{|prediction| !prediction.include?(CONFIDENCE_W) or
                                                                  !prediction.include?(weight_label)  }  ))

           raise ArgumentError, "Not enough data to use the selected prediction method. Lacks %s information." % [weight_label]
        end

        final_confidence = 0.0
        total_weight = 0.0
        weight = 1

        predictions.each do |prediction|
           if !weight_label.nil?
              weight = prediction[weight_label]
           end
           final_confidence += weight * prediction[CONFIDENCE_W]
           total_weight += weight
        end

        final_confidence = total_weight > 0 ? final_confidence / total_weight : Float::INFINITY
        return [combined_prediction, final_confidence]

     end

     def classification_boosting_combiner(options,
                                         full=false)
        # Combines the predictions for a boosted classification ensemble
        # Applies the regression boosting combiner, but per class. Tie breaks
        # use the order of the categories in the ensemble summary to decide.
        grouped_predictions = {}
        @predictions.each do |prediction|
          if !prediction.fetch(BOOSTING_CLASS, nil).nil?
             objective_class = prediction.fetch(BOOSTING_CLASS)
             if grouped_predictions.fetch(objective_class, nil).nil?
                grouped_predictions[objective_class] = []
             end
             grouped_predictions[objective_class] << prediction
          end
        end

        categories = options.fetch("categories", [])
        predictions = {}
        grouped_predictions.each {|key,value|
           predictions[key] = {"probability" => BigML::weighted_sum(value, "weight"),
                               "order" => categories.index(key)}
        }

        grouped_predictions.each {|key,value|
          predictions[key] = {"probability" => BigML::weighted_sum(value, "weight") +
                                               @boosting_offsets.fetch(key, 0),
                              "order" => categories.index(key)}
        }

        predictions = BigML::softmax(predictions)
        predictions = predictions.sort_by {|i,x| [-x["probability"],x["order"]] }
        prediction, prediction_info = predictions[0]
        confidence = prediction_info["probability"].round(BigML::Util::PRECISION)

        if full
          return {"prediction" => prediction,
                  "probability" => confidence,
                  "probabilities" => predictions.collect{|prediction, prediction_info| {"category" => prediction, "probability" =>  prediction_info["probability"].round(BigML::Util::PRECISION)} } }

        else
          return prediction
        end
     end

     def append(prediction_info)
        # Adds a new prediction into a list of predictions

        #   prediction_info should contain at least:
        #   - prediction: whose value is the predicted category or value

        #   for instance:
        #       {'prediction': 'Iris-virginica'}

        #   it may also contain the keys:
        #   - confidence: whose value is the confidence/error of the prediction
        #   - distribution: a list of [category/value, instances] pairs
        #                   describing the distribution at the prediction node
        #   - count: the total number of instances of the training set in the
        #            node
        #
        if prediction_info.is_a?(Hash)
           if prediction_info.include?('prediction')
             order = next_order()
             prediction_info['order'] = order
             @predictions << prediction_info
           else
             warn("Failed to add the prediction.\n The minimal key for the prediction is 'prediction' :\n{'prediction': 'Iris-virginica'")
           end
        end

     end

     def single_out_category(options)
        # Singles out the votes for a chosen category and returns a prediction
        #   for this category iff the number of votes reaches at least the given
        #   threshold.
        #
        if options.nil? or ["threshold", "category"].any? {|option| !options.include?(option)}
            raise Exception, "No category and threshold information was  found.
                              Add threshold and category info.
                              E.g. {\"threshold\": 6, \"category\":
                              \"Iris-virginica\"}."
        end

        length = @predictions.size

        if options["threshold"] > length
            raise Exception, "You cannot set a threshold value larger than "
                             "%s. The ensemble has not enough models to use"
                             " this threshold value." % [length]
        end

        if options["threshold"] < 1
            raise Exception, "The threshold must be a positive value"
        end

        category_predictions = []
        rest_of_predictions = []

        @predictions.each do |prediction|
          if prediction['prediction'] == options["category"]
             category_predictions << prediction
          else
             rest_of_predictions << prediction
          end
        end

        if category_predictions.size >= options["threshold"]
            return MultiVote.new(category_predictions)
        end
        return MultiVote(rest_of_predictions)
     end

     def append_row(prediction_row,
                    prediction_headers=PREDICTION_HEADERS)
        # Adds a new prediction into a list of predictions

        #   prediction_headers should contain the labels for the prediction_row
        #   values in the same order.

        #   prediction_headers should contain at least the following string
        #   - 'prediction': whose associated value in prediction_row
        #                   is the predicted category or value

        #   for instance:
        #       prediction_row = ['Iris-virginica']
        #       prediction_headers = ['prediction']

        #   it may also contain the following headers and values:
        #   - 'confidence': whose associated value in prediction_row
        #                   is the confidence/error of the prediction
        #   - 'distribution': a list of [category/value, instances] pairs
        #                     describing the distribution at the prediction node
        #   - 'count': the total number of instances of the training set in the
        #              node
        #
        if (prediction_row.is_a?(Array) and
                prediction_headers.is_a?(Array) and
                prediction_row.size == prediction_headers.size and
                prediction_headers.include?('prediction'))
            order = next_order()
            begin
                index = prediction_headers.index('order')
                prediction_row[index] = order
            rescue Exception
                prediction_headers << 'order'
                prediction_row << order
            end

            prediction_info = {}
            (0..prediction_row.size-1).each do |i|
               prediction_info[prediction_headers[i]] = prediction_row[i]
            end

            @predictions << prediction_info
         else
            puts "WARNING: failed to add the prediction. The row must have label 'prediction' at least."
         end
     end

     def extend(predictions_info)
        # Given a list of predictions, extends the list with another list of
        #  predictions and adds the order information. For instance,
        #  predictions_info could be:

        #      [{'prediction': 'Iris-virginica', 'confidence': 0.3},
        #      {'prediction': 'Iris-versicolor', 'confidence': 0.8}]
        #  where the expected prediction keys are: prediction (compulsory),
        #  confidence, distribution and count.
        #

        if predictions_info.is_a?(Array)
            order = next_order()
            (0..predictions_info.size-1).each do |i|
               prediction = predictions_info[i]
               if prediction.is_a?(Hash)
                  prediction['order'] = order + i
                  append(prediction)
               else
                 puts "WARNING: failed to add the prediction. Only dict like predictions are expected"
               end
            end
        else
            puts "WARNING: failed to add the predictions Only a list of dict-like predictions are expected."
        end
     end

     def extend_rows(predictions_rows,
                    prediction_headers=PREDICTION_HEADERS)
        #  Given a list of predictions, extends the list with a list of
        #  predictions and adds the order information. For instance,
        #  predictions_info could be:

        #      [['Iris-virginica', 0.3],
        #      ['Iris-versicolor', 0.8]]
        #  and their respective labels are extracted from predition_headers,
        #  that for this example would be:
        #      ['prediction', 'confidence']

        #  The expected prediction elements are: prediction (compulsory),
        #  confidence, distribution and count.
        #
        order = next_order()
        begin
            index = prediction_headers.index('order')
        rescue Exception
            index = prediction_headers.size
            prediction_headers.append('order')
        end

        if predictions_rows.is_a?(Array)
            range(0..predictions_rows.size-1).each do |i|
                prediction = predictions_rows[i]
                if prediction.is_a?(Array)
                   if index == len(prediction)
                      prediction << order+1
                   else
                      prediction[index] = order + i
                   end
                   append_row(prediction, prediction_headers)
                else
                   puts "WARNING: failed to add the prediction. Only row-like predictions are expected."
                end
            end
        else
            puts "WARNING: failed to add the predictions. Only a list of row-like predictions are expected."
        end
     end

  end

end


text:
namespace {

bool CheckCtrlAndAltArePressed(const std::set<ui::DomCode>& pressed_keys) {
  size_t ctrl_keys = pressed_keys.count(ui::DomCode::CONTROL_LEFT) +
                     pressed_keys.count(ui::DomCode::CONTROL_RIGHT);
  size_t alt_keys = pressed_keys.count(ui::DomCode::ALT_LEFT) +
                    pressed_keys.count(ui::DomCode::ALT_RIGHT);
  return ctrl_keys != 0 && alt_keys != 0 &&
    (ctrl_keys + alt_keys == pressed_keys.size());
}

bool IsWinKeyPressed(const std::set<ui::DomCode>& pressed_keys) {
  size_t win_keys = pressed_keys.count(ui::DomCode::META_LEFT) +
                    pressed_keys.count(ui::DomCode::META_RIGHT);
  return win_keys != 0 && win_keys == pressed_keys.size();
}

} // namespace

namespace remoting {

using protocol::ClipboardEvent;
using protocol::KeyEvent;
using protocol::MouseEvent;
using protocol::TextEvent;
using protocol::TouchEvent;

class SessionInputInjectorWin::Core
    : public base::RefCountedThreadSafe<SessionInputInjectorWin::Core>,
      public InputInjector {
 public:
  Core(scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
       std::unique_ptr<InputInjector> nested_executor,
       scoped_refptr<base::SingleThreadTaskRunner> inject_sas_task_runner,
       const base::Closure& inject_sas,
       const base::Closure& lock_workstation);

  // InputInjector implementation.
  void Start(std::unique_ptr<ClipboardStub> client_clipboard) override;

  // protocol::ClipboardStub implementation.
  void InjectClipboardEvent(const ClipboardEvent& event) override;

  // protocol::InputStub implementation.
  void InjectKeyEvent(const KeyEvent& event) override;
  void InjectTextEvent(const TextEvent& event) override;
  void InjectMouseEvent(const MouseEvent& event) override;
  void InjectTouchEvent(const TouchEvent& event) override;

 private:
  friend class base::RefCountedThreadSafe<Core>;
  ~Core() override;

  // Switches to the desktop receiving a user input if different from
  // the current one.
  void SwitchToInputDesktop();

  scoped_refptr<base::SingleThreadTaskRunner> input_task_runner_;

  // Pointer to the next event executor.
  std::unique_ptr<InputInjector> nested_executor_;

  scoped_refptr<base::SingleThreadTaskRunner> execute_action_task_runner_;

  webrtc::ScopedThreadDesktop desktop_;

  // Used to inject Secure Attention Sequence.
  base::Closure inject_sas_;

  // Used to lock the current session on non-home SKUs of Windows.
  base::Closure lock_workstation_;

  // Keys currently pressed by the client, used to detect key sequences.
  std::set<ui::DomCode> pressed_keys_;

  DISALLOW_COPY_AND_ASSIGN(Core);
};

SessionInputInjectorWin::Core::Core(
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
    std::unique_ptr<InputInjector> nested_executor,
    scoped_refptr<base::SingleThreadTaskRunner> execute_action_task_runner,
    const base::Closure& inject_sas,
    const base::Closure& lock_workstation)
    : input_task_runner_(input_task_runner),
      nested_executor_(std::move(nested_executor)),
      execute_action_task_runner_(execute_action_task_runner),
      inject_sas_(inject_sas),
      lock_workstation_(lock_workstation) {}

void SessionInputInjectorWin::Core::Start(
    std::unique_ptr<protocol::ClipboardStub> client_clipboard) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE,
        base::BindOnce(&Core::Start, this, std::move(client_clipboard)));
    return;
  }

  nested_executor_->Start(std::move(client_clipboard));
}

void SessionInputInjectorWin::Core::InjectClipboardEvent(
    const ClipboardEvent& event) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&Core::InjectClipboardEvent, this, event));
    return;
  }

  nested_executor_->InjectClipboardEvent(event);
}

void SessionInputInjectorWin::Core::InjectKeyEvent(const KeyEvent& event) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&Core::InjectKeyEvent, this, event));
    return;
  }

  // HostEventDispatcher should drop events lacking the pressed field.
  DCHECK(event.has_pressed());

  if (event.has_usb_keycode()) {
    ui::DomCode dom_code = static_cast<ui::DomCode>(event.usb_keycode());
    if (event.pressed()) {
      // Simulate secure attention sequence if Ctrl-Alt-Del was just pressed.
      if (dom_code == ui::DomCode::DEL &&
          CheckCtrlAndAltArePressed(pressed_keys_)) {
        VLOG(3) << "Sending Secure Attention Sequence to the session";
        execute_action_task_runner_->PostTask(FROM_HERE, inject_sas_);
      } else if (dom_code == ui::DomCode::US_L &&
                 IsWinKeyPressed(pressed_keys_)) {
        execute_action_task_runner_->PostTask(FROM_HERE, lock_workstation_);
      }

      pressed_keys_.insert(dom_code);
    } else {
      pressed_keys_.erase(dom_code);
    }
  }

  SwitchToInputDesktop();
  nested_executor_->InjectKeyEvent(event);
}

void SessionInputInjectorWin::Core::InjectTextEvent(const TextEvent& event) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&Core::InjectTextEvent, this, event));
    return;
  }

  SwitchToInputDesktop();
  nested_executor_->InjectTextEvent(event);
}

void SessionInputInjectorWin::Core::InjectMouseEvent(const MouseEvent& event) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&Core::InjectMouseEvent, this, event));
    return;
  }

  SwitchToInputDesktop();
  nested_executor_->InjectMouseEvent(event);
}

void SessionInputInjectorWin::Core::InjectTouchEvent(const TouchEvent& event) {
  if (!input_task_runner_->BelongsToCurrentThread()) {
    input_task_runner_->PostTask(
        FROM_HERE, base::BindOnce(&Core::InjectTouchEvent, this, event));
    return;
  }

  SwitchToInputDesktop();
  nested_executor_->InjectTouchEvent(event);
}

SessionInputInjectorWin::Core::~Core() {
}

void SessionInputInjectorWin::Core::SwitchToInputDesktop() {
  // Switch to the desktop receiving user input if different from the current
  // one.
  std::unique_ptr<webrtc::Desktop> input_desktop(
      webrtc::Desktop::GetInputDesktop());
  if (input_desktop.get() != nullptr && !desktop_.IsSame(*input_desktop)) {
    // If SetThreadDesktop() fails, the thread is still assigned a desktop.
    // So we can continue capture screen bits, just from a diffected desktop.
    desktop_.SetThreadDesktop(input_desktop.release());
  }
}

SessionInputInjectorWin::SessionInputInjectorWin(
    scoped_refptr<base::SingleThreadTaskRunner> input_task_runner,
    std::unique_ptr<InputInjector> nested_executor,
    scoped_refptr<base::SingleThreadTaskRunner> inject_sas_task_runner,
    const base::Closure& inject_sas,
    const base::Closure& lock_workstation) {
  core_ = new Core(input_task_runner, std::move(nested_executor),
                   inject_sas_task_runner, inject_sas, lock_workstation);
}

SessionInputInjectorWin::~SessionInputInjectorWin() {
}

void SessionInputInjectorWin::Start(
    std::unique_ptr<protocol::ClipboardStub> client_clipboard) {
  core_->Start(std::move(client_clipboard));
}

void SessionInputInjectorWin::InjectClipboardEvent(
    const protocol::ClipboardEvent& event) {
  core_->InjectClipboardEvent(event);
}

void SessionInputInjectorWin::InjectKeyEvent(const protocol::KeyEvent& event) {
  core_->InjectKeyEvent(event);
}

void SessionInputInjectorWin::InjectTextEvent(
    const protocol::TextEvent& event) {
  core_->InjectTextEvent(event);
}

void SessionInputInjectorWin::InjectMouseEvent(
    const protocol::MouseEvent& event) {
  core_->InjectMouseEvent(event);
}

void SessionInputInjectorWin::InjectTouchEvent(
    const protocol::TouchEvent& event) {
  core_->InjectTouchEvent(event);
}

}  // namespace remoting

redpajama_set_name: RedPajamaGithub


text:
package org.apache.harmony.xnet.provider.jsse;

import org.apache.harmony.xnet.provider.jsse.Message;

import java.io.IOException;

/**
 *
 * Represents Finished message
 * @see TLS 1.0 spec., 7.4.9. Finished
 * (http://www.ietf.org/rfc/rfc2246.txt)
 *
 */
public class Finished extends Message {

    // verify data
    private byte[] data;

    /**
     * Creates outbound message
     * @param bytes
     */
    public Finished(byte[] bytes) {
        data = bytes;
        length = data.length;
    }

    /**
     * Creates inbound message
     * @param in
     * @param length
     * @throws IOException
     */
    public Finished(HandshakeIODataStream in, int length)
            throws IOException {
        if (length == 12 || length == 36) {
            data = in.read(length);
        } else {
            fatalAlert(AlertProtocol.DECODE_ERROR, "DECODE ERROR: incorrect Finished");
        }
    }

    @Override
    public void send(HandshakeIODataStream out) {
        out.write(data);
    }

    /**
     * Returns message type
     * @return
     */
    @Override
    public int getType() {
        return Handshake.FINISHED;
    }

    /**
     * Returns verify data
     * @return
     */
    public byte[] getData() {
        return data;
    }
}


text:
#include "zappersettings.h"

#include <QtCore/QDebug>
#include <QtCore/QDir>
#include <QtCore/QSettings>
#include <QtCore/QStandardPaths>

static char STR_DEFAULT_PATH[]  = "defaultPath";
static char STR_PLAYLIST_PATH[] = "playlistPath";
static char STR_GROUP_KEEP[]    = "keep";
static char STR_GROUP_ZAP[]     = "zap";
static char STR_GROUP_MOVE[]    = "move";
static char STR_COMMAND[]       = "command";
static char STR_PATH[]          = "path";
static char STR_IMMEDIAT[]      = "immediat";
static char STR_DETACHABLE[]    = "detachable";
static char STR_AUTOSAVE[]      = "autosave";

ZapperSettings::ZapperSettings()
    : keepSettings(CommandSettings())
    , zapSettings(CommandSettings())
    , moveSettings(CommandSettings())
    , playlistPath(QString())
    , autosaved(false)
{

}

void ZapperSettings::readSettings()
{
    QSettings settings;

    QString dir = QStandardPaths::writableLocation(QStandardPaths::MusicLocation);
    QString defPath  = QDir::toNativeSeparators(QString("%0/MuzicZapper/").arg(dir));
    QString playlist = QDir::toNativeSeparators(QString("%0/MuzicZapper/playlist.mzf").arg(dir));
    QString keepPath = QDir::toNativeSeparators(QString("%0/MuzicZapper/Saved").arg(dir));
    QString zapPath  = QDir::toNativeSeparators(QString("%0/MuzicZapper/Zapped").arg(dir));
    QString movePath = QDir::toNativeSeparators(QString("%0/MuzicZapper/Deleted").arg(dir));

    settings.beginGroup(STR_GROUP_KEEP);
    keepSettings.command = (Command)settings.value(STR_COMMAND   , 1).toInt();
    keepSettings.path             = settings.value(STR_PATH      , keepPath).toString();
    keepSettings.isImmediat       = settings.value(STR_IMMEDIAT  , true).toBool();
    keepSettings.isDetachable     = settings.value(STR_DETACHABLE, true).toBool();
    settings.endGroup();

    settings.beginGroup(STR_GROUP_ZAP);
    zapSettings.command = (Command)settings.value(STR_COMMAND   , 0).toInt();
    zapSettings.path             = settings.value(STR_PATH      , zapPath).toString();
    zapSettings.isImmediat       = settings.value(STR_IMMEDIAT  , true).toBool();
    zapSettings.isDetachable     = settings.value(STR_DETACHABLE, false).toBool();
    settings.endGroup();

    settings.beginGroup(STR_GROUP_MOVE);
    moveSettings.command = (Command)settings.value(STR_COMMAND   , 2).toInt();
    moveSettings.path             = settings.value(STR_PATH      , movePath).toString();
    moveSettings.isImmediat       = settings.value(STR_IMMEDIAT  , true).toBool();
    moveSettings.isDetachable     = settings.value(STR_DETACHABLE, true).toBool();
    settings.endGroup();

    defaultPath = settings.value(STR_DEFAULT_PATH, defPath).toString();
    playlistPath = settings.value(STR_PLAYLIST_PATH, playlist).toString();
    autosaved = settings.value(STR_AUTOSAVE, true).toBool();

}

void ZapperSettings::writeSettings()
{
    QSettings settings;

    settings.beginGroup(STR_GROUP_KEEP);
    settings.setValue(STR_COMMAND   , (int)keepSettings.command);
    settings.setValue(STR_PATH      ,      keepSettings.path);
    settings.setValue(STR_IMMEDIAT  ,      keepSettings.isImmediat);
    settings.setValue(STR_DETACHABLE,      keepSettings.isDetachable);
    settings.endGroup();

    settings.beginGroup(STR_GROUP_ZAP);
    settings.setValue(STR_COMMAND   , (int)zapSettings.command);
    settings.setValue(STR_PATH      ,      zapSettings.path);
    settings.setValue(STR_IMMEDIAT  ,      zapSettings.isImmediat);
    settings.setValue(STR_DETACHABLE,      zapSettings.isDetachable);
    settings.endGroup();

    settings.beginGroup(STR_GROUP_MOVE);
    settings.setValue(STR_COMMAND   , (int)moveSettings.command);
    settings.setValue(STR_PATH      ,      moveSettings.path);
    settings.setValue(STR_IMMEDIAT  ,      moveSettings.isImmediat);
    settings.setValue(STR_DETACHABLE,      moveSettings.isDetachable);
    settings.endGroup();

    settings.setValue(STR_DEFAULT_PATH, defaultPath);
    settings.setValue(STR_PLAYLIST_PATH, playlistPath);
    settings.setValue(STR_AUTOSAVE, autosaved);

}


text:
package com.microsoft.azure.management.network.v2020_03_01.implementation;

import com.microsoft.azure.management.network.v2020_03_01.ProvisioningState;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.microsoft.rest.serializer.JsonFlatten;
import com.microsoft.azure.SubResource;

/**
 * Virtual Router Peering resource.
 */
@JsonFlatten
public class VirtualRouterPeeringInner extends SubResource {
    /**
     * Peer ASN.
     */
    @JsonProperty(value = "properties.peerAsn")
    private Long peerAsn;

    /**
     * Peer IP.
     */
    @JsonProperty(value = "properties.peerIp")
    private String peerIp;

    /**
     * The provisioning state of the resource. Possible values include:
     * 'Succeeded', 'Updating', 'Deleting', 'Failed'.
     */
    @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY)
    private ProvisioningState provisioningState;

    /**
     * Name of the virtual router peering that is unique within a virtual
     * router.
     */
    @JsonProperty(value = "name")
    private String name;

    /**
     * A unique read-only string that changes whenever the resource is updated.
     */
    @JsonProperty(value = "etag", access = JsonProperty.Access.WRITE_ONLY)
    private String etag;

    /**
     * Peering type.
     */
    @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY)
    private String type;

    /**
     * Get peer ASN.
     *
     * @return the peerAsn value
     */
    public Long peerAsn() {
        return this.peerAsn;
    }

    /**
     * Set peer ASN.
     *
     * @param peerAsn the peerAsn value to set
     * @return the VirtualRouterPeeringInner object itself.
     */
    public VirtualRouterPeeringInner withPeerAsn(Long peerAsn) {
        this.peerAsn = peerAsn;
        return this;
    }

    /**
     * Get peer IP.
     *
     * @return the peerIp value
     */
    public String peerIp() {
        return this.peerIp;
    }

    /**
     * Set peer IP.
     *
     * @param peerIp the peerIp value to set
     * @return the VirtualRouterPeeringInner object itself.
     */
    public VirtualRouterPeeringInner withPeerIp(String peerIp) {
        this.peerIp = peerIp;
        return this;
    }

    /**
     * Get the provisioning state of the resource. Possible values include: 'Succeeded', 'Updating', 'Deleting', 'Failed'.
     *
     * @return the provisioningState value
     */
    public ProvisioningState provisioningState() {
        return this.provisioningState;
    }

    /**
     * Get name of the virtual router peering that is unique within a virtual router.
     *
     * @return the name value
     */
    public String name() {
        return this.name;
    }

    /**
     * Set name of the virtual router peering that is unique within a virtual router.
     *
     * @param name the name value to set
     * @return the VirtualRouterPeeringInner object itself.
     */
    public VirtualRouterPeeringInner withName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get a unique read-only string that changes whenever the resource is updated.
     *
     * @return the etag value
     */
    public String etag() {
        return this.etag;
    }

    /**
     * Get peering type.
     *
     * @return the type value
     */
    public String type() {
        return this.type;
    }

}


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'Album\Module'                        => __DIR__ . '/Module.php',
    'Album\Controller\SkeletonController' => __DIR__ . '/src/Album/Controller/SkeletonController.php',
    'AlbumTest\Framework\TestCase'        => __DIR__ . '/tests/Album/Framework/TestCase.php',
    'AlbumTest\SampleTest'                => __DIR__ . '/tests/Album/SampleTest.php',
);


text:
@echo off
rem
rem Lithium: the most rad php framework
rem
rem @copyright     Copyright 2015, Union of RAD (http://union-of-rad.org)
rem @license       http://opensource.org/licenses/bsd-license.php The BSD License
rem
php -f "%~dp0lithium.php" %*


text:
import AppDispatcher from '../dispatcher/AppDispatcher';
import TodoConstants from '../constants/TodoConstants';

const TodoActions = {

    /**
     * Action fired when the TodoApp component has successfully mounted.
     * Dispatches an action to the stores so that the TodoStore can init the connection.
     */
    initSocket: function(){
        AppDispatcher.dispatch({
            actionType: TodoConstants.INIT_SOCKET
        });
    },

    /**
     * Action fired when the server has successfully retrieved the todos and passes them to the app
     * @param {object} todos The list of todos
     * @param {function} callback The callback to execute after dispatching the action
     */

    sendTodos: function(todos, callback){
        AppDispatcher.dispatch({
            actionType: TodoConstants.READ_SUCCESS,
            todos:todos
        });
        callback();
    },

    /**
    * @param  {string} text
    */
    create: function(text) {
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_CREATE,
            text: text
        });
    },

    /**
     * Action fired when a todo is successfully added to the list.
     * @param  {string} text
     */
    updateSuccess: function(id){
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_SERVER_SUCCESS,
            id
        });
    },

    /**
     * Action fired when a todo is successfully deleted from the list.
     * @param  {string} id The ID of the ToDo item
     */

    deleteSuccess: function(id){
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_DELETE_SERVER_SUCCESS,
            id
        });
    },

    /**
     * @param  {string} id The ID of the ToDo item
     * @param  {string} text
     */
    updateText: function(id, text) {
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_UPDATE_TEXT,
            id: id,
            text: text
        });
    },

    /**
     * Toggle whether a single ToDo is complete
     * @param  {object} todo
     */
    toggleComplete: function(todo) {
        var id = todo.id;
        var actionType = todo.complete ?
        TodoConstants.TODO_UNDO_COMPLETE :
        TodoConstants.TODO_COMPLETE;

        AppDispatcher.dispatch({
            actionType: actionType,
            id: id
        });
    },

    /**
     * Mark all ToDos as complete
     */
    toggleCompleteAll: function() {
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_TOGGLE_COMPLETE_ALL
        });
    },

    /**
     * @param  {string} id
     */
    destroy: function(id) {
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_DESTROY,
            id: id
        });
    },

    /**
     * Delete all the completed ToDos
     */
    destroyCompleted: function() {
        AppDispatcher.dispatch({
            actionType: TodoConstants.TODO_DESTROY_COMPLETED
        });
    }
};

export default TodoActions;


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Iconogr. Mycol. 27(Suppl. 1): 304 (1941)

#### Original name
Amanitopsis avellaneosquamosa S. Imai

### Remarks
null


text:
package edu.utdallas.netsec.sfts.packets;

import edu.utdallas.netsec.sfts.crypt.RandomUtils;
import org.testng.Assert;
import org.testng.annotations.Test;

/**
 * @author Fahad Shaon
 */
public class AuthServerResponseTest {

    @Test
    public void testEncodeDecode() throws Exception {

        MasterServerTicket masterServerTicket = new MasterServerTicket();
        masterServerTicket.clientName = "First client";
        masterServerTicket.departServer = "finance";
        masterServerTicket.sessionKeyClientMaster = RandomUtils.getSecureRandomBytes(64);
        masterServerTicket.sessionKeyMasterDepartment = RandomUtils.getSecureRandomBytes(64);

        DepartmentServerTicket dst = new DepartmentServerTicket();

        dst.clientName = "First Client";
        dst.sessionKeyClientDepartment = RandomUtils.getSecureRandomBytes(64);
        dst.sessionKeyMasterDepartment = RandomUtils.getSecureRandomBytes(64);
        dst.nonce = RandomUtils.getSecureRandomBytes(8);

        byte[] encodedDST = dst.encode();

        masterServerTicket.departmentServerToken = encodedDST;
        masterServerTicket.nonce = RandomUtils.getSecureRandomBytes(8);

        byte[] encodedMST = masterServerTicket.encode();

        AuthServerResponse authServerResponse = new AuthServerResponse();

        authServerResponse.clientName = "First Client";
        authServerResponse.sessionKeyClientMaster = RandomUtils.getSecureRandomBytes(64);
        authServerResponse.sessionKeyClientDepartment = RandomUtils.getSecureRandomBytes(64);
        authServerResponse.masterServerToken = encodedMST;
        authServerResponse.nonce = RandomUtils.getSecureRandomBytes(8);

        byte[] encoded = authServerResponse.encode();

        AuthServerResponse authServerResponseDecoded = new AuthServerResponse();
        authServerResponseDecoded.decode(encoded);

        Assert.assertEquals(authServerResponseDecoded.clientName, authServerResponse.clientName);
        Assert.assertEquals(authServerResponseDecoded.sessionKeyClientMaster, authServerResponse.sessionKeyClientMaster);
        Assert.assertEquals(authServerResponseDecoded.sessionKeyClientDepartment, authServerResponse.sessionKeyClientDepartment);
        Assert.assertEquals(authServerResponseDecoded.masterServerToken, authServerResponse.masterServerToken);
        Assert.assertEquals(authServerResponseDecoded.nonce, authServerResponse.nonce);
    }
}


text:
package org.elasticsearch.action.bulk;

import org.elasticsearch.action.bulk.BulkItemResponse.Failure;
import org.elasticsearch.test.ESTestCase;

import static org.hamcrest.Matchers.containsString;

public class BulkItemResponseTests extends ESTestCase {
    public void testFailureToString() {
        Failure failure = new Failure("index", "type", "id", new RuntimeException("test"));
        String toString = failure.toString();
        assertThat(toString, containsString("\"type\":\"runtime_exception\""));
        assertThat(toString, containsString("\"reason\":\"test\""));
        assertThat(toString, containsString("\"status\":500"));
    }
}


text:
<?php

namespace JLaso\TranslationsBundle\Document;

use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Doctrine\Bundle\MongoDBBundle\Validator\Constraints\Unique as MongoDBUnique;

/**
 * Catalog
 *
 * @MongoDBUnique(fields="projectId,catalog")
 * @MongoDB\Document(repositoryClass="JLaso\TranslationsBundle\Document\Repository\CatalogRepository")
 */
class Catalog
{
    /**
     * @MongoDB\Id
     */
    protected $id;

    /**
     *
     * @MongoDB\Int
     */
    protected $projectId;

    /**
     *
     * @MongoDB\String
     */
    protected $catalog;

    /**
     *
     * @MongoDB\Hash
     */
    protected $keys;

    /**
     * @MongoDB\Timestamp
     */
    protected $createdAt;

    /**
     * @MongoDB\Timestamp
     */
    protected $updatedAt;

    public function __construct()
    {
        $this->projectId = null;
        $this->keys      = null;
        $this->createdAt = new \MongoTimestamp();
        $this->updatedAt = new \MongoTimestamp();
        $this->catalog   = null;
    }

    /**
     * Get id
     *
     * @return id $id
     */
    public function getId()
    {
        return $this->id;
    }

    public function setId($id)
    {
        $this->id = $id;

        return $this;
    }

    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;
    }

    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;
    }

    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    public function getHash()
    {
        return base64_encode(sha1($this->getId()));
    }

    /**
     * @param mixed $catalog
     */
    public function setCatalog($catalog)
    {
        $this->catalog = $catalog;
    }

    /**
     * @return mixed
     */
    public function getCatalog()
    {
        return $this->catalog;
    }

    /**
     * @param mixed $keys
     */
    public function setKeys($keys)
    {
        $this->keys = $keys;
    }

    /**
     * @return mixed
     */
    public function getKeys()
    {
        return $this->keys;
    }

    /**
     * @param int $projectId
     */
    public function setProjectId($projectId)
    {
        $this->projectId = $projectId;
    }

    /**
     * @return int
     */
    public function getProjectId()
    {
        return $this->projectId;
    }
}


text:
from django.db import migrations, models

def raise_error(apps, schema_editor):
    # Test operation in non-atomic migration is not wrapped in transaction
    Publisher = apps.get_model('migrations', 'Publisher')
    Publisher.objects.create(name='Test Publisher')
    raise RuntimeError('Abort migration')

class Migration(migrations.Migration):
    atomic = False

    operations = [
        migrations.CreateModel(
            "Publisher",
            [
                ("name", models.CharField(primary_key=True, max_length=255)),
            ],
        ),
        migrations.RunPython(raise_error),
        migrations.CreateModel(
            "Book",
            [
                ("title", models.CharField(primary_key=True, max_length=255)),
                ("publisher", models.ForeignKey("migrations.Publisher", models.SET_NULL, null=True)),
            ],
        ),
    ]


text:
Increments 'ref' until it reaches 'limit'.

##### Args:

*  <b>`ref`</b>: A mutable `Tensor`. Must be one of the following types: `int32`, `int64`.
    Should be from a scalar `Variable` node.
*  <b>`limit`</b>: An `int`.
    If incrementing ref would bring it above limit, instead generates an
    'OutOfRange' error.
*  <b>`name`</b>: A name for the operation (optional).

##### Returns:

  A `Tensor`. Has the same type as `ref`.
  A copy of the input before increment. If nothing else modifies the
  input, the values produced will all be distinct.


text:
<!-- auto-generated doc! most areas *not* editable -->

## Bolus subType: `dual/square`

> Jump to...(notable fields on this type)

>  - [type](#type)
>  - [subType](#subtype)
>  - [normal](#normal)
>  - [expectedNormal](#expectednormal)
>  - [extended](#extended)
>  - [expectedExtended](#expectedextended)
>  - [duration](#duration)
>  - [expectedDuration](#expectedduration)

**NB:** All fields are *required* unless otherwise noted.

> Jump to example JSON:

>  - [client example](#example-client)
>  - [ingestion example](#example-ingestion)
>  - [storage example](#example-storage)

### type

[ingestion, storage, client] The string `bolus`.

	QUICK SUMMARY
	Required:
		jellyfish: yes
		platform: yes

<!-- start editable commentary on type -->

<!-- end editable commentary on type -->

* * * * *

### subType

[ingestion, storage, client] The string `dual/square`.

	QUICK SUMMARY
	Required:
		jellyfish: yes
		platform: yes

#### Changelog for `subType`

`_schemaVersion` ? (future): We plan to migrate from `dual/square` to `combo` in the future.

<!-- start editable commentary on subType -->

This is the sub-type of `bolus` event that represents a bolus insulin dose programmed to deliver part of the dose using the immediate delivery strategy (a `normal` bolus) and the remainder using the delivery spread evenly over a `duration` strategy (a `square` bolus). The data model is essentially just a combination of the models for [`normal`](normal.md) and [`square`](square.md) boluses.

Most (and perhaps all) insulin pumps ask the user to divide the `normal` and `square` portions of a `dual/square` bolus by *percentage* of the total insulin dose. We do **not** encode this programmed percentage directly, but it is recoverable (for surfacing in a client application's UI) through computation using the appropriate combination of values from the `normal`, `extended`, `expectedNormal`, and `expectedExtended` fields and/or the appropriate sum of these.

We plan to migrate all Tidepool data to use `combo` as the value of this sub-type rather than `dual/square` in order to improve the transparency of the data model and avoid `/` in a `subType` string.

<!-- end editable commentary on subType -->

* * * * *

### normal

[ingestion, storage, client] A floating point value representing units of insulin.

	QUICK SUMMARY
	Required:
		jellyfish: yes
		platform: yes
	Numerical type: Floating point value rounded to the appropriate significant figures for the device's precision.
	Range:
		min: >= 0.0
		max: 100.0

<!-- start editable commentary on normal -->

See the explanation of this field in the documentation for [`normal`](normal.md) boluses.

Note that a 0 for `normal` is allowable in more circumstances for a combo bolus than for a simple `normal` bolus: as long as the `extended` is non-zero for the combo bolus, `normal` may have a value of 0 *without* the requirement that a non-zero `expectedNormal` also be present.

<!-- end editable commentary on normal -->

* * * * *

### expectedNormal

> This field is **optional**.

[ingestion, storage, client] A floating point value representing units of insulin.

	QUICK SUMMARY
	Required:
		jellyfish: no (optional)
		platform: no (optional)
	Numerical type: Floating point value rounded to the appropriate significant figures for the device's precision.
	Range:
		min: > `normal`
		max: 100.0

<!-- start editable commentary on expectedNormal -->

See the explanation of this field in the documentation for [`normal`](normal.md) boluses.

Note that if a `dual/square` bolus is interrupted or canceled during the `normal` portion of delivery, by definition the `extended` delivery should _not_ yet have begun, so the value of `extended` and `duration` should be 0 and `expectedExtended` and `expectedDuration` should have values.

<!-- end editable commentary on expectedNormal -->

* * * * *

### extended

[ingestion, storage, client] A floating point value representing units of insulin.

	QUICK SUMMARY
	Required:
		jellyfish: yes
		platform: yes
	Numerical type: Floating point value rounded to the appropriate significant figures for the device's precision.
	Range:
		min: >= 0.0
		max: 100.0

<!-- start editable commentary on extended -->

See the explanation of this field in the documentation for [`square`](square.md) boluses.

<!-- end editable commentary on extended -->

* * * * *

### expectedExtended

> This field is **optional**.

[ingestion, storage, client] A floating point value representing units of insulin.

	QUICK SUMMARY
	Required:
		jellyfish: no (optional)
		platform: no (optional)
	Numerical type: Floating point value rounded to the appropriate significant figures for the device's precision.
	Range:
		min: > `extended`
		max: 100.0

<!-- start editable commentary on expectedExtended -->

See the explanation of this field in the documentation for [`square`](square.md) boluses.

Note that if a `dual/square` bolus is interrupted or canceled during the `extended` portion of delivery, by definition the `normal` delivery should have completed successfully, so the `expectedNormal` field _should not_ have a value. An example of this type of interruption appears below in the [examples](#example-client).

<!-- end editable commentary on expectedExtended -->

* * * * *

### duration

[ingestion, storage, client] An integer value representing a duration of time in milliseconds.

	QUICK SUMMARY
	Required:
		jellyfish: yes
		platform: yes
	Numerical type: Integer value representing milliseconds.
	Range:
		min: 0
		max: 86400000

<!-- start editable commentary on duration -->

See the explanation of this field in the documentation for [`square`](square.md) boluses.

As with `square` boluses, the `duration` is the elapsed time for the `extended` portion of the bolus. While some insulin pumps that deliver `normal` insulin doses at a slower rate (minutes rather than seconds) for user comfort do include the duration of the `normal` delivery in the data, we do not currently include this information in our bolus data model(s). As with the `square` boluses, it is in theory possible for a user to input 0 `duration` for the `extended` portion of a `combo` bolus, effectively programming a `normal` bolus in a total amount equal to the `normal` and `extended` insulin values added together.

<!-- end editable commentary on duration -->

* * * * *

### expectedDuration

> This field is **optional**.

[ingestion, storage, client] An integer value representing an original programmed duration of time in milliseconds when the programmed event did not complete due to interruption or user cancellation.

	QUICK SUMMARY
	Required:
		jellyfish: no (optional)
		platform: no (optional)
	Numerical type: Integer value representing milliseconds.
	Range:
		min: >= `duration`
		max: 86400000

<!-- start editable commentary on expectedDuration -->

See the explanation of this field in the documentation for [`square`](square.md) boluses.

<!-- end editable commentary on expectedDuration -->

* * * * *

### clockDriftOffset

See [common fields](../../common.md).

<!-- start editable commentary on clockDriftOffset -->
<!-- TODO -->
<!-- end editable commentary on clockDriftOffset -->

* * * * *

### conversionOffset

See [common fields](../../common.md).

<!-- start editable commentary on conversionOffset -->
<!-- TODO -->
<!-- end editable commentary on conversionOffset -->

* * * * *

### deviceId

See [common fields](../../common.md).

<!-- start editable commentary on deviceId -->
<!-- TODO -->
<!-- end editable commentary on deviceId -->

* * * * *

### deviceTime

See [common fields](../../common.md).

<!-- start editable commentary on deviceTime -->
<!-- TODO -->
<!-- end editable commentary on deviceTime -->

* * * * *

### time

See [common fields](../../common.md).

<!-- start editable commentary on time -->
<!-- TODO -->
<!-- end editable commentary on time -->

* * * * *

### timezoneOffset

See [common fields](../../common.md).

<!-- start editable commentary on timezoneOffset -->
<!-- TODO -->
<!-- end editable commentary on timezoneOffset -->

* * * * *

### uploadId

See [common fields](../../common.md).

<!-- start editable commentary on uploadId -->
<!-- TODO -->
<!-- end editable commentary on uploadId -->

* * * * *

### _active

See [common fields](../../common.md).

<!-- start editable commentary on _active -->
<!-- TODO -->
<!-- end editable commentary on _active -->

* * * * *

### _groupId

See [common fields](../../common.md).

<!-- start editable commentary on _groupId -->
<!-- TODO -->
<!-- end editable commentary on _groupId -->

* * * * *

### _schemaVersion

See [common fields](../../common.md).

<!-- start editable commentary on _schemaVersion -->
<!-- TODO -->
<!-- end editable commentary on _schemaVersion -->

* * * * *

### _version

See [common fields](../../common.md).

<!-- start editable commentary on _version -->
<!-- TODO -->
<!-- end editable commentary on _version -->

* * * * *

### createdTime

See [common fields](../../common.md).

<!-- start editable commentary on createdTime -->
<!-- TODO -->
<!-- end editable commentary on createdTime -->

* * * * *

### guid

See [common fields](../../common.md).

<!-- start editable commentary on guid -->
<!-- TODO -->
<!-- end editable commentary on guid -->

* * * * *

### id

See [common fields](../../common.md).

<!-- start editable commentary on id -->
<!-- TODO -->
<!-- end editable commentary on id -->

* * * * *

### example (client)

```json
{
	"type": "bolus",
	"subType": "dual/square",
	"normal": 6.25,
	"extended": 5.75,
	"expectedExtended": 8.625,
	"duration": 23400000,
	"expectedDuration": 35100000,
	"clockDriftOffset": 0,
	"conversionOffset": 0,
	"deviceId": "DevId0987654321",
	"deviceTime": "2018-05-14T18:17:07",
	"guid": "dc114f19-74fe-4075-9676-38faec7cf0cc",
	"id": "d184a41eaf984afcbe553071f80bcdec",
	"time": "2018-05-14T08:17:07.035Z",
	"timezoneOffset": 600,
	"uploadId": "SampleUploadId"
}
```

### example (ingestion)

```json
{
	"type": "bolus",
	"subType": "dual/square",
	"normal": 9.25,
	"extended": 5.5,
	"expectedExtended": 8.25,
	"duration": 57600000,
	"expectedDuration": 86400000,
	"clockDriftOffset": 0,
	"conversionOffset": 0,
	"deviceId": "DevId0987654321",
	"deviceTime": "2018-05-14T18:17:07",
	"time": "2018-05-14T08:17:07.035Z",
	"timezoneOffset": 600,
	"uploadId": "SampleUploadId"
}
```

### example (storage)

```json
{
	"type": "bolus",
	"subType": "dual/square",
	"normal": 2.25,
	"extended": 9.5,
	"expectedExtended": 14.25,
	"duration": 48600000,
	"expectedDuration": 72900000,
	"_active": true,
	"_groupId": "abcdef",
	"_schemaVersion": 0,
	"_version": 0,
	"clockDriftOffset": 0,
	"conversionOffset": 0,
	"createdTime": "2018-05-14T08:17:12.035Z",
	"deviceId": "DevId0987654321",
	"deviceTime": "2018-05-14T18:17:07",
	"guid": "cf850a7a-1f28-4bbc-8a56-36cbe0326f20",
	"id": "4f8b8b133b22401aa1f281be9eb954ad",
	"time": "2018-05-14T08:17:07.035Z",
	"timezoneOffset": 600,
	"uploadId": "SampleUploadId"
}
```


text:
<#
.SYNOPSIS
    Clear the host content.

.DESCRIPTION
    This function replaces the standard Clear-Host and is aliased by "cls".
#>
function Clear-Host
{
    $host.PrivateData.ClearHost()
}

<#
.SYNOPSIS
    Simple path completion function for PowerConsole.
#>
function _TabExpansionPath($line)
{
    function UnquoteString($s) {
        if ($s.StartsWith('"') -or $s.StartsWith("'")) {
            $s = $s.Substring(1)
        }
        if ($s.EndsWith('"') -or $s.EndsWith("'")) {
            $s = $s.Substring(0, $s.Length - 1)
        }
        return $s
    }

    $e = $null
    $tokens = @([System.Management.Automation.PSParser]::Tokenize($line, [ref]$e))
    $lastToken = $tokens | Select-Object -Last 1

    $replaceStart = -1
    $lastWord = $null

    if ($lastToken -and ($lastToken.EndColumn -gt $line.Length)) {
        #Last token is terminated

        if ($tokens.Length -gt 1) {
            $prevToken = $tokens[$tokens.Length - 2]
            if ($prevToken.EndColumn -eq $lastToken.StartColumn) {
                $replaceStart = $prevToken.StartColumn - 1
                $lastWord = (UnquoteString $prevToken.Content) + (UnquoteString $lastToken.Content)
            }
        }

        if ($replaceStart -lt 0) {
            $replaceStart = $lastToken.StartColumn - 1
            $lastWord = UnquoteString $lastToken.Content
        }
    } else {
        #There is unrecognized/unterminated words

        if(!$lastToken) {
            $lastWord = $line
        } else {
            $lastWord = $line.Substring($lastToken.EndColumn - 1).TrimStart()
        }
        $replaceStart = $line.Length - $lastWord.Length
        $lastWord = UnquoteString $lastWord
    }

    # If previously unquoted, put back quote in results
    $unquoted = ($replaceStart -lt ($line.Length - $lastWord.Length))
    $relative = !(($lastWord.IndexOf(':') -ge 0) -or $lastWord.StartsWith('/') -or $lastWord.StartsWith('\'))

    $result = "" | select ReplaceStart, Paths
    $result.ReplaceStart = $replaceStart
    $result.Paths = @(Resolve-Path ${lastWord}* -ErrorAction SilentlyContinue -Relative:$relative | %{

        # Resolve-Path may return PathInfo or String (e.g. when passing different -Relative)
        $path = $_.ToString()

        if ($unquoted -or ($path.IndexOf(' ') -ge 0)) {
            "'$path'"
        } else {
            $path
        }
    })

    $result
}

<#
.SYNOPSIS
    Get an explict interface on an object so that you can invoke the interface members.

.DESCRIPTION
    PowerShell object adapter does not provide explict interface members. For COM objects
    it only makes IDispatch members available.

    This function helps access interface members on an object through reflection. A new
    object is returned with the interface members as ScriptProperties and ScriptMethods.

.EXAMPLE
    $dte2 = Get-Interface $dte ([EnvDTE80.DTE2])
#>
function Get-Interface
{
    Param(
        $Object,
        [type]$InterfaceType
    )

    [NuGetConsole.Host.PowerShell.Implementation.PSTypeWrapper]::GetInterface($Object, $InterfaceType)
}

<#
.SYNOPSIS
    Get a VS service.

.EXAMPLE
    Get-VSService ([Microsoft.VisualStudio.Shell.Interop.SVsShell]) ([Microsoft.VisualStudio.Shell.Interop.IVsShell])
#>
function Get-VSService
{
    Param(
        [type]$ServiceType,
        [type]$InterfaceType
    )

    $service = [Microsoft.VisualStudio.Shell.Package]::GetGlobalService($ServiceType)
    if ($service -and $InterfaceType) {
        $service = Get-Interface $service $InterfaceType
    }

    $service
}

<#
.SYNOPSIS
    Get VS IComponentModel service to access VS MEF hosting.
#>
function Get-VSComponentModel
{
    Get-VSService ([Microsoft.VisualStudio.ComponentModelHost.SComponentModel]) ([Microsoft.VisualStudio.ComponentModelHost.IComponentModel])
}

# Set initial directory
Set-Location "$env:USERPROFILE"

# Backup the original tab expansion function
if ((Test-Path Function:\DefaultTabExpansion) -eq $false) {
    Rename-Item Function:\TabExpansion DefaultTabExpansion
}

function TabExpansion($line, $lastWord) {
    $nugetSuggestions = NuGetTabExpansion $line $lastWord

    if ($nugetSuggestions.NoResult) {
        return DefaultTabExpansion $line $lastWord
    }
    else {
        return $nugetSuggestions
    }
}

# default prompt
function prompt {
    "PM>"
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<!--
  ~ Copyright 2017 Open Language for Internet of Things (Oliot)
  ~
  ~ Licensed under the Apache License, Version 2.0 (the "License");
  ~ you may not use this file except in compliance with the License.
  ~ You may obtain a copy of the License at
  ~
  ~     http://www.apache.org/licenses/LICENSE-2.0
  ~
  ~ Unless required by applicable law or agreed to in writing, software
  ~ distributed under the License is distributed on an "AS IS" BASIS,
  ~ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  ~ See the License for the specific language governing permissions and
  ~ limitations under the License.
  -->

<product_data:productData xmlns:product_data="urn:gs1:tsd:product_data:xsd:1"
                          xmlns:basic_product_information_module="urn:gs1:tsd:basic_product_information_module:xsd:1"
>
    <gtin>08808244201014</gtin>
    <targetMarket codeListVersion="1.1">410</targetMarket>
    <informationProviderGLN>1234567891234</informationProviderGLN>
    <informationProviderName>Lotte Mart</informationProviderName>
    <productDataRecord>
        <module>
            <basic_product_information_module:basicProductInformationModule>
                <productName languageCode="kr" codeListVersion="1.1">삼다수</productName>
                <gpcCategoryCode>12345678</gpcCategoryCode>
                <brandNameInformation>
                    <brandName>제주</brandName>
                    <languageSpecificBrandName languageCode="en" codeListVersion="1.1">Jeju</languageSpecificBrandName>
                </brandNameInformation>
                <productInformationLink>
                    <url>http://www.lottemart.com/product/ProductDetail.do?ProductCD=8808244201014</url>
                    <productInformationTypeCode>MARKETING_INFORMATION</productInformationTypeCode>
                    <languageCode>kr</languageCode>
                </productInformationLink>
                <imageLink>
                    <url>http://res.cloudinary.com/hcxh60wvk/image/upload/v1505284214/08808244201014/1.jpg</url>
                    <imageTypeCode>PRODUCT_IMAGE</imageTypeCode>
                    <languageCode>kr</languageCode>
                </imageLink>
            </basic_product_information_module:basicProductInformationModule>
        </module>
    </productDataRecord>
</product_data:productData>


text:
<?php

use Illuminate\Database\Migrations\Migration;

class CreateDvsMenus extends Migration {

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dvs_menus', function($table) {
            $table->increments('id');
            $table->unsignedInteger('language_id');
            $table->integer('translated_from_menu_id')->default(0);
            $table->string('name', 255);
            $table->text('links')->nullable();
            $table->timestamp('created_at')->default('0000-00-00 00:00:00');
            $table->timestamp('updated_at')->default('0000-00-00 00:00:00');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('dvs_menus');
    }

}


text:
//
//  Generated by the J2ObjC translator.  DO NOT EDIT!
//  source: ./core/src/java/org/apache/lucene/store/NRTCachingDirectory.java
//

#include "J2ObjC_header.h"

#pragma push_macro("INCLUDE_ALL_OrgApacheLuceneStoreNRTCachingDirectory")
#ifdef RESTRICT_OrgApacheLuceneStoreNRTCachingDirectory
#define INCLUDE_ALL_OrgApacheLuceneStoreNRTCachingDirectory 0
#else
#define INCLUDE_ALL_OrgApacheLuceneStoreNRTCachingDirectory 1
#endif
#undef RESTRICT_OrgApacheLuceneStoreNRTCachingDirectory

#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif

#if !defined (OrgApacheLuceneStoreNRTCachingDirectory_) && (INCLUDE_ALL_OrgApacheLuceneStoreNRTCachingDirectory || defined(INCLUDE_OrgApacheLuceneStoreNRTCachingDirectory))
#define OrgApacheLuceneStoreNRTCachingDirectory_

#define RESTRICT_OrgApacheLuceneStoreFilterDirectory 1
#define INCLUDE_OrgApacheLuceneStoreFilterDirectory 1
#include "org/apache/lucene/store/FilterDirectory.h"

#define RESTRICT_OrgApacheLuceneUtilAccountable 1
#define INCLUDE_OrgApacheLuceneUtilAccountable 1
#include "org/apache/lucene/util/Accountable.h"

@class IOSObjectArray;
@class OrgApacheLuceneStoreDirectory;
@class OrgApacheLuceneStoreIOContext;
@class OrgApacheLuceneStoreIndexInput;
@class OrgApacheLuceneStoreIndexOutput;
@protocol JavaUtilCollection;

/*!
 @brief Wraps a RAMDirectory
  around any provided delegate directory, to
  be used during NRT search.

This class is likely only useful in a near-real-time
  context, where indexing rate is lowish but reopen
  rate is highish, resulting in many tiny files being
  written.  This directory keeps such segments (as well as
  the segments produced by merging them, as long as they
  are small enough), in RAM.

This is safe to use: when your app calls {IndexWriter#commit},
  all cached files will be flushed from the cached and sync'd.

Here's a simple example usage:

    Directory fsDir = FSDirectory.open(new File("/path/to/index").toPath());
    NRTCachingDirectory cachedFSDir = new NRTCachingDirectory(fsDir, 5.0, 60.0);
    IndexWriterConfig conf = new IndexWriterConfig(analyzer);
    IndexWriter writer = new IndexWriter(cachedFSDir, conf);

@endcode

This will cache all newly flushed segments, all merges
  whose expected segment size is <= 5 MB, unless the net
  cached bytes exceeds 60 MB at which point all writes will
  not be cached (until the net bytes falls below 60 MB).

 */
@interface OrgApacheLuceneStoreNRTCachingDirectory : OrgApacheLuceneStoreFilterDirectory < OrgApacheLuceneUtilAccountable >

#pragma mark Public

/*!
 @brief We will cache a newly created output if 1) it's a
   flush or a merge and the estimated size of the merged segment is
 <= maxMergeSizeMB, and 2) the total cached bytes is
   <= maxCachedMB
 */
- (instancetype __nonnull)initWithOrgApacheLuceneStoreDirectory:(OrgApacheLuceneStoreDirectory *)delegate
                                                     withDouble:(jdouble)maxMergeSizeMB
                                                     withDouble:(jdouble)maxCachedMB;

/*!
 @brief Close this directory, which flushes any cached files
   to the delegate and then closes the delegate.
 */
- (void)close;

- (OrgApacheLuceneStoreIndexOutput *)createOutputWithNSString:(NSString *)name
                            withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context;

- (void)deleteFileWithNSString:(NSString *)name;

- (jlong)fileLengthWithNSString:(NSString *)name;

- (id<JavaUtilCollection>)getChildResources;

- (IOSObjectArray *)listAll;

- (IOSObjectArray *)listCachedFiles;

- (OrgApacheLuceneStoreIndexInput *)openInputWithNSString:(NSString *)name
                        withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context;

- (jlong)ramBytesUsed;

- (void)renameFileWithNSString:(NSString *)source
                  withNSString:(NSString *)dest;

- (void)syncWithJavaUtilCollection:(id<JavaUtilCollection>)fileNames;

- (NSString *)description;

#pragma mark Protected

/*!
 @brief Subclass can override this to customize logic; return
   true if this file should be written to the RAMDirectory.
 */
- (jboolean)doCacheWriteWithNSString:(NSString *)name
   withOrgApacheLuceneStoreIOContext:(OrgApacheLuceneStoreIOContext *)context;

// Disallowed inherited constructors, do not use.

- (instancetype __nonnull)initWithOrgApacheLuceneStoreDirectory:(OrgApacheLuceneStoreDirectory *)arg0 NS_UNAVAILABLE;

@end

J2OBJC_EMPTY_STATIC_INIT(OrgApacheLuceneStoreNRTCachingDirectory)

FOUNDATION_EXPORT void OrgApacheLuceneStoreNRTCachingDirectory_initWithOrgApacheLuceneStoreDirectory_withDouble_withDouble_(OrgApacheLuceneStoreNRTCachingDirectory *self, OrgApacheLuceneStoreDirectory *delegate, jdouble maxMergeSizeMB, jdouble maxCachedMB);

FOUNDATION_EXPORT OrgApacheLuceneStoreNRTCachingDirectory *new_OrgApacheLuceneStoreNRTCachingDirectory_initWithOrgApacheLuceneStoreDirectory_withDouble_withDouble_(OrgApacheLuceneStoreDirectory *delegate, jdouble maxMergeSizeMB, jdouble maxCachedMB) NS_RETURNS_RETAINED;

FOUNDATION_EXPORT OrgApacheLuceneStoreNRTCachingDirectory *create_OrgApacheLuceneStoreNRTCachingDirectory_initWithOrgApacheLuceneStoreDirectory_withDouble_withDouble_(OrgApacheLuceneStoreDirectory *delegate, jdouble maxMergeSizeMB, jdouble maxCachedMB);

J2OBJC_TYPE_LITERAL_HEADER(OrgApacheLuceneStoreNRTCachingDirectory)

#endif

#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma pop_macro("INCLUDE_ALL_OrgApacheLuceneStoreNRTCachingDirectory")


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright 2016 Tse Kit Yam

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

</resources>


text:
package org.nd4j.linalg.api.ops.impl.layers.convolution;

import lombok.Builder;
import lombok.extern.slf4j.Slf4j;
import org.nd4j.autodiff.samediff.SDVariable;
import org.nd4j.autodiff.samediff.SameDiff;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.api.ops.impl.layers.convolution.config.Pooling2DConfig;

import java.util.List;

/**
 * Pooling2DDerivative operation
 */
@Slf4j
public class Pooling2DDerivative extends Pooling2D {
    @Builder(builderMethodName = "derivativeBuilder")
    public Pooling2DDerivative(SameDiff sameDiff, SDVariable[] inputs, INDArray[] arrayInputs, INDArray[] arrayOutputs, Pooling2DConfig config) {
        super(sameDiff, inputs, arrayInputs, arrayOutputs, config);
    }

    public Pooling2DDerivative() {}

    @Override
    public String opName() {
         return super.opName() + "_bp";
    }

   @Override
    public List<SDVariable> doDiff(List<SDVariable> f1) {
       throw new UnsupportedOperationException("Unable to take derivative of derivative.");
    }

}


text:
'use strict';

angular.module('soundgrid.controller.about', ['ngRoute'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/soundgrid/about', {
    templateUrl: 'soundgrid/about/about.html',
    controller: 'AboutCtrl'
  });
}])

.controller('AboutCtrl', [function() {

}]);


text:
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { assert } from 'chai';
import { create, SheetsRegistry } from 'jss';
import { createMount } from '@material-ui/core/test-utils';
import StylesProvider, { StylesContext } from './StylesProvider';
import makeStyles from '../makeStyles';
import createGenerateClassName from '../createGenerateClassName';
import consoleErrorMock from 'test/utils/consoleErrorMock';

function Test() {
  const options = React.useContext(StylesContext);
  return <span options={options} />;
}

function getOptions(wrapper) {
  return wrapper.find('span').props().options;
}

describe('StylesProvider', () => {
  let mount;
  let generateClassName;

  before(() => {
    mount = createMount({ strict: true });
  });

  beforeEach(() => {
    generateClassName = createGenerateClassName();
  });

  after(() => {
    mount.cleanUp();
  });

  it('should provide the options', () => {
    const wrapper = mount(
      <StylesProvider disableGeneration>
        <Test />
      </StylesProvider>,
    );
    assert.strictEqual(getOptions(wrapper).disableGeneration, true);
  });

  it('should merge the themes', () => {
    const wrapper = mount(
      <StylesProvider>
        <StylesProvider disableGeneration>
          <Test />
        </StylesProvider>
      </StylesProvider>,
    );
    assert.strictEqual(getOptions(wrapper).disableGeneration, true);
  });

  it('should handle injectFirst', () => {
    const wrapper = mount(
      <StylesProvider injectFirst>
        <Test />
      </StylesProvider>,
    );
    assert.strictEqual(getOptions(wrapper).jss.options.insertionPoint.nodeType, 8);
  });

  describe('server-side', () => {
    // Only run the test on node.
    if (!/jsdom/.test(window.navigator.userAgent)) {
      return;
    }

    const useStyles = makeStyles({ root: { display: 'flex' } });
    const Button = props => {
      const classes = useStyles();
      return <button type="button" className={classes.root} {...props} />;
    };

    function assertRendering(markup, sheetsRegistry) {
      assert.notStrictEqual(markup.match('Hello World'), null);
      assert.strictEqual(sheetsRegistry.registry.length, 1);
      assert.strictEqual(sheetsRegistry.toString().length > 10, true);
      assert.deepEqual(sheetsRegistry.registry[0].classes, {
        root: 'makeStyles-root-1',
      });
    }

    it('should be able to extract the styles', () => {
      const sheetsRegistry = new SheetsRegistry();

      const markup = ReactDOMServer.renderToString(
        <StylesProvider
          sheetsManager={new Map()}
          sheetsRegistry={sheetsRegistry}
          generateClassName={generateClassName}
        >
          <Button>Hello World</Button>
        </StylesProvider>,
      );

      assertRendering(markup, sheetsRegistry);
    });

    it('should be able to cache the sheets between two requests', () => {
      const sheetsCache = new Map();

      const sheetsRegistry1 = new SheetsRegistry();
      const markup1 = ReactDOMServer.renderToString(
        <StylesProvider
          sheetsManager={new Map()}
          sheetsCache={sheetsCache}
          sheetsRegistry={sheetsRegistry1}
          generateClassName={generateClassName}
        >
          <Button>Hello World</Button>
        </StylesProvider>,
      );
      assertRendering(markup1, sheetsRegistry1);

      const sheetsRegistry2 = new SheetsRegistry();
      const markup2 = ReactDOMServer.renderToString(
        <StylesProvider
          sheetsManager={new Map()}
          sheetsCache={sheetsCache}
          sheetsRegistry={sheetsRegistry2}
          generateClassName={generateClassName}
        >
          <Button>Hello World</Button>
        </StylesProvider>,
      );
      assertRendering(markup2, sheetsRegistry2);

      // The most important check:
      assert.strictEqual(sheetsRegistry1.registry[0], sheetsRegistry2.registry[0]);
    });
  });

  it('should accept a custom JSS instance', () => {
    const jss = create();
    const wrapper = mount(
      <StylesProvider jss={jss}>
        <Test />
      </StylesProvider>,
    );
    assert.strictEqual(getOptions(wrapper).jss, jss);
  });

  describe('warnings', () => {
    beforeEach(() => {
      consoleErrorMock.spy();
    });

    afterEach(() => {
      consoleErrorMock.reset();
    });

    it('should support invalid input', () => {
      const jss = create();
      mount(
        <StylesProvider injectFirst jss={jss}>
          <Test />
        </StylesProvider>,
      );
      assert.strictEqual(consoleErrorMock.callCount(), 1);
      assert.include(
        consoleErrorMock.args()[0][0],
        'you cannot use the jss and injectFirst props at the same time',
      );
    });
  });
});


text:
'use strict';

var expect = require("expect.js");
var star_theme = require("../lib/star-theme");

describe("star_theme", function () {
    it("is defined", function () {
        expect(star_theme).to.be.an('object');
    });
});


text:
package constant

//---------------------------------------------
// UserTrait
//---------------------------------------------
const (
	AdminUserTrait        = "AdminUserTrait"
	GeneralUserTrait      = "GeneralUserTrait"
	GuestUserTrait        = "GuestUserTrait"
	PaginatorHeaderTrait  = "PaginatorHeaderTrait"
	PaginatorHeaderTrait2 = "PaginatorHeaderTrait2"
	GAECronTrait          = "PaginatorHeader"
)

//---------------------------------------------
// etc
//---------------------------------------------

const (
	AtndID = iota + 1
	ConnpassID
	DoorkeeperID
)

const (
	Atnd       = "atnd"
	Connpass   = "connpass"
	Doorkeeper = "doorkeeper"
)

const SearchPeriod = 1

//---------------------------------------------
// etc
//---------------------------------------------

const (
	InternalErr   = "サーバーとの通信中にエラーが発生しました type: %s number: %d"
	BadRequestErr = "リクエスト内容に不備があります type: %s number: %d"
)


text:
/*
* Chris Samuel
* ksamuel.chris@gmail.com
*
* October 2 2015
*
*
*
* */

'use strict';

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

var _createClass = (function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ('value' in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })();

var _get = function get(_x, _x2, _x3) { var _again = true; _function: while (_again) { var object = _x, property = _x2, receiver = _x3; desc = parent = getter = undefined; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x = parent; _x2 = property; _x3 = receiver; _again = true; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } };

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

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

var _reactRouter = require('react-router');

var _Navbar = require('./Navbar');

var _Navbar2 = _interopRequireDefault(_Navbar);

var _Footer = require('./Footer');

var _Footer2 = _interopRequireDefault(_Footer);

var App = (function (_React$Component) {
    _inherits(App, _React$Component);

    function App() {
        _classCallCheck(this, App);

        _get(Object.getPrototypeOf(App.prototype), 'constructor', this).apply(this, arguments);
    }

    _createClass(App, [{
        key: 'render',
        value: function render() {
            return _react2['default'].createElement(
                'div',
                null,
                _react2['default'].createElement(_Navbar2['default'], null),
                _react2['default'].createElement(_reactRouter.RouteHandler, null),
                _react2['default'].createElement(_Footer2['default'], null)
            );
        }
    }]);

    return App;
})(_react2['default'].Component);

exports['default'] = App;

/*
* Routehandler is a component that renders the active child route handler.
* It will render one of the following components depending on the URL path:
* Home,Top 100, Profile or Add Character.
*
*       AngularJS Equivalent : <div ng-view></div>
 *              Which includes the rendered template of current route
*               into the main layout.
 *
  * */
module.exports = exports['default'];

//# sourceMappingURL=app-compiled.js.map


text:
aliases: [ 'depressionalt' ]
title: "#depression-alt rules"
date: 2019-01-03T10:07:10Z
draft: false
type: "page"
---

## #depression-alt

[Purpose](#purpose) || [Channel Operators](#ops) || [Rules & Guidelines](#guidelines) || [Ban Appeals](https://www.reddit.com/r/SnoonetDepression/) || {{< webchat channel="#depression-alt" >}}

##
Purpose

#depression-alt provides a space away from #depression where the rules are relaxed. Certain topics normally prohibited in the main channel will be permitted here, meaning that discretion is advised.

If you can not handle discussion of self harm and/or more specific suicide methods, it is advised to immediately /part or /leave the channel. Network and channel rules still apply. Please see below for more information.

## Channel Operators
The team handling #depression-alt is the same team that currently handles the #depression channel.

If you need to contact an operator for assistance, you may find a list of operators by [clicking here](/depression#ops).

## Rules & Guidelines
1. In order to encourage open discussion, try to keep discussions in the channel.
2. Please use discretion when discussing certain sensitive topics (such as politics and/or religion) in the channel.
3. You may not advertise your own channel or service through our channel or directly through our users unless authorization has been provided by channel operators.
4. Please refrain from bringing drama into our channel from other IRC channels. Additionally, please do not share others' personal information in the channel.
5. Graphic depictions of specific suicide/self harm methods and abuse as well as glorification of suicide/self harm are prohibited in this channel.
6. Any decisions made by our operators are final. If you believe that a decision made by particular operator is unfair, please try talking to that operator directly, or message another channel operator.