text:
require 'thread'
require 'open-uri'
require 'nokogiri'
require 'cgi'
require 'csv'
require 'set'
require 'with_validations'
require 'string_to_pinyin'
require 'chinese_vocab/scraper'
require 'chinese_vocab/modules/helper_methods'
require 'chinese_vocab/core_ext/hash'
require 'chinese_vocab/core_ext/queue'

module Chinese
  class Vocab
    include WithValidations
    include HelperMethods

    # The list of Chinese words after calling {#edit_vocab}. Editing includes:
    #
    #  * Removing parentheses (with the content inside each parenthesis).
    #  * Removing any slash (/) and only keeping the longest part.
    #  * Removing trailing '儿' from any word longer than two characters.
    #  * Removing non-word characters such as points and commas.
    #  * Removing and duplicate words.
    #@return [Array<String>]
    attr_reader :words
    #@return [Boolean] the value of the _:compact_ options key.
    attr_reader :compact
    #@return [Array<String>] holds those Chinese words from {#words} that could not be found in any
    # of the supported online dictionaries during a call to either {#sentences} or {#min_sentences}.
    # Defaults to `[]`.
    attr_reader :not_found
    #@return [Boolean] the value of the `:with_pinyin` option key.
    attr_reader :with_pinyin
    #@return [Array<Hash>] holds the return value of either {#sentences} or {#min_sentences},
    #  whichever was called last. Defaults to `[]`.
    attr_reader :stored_sentences

    # Mandatory constant for the [WithValidations](http://rubydoc.info/github/bytesource/with_validations/file/README.md) module. Each key-value pair is of the following type:
    #  `option_key => [default_value, validation]`
    OPTIONS = {:compact      => [false, lambda {|value| is_boolean?(value) }],
               :with_pinyin  => [true,  lambda {|value| is_boolean?(value) }],
               :thread_count => [8,     lambda {|value| value.kind_of?(Integer) }]}

    # Intializes an object.
    # @note Words that are composite expressions must be written with a least one non-word
    #   character (such as whitespace) between each sub-expression. Example: "除了 以外" or
    #   "除了。。以外" instead of "除了以外".
    # @overload initialize(word_array, options)
    #  @param [Array<String>] word_array An array of Chinese words that is stored in {#words} after
    #   all non-ascii, non-unicode characters have been stripped and double entries removed.
    #  @param [Hash] options The options to customize the following feature.
    #  @option options [Boolean] :compact Whether or not to remove all single character words that
    #   also appear in at least one multi character word. Example: (["看", "看书"] => [看书])
    #   The reason behind this option is to remove redundancy in meaning and focus on learning distinct words.
    #   Defaults to `false`.
    # @overload initialize(word_array)
    # @param [Array<String>] word_array An array of Chinese words that is stored in {#words} after
    #  all non-ascii, non-unicode characters have been stripped and double entries removed.
    # @example (see #sentences_unique_chars)
    def initialize(word_array, options={})
      @compact = validate { :compact }
      @words    = edit_vocab(word_array)
      @words    = remove_redundant_single_char_words(@words)  if @compact
      @chinese  = is_unicode?(@words[0])
      @not_found        = []
      @stored_sentences = []
    end

    # Extracts the vocabulary column from a CSV file as an array of strings. The array is
    #   normally provided as an argument to {#initialize}
    # @note (see #initialize)
    # @overload parse_words(path_to_csv, word_col, options)
    #  @param [String] path_to_csv The relative or full path to the CSV file.
    #  @param [Integer] word_col The column number of the vocabulary column (counting starts at 1).
    #  @param [Hash] options The [supported options](http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#method-c-new) of Ruby's CSV library as well as the `:encoding` parameter.
    #    Exceptions: `:encoding` is always set to `utf-8` and `:skip_blanks` to `true` internally.
    # @overload parse_words(path_to_csv, word_col)
    #  @param [String] path_to_csv The relative or full path to the CSV file.
    #  @param [Integer] word_col The column number of the vocabulary column (counting starts at 1).
    # @return [Array<String>] The vocabluary (Chinese words)
    # @example (see #sentences_unique_chars)
    def self.parse_words(path_to_csv, word_col, options={})
      # Enforced options:
      # encoding: utf-8 (necessary for parsing Chinese characters)
      # skip_blanks: true
      options.merge!({:encoding => 'utf-8', :skip_blanks => true})
      csv = CSV.read(path_to_csv, options)

      raise ArgumentError, "Column number (#{word_col}) out of range."  unless within_range?(word_col, csv[0])
      # 'word_col counting starts at 1, but CSV.read returns an array,
      # where counting starts at 0.
      col = word_col-1
      csv.reduce([]) {|words, row|
        word = row[col]
        # If word_col contains no data, CSV::read returns nil.
        # We also want to skip empty strings or strings that only contain whitespace.
        words << word  unless word.nil? || word.strip.empty?
        words
      }
    end

    # For every Chinese word in {#words} fetches a Chinese sentence and its English translation
    # from an online dictionary,
    # @note (Normally you only call this method directly if you really need one sentence
    #  per Chinese word (even if these words might appear in more than one of the sentences.).
    # @note (see #min_sentences)
    # @overload sentences(options)
    #  @param [Hash] options The options to customize the following features.
    #  @option options [Symbol] :source The online dictionary to download the sentences from,
    #    either [:nciku](http://www.nciku.com) or [:jukuu](http://www.jukuu.com).
    #    Defaults to *:nciku*.
    #  @option options [Symbol] :size The size of the sentence to return from a possible set of
    #    several sentences. Supports the values *:short*, *:average*, and *:long*.
    #    Defaults to *:short*.
    #  @option options [Boolean] :with_pinyin Whether or not to return the pinyin representation
    #    of a sentence.
    #    Defaults to `true`.
    #  @option options [Integer] :thread_count The number of threads used to download the sentences.
    #    Defaults to `8`.
    # @return [Hash] By default each hash holds the following key-value pairs (The return value is also stored in {#stored_sentences}.):
    #
    #    * :chinese => Chinese sentence
    #    * :english => English translation
    #    * :pinyin  => Pinyin
    #   The return value is also stored in {#stored_sentences}.
    # @example
    #  require 'chinese_vocab'
    #
    #  # Extract the Chinese words from a CSV file.
    #  words = Chinese::Vocab.parse_words('path/to/file/hsk.csv', 4)
    #
    #  # Initialize Chinese::Vocab with word array
    #  # :compact => true means single character words are that also appear in multi-character
    #  # words are removed from the word array (["看", "看书"] => [看书])
    #  vocabulary = Chinese::Vocab.new(words, :compact => true)
    #
    #  # Return a sentence for each word
    #  vocabulary.sentences(:size => small)
    def sentences(options={})
      puts "Fetching sentences..."
      # Always run this method.

      # We assign all options to a variable here (also those that are passed on)
      # as we need them in order to calculate the id.
      @with_pinyin = validate { :with_pinyin }
      thread_count = validate { :thread_count }
      id           = make_hash(@words, options.to_a.sort)
      words        = @words

      from_queue  = Queue.new
      to_queue    = Queue.new
      file_name   = id

      if File.exist?(file_name)
        puts "Examining file..."
        words, sentences, not_found = File.open(file_name) { |f| f.readlines }
        words = convert(words)
        convert(sentences).each { |s| to_queue << s }
        @not_found = convert(not_found)
        size_a = words.size
        size_b = to_queue.size
        puts "Size(@not_found)  = #{@not_found.size}"
        puts "Size(words)       = #{size_a}"
        puts "Size(to_queue)    = #{size_b}"
        puts "Size(words+queue) = #{size_a+size_b}"
        puts "Size(sentences)   = #{to_queue.size}"

        # Remove file
        File.unlink(file_name)
      end

      words.each {|word| from_queue << word }
      result = []

      Thread.abort_on_exception = false

      1.upto(thread_count).map {
        Thread.new do

          while(word = from_queue.pop!) do

            begin
              local_result = select_sentence(word, options)
              puts "Processing word: #{word} (#{from_queue.size} words left)"
              # rescue SocketError, Timeout::Error, Errno::ETIMEDOUT,
              # Errno::ECONNREFUSED, Errno::ECONNRESET, EOFError => e
            rescue Exception => e
              puts " #{e.message}."
              puts "Please DO NOT abort, but wait for either the program to continue or all threads"
              puts "to terminate (in which case the data will be saved to disk for fast retrieval on the next run.)"
              puts "Number of running threads: #{Thread.list.size - 1}."
              raise

            ensure
              from_queue << word  if $!
              puts "Wrote '#{word}' back to queue"  if $!
            end

            to_queue << local_result  unless local_result.nil?

          end
        end
      }.each {|thread| thread.join }

      @stored_sentences = to_queue.to_a
      @stored_sentences

    ensure
      if $!
        while(Thread.list.size > 1) do # Wait for all child threads to terminate.
          sleep 5
        end

        File.open(file_name, 'w') do |f|
          p "============================="
          p "Writing data to file..."
          f.write from_queue.to_a
          f.puts
          f.write to_queue.to_a
          f.puts
          f.write @not_found
          puts "Finished writing data."
          puts "Please run the program again after solving the (connection) problem."
        end
      end
    end

    # For every Chinese word in {#words} fetches a Chinese sentence and its English translation
    # from an online dictionary, then calculates and the minimum number of sentences
    # necessary to cover every word in {#words} at least once.
    # The calculation is based on the fact that many words occur in more than one sentence.
    #
    # @note In case of a network error during dowloading the sentences the data fetched
    #  so far is automatically copied to a file after several retries. This data is read and
    #  processed on the next run to reduce the time spend with downloading the sentences
    #  (which is by far the most time-consuming part).
    # @note Despite the download source chosen (by using the default or setting the `:source` options), if a word was not found on the first site, the second site is used as an alternative.
    # @overload min_sentences(options)
    #  @param [Hash] options The options to customize the following features.
    #  @option options [Symbol] :source The online dictionary to download the sentences from,
    #    either [:nciku](http://www.nciku.com) or [:jukuu](http://www.jukuu.com).
    #    Defaults to `:nciku`.
    #  @option options [Symbol] :size The size of the sentence to return from a possible set of
    #    several sentences. Supports the values `:short`, `:average`, and `:long`.
    #    Defaults to `:short`.
    #  @option options [Boolean] :with_pinyin Whether or not to return the pinyin representation
    #    of a sentence.
    #    Defaults to `true`.
    #  @option options [Integer] :thread_count The number of threads used to download the sentences.
    #    Defaults to `8`.
    # @return [Array<Hash>, []] By default each hash holds the following key-value pairs (The return value is also stored in {#stored_sentences}.):
    #
    #    * :chinese => Chinese sentence
    #    * :english => English translation
    #    * :pinyin  => Pinyin
    #    * :uwc     => Unique words count tag (String) of the form "x_words",
    #      where *x* denotes the number of unique words from {#words} found in the sentence.
    #    * :uws     => Unique words string tag (String) of the form "[词语1,词语2,...]",
    #      where *词语* denotes the actual word(s) from {#words} found in the sentence.
    #   The return value is also stored in {#stored_sentences}.
    # @example (see #sentences_unique_chars)
    def min_sentences(options = {})
      @with_pinyin = validate { :with_pinyin }
      # Always run this method.
      thread_count = validate { :thread_count }
      sentences    = sentences(options)

      # Remove those words that don't have a sentence
      words             = @words - @not_found
      puts "Determining the target words for every sentence..."
      sentences         = add_target_words(sentences, words)

      minimum_sentences = find_minimum_sentences(sentences, words)

      # :uwc = 'unique words count'
      with_uwc_tag = add_key(minimum_sentences, :uwc) {|row| uwc_tag(row[:target_words]) }
      # :uws = 'unique words string'
      with_uwc_uws_tags = add_key(with_uwc_tag, :uws) do |row|
        words = row[:target_words].sort.join(', ')
        "[" + words + "]"
      end
      # Remove those keys we don't need anymore
      result = remove_keys(with_uwc_uws_tags, :target_words, :word)
      @stored_sentences = result
      @stored_sentences
    end

    def find_minimum_sentences(sentences, words)
      min_sentences   = []
      # At the start the variable 'remaining words' contains all
      # target words - minus those with no sentence found.
      remaining_words = Set.new(words.dup)

      # On every round:
      # Finds the sentence with the most target words ('best sentence').
      # Adds that sentence to the result array.
      # Deletes all target words from the remaining words that are part of
      # the best sentence.
      while(!remaining_words.empty?) do
        puts "Number of remaining_words: #{remaining_words.size}"
        # puts "Take five: #{remaining_words.take(5)}"

        # Return the sentence with the largest number of target words.
        sentences = sentences.sort_by do |row|
          # Returns a new array containing elements common to
          # the two arrays, with no duplicates.
          words_left = remaining_words.intersection(row[:target_words])

          # Sort by size of words left first (in descsending order),
          # if equal, sort by length of the Chinese sentence (in ascending order).
          [-words_left.size, row[:chinese].size]
        end

        best_sentence = sentences.first

        # Add the sentence with the largest number of
        # target words to the result array.
        min_sentences << best_sentence
        # Remove the target words that are part of the
        # best sentence from the remaining words.
        remaining_words = remaining_words - best_sentence[:target_words]
      end

      # puts "Number of minimum sentences: #{min_sentences.size}"
      min_sentences
    end

    # Finds the unique Chinese characters from either the data in {#stored_sentences} or an
    # array of Chinese sentences passed as an argument.
    # @overload sentences_unique_chars(sentences)
    #  @param [Array<String>, Array<Hash>] sentences An array of chinese sentences or an array of hashes with the key `:chinese`.
    # @note If no argument is passed, the data from {#stored_sentences} is used as input
    # @return [Array<String>] The unique Chinese characters
    # @example
    #  require 'chinese_vocab'
    #
    #  # Extract the Chinese words from a CSV file.
    #  words = Chinese::Vocab.parse_words('path/to/file/hsk.csv', 4)
    #
    #  # Initialize Chinese::Vocab with word array
    #  # :compact => true means single character words are that also appear in multi-character
    #  # words are removed from the word array (["看", "看书"] => [看书])
    #  vocabulary = Chinese::Vocab.new(words, :compact => true)
    #
    #  # Return minimum necessary sentences.
    #  vocabulary.min_sentences(:size => small)
    #
    #  # See how what are the unique characters in all these sentences.
    #  vocabulary.sentences_unique_chars(my_sentences)
    #  # => ["我", "们", "跟", "他", "是", "好", "朋", "友", ...]
    #
    #  # Save to file
    #  vocabulary.to_csv('path/to_file/vocab_sentences.csv')
    def sentences_unique_chars(sentences = stored_sentences)
      # If the argument is an array of hashes, then it must be the data from @stored_sentences
      sentences = sentences.map { |hash| hash[:chinese] }  if sentences[0].kind_of?(Hash)

      sentences.reduce([]) do |acc, row|
        acc = acc | row.scan(/\p{Word}/) # only return characters, skip punctuation marks
        acc
      end
    end

    # Saves the data stored in {#stored_sentences} to disk.
    # @overload to_csv(path_to_file, options)
    #  @param [String] path_to_file file name and path of where to save the file.
    #  @param [Hash] options The [supported options](http://ruby-doc.org/stdlib-1.9.3/libdoc/csv/rdoc/CSV.html#method-c-new) of Ruby's CSV library.
    # @overload to_csv(path_to_file)
    #  @param [String] path_to_file file name and path of where to save the file.
    # @return [void]
    # @example (see #sentences_unique_chars)
    def to_csv(path_to_file, options = {})

      CSV.open(path_to_file, "w", options) do |csv|
        @stored_sentences.each do |row|
          csv << row.values
        end
      end
    end

    # Helper functions
    # -----------------
    def remove_parens(word)
      # 1) Remove all ASCII parens and all data in between.
      # 2) Remove all Chinese parens and all data in between.
      word.gsub(/\(.*?\)/, '').gsub(/(.*?)/, '')
    end

    def is_boolean?(value)
      # Only true for either 'false' or 'true'
      !!value == value
    end

    # Remove all non-word characters
    def edit_vocab(word_array)

      word_array.map {|word|
        edited = remove_parens(word)
        edited = remove_slash(edited)
        edited = remove_er_character_from_end(edited)
        distinct_words(edited).join(' ')
      }.uniq
    end

    def remove_er_character_from_end(word)
      if word.size > 2
      word.gsub(/儿$/, '')
      else # Don't remove "儿" form words like 女儿
        word
      end
    end

    def remove_slash(word)
      if word.match(/\//)
        word.split(/\//).sort_by { |w| w.size }.last
      else
        word
      end
    end

    def make_hash(*data)
      require 'digest'
      data = data.reduce("") { |acc, item| acc << item.to_s }
      Digest::SHA2.hexdigest(data)[0..6]
    end

    # Input: ["看", "书", "看书"]
    # Output: ["看书"]
    def remove_redundant_single_char_words(words)
      puts "Removing redundant single character words from the vocabulary..."

      single_char_words, multi_char_words = words.partition {|word| word.length == 1 }
      return single_char_words  if multi_char_words.empty?

      non_redundant_single_char_words = single_char_words.reduce([]) do |acc, single_c|

        already_found = multi_char_words.find do |multi_c|
          multi_c.include?(single_c)
        end
        # Add single char word to array if it is not part of any of the multi char words.
        acc << single_c  unless already_found
        acc
      end

      non_redundant_single_char_words + multi_char_words
    end

    # Uses options passed from #sentences
    def select_sentence(word, options)
      sentence_pair = Scraper.sentence(word, options)

      sources = Scraper::Sources.keys
      sentence_pair = try_alternate_download_sources(sources, word, options)  if sentence_pair.empty?

      if sentence_pair.empty?
        @not_found << word
        return nil
      else
        chinese, english = sentence_pair

        result = Hash.new
        result.merge!(word:    word)
        result.merge!(chinese: chinese)
        result.merge!(pinyin:  chinese.to_pinyin)  if @with_pinyin
        result.merge!(english: english)
      end
    end

    def try_alternate_download_sources(alternate_sources, word, options)
      sources = alternate_sources.dup
      sources.delete(options[:source])

      result = sources.find do |s|
        options  = options.merge(:source => s)
        sentence = Scraper.sentence(word, options)
        sentence.empty? ? nil : sentence
      end

      if result
        optins = options.merge(:source => result)
        Scraper.sentence(word, options)
      else
        []
      end
    end

    def convert(text)
      eval(text.chomp)
    end

    def add_target_words(hash_array, words)
      from_queue  = Queue.new
      to_queue    = Queue.new
      # semaphore = Mutex.new
      result      = []
      # words       = @words
      hash_array.each {|hash| from_queue << hash}

      10.times.map {
        Thread.new(words) do

          while(row = from_queue.pop!)
            sentence     = row[:chinese]
            target_words = target_words_per_sentence(sentence, words)

            to_queue << row.merge(:target_words => target_words)

          end
        end
      }.map {|thread| thread.join}

      to_queue.to_a

    end

    def target_words_per_sentence(sentence, words)
       words.select {|w| include_every_char?(w, sentence) }
    end

    def sort_by_target_word_count(with_target_words)

      # First sort by size of unique word array (from large to short)
      # If the unique word count is equal, sort by the length of the sentence (from small to large)
      with_target_words.sort_by {|row|
        [-row[:target_words].size, row[:chinese].size] }

        #  The above is the same as:
        #   with_target_words.sort {|a,b|
        #     first = -(a[:target_words].size <=> b[:target_words].size)
        #     first.nonzero? || (a[:chinese].size <=> b[:chinese].size) }
    end

    # Calculates the number of occurences of every word of {#words} in {#stored_sentences}
    # @return [Hash] Keys are the words in {#words} with the values indicating the number of
    #   occurences in {#stored_sentences}
    def word_frequency

      words.reduce({}) do |acc, word|
        acc[word] = 0 # Set key with a default value of zero.

        stored_sentences.each do |row|
          sentence = row[:chinese]
          acc[word] += 1 if include_every_char?(word, sentence)
        end
        acc
      end
    end

    # @deprecated  This method has been replaced by {#find_minimum_sentences}.
    def select_minimum_necessary_sentences(sentences)
      words = @words - @not_found
      with_target_words = add_target_words(sentences, words)
      rows              = sort_by_target_word_count(with_target_words)

      selected_rows   = []
      unmatched_words = @words.dup
      matched_words   = []

      rows.each do |row|
        words = row[:target_words].dup
        # Delete all words from 'words' that have already been encoutered
        # (and are included in 'matched_words').
        words = words - matched_words

        if words.size > 0  # Words that where not deleted above have to be part of 'unmatched_words'.
          selected_rows << row  # Select this row.

          # When a row is selected, its 'words' are no longer unmatched but matched.
          unmatched_words = unmatched_words - words
          matched_words   = matched_words + words
        end
      end
      selected_rows
    end

    def occurrence_count(word_array, frequency)
      word_array.reduce(0) do |acc, word|
        acc + frequency[word]
      end
    end

    def remove_keys(hash_array, *keys)
      hash_array.map { |row| row.delete_keys(*keys) }
    end

    def add_key(hash_array, key, &block)
      hash_array.map do |row|
        if block
          row.merge({key => block.call(row)})
        else
          row
        end
      end
    end

    def uwc_tag(string)
      size = string.length
      case size
      when 1
        "1_word"
      else
        "#{size}_words"
      end
    end

    def contains_all_target_words?(selected_rows, sentence_key)

      matched_words = @words.reduce([]) do |acc, word|

        result = selected_rows.find do |row|
          sentence = row[sentence_key]
          include_every_char?(word, sentence)
        end

        if result
          acc << word
        end

        acc
      end

      # matched_words.size == @words.size

      if matched_words.size == @words.size
        true
      else
        puts "Words not found in sentences:"
        p @words - matched_words
        false
      end
    end

    # Input:
    # column: word column number (counting from 1)
    # row   : Array of the processed CSV data that contains our word column.
    def self.within_range?(column, row)
      no_of_cols = row.size
      column >= 1 && column <= no_of_cols
    end

    def alternate_source(sources, selection)
      sources = sources.dup
      sources.delete(selection)
      sources.pop
    end

  end
end


text:
namespace Microsoft.Azure.Management.Redis.Models
{
    using Microsoft.Rest;
    using Newtonsoft.Json;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Managed service identity (system assigned and/or user assigned
    /// identities)
    /// </summary>
    public partial class ManagedServiceIdentity
    {
        /// <summary>
        /// Initializes a new instance of the ManagedServiceIdentity class.
        /// </summary>
        public ManagedServiceIdentity()
        {
            CustomInit();
        }

        /// <summary>
        /// Initializes a new instance of the ManagedServiceIdentity class.
        /// </summary>
        /// <param name="type">Possible values include: 'None',
        /// 'SystemAssigned', 'UserAssigned', 'SystemAssigned,
        /// UserAssigned'</param>
        /// <param name="principalId">The service principal ID of the system
        /// assigned identity. This property will only be provided for a system
        /// assigned identity.</param>
        /// <param name="tenantId">The tenant ID of the system assigned
        /// identity. This property will only be provided for a system assigned
        /// identity.</param>
        public ManagedServiceIdentity(string type, System.Guid? principalId = default(System.Guid?), System.Guid? tenantId = default(System.Guid?), IDictionary<string, UserAssignedIdentity> userAssignedIdentities = default(IDictionary<string, UserAssignedIdentity>))
        {
            PrincipalId = principalId;
            TenantId = tenantId;
            Type = type;
            UserAssignedIdentities = userAssignedIdentities;
            CustomInit();
        }

        /// <summary>
        /// An initialization method that performs custom operations like setting defaults
        /// </summary>
        partial void CustomInit();

        /// <summary>
        /// Gets the service principal ID of the system assigned identity. This
        /// property will only be provided for a system assigned identity.
        /// </summary>
        [JsonProperty(PropertyName = "principalId")]
        public System.Guid? PrincipalId { get; private set; }

        /// <summary>
        /// Gets the tenant ID of the system assigned identity. This property
        /// will only be provided for a system assigned identity.
        /// </summary>
        [JsonProperty(PropertyName = "tenantId")]
        public System.Guid? TenantId { get; private set; }

        /// <summary>
        /// Gets or sets possible values include: 'None', 'SystemAssigned',
        /// 'UserAssigned', 'SystemAssigned, UserAssigned'
        /// </summary>
        [JsonProperty(PropertyName = "type")]
        public string Type { get; set; }

        /// <summary>
        /// </summary>
        [JsonProperty(PropertyName = "userAssignedIdentities")]
        public IDictionary<string, UserAssignedIdentity> UserAssignedIdentities { get; set; }

        /// <summary>
        /// Validate the object.
        /// </summary>
        /// <exception cref="ValidationException">
        /// Thrown if validation fails
        /// </exception>
        public virtual void Validate()
        {
            if (Type == null)
            {
                throw new ValidationException(ValidationRules.CannotBeNull, "Type");
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package component.liba;

import android.content.Context;
import android.support.annotation.Nullable;
import android.util.AttributeSet;

/**
 * Created by ws on 17/9/9.
 */

public class LibAView extends android.support.v7.widget.AppCompatTextView {
    public LibAView(Context context) {
        this(context, null);
    }

    public LibAView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public LibAView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        setText(R.string.tv_test_liba);

        setBackgroundResource(R.drawable.lib_a);

    }

}


text:
Amazon::Ecs.configure do |options|
    options[:AWS_access_key_id]    = Rails.application.secrets.aws_access_key_id
    options[:AWS_secret_key]       = Rails.application.secrets.aws_secret_key
    options[:associate_tag]        = Rails.application.secrets.associate_tag
end


text:
package org.openkilda.wfm.topology.nbworker.services;

import org.openkilda.messaging.info.network.PathsInfoData;
import org.openkilda.model.FlowEncapsulationType;
import org.openkilda.model.KildaConfiguration;
import org.openkilda.model.PathComputationStrategy;
import org.openkilda.model.SwitchId;
import org.openkilda.model.SwitchProperties;
import org.openkilda.pce.AvailableNetworkFactory;
import org.openkilda.pce.Path;
import org.openkilda.pce.PathComputer;
import org.openkilda.pce.PathComputerConfig;
import org.openkilda.pce.PathComputerFactory;
import org.openkilda.pce.exception.RecoverableException;
import org.openkilda.pce.exception.UnroutableFlowException;
import org.openkilda.persistence.repositories.KildaConfigurationRepository;
import org.openkilda.persistence.repositories.RepositoryFactory;
import org.openkilda.persistence.repositories.SwitchPropertiesRepository;
import org.openkilda.persistence.repositories.SwitchRepository;
import org.openkilda.wfm.error.SwitchNotFoundException;
import org.openkilda.wfm.error.SwitchPropertiesNotFoundException;
import org.openkilda.wfm.share.mappers.PathMapper;

import lombok.extern.slf4j.Slf4j;

import java.time.Duration;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Slf4j
public class PathsService {
    private final int defaultMaxPathCount;
    private PathComputer pathComputer;
    private SwitchRepository switchRepository;
    private SwitchPropertiesRepository switchPropertiesRepository;
    private KildaConfigurationRepository kildaConfigurationRepository;

    public PathsService(RepositoryFactory repositoryFactory, PathComputerConfig pathComputerConfig) {
        switchRepository = repositoryFactory.createSwitchRepository();
        switchPropertiesRepository = repositoryFactory.createSwitchPropertiesRepository();
        kildaConfigurationRepository = repositoryFactory.createKildaConfigurationRepository();
        PathComputerFactory pathComputerFactory = new PathComputerFactory(
                pathComputerConfig, new AvailableNetworkFactory(pathComputerConfig, repositoryFactory));
        pathComputer = pathComputerFactory.getPathComputer();
        defaultMaxPathCount = pathComputerConfig.getMaxPathCount();
    }

    /**
     * Get paths.
     */
    public List<PathsInfoData> getPaths(
            SwitchId srcSwitchId, SwitchId dstSwitchId, FlowEncapsulationType requestEncapsulationType,
            PathComputationStrategy requestPathComputationStrategy, Duration maxLatency, Duration maxLatencyTier2,
            Integer maxPathCount) throws RecoverableException, SwitchNotFoundException, UnroutableFlowException {
        if (Objects.equals(srcSwitchId, dstSwitchId)) {
            throw new IllegalArgumentException(
                    String.format("Source and destination switch IDs are equal: '%s'", srcSwitchId));
        }
        if (!switchRepository.exists(srcSwitchId)) {
            throw new SwitchNotFoundException(srcSwitchId);
        }
        if (!switchRepository.exists(dstSwitchId)) {
            throw new SwitchNotFoundException(dstSwitchId);
        }

        KildaConfiguration kildaConfiguration = kildaConfigurationRepository.getOrDefault();
        FlowEncapsulationType flowEncapsulationType = Optional.ofNullable(requestEncapsulationType)
                .orElse(kildaConfiguration.getFlowEncapsulationType());

        SwitchProperties srcProperties = switchPropertiesRepository.findBySwitchId(srcSwitchId).orElseThrow(
                () -> new SwitchPropertiesNotFoundException(srcSwitchId));
        if (!srcProperties.getSupportedTransitEncapsulation().contains(flowEncapsulationType)) {
            throw new IllegalArgumentException(String.format("Switch %s doesn't support %s encapslation type. Choose "
                    + "one of the supported encapsulation types %s or update switch properties and add needed "
                    + "encapsulation type.", srcSwitchId, flowEncapsulationType,
                    srcProperties.getSupportedTransitEncapsulation()));
        }

        SwitchProperties dstProperties = switchPropertiesRepository.findBySwitchId(dstSwitchId).orElseThrow(
                () -> new SwitchPropertiesNotFoundException(dstSwitchId));
        if (!dstProperties.getSupportedTransitEncapsulation().contains(flowEncapsulationType)) {
            throw new IllegalArgumentException(String.format("Switch %s doesn't support %s encapslation type. Choose "
                    + "one of the supported encapsulation types %s or update switch properties and add needed "
                    + "encapsulation type.", dstSwitchId, requestEncapsulationType,
                    dstProperties.getSupportedTransitEncapsulation()));
        }

        PathComputationStrategy pathComputationStrategy = Optional.ofNullable(requestPathComputationStrategy)
                .orElse(kildaConfiguration.getPathComputationStrategy());

        if (maxPathCount == null) {
            maxPathCount = defaultMaxPathCount;
        }

        if (maxPathCount <= 0) {
            throw new IllegalArgumentException(String.format("Incorrect maxPathCount: %s", maxPathCount));
        }

        List<Path> flowPaths = pathComputer.getNPaths(srcSwitchId, dstSwitchId, maxPathCount, flowEncapsulationType,
                pathComputationStrategy, maxLatency, maxLatencyTier2);

        return flowPaths.stream().map(PathMapper.INSTANCE::map)
                .map(path -> PathsInfoData.builder().path(path).build())
                .collect(Collectors.toList());
    }
}


text:
package io.gatling.core.controller.throttle

import scala.concurrent.duration._

import io.gatling.commons.util.Maps._

import akka.actor.ActorRef

sealed trait ThrottlerControllerCommand

object ThrottlerControllerCommand {
  case object Start extends ThrottlerControllerCommand
  case class OverrideStart(overrides: Throttlings) extends ThrottlerControllerCommand
  case object OverrideStop extends ThrottlerControllerCommand
  case object Tick extends ThrottlerControllerCommand
}

private[throttle] class ThrottlerController(throttler: ActorRef, defaults: Throttlings) extends ThrottlerControllerFSM {

  import ThrottlerControllerState._
  import ThrottlerControllerData._
  import ThrottlerControllerCommand._

  def notifyThrottler(throttlings: Throttlings, tick: Int): Unit = {

    val throttles = Throttles(
      global = throttlings.global.map(p => new Throttle(p.limit(tick))),
      perScenario = throttlings.perScenario.forceMapValues(p => new Throttle(p.limit(tick)))
    )

    throttler ! throttles
  }

  startWith(WaitingToStart, NoData)

  when(WaitingToStart) {

    case Event(Start, NoData) =>
      system.scheduler.schedule(Duration.Zero, 1 second, self, Tick)
      notifyThrottler(defaults, 0)
      goto(Started) using StartedData(0)
  }

  when(Started) {

    case Event(Tick, StartedData(tick)) =>
      notifyThrottler(defaults, tick)
      stay() using StartedData(tick + 1)

    case Event(OverrideStart(overrides), StartedData(tick)) =>
      goto(Overridden) using OverrideData(overrides, tick)

    case Event(OverrideStop, _) =>
      // out fo band
      stay()
  }

  when(Overridden) {

    case Event(Tick, OverrideData(overrides, tick)) =>
      notifyThrottler(overrides, tick)
      stay() using OverrideData(overrides, tick + 1)

    case Event(OverrideStart(newOverrides), OverrideData(_, tick)) =>
      stay() using OverrideData(newOverrides, tick)

    case Event(OverrideStop, OverrideData(_, tick)) =>
      goto(Started) using StartedData(tick)
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<!-- Main content view -->
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    tools:context=".GuidesActivity"
    >

    <TabHost
        android:id="@android:id/tabhost"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >

            <TabWidget
                android:id="@android:id/tabs"
                android:background="#ffffff"
                android:orientation="horizontal"
                android:layout_width="fill_parent"
                android:elevation="3dp"
                android:layout_height="42dp"
                android:layout_weight="0" />

            <FrameLayout
                android:id="@android:id/tabcontent"
                android:layout_width="0dp"
                android:layout_height="0dp"
                android:layout_weight="0" />

            <androidx.viewpager.widget.ViewPager
                android:id="@+id/viewpager"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="bottom" />

        </LinearLayout>
    </TabHost>

</LinearLayout>


text:
#pragma once
#include <GL/glew.h>
#include <vector>
#include <engine/util/Logger.h>

class VBODescription
{
    friend class MeshBuilder;

    /**
    * Used to queue attributes to deduce offset and stride.
    */
    struct Attr
    {
        Attr() : offset(nullptr) { }

        Attr(GLint size, GLenum type, GLuint divisor, GLboolean normalized)
            : size(size), type(type), divisor(divisor), normalized(normalized), offset(nullptr) { }

        Attr(GLint size, GLenum type, GLuint divisor, GLboolean normalized, const void* offset, size_t stride)
            : size(size), type(type), divisor(divisor), normalized(normalized), offset(offset), stride(stride) { }

        GLint size{0};
        GLenum type{0};
        GLuint divisor{0};
        GLboolean normalized{false};
        const void* offset;
        size_t stride{0};
    };

public:
    /**
    * Creates a vertex buffer object with the given size and a pointer to the data.
    * Usage is defined to be GL_STATIC_DRAW by default.
    */
    VBODescription(size_t size, const void* data, GLenum usage = GL_STATIC_DRAW);

    /**
    * Specify the next vertex attribute - offsets and stride will be deduced when finalize() is called.
    * Attributes in the vertex buffer object are expected to be interleaved.
    * Order of attribute() calls should correspond to the order of attributes in the interleaved buffer object.
    */
    VBODescription& attribute(GLint size, GLenum type, GLuint attribDivisor = 0, GLboolean normalized = false);

    /**
    * Specify the next vertex attribute with offset and stride.
    * Order of attribute() calls should correspond to the order of attributes in the buffer object.
    */
    VBODescription& attribute(GLint size, GLenum type, const void* offset, GLsizei stride, GLuint attribDivisor = 0, GLboolean normalized = false);

private:
    bool m_deducedOffset{true};

    size_t m_size{0};
    const void* m_data;
    GLenum m_usage;
    std::vector<Attr> m_attributes;
};

class MeshBuilder
{
public:
    explicit MeshBuilder(size_t vertexCount);

    void reset();

    /**
    * Creates a vertex buffer object with the given size and a pointer to the data.
    * Usage is defined to be GL_STATIC_DRAW by default.
    */
    MeshBuilder& createVBO(VBODescription& vboDescription);

    /**
    * Creates an index buffer object with the given index count and a pointer to the data.
    * Specify the index type as a template paramter - e.g. createIBO<GLuint>()
    * The type of the indicies is defined to be GL_UNSIGNED_INT by default.
    * Usage is defined to be GL_STATIC_DRAW by default.
    */
    MeshBuilder& createIBO(size_t indexCount, const void* data, GLenum indexType = GL_UNSIGNED_INT, GLenum usage = GL_STATIC_DRAW);

    /**
    * Creates a vertex array object and binds attributes.
    */
    void finalize();

    std::vector<GLuint> getVBOs() const { return m_vbos; }

    GLuint getVBO(size_t idx) const { return m_vbos[idx]; }

    GLuint getIBO() const { return m_ibo; }

    GLuint getVAO() const { return m_vao; }

    size_t getIndexCount() const { return m_indexCount; }

    size_t getVertexCount() const { return m_vertexCount; }

    GLenum getIndexType() const { return m_indexType; }

private:
    std::vector<VBODescription> m_vboDescriptions;
    std::vector<GLuint> m_vbos;
    GLuint m_ibo{0};
    GLuint m_vao{0};

    GLenum m_indexType{0};
    size_t m_indexCount{0};
    size_t m_vertexCount{0};
};


text:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <getopt.h>
#include <stdarg.h>

#include "tz_finder_location.h"
#include "tz_system_utils.h"

#include "config.h"

#ifndef PACKAGE_STRING
#define PACKAGE_STRING "gettz"
#endif
#ifndef PACKAGE_BUGREPORT
#define PACKAGE_BUGREPORT "mr.zoltan.gyarmati@gmail.com"
#endif

// can be increased to add verbosity
int verbose = 0;
// 0 or 1, when 1, we print only the timezone
int quiet = 0;

#ifndef DEFAULT_SHP_FILE
#define DEFAULT_SHP_FILE "/usr/share/timezoned/dist/combined_shapefile.shp"
#endif

#ifndef DEFAULT_DBF_FILE
#define DEFAULT_DBF_FILE "/usr/share/timezoned/dist/combined_shapefile.dbf"
#endif

void
print_version()
{
    fputs(PACKAGE_STRING "/gettz\n", stderr);
    fputs("Version: " PACKAGE_VERSION "\n", stderr);
    fputs("Please report bugs to: " PACKAGE_BUGREPORT"\n", stderr);
}

void
print_help()
{
    fputs("Usage:\n\n",stderr);
    fputs("gettz <options> longitude latitude\n\n",stderr);
    fputs("where longitude and latitude are the geographical coordinates in decimal format\n",stderr);
    fputs("Options:\n",stderr);
    fputs("\t-h, --help           Print this help\n",stderr);
    fputs("\t-V, --version        Print version info\n",stderr);
    fputs("\t-s, --set-timezone   Set the system timezone to the requested value\n",stderr);
    fputs("\t-v, --verbose        Verbose output, multiple for more verbose\n",stderr);
    fputs("\t-q, --quiet          Print only the timezone (or nothing), overrides -v\n",stderr);
}

void
verbosemsg(int level, const char *formatstring,...)
{
    if (level > verbose || quiet){
        return;
    }
    va_list args;
    va_start (args, formatstring);
    vprintf(formatstring, args);
    va_end(args);
}

void
errormsg(const char *formatstring,...)
{
    va_list args;
    va_start (args, formatstring);
    vfprintf(stderr, formatstring, args);
    va_end(args);
    fputc('\n', stderr);
}

int
main (int argc, char * argv[])
{
    //parse command line args
    int  set_system_tz = 0;
    char ch;
    static struct option long_options[] = {
        {"help",    no_argument,       0,  'h' },
        {"version", no_argument,       0,  'V' },
        {"set-timezone",     no_argument,       0,  's' },
        {"verbose", no_argument,       0,  'v' },
        {"quiet", no_argument,         0,  'q' },
        {0,         0,                 0,  0 }};

    while ((ch = getopt_long(argc, argv, "hvsVq", long_options, NULL)) != -1){
        switch (ch){
            case 'h':
                print_help();
                exit(EXIT_SUCCESS);
                break;
            case 'V':
                print_version();
                exit(EXIT_SUCCESS);
                break;
            case 's':
                set_system_tz = 1;
                break;
            case 'v':
                verbose++;
                break;
            case 'q':
                quiet = 1;
                break;
        }
    }

    if ((argc-optind) != 2){
        errormsg("Need 2 coordinate parameters!\n");
        print_help();
        exit(EXIT_FAILURE);
    }
    char *endptr;
    double longitude = strtof(argv[optind],&endptr);
    if (argv[optind++] == endptr) {
        errormsg("can't convert longitude value <%s>, exiting...\n",argv[--optind]);
        exit(EXIT_FAILURE);
    }
    double latitude = strtof(argv[optind], &endptr);
    if (argv[optind++] == endptr) {
        errormsg("can't convert latitude value <%s>, exiting...\n",argv[--optind]);
        exit(EXIT_FAILURE);
    }
    //get shp and dbf file paths
    char *shp_path = getenv("GETTZ_SHP_FILE");
    char *dbf_path = getenv("GETTZ_DBF_FILE");

    if (shp_path == NULL){
        shp_path = DEFAULT_SHP_FILE;
    }
    if (dbf_path == NULL){
        dbf_path = DEFAULT_DBF_FILE;
    }

    //get to the business
    verbosemsg(1,"Coordinates: longitude %f, latitude %f\n", longitude, latitude);
    verbosemsg(1,"Map files: %s, %s\n",shp_path, dbf_path);
    char * tz_name = tz_get_name_by_coordinates(longitude, latitude,
                                                shp_path, dbf_path);
    if (tz_name == NULL){
        errormsg("Failed to look up timezone for the given coordinates");
        return EXIT_FAILURE;
    }

    if (!quiet){
        printf("Timezone: %s\n", tz_name);
    }
    else {
        printf("%s\n", tz_name);
    }
    if(set_system_tz){
#ifdef USE_SYSTEMD
        system_set_tz_dbus(tz_name);
#else
        system_set_tz_symlink(tz_name);
#endif
    }
    return EXIT_SUCCESS;
}


text:
#include "css/test_rule.h++"

#include <css/ostream.h++>
#include <css/grammar/color_stop.h++>

namespace
{
  const auto color = "red";

  const auto color_percentage = "blue 5.4%";
  const auto color_length = "green .3in";

  const auto color_angle = "yellow .5turn";
}

int main()
{
  using skui::test::check_rule_success;

  using skui::css::grammar::linear_color_stop;
  check_rule_success(linear_color_stop, color, {skui::css::colors::red, {}});
  check_rule_success(linear_color_stop, color_percentage, {skui::css::colors::blue, skui::css::length{5.4f, skui::css::unit::percentage}});
  check_rule_success(linear_color_stop, color_length, {skui::css::colors::green, skui::css::length{.3f, skui::css::unit::in}});

  using skui::css::grammar::angular_color_stop;
  check_rule_success(angular_color_stop, color, {skui::css::colors::red, {}});
  check_rule_success(angular_color_stop, color_angle, {skui::css::colors::yellow, 180});

  return skui::test::exit_code;
}


text:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.bindstone.graphbank.repository.TransactionMapper">

   <resultMap type="com.bindstone.graphbank.domain.Transaction" id="TransactionMap">
      <result column="TRANSACTION_COUNTER" property="transactionNumber" jdbcType="NUMERIC"/>
      <result column="TRANSACTION_EXCHANGE" property="exchange" jdbcType="NUMERIC"/>
      <result column="TRANSACTION_VALUE" property="value" jdbcType="NUMERIC"/>
      <association property="from" javaType="com.bindstone.graphbank.domain.Account">
         <result column="A1_ACCOUNT_UUID" property="id" jdbcType="VARCHAR"/>
         <result column="A1_ACCOUNT_IBAN" property="iban" jdbcType="VARCHAR"/>
         <result column="A1_ACCOUNT_TRANSACTION_COUNTER" property="transactionCounter" jdbcType="NUMERIC"/>
         <result column="A1_ACCOUNT_VALUE" property="value" jdbcType="NUMERIC"/>
         <result column="A1_ACCOUNT_CREATED" property="created" javaType="java.time.LocalDateTime" jdbcType="NUMERIC"
                 typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         <result column="A1_ACCOUNT_MODIFIED" property="modified" javaType="java.time.LocalDateTime" jdbcType="NUMERIC"
                 typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         <association property="currency" javaType="com.bindstone.graphbank.domain.Currency">
            <id column="ID" property="nodeId"/>
            <result column="A1_CURRENCY_UUID" property="id" jdbcType="VARCHAR"/>
            <result column="A1_CURRENCY_NAME" property="name" jdbcType="VARCHAR"/>
            <result column="A1_CURRENCY_ISO" property="iso" jdbcType="VARCHAR"/>
            <result column="A1_CURRENCY_CODE" property="code" jdbcType="VARCHAR"/>
            <result column="A1_CURRENCY_CREATED" property="created" javaType="java.time.LocalDateTime"
                    jdbcType="NUMERIC"
                    typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
            <result column="A1_CURRENCY_MODIFIED" property="modified" javaType="java.time.LocalDateTime"
                    jdbcType="NUMERIC"
                    typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         </association>
      </association>
      <association property="to" javaType="com.bindstone.graphbank.domain.Account">
         <result column="A2_ACCOUNT_UUID" property="id" jdbcType="VARCHAR"/>
         <result column="A2_ACCOUNT_IBAN" property="iban" jdbcType="VARCHAR"/>
         <result column="A2_ACCOUNT_TRANSACTION_COUNTER" property="transactionCounter" jdbcType="NUMERIC"/>
         <result column="A2_ACCOUNT_VALUE" property="value" jdbcType="NUMERIC"/>
         <result column="A2_ACCOUNT_CREATED" property="created" javaType="java.time.LocalDateTime" jdbcType="NUMERIC"
                 typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         <result column="A2_ACCOUNT_MODIFIED" property="modified" javaType="java.time.LocalDateTime" jdbcType="NUMERIC"
                 typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         <association property="currency" javaType="com.bindstone.graphbank.domain.Currency">
            <id column="ID" property="nodeId"/>
            <result column="A2_CURRENCY_UUID" property="id" jdbcType="VARCHAR"/>
            <result column="A2_CURRENCY_NAME" property="name" jdbcType="VARCHAR"/>
            <result column="A2_CURRENCY_ISO" property="iso" jdbcType="VARCHAR"/>
            <result column="A2_CURRENCY_CODE" property="code" jdbcType="VARCHAR"/>
            <result column="A2_CURRENCY_CREATED" property="created" javaType="java.time.LocalDateTime"
                    jdbcType="NUMERIC"
                    typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
            <result column="A2_CURRENCY_MODIFIED" property="modified" javaType="java.time.LocalDateTime"
                    jdbcType="NUMERIC"
                    typeHandler="com.bindstone.graphbank.utils.typehandler.LocalDateTimeTypeHandler"/>
         </association>
      </association>
   </resultMap>

   <select id="findByAccount" parameterType='com.bindstone.graphbank.domain.Account' resultMap="TransactionMap">
      MATCH ((account1:Account{id: #{from.id}}) -[:HAS]-> (currency1:Currency))
      MATCH ((account1)-[trans:TRANSFER]->(account2:Account)-[:HAS]-> (currency2:Currency))
      RETURN
      <!--ACCOUNT 1-->
      account1.id AS A1_ACCOUNT_UUID,
      account1.iban AS A1_ACCOUNT_IBAN,
      account1.transaction_counter AS A1_ACCOUNT_TRANSACTION_COUNTER,
      account1.value as A1_ACCOUNT_VALUE,
      account1.created AS A1_ACCOUNT_CREATED,
      account1.modified AS A1_ACCOUNT_MODIFIED,
      currency1.id AS A1_CURRENCY_UUID,
      currency1.name AS A1_CURRENCY_NAME,
      currency1.iso AS A1_CURRENCY_ISO,
      currency1.code AS A1_CURRENCY_CODE,
      currency1.created AS A1_CURRENCY_CREATED,
      currency1.modified AS A1_CURRENCY_MODIFIED,
      <!--ACCOUNT 2-->
      account2.id AS A2_ACCOUNT_UUID,
      account2.iban AS A2_ACCOUNT_IBAN,
      account2.transaction_counter AS A2_ACCOUNT_TRANSACTION_COUNTER,
      account2.value as A2_ACCOUNT_VALUE,
      account2.created AS A2_ACCOUNT_CREATED,
      account2.modified AS A2_ACCOUNT_MODIFIED,
      currency2.id AS A2_CURRENCY_UUID,
      currency2.name AS A2_CURRENCY_NAME,
      currency2.iso AS A2_CURRENCY_ISO,
      currency2.code AS A2_CURRENCY_CODE,
      currency2.created AS A2_CURRENCY_CREATED,
      currency2.modified AS A2_CURRENCY_MODIFIED,
      <!--TRANSACTION-->
      trans.transaction_counter AS TRANSACTION_COUNTER,
      trans.exchange AS TRANSACTION_EXCHANGE,
      trans.transaction_value AS TRANSACTION_VALUE
   </select>

   <update id="transfer">
      MATCH (fromAccount:Account {id: #{from.id}}),(toAccount:Account {id: #{to.id}})
      MERGE (fromAccount)-
        [:TRANSFER {
          master: #{master},
          transaction_counter: #{transactionNumber},
          transaction_value: #{value},
          exchange: #{exchange}
        }]->(toAccount)
   </update>

</mapper>


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

<title>Uses of Class org.apache.poi.poifs.crypt.ChainingMode (POI API Documentation)</title>
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

Uses of Class
org.apache.poi.poifs.crypt.ChainingMode

Packages that use ChainingMode

Package
Description

org.apache.poi.poifs.crypt

Implementation of the ECMA-376 Document Encryption

org.apache.poi.poifs.crypt.agile

org.apache.poi.poifs.crypt.standard

Uses of ChainingMode in org.apache.poi.poifs.crypt

Methods in org.apache.poi.poifs.crypt that return ChainingMode

Modifier and Type
Method and Description

ChainingMode
EncryptionHeader.getChainingMode()

ChainingMode
EncryptionVerifier.getChainingMode()

static ChainingMode
ChainingMode.valueOf(java.lang.String name)

Returns the enum constant of this type with the specified name.

static ChainingMode[]
ChainingMode.values()

Returns an array containing the constants of this enum type, in
the order they are declared.

Methods in org.apache.poi.poifs.crypt with parameters of type ChainingMode

Modifier and Type
Method and Description

static javax.crypto.Cipher
CryptoFunctions.getCipher(java.security.Key key,
         CipherAlgorithm cipherAlgorithm,
         ChainingMode chain,
         byte[] vec,
         int cipherMode,
         java.lang.String padding)

Initialize a new cipher object with the given cipher properties
 If the given algorithm is not implemented in the JCE, it will try to load it from the bouncy castle
 provider.

static javax.crypto.Cipher
CryptoFunctions.getCipher(javax.crypto.SecretKey key,
         CipherAlgorithm cipherAlgorithm,
         ChainingMode chain,
         byte[] vec,
         int cipherMode)

void
EncryptionInfoBuilder.initialize(EncryptionInfo ei,
          CipherAlgorithm cipherAlgorithm,
          HashAlgorithm hashAlgorithm,
          int keyBits,
          int blockSize,
          ChainingMode chainingMode)

protected void
EncryptionHeader.setChainingMode(ChainingMode chainingMode)

protected void
EncryptionVerifier.setChainingMode(ChainingMode chainingMode)

Constructors in org.apache.poi.poifs.crypt with parameters of type ChainingMode

Constructor and Description

EncryptionInfo(DirectoryNode dir,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

EncryptionInfo(NPOIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

EncryptionInfo(POIFSFileSystem fs,
              EncryptionMode encryptionMode,
              CipherAlgorithm cipherAlgorithm,
              HashAlgorithm hashAlgorithm,
              int keyBits,
              int blockSize,
              ChainingMode chainingMode)

Uses of ChainingMode in org.apache.poi.poifs.crypt.agile

Methods in org.apache.poi.poifs.crypt.agile with parameters of type ChainingMode

Modifier and Type
Method and Description

void
AgileEncryptionInfoBuilder.initialize(EncryptionInfo info,
          CipherAlgorithm cipherAlgorithm,
          HashAlgorithm hashAlgorithm,
          int keyBits,
          int blockSize,
          ChainingMode chainingMode)

Constructors in org.apache.poi.poifs.crypt.agile with parameters of type ChainingMode

Constructor and Description

AgileEncryptionHeader(CipherAlgorithm algorithm,
                     HashAlgorithm hashAlgorithm,
                     int keyBits,
                     int blockSize,
                     ChainingMode chainingMode)

AgileEncryptionVerifier(CipherAlgorithm cipherAlgorithm,
                       HashAlgorithm hashAlgorithm,
                       int keyBits,
                       int blockSize,
                       ChainingMode chainingMode)

Uses of ChainingMode in org.apache.poi.poifs.crypt.standard

Methods in org.apache.poi.poifs.crypt.standard with parameters of type ChainingMode

Modifier and Type
Method and Description

void
StandardEncryptionInfoBuilder.initialize(EncryptionInfo info,
          CipherAlgorithm cipherAlgorithm,
          HashAlgorithm hashAlgorithm,
          int keyBits,
          int blockSize,
          ChainingMode chainingMode)

Constructors in org.apache.poi.poifs.crypt.standard with parameters of type ChainingMode

Constructor and Description

StandardEncryptionHeader(CipherAlgorithm cipherAlgorithm,
                        HashAlgorithm hashAlgorithm,
                        int keyBits,
                        int blockSize,
                        ChainingMode chainingMode)

StandardEncryptionVerifier(CipherAlgorithm cipherAlgorithm,
                          HashAlgorithm hashAlgorithm,
                          int keyBits,
                          int blockSize,
                          ChainingMode chainingMode)

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

PREV

NEXT

FRAMES

NO FRAMES

All Classes

                Copyright 2014 The Apache Software Foundation or
        its licensors, as applicable.


text:
"""Set ``conn_type`` as non-nullable

Revision ID: 8f966b9c467a
Revises: 3c20cacc0044
Create Date: 2020-06-08 22:36:34.534121

"""

import sqlalchemy as sa
from alembic import op
from sqlalchemy.ext.declarative import declarative_base

# revision identifiers, used by Alembic.
revision = "8f966b9c467a"
down_revision = "3c20cacc0044"
branch_labels = None
depends_on = None
airflow_version = '2.0.0'

def upgrade():
    """Apply Set ``conn_type`` as non-nullable"""
    Base = declarative_base()

    class Connection(Base):
        __tablename__ = "connection"

        id = sa.Column(sa.Integer(), primary_key=True)
        conn_id = sa.Column(sa.String(250))
        conn_type = sa.Column(sa.String(500))

    # Generate run type for existing records
    connection = op.get_bind()
    sessionmaker = sa.orm.sessionmaker()
    session = sessionmaker(bind=connection)

    # imap_default was missing it's type, let's fix that up
    session.query(Connection).filter_by(conn_id="imap_default", conn_type=None).update(
        {Connection.conn_type: "imap"}, synchronize_session=False
    )
    session.commit()

    with op.batch_alter_table("connection", schema=None) as batch_op:
        batch_op.alter_column("conn_type", existing_type=sa.VARCHAR(length=500), nullable=False)

def downgrade():
    """Unapply Set ``conn_type`` as non-nullable"""
    with op.batch_alter_table("connection", schema=None) as batch_op:
        batch_op.alter_column("conn_type", existing_type=sa.VARCHAR(length=500), nullable=True)


text:
import { Component } from 'substance'

/**
  ModalDialog component

  @class
  @component

  @prop {String} width 'small', 'medium', 'large' and 'full'

  @example

  ```js
  var form = $$(ModalDialog, {
    width: 'medium',
    textAlign: 'center'
  });
  ```
*/
export default class ModalDialog extends Component {
  getActionHandlers () {
    return {
      'close': this.close
    }
  }

  render ($$) {
    let width = this.props.width || 'large'
    let el = $$('div').addClass(this._getClassName())
    if (this.props.width) {
      el.addClass('sm-width-' + width)
    }
    if (this.props.transparent) {
      el.addClass('sm-transparent-bg')
    }
    el.on('keydown', this._onKeydown)

    let verticalContainer = $$('div').addClass('se-vertical-container')
    let horizontalContainer = $$('div').addClass('se-horizontal-container')
    horizontalContainer.append(
      $$('div').addClass('se-horizontal-spacer'),
      this._renderModalBody($$),
      $$('div').addClass('se-horizontal-spacer')
    )
    verticalContainer.append(
      $$('div').addClass('se-vertical-spacer'),
      horizontalContainer,
      $$('div').addClass('se-vertical-spacer')
    )
    el.append(verticalContainer)

    return el
  }

  _getClassName () {
    return 'sc-modal-dialog'
  }

  _renderModalBody ($$) {
    const Button = this.getComponent('button')
    const closeButton = $$(Button, {
      icon: 'close'
    }).addClass('se-close-button')
      .on('click', this._onCloseButtonClick)
    let modalBody = $$('div').addClass('se-body').ref('body')
    // ATTENTION: it is not possible to set a ref on a component passed in as prop (different owner)
    modalBody.append(
      this.props.content.addClass('se-content')
    )
    modalBody.append(closeButton)
    return modalBody
  }

  _onKeydown (e) {
    e.stopPropagation()
  }

  _onCloseButtonClick (e) {
    e.preventDefault()
    e.stopPropagation()
    this.close()
  }

  close () {
    // let the content handl
    let content = this._getContent()
    if (content.beforeClose) {
      let result = content.beforeClose()
      if (result === false) {
        return
      }
    }
    this.send('closeModal')
  }

  _getContent () {
    // Unfortunately we can not have a ref on the content,
    // because it is passed as property.
    // ATM, Substance allows only the owner to set a ref.
    // Thus, we have to find the component manually.
    return this.refs.body.getChildren().find(c => c.el.hasClass('se-content'))
  }
}


text:
#ifndef USBPHY_H
#define USBPHY_H

#include "USBPhyTypes.h"
#include "USBPhyEvents.h"

/** Abstract interface to physical USB hardware
 *
 * # Defined behavior
 * * You can use any endpoint configurations that fit in the parameters
 *      of the table returned by USBPhy::endpoint_table.
 * * You can use all endpoints in any valid endpoint configuration concurrently.
 * * The device supports use of at least one control, bulk, interrupt and
 *      isochronous in each direction at the same time - at least 8 endpoints.
 * * USBPhy supports all standard endpoint sizes (wMaxPacketSize).
 * * USBPhy can handle an interrupt latency of at least 100ms if the host PC
 *      is not performing a reset or setting the device's address.
 * * USBPhy only sends USBPhyEvents when it is in the initialized state.
 * * When unpowered, USBPhy only sends the USBPhyEvents::power event.
 * * On USB reset, all endpoints are removed except for endpoint 0.
 * * A call to USBPhy::ep0_write results in the call of USBPhyEvents::in when
 *      the PC reads the data unless a power loss, reset, or a call to
 *      USBPhy::disconnect occurs first.
 * * A call to USBPhy::endpoint_write results in the call of USBPhyEvents::in
 *      when the pc reads the data unless a power loss, reset, or a call to
 *      USBPhy::endpoint_abort occurs first.
 * * A call to USBPhy::endpoint_read results in the call of USBPhyEvents::out
 *      when the pc sends data unless a power loss, reset, or a call to
 *      USBPhy::endpoint_abort occurs first.
 * * Endpoint 0 naks all transactions aside from setup packets until
 *      higher-level code calls one of USBPhy::ep0_read, USBPhy::ep0_write or
 *      USBPhy::ep0_stall.
 * * Endpoint 0 stall automatically clears on reception of a setup packet.
 *
 * # Undefined behavior
 * * Calling USBPhy::endpoint_add or USBPhy::endpoint_remove outside of the
 *      control requests SetInterface or SetConfiguration.
 * * Calling USBPhy::endpoint_remove on an endpoint that has an ongoing read
 *      or write operation. To avoid undefined behavior, you must abort ongoing
 *      operations with USBPhy::endpoint_abort.
 * * Devices behavior is undefined if latency is greater than 2ms when address
 *      is being set - see USB spec 9.2.6.3.
 * * Devices behavior is undefined if latency is greater than 10ms when a
 *      reset occurs - see USB spec 7.1.7.5.
 * * Calling any of the USBPhy::endpoint_* functions on endpoint 0.
 *
 * # Notes
 * * Make sure USBPhy sends USBPhyEvents in the correct order when multiple
 *      packets are present. USBPhy must send IN endpoint events before OUT
 *      endpoint events if both are pending.
 * * A host PC may resend setup packets to a USB device if there is noise on
 *      the USB line. The USBPhy should be able to handle this scenario and
 *      respond to the setup packet with an ACK.
 * * Bidirectional protocols making use of alternating IN and OUT phases
 *      should not rely on the last ACK an IN transfer to indicate that the
 *      OUT phase should start. Instead, the OUT phase should be started at
 *      the same time the last IN transfer is started. This is because the ACK
 *      to the last in transfer may be dropped if there is noise on the USB
 *      line. If dropped, it will only be resent on the next IN phase. You can
 *      find more information on this in section 8.5.3.3 of the USB
 *      specification.
 *
 * @ingroup usb_device_core
 */
class USBPhy {
public:
    USBPhy() {};
    virtual ~USBPhy() {};

    /**
     * Initialize this USBPhy instance
     *
     * This function must be called before calling
     * any other functions of this class, unless specifically
     * noted.
     *
     * @param events Callback class to handle USB events
     */
    virtual void init(USBPhyEvents *events) = 0;

    /**
     * Power down this USBPhy instance
     *
     * Disable interrupts and stop sending events.
     */
    virtual void deinit() = 0;

    /**
     * Check if USB power is present
     *
     * Devices which don't support checking the USB power state
     * must always return true.
     *
     * @return true if USB power is present, false otherwise
     */
    virtual bool powered() = 0;

    /**
     * Make the USB phy visible to the USB host
     *
     * Enable either the D+ or D-  pullup so the host can detect
     * the presence of this device.
     */
    virtual void connect() = 0;

    /**
     * Detach the USB phy
     *
     * Disable the D+ and D- pullup and stop responding to
     * USB traffic.
     */
    virtual void disconnect() = 0;

    /**
     * Set this device to the configured state
     *
     * Enable added endpoints if they are not enabled
     * already.
     */
    virtual void configure() = 0;

    /**
     * Leave the configured state
     *
     * This is a notification to the USBPhy indicating that the device
     * is leaving the configured state. The USBPhy can disable all
     * endpoints other than endpoint 0.
     *
     */
    virtual void unconfigure() = 0;

    /**
     * Enable the start of frame interrupt
     *
     * Call USBPhyEvents::sof on every frame.
     */
    virtual void sof_enable() = 0;

    /**
     * Disable the start of frame interrupt
     *
     * Stop calling USBPhyEvents::sof.
     */
    virtual void sof_disable() = 0;

    /**
     * Set the USBPhy's address
     *
     * @param address This device's USB address
     */
    virtual void set_address(uint8_t address) = 0;

    /**
     * Wake upstream devices
     */
    virtual void remote_wakeup() = 0;

    /**
     * Get the endpoint table
     *
     * This function returns a table which describes the endpoints
     * can be used, the functionality of those endpoints and the
     * resource cost.
     */
    virtual const usb_ep_table_t *endpoint_table() = 0;

    /**
     * Set wMaxPacketSize of endpoint 0
     *
     * @param max_packet The wMaxPacketSize value for endpoint 0
     * @return The actual size of endpoint 0
     */
    virtual uint32_t ep0_set_max_packet(uint32_t max_packet) = 0;

    /**
     * Read the contents of the SETUP packet
     *
     * @param buffer Buffer to fill with data
     * @param size Size of buffer passed in
     */
    virtual void ep0_setup_read_result(uint8_t *buffer, uint32_t size) = 0;

    /**
     * Start receiving a packet of up to wMaxPacketSize on endpoint 0
     *
     * @param data Buffer to fill with the data read
     * @param size Size of buffer
     */
    virtual void ep0_read(uint8_t *data, uint32_t size) = 0;

    /**
     * Read the contents of a received packet
     *
     * @return Size of data read
     */
    virtual uint32_t ep0_read_result() = 0;

    /**
     * Write a packet on endpoint 0
     *
     * @param buffer Buffer fill with data to send
     * @param size Size of data to send
     */
    virtual void ep0_write(uint8_t *buffer, uint32_t size) = 0;

    /**
     * Protocol stall on endpoint 0
     *
     * Stall all IN and OUT packets on endpoint 0 until a setup packet
     * is received.
     * @note The stall is cleared automatically when a setup packet is received
     */
    virtual void ep0_stall() = 0;

    /**
     * Configure and enable an endpoint
     *
     * @param endpoint Endpoint to configure and enable
     * @param max_packet The maximum packet size that can be sent or received
     * @param type The type of endpoint this should be configured as -
     *  USB_EP_TYPE_BULK, USB_EP_TYPE_INT or USB_EP_TYPE_ISO
     * @note This function cannot be used to configure endpoint 0. That must be done
     * with ep0_set_max_packet
     */
    virtual bool endpoint_add(usb_ep_t endpoint, uint32_t max_packet, usb_ep_type_t type) = 0;

    /**
     * Disable an endpoint
     *
     * @param endpoint Endpoint to disable
     */
    virtual void endpoint_remove(usb_ep_t endpoint) = 0;

    /**
     * Perform a functional stall on the given endpoint
     *
     * Set the HALT feature for this endpoint so that all further
     * communication is aborted.
     *
     * @param endpoint Endpoint to stall
     */
    virtual void endpoint_stall(usb_ep_t endpoint) = 0;

    /**
     * Un-stall the endpoint
     *
     * Clear the HALT feature on this endpoint so communication can
     * resume.
     *
     * @param endpoint Endpoint to stall
     */
    virtual void endpoint_unstall(usb_ep_t endpoint) = 0;

    /**
     * Start a read on the given endpoint
     *
     * @param endpoint Endpoint to start the read on
     * @param data Buffer to fill with data
     * @param size Size of the read buffer. This must be at least
     *     the max packet size for this endpoint.
     * @return true if the read was successfully started, false otherwise
     */
    virtual bool endpoint_read(usb_ep_t endpoint, uint8_t *data, uint32_t size) = 0;

    /**
     * Finish a read on the given endpoint
     *
     * @param endpoint Endpoint to check
     * @return The number of bytes received
     */
    virtual uint32_t endpoint_read_result(usb_ep_t endpoint) = 0;

    /**
     * Start a write on the given endpoint
     *
     * @param endpoint Endpoint to write to
     * @param data Buffer to write
     * @param size Size of data to write
     * @return true if the data was prepared for transmit, false otherwise
     */
    virtual bool endpoint_write(usb_ep_t endpoint, uint8_t *data, uint32_t size) = 0;

    /**
     * Abort the current transfer if it has not yet been sent
     *
     * @param endpoint Endpoint to abort the transfer on. It is implementation defined
     * if this function has an effect on receive endpoints.
     */
    virtual void endpoint_abort(usb_ep_t endpoint) = 0;

    /**
     * Callback used for performing USB processing
     *
     * USBPhy processing should be triggered by calling USBPhyEvents::start_process
     * and done inside process. All USBPhyEvents callbacks aside from
     * USBPhyEvents::start_process must be called in the context of process
     */
    virtual void process() = 0;
};

#endif


text:
'use strict';

var _ = require('mano').i18n;

exports._parent = require('./user-base');

exports['sub-main'] = {
	class: { content: true },
	content: function () {
		ul({ id: 'statistics-sub-menu', class: 'pills-nav' }, [
			li({ id: 'completed-files-nav' },
				a({ href: '/files/', class: 'pills-nav-pill' }, _("Completed files"))),
			li({ id: 'pending-files-nav' },
				a({ href: '/files/pending/', class: 'pills-nav-pill' }, _("Pending files"))),
			li({ id: 'accounts-nav' },
				a({ href: '/files/accounts/', class: 'pills-nav-pill' }, _("Accounts")))
		]);
		div({ class: 'statistics-main blocks-container', id: 'statistics-main' });
	}
};


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <title>James' EDA Blog</title>
  <meta name="description" content="">
  <meta name="author" content="">

  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link href="//fonts.googleapis.com/css?family=Raleway:400,300,600" rel="stylesheet" type="text/css">

  <link rel="stylesheet" href="https://james-inglis-01.github.io/css/normalize.css">
  <link rel="stylesheet" href="https://james-inglis-01.github.io/css/skeleton.css">
  <link rel="stylesheet" href="https://james-inglis-01.github.io/css/custom.css">

  <link rel="icon" type="image/png" href="https://james-inglis-01.github.io/images/favicon-eda-blog.png">

        Home
        Blog
        About

Scope

              What is 'scope', and how does it work in JavaScript?

              Scope is a way of assigning variables to the entirety of your JavaScript file (global scope) or to a specific function (local   scope). Scope defines the part of the program where a particular variable is accessible.
              Imagine that our JavaScript file is the planet Earth. Cities, countries and even continents are like JavaScript functions   with local variables, even with the continent sized functions. However these are all surrounded by the oceans which can't be  described as local because they wrap around everything else, therefore it's called a global variable.

Here's an example of a global & local variable (test):

                var test = "I'm global";

                function testScope() {
                  var test = "I'm local";

                  console.log (test);
                }

                testScope();           // output: I'm local

                console.log(test);     // output: I'm global


text:
"use strict";

class ProjectUtils {

    /**
     * @constructor
     *
     * @param {Object} request - expressjs request
     */
    constructor(request) {
        this.request = request;
    };

    /**
     * Validate request for create new project or update existing (without certs)
     *
     * @param {boolean} isUpdate - is it update operation or create new
     * @param {DatabaseOperationCallback} callback - database operation callback
     */
    validateProjectActionCreateNewOrUpdateProject(isUpdate, callback) {
        var name = this.request.body.name;

        this.request.project.setName(name);

        if (typeof name === 'undefined') {
            return callback('Not enough data in the request.');
        }

        name = name.trim();

        if (name.length < this.request.projectManager.MIN_TEXT_FIELD_LENGTH) {
            return callback(
                'Name should be at least ' + this.request.projectManager.MIN_TEXT_FIELD_LENGTH + ' characters.'
            );
        }

        var projectId = (isUpdate === true) ? this.request.project.getId() : -1;

        this.request.projectManager.doesExistWithSameName(name, projectId, (error, check) => {
            if (check) {
                return callback('Project with name [' + name + '] already exists.');
            }

            this.request.project.setName(name);

            if (!isUpdate) {
                return this.validateProjectActionUpdateCerts(callback);
            } else {
                return callback(null);
            }
        });
    };

    /**
     * Validate request for create new project or update existing (without certs)
     *
     * @param {DatabaseOperationCallback} callback - database operation callback
     */
    validateProjectActionUpdateCerts(callback) {
        var
            fs = require('fs'),
            fileCA = '',
            fileCERT = '',
            fileKEY = '',
            error = null;

        for (var i in this.request.files) {
            var content = fs.readFileSync(this.request.files[i].path);
            fs.unlinkSync(this.request.files[i].path);

            switch (this.request.files[i].fieldname) {
                case 'file_key':
                    fileKEY = content;
                    break;

                case 'file_ca':
                    fileCA = content;
                    break;

                case 'file_cert':
                    fileCERT = content;
                    break;

                default:
                    error = 'Wrong filename in the request [' + this.request.files[i].fieldname + ']';
            }
        }

        if (error !== null) {
            callback(error);
        }

        if ((fileCA === '') || (fileCERT === '') || (fileKEY === '')) {
            return callback('There are not all files in the request');
        }

        this.request.project
            .setCA(fileCA)
            .setCERT(fileCERT)
            .setKEY(fileKEY);

        return callback(null);
    };

}

module.exports = ProjectUtils;


text:
<?php

namespace Hackspace\Bundle\CalciferBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\PersistentCollection;
use enko\RelativeDateParser\RelativeDateParser;

/**
 * RepeatEvent
 *
 * @property \DateTime $nextdate
 * @property integer $duration
 * @property string $repeating_pattern
 * @property string $summary
 * @property string $description
 * @property Location $location
 * @property string $url
 * @property array $tags
 *
 * @ORM\Table(name="repeating_events")
 * @ORM\Entity
 */
class RepeatingEvent extends BaseEntity
{
    use TagTrait;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="nextdate", type="datetimetz")
     */
    protected $nextdate;

    /**
     * @var integer
     *
     * @ORM\Column(name="duration", type="integer", nullable=true)
     */
    protected $duration;

    /**
     * @var string
     *
     * @ORM\Column(name="repeating_pattern", type="string", length=255)
     */
    protected $repeating_pattern = '';

    /**
     * @var string
     *
     * @ORM\Column(name="summary", type="string", length=255)
     */
    protected $summary;

    /**
     * @var string
     *
     * @ORM\Column(name="description", type="text", nullable=true)
     */
    protected $description;

    /**
     * @var Location
     *
     * @ORM\ManyToOne(targetEntity="Location")
     * @ORM\JoinColumn(name="locations_id", referencedColumnName="id")
     */
    protected $location;

    /**
     * @var string
     *
     * @ORM\Column(name="url", type="string", length=255, nullable=true)
     */
    protected $url;

    /**
     * @var array
     *
     * @ORM\ManyToMany(targetEntity="Tag")
     * @ORM\JoinTable(name="repeating_events2tags",
     *      joinColumns={@ORM\JoinColumn(name="repeating_events_id", referencedColumnName="id")},
     *      inverseJoinColumns={@ORM\JoinColumn(name="tags_id", referencedColumnName="id")}
     *      )
     */
    protected $tags = [];

    public function isValid() {
        $errors = [];
        if ((is_null($this->nextdate)) && (strlen($this->nextdate) > 0)) {
            $errors['nextdate'] = "Bitte gebe einen nächsten Termin an.";
        }
        if ((is_null($this->repeating_pattern)) && (strlen($this->repeating_pattern) > 0)) {
            $errors['repeating_pattern'] = "Bitte gebe ein gültiges Wiederholungsmuster an.";
        } else {
            $this->nextdate->setTimezone(new \DateTimeZone('Europe/Berlin'));
            try {
                $parser = new RelativeDateParser($this->repeating_pattern,$this->nextdate,'de');
            } catch (\Exception $e) {
                $errors['repeating_pattern'] = "Bitte gebe ein gültiges Wiederholungsmuster an.";
            }
        }
        if ((is_null($this->summary)) && (strlen($this->summary) > 0)) {
            $errors['summary'] = "Bitte gebe eine Zusammenfassung an.";
        }
        return $errors;
    }
}


text:
import {IForm, IFormNavigation} from "../forms/Interfaces";
import * as Mof from "Mof";
import { IFormConfiguration } from "../forms/IFormConfiguration";

export interface IFormField
{
    configuration: IFormConfiguration;

    // Defines the field to be used to create the dom for the field
    field: Mof.DmObject;

    isReadOnly: boolean;

    // Is connected to the item url of the element being connected to that element
    itemUrl: string;

    form: IFormNavigation;

    // Creates the dom depending on the given field and the internal object
    createDom(dmElement: Mof.DmObject) : Promise<JQuery<HTMLElement>>;

    // Evaluates the result of the user and injects it into the given element
    evaluateDom(dmElement: Mof.DmObject);

    /**
     * Gets a value whether the name of the corresponding field shall be shown.
     * This can be used for RowForms when we need a content cell which covers
     * the name column, but also the value column.
     */
    showNameField?(): boolean;
}

export class BaseField
{
    configuration: IFormConfiguration;
    field: Mof.DmObject;
    isReadOnly: boolean;
    form: IFormNavigation;
    itemUrl: string;
}


text:
from oslo_versionedobjects import fields

from cinder import objects
from cinder.tests.unit import fake_constants as fake

def fake_db_group(**updates):
    db_group = {
        'id': fake.GROUP_ID,
        'name': 'group-1',
        'status': 'available',
        'user_id': fake.USER_ID,
        'project_id': fake.PROJECT_ID,
        'group_type_id': fake.GROUP_TYPE_ID,
    }

    for name, field in objects.Group.fields.items():
        if name in db_group:
            continue
        if field.nullable:
            db_group[name] = None
        elif field.default != fields.UnspecifiedDefault:
            db_group[name] = field.default
        else:
            raise Exception('fake_db_group needs help with %s.' % name)

    if updates:
        db_group.update(updates)

    return db_group

def fake_db_group_type(**updates):
    db_group_type = {
        'id': fake.GROUP_TYPE_ID,
        'name': 'type-1',
        'description': 'A fake group type',
        'is_public': True,
        'projects': [],
        'group_specs': {},
    }

    for name, field in objects.GroupType.fields.items():
        if name in db_group_type:
            continue
        if field.nullable:
            db_group_type[name] = None
        elif field.default != fields.UnspecifiedDefault:
            db_group_type[name] = field.default
        else:
            raise Exception('fake_db_group_type needs help with %s.' % name)

    if updates:
        db_group_type.update(updates)

    return db_group_type

def fake_group_obj(context, **updates):
    return objects.Group._from_db_object(
        context, objects.Group(), fake_db_group(**updates))

def fake_group_type_obj(context, **updates):
    return objects.GroupType._from_db_object(
        context, objects.GroupType(), fake_db_group_type(**updates))


text:
namespace Moya.Utility
{
    using System;
    using System.Reflection;
    using Attributes;

    /// <summary>
    /// Utility class which provides reflection support.
    /// </summary>
    internal class Reflection
    {
        /// <summary>
        /// Checks if a <see cref="MethodInfo"/> is attributed with a <see cref="MoyaAttribute"/>.
        /// </summary>
        /// <param name="methodInfo">The <see cref="MethodInfo"/> we want to check.</param>
        /// <returns><see cref="c:true"/> if the <see cref="MethodInfo"/> is attributed with a
        /// <see cref="MoyaAttribute"/>, <see cref="c:false"/> otherwise.</returns>
        public static bool MethodInfoHasMoyaAttribute(MethodInfo methodInfo)
        {
            return methodInfo.GetCustomAttributes(typeof(MoyaAttribute), false).Length > 0;
        }

        /// <summary>
        /// Checks if a <see cref="Type"/> is a <see cref="MoyaAttribute"/>.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> we want to check.</param>
        /// <returns><see cref="c:true"/> if the <see cref="Type"/> is a
        /// <see cref="MoyaAttribute"/>, <see cref="c:false"/> otherwise.</returns>
        public static bool TypeIsMoyaAttribute(Type type)
        {
            return type.IsSubclassOf(typeof(MoyaAttribute));
        }
    }
}


text:
package controllers;

import com.google.gson.JsonSerializer;

import play.mvc.Controller;
import results.RenderCustomJson;

/**
 * This class overrides the renderJSON methods found in play.mvc.Controller
 * substituting their call to play.mvc.results.RenderJson with RenderCustomJson.
 *
 * This allows the Gson object to be configured before use.
 *
 * This class is intended to be extended for all Play controllers that require the
 * use of the RenderCustomJson class.
 *
 * @see Controller
 * @author Alex Jarvis axj7@aber.ac.uk
 */
public class RenderJSONEnhancer extends Controller {

	/**
     * Render a 200 OK application/json response
     * @param jsonString The JSON string
     */
	protected static void renderJSON(String jsonString) {
		throw new RenderCustomJson(jsonString);
	}

	/**
     * Render a 200 OK application/json response
     * @param o The Java object to serialize
     */
	protected static void renderJSON(Object o) {
		throw new RenderCustomJson(o);
	}

	/**
     * Render a 200 OK application/json response.
     * @param o The Java object to serialize
     * @param adapters A set of GSON serializers/deserializers/instance creator to use
     */
	protected static void renderJSON(Object o, JsonSerializer<?>... adapters) {
		throw new RenderCustomJson(o, adapters);
	}

}


text:
using k8s.Models;
using System.Threading;
using System.Threading.Tasks;

namespace k8s.LeaderElection.ResourceLock
{
    public class LeaseLock : MetaObjectLock<V1Lease>
    {
        public LeaseLock(IKubernetes client, string @namespace, string name, string identity)
            : base(client, @namespace, name, identity)
        {
        }

        protected override Task<V1Lease> ReadMetaObjectAsync(IKubernetes client, string name, string namespaceParameter,
            CancellationToken cancellationToken)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return client.CoordinationV1.ReadNamespacedLeaseAsync(name, namespaceParameter, cancellationToken: cancellationToken);
        }

        protected override LeaderElectionRecord GetLeaderElectionRecord(V1Lease obj)
        {
            if (obj == null)
            {
                return null;
            }

            return new LeaderElectionRecord()
            {
                AcquireTime = obj.Spec.AcquireTime,
                HolderIdentity = obj.Spec.HolderIdentity,
                LeaderTransitions = obj.Spec.LeaseTransitions ?? 0,
                LeaseDurationSeconds = obj.Spec.LeaseDurationSeconds ?? 15, // 15 = default value
                RenewTime = obj.Spec.RenewTime,
            };
        }

        protected override V1Lease SetLeaderElectionRecord(LeaderElectionRecord record, V1Lease metaObj)
        {
            if (record == null)
            {
                throw new NullReferenceException(nameof(record));
            }

            if (metaObj == null)
            {
                throw new NullReferenceException(nameof(metaObj));
            }

            metaObj.Spec = new V1LeaseSpec()
            {
                AcquireTime = record.AcquireTime,
                HolderIdentity = record.HolderIdentity,
                LeaseTransitions = record.LeaderTransitions,
                LeaseDurationSeconds = record.LeaseDurationSeconds,
                RenewTime = record.RenewTime,
            };

            return metaObj;
        }

        protected override Task<V1Lease> CreateMetaObjectAsync(IKubernetes client, V1Lease obj, string namespaceParameter,
            CancellationToken cancellationToken)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return client.CoordinationV1.CreateNamespacedLeaseAsync(obj, namespaceParameter, cancellationToken: cancellationToken);
        }

        protected override Task<V1Lease> ReplaceMetaObjectAsync(IKubernetes client, V1Lease obj, string name, string namespaceParameter,
            CancellationToken cancellationToken)
        {
            if (client is null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            return client.CoordinationV1.ReplaceNamespacedLeaseAsync(obj, name, namespaceParameter, cancellationToken: cancellationToken);
        }
    }
}


text:
import React, { Component, PropTypes } from 'react';
import SearchResults from './SearchResults';
import styles from './rbox.css';

/**
 * @author sylvenas
 * @doc 左侧搜索结果展示面板
 * @class Rbox
 * @extends {Component}
 */
class Rbox extends Component {
    /**
     * Creates an instance of Rbox.
     *
     * @param {Object} props
     * @state show->控制Rbox是否展示,true展示,false隐藏,默认true
     * @memberOf Rbox
     */
    constructor(props) {
        super(props);
        this.state = {
            show: true,
            data: null
        }
    }
    /**
     * @doc 点击panCtrl反转show,切换Rbox的展示与隐藏
     * @memberOf Rbox
     */
    toggle() {
        this.setState({
            show: !this.state.show
        })
    }
    /**
     * @doc 设置要显示的子组件'
     * @param {Object} nextProps
     * @memberOf Rbox
     */
    componentWillReceiveProps(nextProps) {
        if (nextProps.searchRes == this.props.searchRes && nextProps.queryRes == this.props.queryRes) {

        } else if (nextProps.searchRes != this.props.searchRes && nextProps.queryRes == this.props.queryRes) {
            this.setState({ data: nextProps.searchRes.searchResults });

        } else if (nextProps.searchRes == this.props.searchRes && nextProps.queryRes != this.props.queryRes) {
            this.setState({ data: nextProps.queryRes.queryResults });

        }
    }
    /**
     * @child 异步请求返回的查询结果的数据
     * @returns Rbox组件
     * @memberOf Rbox
     */
    render() {
        return (

                <SearchResults data={this.state.data} />

 this.toggle()}>

        );
    }

}

Rbox.propTypes = {

};

export default Rbox;