jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
      def call(exception, locale, key, options)
        if exception.is_a?(MissingTranslation)
          #
          # TODO: this block is to be replaced by `exception.message` when
          # rescue_format is removed
          if options[:rescue_format] == :html
            if @rescue_format_deprecation
              $stderr.puts "[DEPRECATED] I18n's :recue_format option will be removed from a future release. All exception messages will be plain text. If you need the exception handler to return an html format please set or pass a custom exception handler."
              @rescue_format_deprecation = true
            end
            exception.html_message
          else
            exception.message
          end

        elsif exception.is_a?(Exception)
          raise exception
        else
          throw :exception, exception
        end
      end
//  [ruby]
      def call(exception, locale, key, options)
        if exception.is_a?(MissingTranslation)
          options[:rescue_format] == :html ? exception.html_message : exception.message
        elsif exception.is_a?(Exception)
          raise exception
        else
          throw :exception, exception
        end
      end
//  [ruby]
  def redirect_back_or_default(default, options={})
    back_url = params[:back_url].to_s
    if back_url.present?
      begin
        uri = URI.parse(back_url)
        # do not redirect user to another host or to the login or register page
        if ((uri.relative? && back_url.match(%r{\A/\w})) || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
          redirect_to(back_url)
          return
        end
      rescue URI::InvalidURIError
        logger.warn("Could not redirect to invalid URL #{back_url}")
        # redirect to default
      end
    elsif options[:referer]
      redirect_to_referer_or default
      return
    end
    redirect_to default
    false
  end
//  [ruby]
  def redirect_back_or_default(default, options={})
    back_url = params[:back_url].to_s
    if back_url.present?
      begin
        uri = URI.parse(back_url)
        # do not redirect user to another host or to the login or register page
        if (uri.relative? || (uri.host == request.host)) && !uri.path.match(%r{/(login|account/register)})
          redirect_to(back_url)
          return
        end
      rescue URI::InvalidURIError
        logger.warn("Could not redirect to invalid URL #{back_url}")
        # redirect to default
      end
    elsif options[:referer]
      redirect_to_referer_or default
      return
    end
    redirect_to default
    false
  end
//  [ruby]
    it 'does not include user or group archived messages' do
      UserArchivedMessage.archive!(user.id, group_message)
      UserArchivedMessage.archive!(user.id, private_message)

      topics = TopicQuery.new(nil).list_private_messages_all(user).topics

      expect(topics).to eq([])

      GroupArchivedMessage.archive!(group.id, group_message)

      topics = TopicQuery.new(nil).list_private_messages_all(user_2).topics

      expect(topics).to contain_exactly(private_message)
    end
//  [ruby]
    it 'does not include user or group archived messages' do
      UserArchivedMessage.archive!(user.id, group_message)
      UserArchivedMessage.archive!(user.id, private_message)

      topics = TopicQuery.new(nil).list_private_messages_all(user).topics

      expect(topics).to eq([])

      GroupArchivedMessage.archive!(user_2.id, group_message)

      topics = TopicQuery.new(nil).list_private_messages_all(user_2).topics

      expect(topics).to contain_exactly(private_message)
    end
//  [ruby]
    it 'returns a list of all private messages that has been archived' do
      UserArchivedMessage.archive!(user_2.id, private_message)
      GroupArchivedMessage.archive!(group.id, group_message)

      topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics

      expect(topics).to contain_exactly(private_message, group_message)
    end
//  [ruby]
    it 'returns a list of all private messages that has been archived' do
      UserArchivedMessage.archive!(user_2.id, private_message)
      GroupArchivedMessage.archive!(user_2.id, group_message)

      topics = TopicQuery.new(nil).list_private_messages_all_archive(user_2).topics

      expect(topics).to contain_exactly(private_message, group_message)
    end
//  [ruby]
  def setup
    @store = Redis::Store.new serializer: Marshal
    @rabbit = OpenStruct.new :name => "bunny"
    @white_rabbit = OpenStruct.new :color => "white"
    @store.set "rabbit", @rabbit
    @store.del "rabbit2"
  end
//  [ruby]
  def setup
    @store = Redis::Store.new :marshalling => true
    @rabbit = OpenStruct.new :name => "bunny"
    @white_rabbit = OpenStruct.new :color => "white"
    @store.set "rabbit", @rabbit
    @store.del "rabbit2"
  end
//  [ruby]
  def add_to_group
    Log.add_info(request, params.inspect)

    return unless request.post?

    if params[:thetisBoxSelKeeper].blank?
      render(:partial => 'ajax_groups', :layout => false)
      return
    end

    group_id = params[:thetisBoxSelKeeper].split(':').last
    unless group_id == '0'  # '0' for ROOT
      begin
        group = Group.find(group_id)
      rescue => evar
        Log.add_error(request, evar)
      ensure
        if group.nil?
          render(:partial => 'ajax_groups', :layout => false)
          return
        end
      end
    end

    begin
      @user = User.find(params[:user_id])
    rescue => evar
      Log.add_error(request, evar)
    end

    unless @user.nil?

      is_modified = false

      # Change, not simply Add
      unless params[:current_id].blank?
        if @user.exclude_from(params[:current_id])
          is_modified = true
        end
      end

      is_modified = true if @user.add_to(group_id)

      if is_modified == true
        @user.save!

        if @user.id == @login_user.id
          @login_user = @user
        end
      end
    end

    render(:partial => 'ajax_groups', :layout => false)
  end
//  [ruby]
  def add_to_group
    Log.add_info(request, params.inspect)

    if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      render(:partial => 'ajax_groups', :layout => false)
      return
    end

    group_id = params[:thetisBoxSelKeeper].split(':').last
    unless group_id == '0'  # '0' for ROOT
      begin
        group = Group.find(group_id)
      rescue => evar
        Log.add_error(request, evar)
      ensure
        if group.nil?
          render(:partial => 'ajax_groups', :layout => false)
          return
        end
      end
    end

    begin
      @user = User.find(params[:user_id])
    rescue => evar
      Log.add_error(request, evar)
    end

    unless @user.nil?

      is_modified = false

      # Change, not simply Add
      unless params[:current_id] == nil or params[:current_id].empty?
        if @user.exclude_from(params[:current_id])
          is_modified = true
        end
      end

      is_modified = true if @user.add_to(group_id)

      if is_modified == true
#        @user.update_attribute(:groups, @user.groups)
        @user.save!

        if @user.id == @login_user.id
          @login_user = @user
        end
      end
    end

    render(:partial => 'ajax_groups', :layout => false)
  end
//  [ruby]
  def destroy
    Log.add_info(request, params.inspect)

    return unless request.post?

    if params[:check_user].nil?
      list
      render(:action => 'list')
      return
    end

    count = 0
    params[:check_user].each do |user_id, value|
      if value == '1'
        SqlHelper.validate_token([user_id])
        begin
          User.destroy(user_id)
        rescue => evar
          Log.add_error(request, evar)
        end

        count += 1
      end
    end
    flash[:notice] = count.to_s + t('user.deleted')
    redirect_to(:action => 'list')
  end
//  [ruby]
  def destroy
    Log.add_info(request, params.inspect)

    if params[:check_user].nil?
      list
      render(:action => 'list')
      return
    end

    count = 0
    params[:check_user].each do |user_id, value|
      if value == '1'

        begin
          User.destroy(user_id)
        rescue => evar
          Log.add_error(request, evar)
        end

        count += 1
      end
    end
    flash[:notice] = count.to_s + t('user.deleted')
    redirect_to(:action => 'list')
  end
//  [ruby]
  def create_title

    return unless request.post?

    titles = User.get_config_titles
    titles = [] if titles.nil?
    titles << t('user.new_title')
    User.save_config_titles(titles)

    render(:partial => 'ajax_title', :layout => false)
  end
//  [ruby]
  def create_title

    titles = User.get_config_titles
    titles = [] if titles.nil?
    titles << t('user.new_title')
    User.save_config_titles titles

    render(:partial => 'ajax_title', :layout => false)
  end
//  [ruby]
  def import_csv
    Log.add_info(request, params.inspect)

    return unless request.post?

    file = params[:imp_file]
    mode = params[:mode]
    enc = params[:enc]

    all_users = User.find_all

    user_names = []
#   user_emails = []
    if mode == 'add'
      all_users.each do |user|
        user_names << user.name
#       user_emails << user.email
      end
    end

    @imp_errs = {}
    count = -1  # 0 for Header-line
    users = [] 

    opt = {
      :skip_blanks => true
    }

    csv = file.read
    begin
      csv.encode!(Encoding::UTF_8, enc, {:invalid => :replace, :undef => :replace, :replace => ' '})
    rescue => evar
      Log.add_error(request, evar)
    end

    found_update = false

    CSV.parse(csv, opt) do |row|
      unless row.first.nil?
        next if row.first.lstrip.index('#') == 0
      end
      next if row.compact.empty?

      count += 1
      next if count == 0  # for Header Line

      user = User.parse_csv_row(row)

      check = user.check_import(mode, user_names)  #, user_emails

      @imp_errs[count] = check unless check.empty?

      users << user

      if mode == 'update'
        update_user = all_users.find do |u|
          u.id == user.id
        end
        unless update_user.nil?
          all_users.delete(update_user)
          found_update = true
        end
      end
    end

    if users.empty?
      @imp_errs[0] = [t('user.nothing_to_import')]
    else
      if mode == 'update'
        if found_update
          user_admin = users.find do |user|
            user.admin?(User::AUTH_USER)
          end
          if user_admin.nil?
            @imp_errs[0] = [t('user.no_user_auth_import')]
          end

        else
          @imp_errs[0] = [t('user.nothing_to_update')]
        end
      end
    end

    # Create or Update
    count = 0
    @imp_cnt = 0
    if @imp_errs.empty?
      users.each do |user|
        count += 1
        begin
          user_id = user.id

          user.save!

          if user_id.nil?
            user.setup
          end

          @imp_cnt += 1

        rescue => evar
          @imp_errs[count] = [t('user.failed_to_save') + evar.to_s]
        end
      end
    end

    # Delete
    # Actually, the correct order of the process is Delete -> Create,
    # not to duplicate a User Name.
    #    3: morita   <- Delete
    #     : morita   <- Create
    # But such a case is most likely to be considered as a 
    # user's miss-operation. We can avoid this case with
    # 'opposite' process.
    del_cnt = 0
    if @imp_errs.empty? and mode == 'update'
      all_users.each do |user|
        user.destroy
        del_cnt += 1
      end
    end

    # Set order to display
    User.update_xorder(nil, User::XORDER_MAX)

    titles = User.get_config_titles
    unless titles.nil?
      idx = 0
      titles.each do |title|
        User.update_xorder title, idx
        idx += 1
      end
    end

    if @imp_errs.empty?
      flash[:notice] = users.length.to_s + t('user.imported')
      if del_cnt > 0
        flash[:notice] << '<br/>' + del_cnt.to_s + t('user.deleted')
      end
    end

    list
    render(:action => 'list')
  end
//  [ruby]
  def import_csv
    Log.add_info(request, params.inspect)

    file = params[:imp_file]
    mode = params[:mode]
    enc = params[:enc]

    all_users = User.find_all

    user_names = []
#   user_emails = []
    if mode == 'add'
      all_users.each do |user|
        user_names << user.name
#       user_emails << user.email
      end
    end

    @imp_errs = {}
    count = -1  # 0 for Header-line
    users = [] 

    opt = {
      :skip_blanks => true
    }

    csv = file.read
    begin
      csv.encode!(Encoding::UTF_8, enc, {:invalid => :replace, :undef => :replace, :replace => ' '})
    rescue => evar
      Log.add_error(request, evar)
    end

    found_update = false

    CSV.parse(csv, opt) do |row|
      unless row.first.nil?
        next if row.first.lstrip.index('#') == 0
      end
      next if row.compact.empty?

      count += 1
      next if count == 0  # for Header Line

      user = User.parse_csv_row(row)

      check = user.check_import(mode, user_names)  #, user_emails

      @imp_errs[count] = check unless check.empty?

      users << user

      if mode == 'update'
        update_user = all_users.find do |u|
          u.id == user.id
        end
        unless update_user.nil?
          all_users.delete(update_user)
          found_update = true
        end
      end
    end

    if users.empty?

      @imp_errs[0] = [t('user.nothing_to_import')]
    else

      if mode == 'update'

        if found_update

          user_admin = users.find do |user|
            user.admin?(User::AUTH_USER)
          end
          if user_admin.nil?
            @imp_errs[0] = [t('user.no_user_auth_import')]
          end

        else
          @imp_errs[0] = [t('user.nothing_to_update')]
        end
      end
    end

    # Create or Update
    count = 0
    @imp_cnt = 0
    if @imp_errs.empty?
      users.each do |user|
        count += 1
        begin
          user_id = user.id

          user.save!

          if user_id.nil?
            user.setup
          end

          @imp_cnt += 1

        rescue => evar
          @imp_errs[count] = [t('user.failed_to_save') + evar.to_s]
        end
      end
    end

    # Delete
    # Actually, the correct order of the process is Delete -> Create,
    # not to duplicate a User Name.
    #    3: morita   <- Delete
    #     : morita   <- Create
    # But such a case is most likely to be considered as a 
    # user's miss-operation. We can avoid this case with
    # 'opposite' process.
    del_cnt = 0
    if @imp_errs.empty? and mode == 'update'
      all_users.each do |user|
        user.destroy
        del_cnt += 1
      end
    end

    # Set order to display
    User.update_xorder(nil, User::XORDER_MAX)

    titles = User.get_config_titles
    unless titles.nil?
      idx = 0
      titles.each do |title|
        User.update_xorder title, idx
        idx += 1
      end
    end

    if @imp_errs.empty?
      flash[:notice] = users.length.to_s + t('user.imported')
      if del_cnt > 0
        flash[:notice] << '<br/>' + del_cnt.to_s + t('user.deleted')
      end
    end

    list
    render(:action => 'list')
  end
//  [ruby]
  def rename_title
    Log.add_info(request, params.inspect)

    return unless request.post?

    org_title = params[:org_title]
    new_title = params[:new_title]

    if org_title.nil? or new_title.nil? or org_title == new_title
      render(:partial => 'ajax_title', :layout => false)
      return
    end

    titles = User.get_config_titles
    unless titles.nil?
      if titles.include?(new_title)
        flash[:notice] = 'ERROR:' + t('user.title_duplicated')
      else
        idx = titles.index(org_title)
        unless idx.nil?
          titles[idx] = new_title
          User.save_config_titles(titles)

          User.rename_title(org_title, new_title)
          User.update_xorder(new_title, idx)
        end
      end
    end

    render(:partial => 'ajax_title', :layout => false)
  end
//  [ruby]
  def rename_title
    Log.add_info(request, params.inspect)

    org_title = params[:org_title]
    new_title = params[:new_title]

    if org_title.nil? or new_title.nil? or org_title == new_title
      render(:partial => 'ajax_title', :layout => false)
      return
    end

    titles = User.get_config_titles
    unless titles.nil?
      if titles.include?(new_title)

        flash[:notice] = 'ERROR:' + t('user.title_duplicated')

      else

        idx = titles.index(org_title)
        unless idx.nil?
          titles[idx] = new_title
          User.save_config_titles titles

          User.rename_title(org_title, new_title)
          User.update_xorder(new_title, idx)
        end
      end
    end

    render(:partial => 'ajax_title', :layout => false)
  end
//  [ruby]
  def exclude_from_group
    Log.add_info(request, params.inspect)

    return unless request.post?

    if params[:group_id].blank?
      render(:partial => 'ajax_groups', :layout => false)
      return
    end

    group_id = params[:group_id]

    begin
      @user = User.find(params[:id])
      unless @user.nil?
        if @user.exclude_from(group_id)
          @user.save

          if @user.id == @login_user.id
            @login_user = @user
          end
        end
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    render(:partial => 'ajax_groups', :layout => false)
  end
//  [ruby]
  def exclude_from_group
    Log.add_info(request, params.inspect)

    if params[:group_id].nil? or params[:group_id].empty?
      render(:partial => 'ajax_groups', :layout => false)
      return
    end

    group_id = params[:group_id]

    begin
      @user = User.find(params[:id])
      unless @user.nil?
        if @user.exclude_from(group_id)
          @user.save

          if @user.id == @login_user.id
            @login_user = @user
          end
        end
      end
    rescue => evar
      Log.add_error(request, evar)
    end

    render(:partial => 'ajax_groups', :layout => false)
  end
//  [ruby]
  def team_organize
    Log.add_info(request, params.inspect)

    team_id = params[:team_id]
    unless team_id.blank?
      begin
        @team = Team.find(team_id)
      rescue
        @team = nil
      ensure
        if @team.nil?
          flash[:notice] = t('msg.already_deleted', :name => Team.model_name.human)
          return
        end
      end

      users = @team.get_users_a
    end

    team_members = params[:team_members]
    SqlHelper.validate_token([team_members])

    created = false
    modified = false

    if team_members.nil? or team_members.empty?

      unless team_id.blank?
        # @team must not be nil.
        @team.save if modified = @team.clear_users
      end

    else

      if team_members != users

        if team_id.blank?

          item = Item.find(params[:id])

          created = true
          @team = Team.new
          @team.name = item.title
          @team.item_id = params[:id]
          @team.status = Team::STATUS_STANDBY

        else

          @team.clear_users
        end

        @team.add_users(team_members)
        @team.save
        @team.remove_application(team_members)

        modified = true 
      end
     end

    if created
      @team.create_team_folder
    end

    @item = @team.item

    if modified
      flash[:notice] = t('msg.register_success')
    end
    render(:partial => 'ajax_team_info', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_team_info', :layout => false)
  end
//  [ruby]
  def _process_user_attrs(user, attrs)

    if attrs[:birthday].nil?
      begin
        attrs[:birthday] = attrs[:birthday_y] + '-' + attrs[:birthday_m] + '-' + attrs[:birthday_d]
      rescue
      end
      attrs.delete(:birthday_y)
      attrs.delete(:birthday_m)
      attrs.delete(:birthday_d)
    end

    if !attrs[:name].nil? or !attrs[:password].nil?
      user_name = attrs[:name]
      user_name ||= user.name unless user.nil?
      password = attrs[:password]
      if password.blank?
        password = UsersHelper.generate_password
        attrs[:password] = password
      end
      attrs[:pass_md5] = UsersHelper.generate_digest_pass(user_name, password)
    end
    return attrs
  end
//  [ruby]
  def _process_user_attrs(user, attrs)

    if attrs[:birthday].nil?
      begin
        attrs[:birthday] = attrs[:birthday_y] + '-' + attrs[:birthday_m] + '-' + attrs[:birthday_d]
      rescue
      end
      attrs.delete(:birthday_y)
      attrs.delete(:birthday_m)
      attrs.delete(:birthday_d)
    end

    if !attrs[:name].nil? or !attrs[:password].nil?
      user_name = attrs[:name]
      user_name ||= user.name unless user.nil?
      password = attrs[:password]
      if password.nil? or password.empty?
        password = UsersHelper.generate_password
        attrs[:password] = password
      end
      attrs[:pass_md5] = UsersHelper.generate_digest_pass(user_name, password)
    end
    return attrs
  end
//  [ruby]
    it "should not display completed tasks" do
      task_1 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Your first task", :bucket => "due_asap", :assigned_to => current_user.id)
      task_2 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Completed task", :bucket => "due_asap", :completed_at => 1.days.ago, :completed_by => current_user.id, :assigned_to => current_user.id)

      get :index
      assigns[:my_tasks].should == [task_1]
    end
//  [ruby]
		it "should not display completed tasks" do
			task_1 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Your first task", :bucket => "due_asap", :assigned_to => current_user.id)
			task_2 = FactoryGirl.create(:task, :user_id => current_user.id, :name => "Completed task", :bucket => "due_asap", :completed_at => 1.days.ago, :completed_by => current_user.id, :assigned_to => current_user.id)

			get :index
			assigns[:my_tasks].should == [task_1]
		end
//  [ruby]
  def self.parse_csv_row(row, book, idxs, user)

    imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)
    SqlHelper.validate_token([imp_id])
    unless imp_id.blank?
      org_address = Address.find_by_id(imp_id)
    end

    if org_address.nil?
      address = Address.new
    else
      address = org_address
    end

    address.id = imp_id
    attr_names = [
      :name,
      :name_ruby,
      :nickname,
      :screenname,
      :email1,
      :email2,
      :email3,
      :postalcode,
      :address,
      :tel1_note,
      :tel1,
      :tel2_note,
      :tel2,
      :tel3_note,
      :tel3,
      :fax,
      :url,
      :organization,
      :title,
      :memo,
      :xorder,
      :groups,
      :teams
    ]
    attr_names.each_with_index do |attr_name, idx|
      row_idx = idxs[idx+1]
      break if row_idx.nil?

      val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)
      address.send(attr_name.to_s + '=', val)
    end
    if (address.groups == Address::EXP_IMP_FOR_ALL) \
        or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)
      address.groups = nil
      address.teams = nil
      address.owner_id = 0
    elsif !address.groups.blank? or !address.teams.blank?
      address.owner_id = 0
    else
      address.owner_id = user.id
    end

    return address
  end
//  [ruby]
  def self.parse_csv_row(row, book, idxs, user)

    imp_id = (idxs[0].nil? or row[idxs[0]].nil?)?(nil):(row[idxs[0]].strip)
    unless imp_id.nil? or imp_id.empty?
      org_address = Address.find_by_id(imp_id)
    end

    if org_address.nil?
      address = Address.new
    else
      address = org_address
    end

    address.id = imp_id
    attr_names = [
      :name,
      :name_ruby,
      :nickname,
      :screenname,
      :email1,
      :email2,
      :email3,
      :postalcode,
      :address,
      :tel1_note,
      :tel1,
      :tel2_note,
      :tel2,
      :tel3_note,
      :tel3,
      :fax,
      :url,
      :organization,
      :title,
      :memo,
      :xorder,
      :groups,
      :teams
    ]
    attr_names.each_with_index do |attr_name, idx|
      row_idx = idxs[idx+1]
      break if row_idx.nil?

      val = (row[row_idx].nil?)?(nil):(row[row_idx].strip)
      address.send(attr_name.to_s + '=', val)
    end
    if (address.groups == Address::EXP_IMP_FOR_ALL) \
        or (book == Address::BOOK_COMMON and address.groups.blank? and address.teams.blank?)
      address.groups = nil
      address.teams = nil
      address.owner_id = 0
    elsif !address.groups.blank? or !address.teams.blank?
      address.owner_id = 0
    else
      address.owner_id = user.id
    end

    return address
  end
//  [ruby]
  def check_import(mode, address_names)    #, address_emails

    err_msgs = []

    # Existing Addresss
    unless self.id.nil? or self.id == 0 or self.id == ''
      if mode == 'add'
        err_msgs << I18n.t('address.import.dont_specify_id')
      else
        begin
          org_address = Address.find(self.id)
        rescue
        end
        if org_address.nil?
          err_msgs << I18n.t('address.import.not_found')
        end
      end
    end

    # Requierd
    if self.name.nil? or self.name.empty?
      err_msgs <<  Address.human_attribute_name('name') + I18n.t('msg.is_required')
    end

    # Groups
    unless self.groups.nil? or self.groups.empty?

      if (/^|([0-9]+|)+$/ =~ self.groups) == 0

        self.get_groups_a.each do |group_id|
          begin
            group = Group.find(group_id)
          rescue => evar
            group = nil
          end
          if group.nil?
            err_msgs << I18n.t('address.import.not_valid_groups') + ': '+group_id.to_s
            break
          end
        end
      else
        err_msgs << I18n.t('address.import.invalid_groups_format')
      end
    end

    # Teams
    unless self.teams.nil? or self.teams.empty?

      if (/^|([0-9]+|)+$/ =~ self.teams) == 0

        self.get_teams_a.each do |team_id|
          begin
            team = Team.find(team_id)
          rescue => evar
            team = nil
          end
          if team.nil?
            err_msgs << I18n.t('address.import.not_valid_teams') + ': '+team_id.to_s
            break
          end
        end

      else
        err_msgs << I18n.t('address.import.invalid_teams_format')
      end
    end

    return err_msgs
  end
//  [ruby]
  def check_import(mode, address_names)    #, address_emails

    err_msgs = []

    # Existing Addresss
    unless self.id.nil? or self.id == 0 or self.id == ''
      if mode == 'add'
        err_msgs << I18n.t('address.import.dont_specify_id')
      else
        begin
          org_address = Address.find(self.id)
        rescue
        end
        if org_address.nil?
          err_msgs << I18n.t('address.import.not_found')
        end
      end
    end

    # Requierd
    if self.name.nil? or self.name.empty?
      err_msgs <<  Address.human_attribute_name('name') + I18n.t('msg.is_required')
    end

    # Groups
    unless self.groups.nil? or self.groups.empty?

      if (/^|([0-9]+|)+$/ =~ self.groups) == 0

        self.get_groups_a.each do |group_id|
          group = Group.find_by_id(group_id)
          if group.nil?
            err_msgs << I18n.t('address.import.not_valid_groups') + ': '+group_id.to_s
            break
          end
        end
      else
        err_msgs << I18n.t('address.import.invalid_groups_format')
      end
    end

    # Teams
    unless self.teams.nil? or self.teams.empty?

      if (/^|([0-9]+|)+$/ =~ self.teams) == 0

        self.get_teams_a.each do |team_id|
          team = Team.find_by_id(team_id)
          if team.nil?
            err_msgs << I18n.t('address.import.not_valid_teams') + ': '+team_id.to_s
            break
          end
        end

      else
        err_msgs << I18n.t('address.import.invalid_teams_format')
      end
    end

    return err_msgs
  end
//  [ruby]
  def self.get_for(user_id)

    SqlHelper.validate_token([user_id])

    return Research.where("user_id=#{user_id.to_i}").first
  end
//  [ruby]
  def self.get_for(user_id)

    SqlHelper.validate_token([user_id])

    return Research.where("user_id=#{user_id}").first
  end
//  [ruby]
      def generation_time
        Time.at(data.unpack("N")[0]).utc
      end
//  [ruby]
      def generation_time
        Time.at(@data.pack("C4").unpack("N")[0]).utc
      end
//  [ruby]
    def valid?(user, password)

      return false if user.blank?

      if PasswordHash.legacy?(user.password, password)
        update_password(user, password)
        return true
      end

      password_verified = PasswordHash.verified?(user.password, password)

      raise Exceptions::NotAuthorized, 'Please verify your account before you can login!' if !user.verified && user.source == 'signup' && password_verified

      password_verified
    end
//  [ruby]
    def valid?(user, password)

      return false if user.blank?

      if PasswordHash.legacy?(user.password, password)
        update_password(user, password)
        return true
      end

      PasswordHash.verified?(user.password, password)
    end
//  [ruby]
  def bulk_unread_topic_ids
    topic_query = TopicQuery.new(current_user)

    if inbox = params[:private_message_inbox]
      filter = private_message_filter(topic_query, inbox)
      topic_query.options[:limit] = false
      topics = topic_query.filter_private_messages_unread(current_user, filter)
    else
      topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics
      topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == "true"

      if params[:category_id]
        if params[:include_subcategories]
          topics = topics.where(<<~SQL, category_id: params[:category_id])
            category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR
            category_id = :category_id
          SQL
        else
          topics = topics.where('category_id = ?', params[:category_id])
        end
      end

      if params[:tag_name].present?
        topics = topics.joins(:tags).where("tags.name": params[:tag_name])
      end
    end

    topics.pluck(:id)
  end
//  [ruby]
  def bulk_unread_topic_ids
    topic_query = TopicQuery.new(current_user)

    if inbox = params[:private_message_inbox]
      filter = private_message_filter(topic_query, inbox)
      topic_query.options[:limit] = false

      topic_query
        .filter_private_messages_unread(current_user, filter)
        .distinct(false)
        .pluck(:id)
    else
      topics = TopicQuery.unread_filter(topic_query.joined_topic_user, staff: guardian.is_staff?).listable_topics
      topics = TopicQuery.tracked_filter(topics, current_user.id) if params[:tracked].to_s == "true"

      if params[:category_id]
        if params[:include_subcategories]
          topics = topics.where(<<~SQL, category_id: params[:category_id])
            category_id in (select id FROM categories WHERE parent_category_id = :category_id) OR
            category_id = :category_id
          SQL
        else
          topics = topics.where('category_id = ?', params[:category_id])
        end
      end

      if params[:tag_name].present?
        topics = topics.joins(:tags).where("tags.name": params[:tag_name])
      end

      topics.pluck(:id)
    end
  end
//  [ruby]
  def private_message_reset_new
    topic_query = TopicQuery.new(current_user, limit: false)

    if params[:topic_ids].present?
      unless Array === params[:topic_ids]
        raise Discourse::InvalidParameters.new(
          "Expecting topic_ids to contain a list of topic ids"
        )
      end

      topic_scope = topic_query
        .private_messages_for(current_user, :all)
        .where("topics.id IN (?)", params[:topic_ids].map(&:to_i))
    else
      params.require(:inbox)
      inbox = params[:inbox].to_s
      filter = private_message_filter(topic_query, inbox)
      topic_scope = topic_query.filter_private_message_new(current_user, filter)
    end

    topic_ids = TopicsBulkAction.new(
      current_user,
      topic_scope.pluck(:id),
      type: "dismiss_topics"
    ).perform!

    render json: success_json.merge(topic_ids: topic_ids)
  end
//  [ruby]
  def private_message_reset_new
    topic_query = TopicQuery.new(current_user, limit: false)

    if params[:topic_ids].present?
      unless Array === params[:topic_ids]
        raise Discourse::InvalidParameters.new(
          "Expecting topic_ids to contain a list of topic ids"
        )
      end

      topic_scope = topic_query
        .private_messages_for(current_user, :all)
        .where("topics.id IN (?)", params[:topic_ids].map(&:to_i))
    else
      params.require(:inbox)
      inbox = params[:inbox].to_s
      filter = private_message_filter(topic_query, inbox)
      topic_scope = topic_query.filter_private_message_new(current_user, filter)
    end

    topic_ids = TopicsBulkAction.new(
      current_user,
      topic_scope.distinct(false).pluck(:id),
      type: "dismiss_topics"
    ).perform!

    render json: success_json.merge(topic_ids: topic_ids)
  end
//  [ruby]
  def output_versions output, versions
    versions.each do |gem_name, matching_tuples|
      matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse

      platforms = Hash.new { |h,version| h[version] = [] }

      matching_tuples.each do |n, _|
        platforms[n.version] << n.platform if n.platform
      end

      seen = {}

      matching_tuples.delete_if do |n,_|
        if seen[n.version] then
          true
        else
          seen[n.version] = true
          false
        end
      end

      output << clean_text(make_entry(matching_tuples, platforms))
    end
  end
//  [ruby]
  def output_versions output, versions
    versions.each do |gem_name, matching_tuples|
      matching_tuples = matching_tuples.sort_by { |n,_| n.version }.reverse

      platforms = Hash.new { |h,version| h[version] = [] }

      matching_tuples.each do |n, _|
        platforms[n.version] << n.platform if n.platform
      end

      seen = {}

      matching_tuples.delete_if do |n,_|
        if seen[n.version] then
          true
        else
          seen[n.version] = true
          false
        end
      end

      output << make_entry(matching_tuples, platforms)
    end
  end
//  [ruby]
  def process
    # We don't want any tracking back in the fs.  Unlikely, but there
    # you go.
    if host =~ Regexp.union(/[#{SEPARATOR}]/, /\A\.\.?\Z/)
      raise ArgumentError, "Invalid node name #{host.inspect}"
    end

    dir = File.join(Puppet[:reportdir], host)

    if ! FileTest.exists?(dir)
      FileUtils.mkdir_p(dir)
      FileUtils.chmod_R(0750, dir)
    end

    # Now store the report.
    now = Time.now.gmtime
    name = %w{year month day hour min}.collect do |method|
      # Make sure we're at least two digits everywhere
      "%02d" % now.send(method).to_s
    end.join("") + ".yaml"

    file = File.join(dir, name)

    f = Tempfile.new(name, dir)
    begin
      begin
        f.chmod(0640)
        f.print to_yaml
      ensure
        f.close
      end
      FileUtils.mv(f.path, file)
    rescue => detail
      puts detail.backtrace if Puppet[:trace]
      Puppet.warning "Could not write report for #{host} at #{file}: #{detail}"
    end

    # Only testing cares about the return value
    file
  end
//  [ruby]
  def process
    # We don't want any tracking back in the fs.  Unlikely, but there
    # you go.
    client = self.host.gsub("..",".")

    dir = File.join(Puppet[:reportdir], client)

    if ! FileTest.exists?(dir)
      FileUtils.mkdir_p(dir)
      FileUtils.chmod_R(0750, dir)
    end

    # Now store the report.
    now = Time.now.gmtime
    name = %w{year month day hour min}.collect do |method|
      # Make sure we're at least two digits everywhere
      "%02d" % now.send(method).to_s
    end.join("") + ".yaml"

    file = File.join(dir, name)

    f = Tempfile.new(name, dir)
    begin
      begin
        f.chmod(0640)
        f.print to_yaml
      ensure
        f.close
      end
      FileUtils.mv(f.path, file)
    rescue => detail
      puts detail.backtrace if Puppet[:trace]
      Puppet.warning "Could not write report for #{client} at #{file}: #{detail}"
    end

    # Only testing cares about the return value
    file
  end
//  [ruby]
        def _marshal(val, options)
          yield marshal?(options) ? @serializer.dump(val) : val
        end
//  [ruby]
        def _marshal(val, options)
          yield marshal?(options) ? Marshal.dump(val) : val
        end
//  [ruby]
  def get_users
    if params[:action] == 'get_users'
      Log.add_info(request, params.inspect)
    end

    @group_id = params[:id]

=begin
#    @users = Group.get_users(params[:id])
=end

# FEATURE_PAGING_IN_TREE >>>
    con = ['User.id > 0']

    unless @group_id.nil?
      if @group_id == '0'
        con << "((groups like '%|0|%') or (groups is null))"
      else
        con << SqlHelper.get_sql_like([:groups], "|#{@group_id}|")
      end
    end

    unless params[:keyword].blank?
      key_array = params[:keyword].split(nil)
      key_array.each do |key| 
        con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization, :tel1, :tel2, :tel3, :fax, :url, :postalcode, :title], key)
      end
    end

    where = ''
    unless con.empty?
      where = ' where ' + con.join(' and ')
    end

    order_by = nil
    @sort_col = params[:sort_col]
    @sort_type = params[:sort_type]

    if @sort_col.blank? or @sort_type.blank?
      @sort_col = 'OfficialTitle.xorder'
      @sort_type = 'ASC'
    end

    SqlHelper.validate_token([@sort_col, @sort_type])
    order_by = @sort_col + ' ' + @sort_type

    if @sort_col == 'OfficialTitle.xorder'
      order_by = '(OfficialTitle.xorder is null) ' + @sort_type + ', ' + order_by
    else
      order_by << ', (OfficialTitle.xorder is null) ASC, OfficialTitle.xorder ASC'
    end
    if @sort_col != 'name'
      order_by << ', name ASC'
    end

    sql = 'select distinct User.* from (users User left join user_titles UserTitle on User.id=UserTitle.user_id)'
    sql << ' left join official_titles OfficialTitle on UserTitle.official_title_id=OfficialTitle.id'

    sql << where + ' order by ' + order_by

    @user_pages, @users, @total_num = paginate_by_sql(User, sql, 50)
# FEATURE_PAGING_IN_TREE <<<

    session[:group_id] = @group_id
    session[:group_option] = 'user'

    render(:partial => 'ajax_group_users', :layout => false)
  end
//  [ruby]
  def get_users
    if params[:action] == 'get_users'
      Log.add_info(request, params.inspect)
    end

    @group_id = params[:id]

=begin
#    @users = Group.get_users(params[:id])
=end

# FEATURE_PAGING_IN_TREE >>>
    con = ['User.id > 0']

    unless @group_id.nil?
      if @group_id == '0'
        con << "((groups like '%|0|%') or (groups is null))"
      else
        con << ApplicationHelper.get_sql_like([:groups], "|#{@group_id}|")
      end
    end

    unless params[:keyword].blank?
      key_array = params[:keyword].split(nil)
      key_array.each do |key| 
        con << SqlHelper.get_sql_like([:name, :email, :fullname, :address, :organization, :tel1, :tel2, :tel3, :fax, :url, :postalcode, :title], key)
      end
    end

    where = ''
    unless con.empty?
      where = ' where ' + con.join(' and ')
    end

    order_by = nil
    @sort_col = params[:sort_col]
    @sort_type = params[:sort_type]

    if @sort_col.blank? or @sort_type.blank?
      @sort_col = 'OfficialTitle.xorder'
      @sort_type = 'ASC'
    end

    SqlHelper.validate_token([@sort_col, @sort_type])
    order_by = @sort_col + ' ' + @sort_type

    if @sort_col == 'OfficialTitle.xorder'
      order_by = '(OfficialTitle.xorder is null) ' + @sort_type + ', ' + order_by
    else
      order_by << ', (OfficialTitle.xorder is null) ASC, OfficialTitle.xorder ASC'
    end
    if @sort_col != 'name'
      order_by << ', name ASC'
    end

    sql = 'select distinct User.* from (users User left join user_titles UserTitle on User.id=UserTitle.user_id)'
    sql << ' left join official_titles OfficialTitle on UserTitle.official_title_id=OfficialTitle.id'

    sql << where + ' order by ' + order_by

    @user_pages, @users, @total_num = paginate_by_sql(User, sql, 50)
# FEATURE_PAGING_IN_TREE <<<

    session[:group_id] = @group_id
    session[:group_option] = 'user'

    render(:partial => 'ajax_group_users', :layout => false)
  end
//  [ruby]
      def download(url, remote_headers = {})
        headers = remote_headers.
          reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}")
        uri = process_uri(url.to_s)
        begin
          if skip_ssrf_protection?(uri)
            response = OpenURI.open_uri(process_uri(url.to_s), headers)
          else
            request = nil
            response = SsrfFilter.get(uri, headers: headers) do |req|
              request = req
            end
            response.uri = request.uri
            response.value
          end
        rescue StandardError => e
          raise CarrierWave::DownloadError, "could not download file: #{e.message}"
        end
        CarrierWave::Downloader::RemoteFile.new(response)
      end
//  [ruby]
      def download(url, remote_headers = {})
        headers = remote_headers.
          reverse_merge('User-Agent' => "CarrierWave/#{CarrierWave::VERSION}")
        begin
          file = OpenURI.open_uri(process_uri(url.to_s), headers)
        rescue StandardError => e
          raise CarrierWave::DownloadError, "could not download file: #{e.message}"
        end
        CarrierWave::Downloader::RemoteFile.new(file)
      end
//  [ruby]
        def _unmarshal(val, options)
          unmarshal?(val, options) ? @serializer.load(val) : val
        end
//  [ruby]
        def _unmarshal(val, options)
          unmarshal?(val, options) ? Marshal.load(val) : val
        end
//  [ruby]
  def self.destroy(host)
    if host =~ Regexp.union(/[#{SEPARATOR}]/, /\A\.\.?\Z/)
      raise ArgumentError, "Invalid node name #{host.inspect}"
    end

    dir = File.join(Puppet[:reportdir], host)

    if File.exists?(dir)
      Dir.entries(dir).each do |file|
        next if ['.','..'].include?(file)
        file = File.join(dir, file)
        File.unlink(file) if File.file?(file)
      end
      Dir.rmdir(dir)
    end
  end
//  [ruby]
  def self.destroy(host)
    client = host.gsub("..",".")
    dir = File.join(Puppet[:reportdir], client)

    if File.exists?(dir)
      Dir.entries(dir).each do |file|
        next if ['.','..'].include?(file)
        file = File.join(dir, file)
        File.unlink(file) if File.file?(file)
      end
      Dir.rmdir(dir)
    end
  end
//  [ruby]
  def request(args = {})
    args = {
      :key => 'key',
      :node => 'host.domain.com',
      :ip => '10.1.1.1',
      :authenticated => true
    }.merge(args)
    ['test', :find, args[:key], args]
  end
//  [ruby]
  def request(args = {})
    { :ip => '10.1.1.1', :node => 'host.domain.com', :key => 'key', :authenticated => true }.each do |k,v|
      args[k] ||= v
    end
    ['test', :find, args[:key], args]
  end
//  [ruby]
  def test_should_sanitize_illegal_style_properties
    raw      = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
    expected = %(display:block;width:100%;height:100%;background-color:black;background-x:center;background-y:center;)
    assert_equal expected, sanitize_css(raw)
  end
//  [ruby]
  def test_should_sanitize_illegal_style_properties
    raw      = %(display:block; position:absolute; left:0; top:0; width:100%; height:100%; z-index:1; background-color:black; background-image:url(http://www.ragingplatypus.com/i/cam-full.jpg); background-x:center; background-y:center; background-repeat:repeat;)
    expected = %(display: block; width: 100%; height: 100%; background-color: black; background-x: center; background-y: center;)
    assert_equal expected, sanitize_css(raw)
  end
//  [ruby]
  def test_should_sanitize_with_trailing_space
    raw = "display:block; "
    expected = "display:block;"
    assert_equal expected, sanitize_css(raw)
  end
//  [ruby]
  def test_should_sanitize_with_trailing_space
    raw = "display:block; "
    expected = "display: block;"
    assert_equal expected, sanitize_css(raw)
  end
//  [ruby]
  def edit
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.blank?
      @date = Date.today
      date_s = @date.strftime(Schedule::SYS_DATE_FORM)
    else
      @date = Date.parse(date_s)
    end

    if params[:user_id].nil?
      @selected_user = @login_user
    else
      @selected_user = User.find(params[:user_id])
    end

    @timecard = Timecard.get_for(@selected_user.id, date_s)

    if @selected_user == @login_user
      @schedules = Schedule.get_user_day(@login_user, @date)
    end

    if !params[:display].nil? and params[:display].split('_').first == 'group'
      @group_id = params[:display].split('_').last
    end
  end
//  [ruby]
  def edit
    Log.add_info(request, params.inspect)

    date_s = params[:date]

    if date_s.nil? or date_s.empty?
      @date = Date.today
      date_s = @date.strftime(Schedule::SYS_DATE_FORM)
    else
      @date = Date.parse(date_s)
    end

    if params[:user_id].nil?
      @selected_user = @login_user
    else
      @selected_user = User.find(params[:user_id])
    end

    @timecard = Timecard.get_for(@selected_user.id, date_s)

    if @selected_user == @login_user
      @schedules = Schedule.get_user_day(@login_user, @date)
    end

    if !params[:display].nil? and params[:display].split('_').first == 'group'
      @group_id = params[:display].split('_').last
    end
  end
//  [ruby]
  def scope_allowed_attributes(attributes)
    old_attributes = Rails::Html::WhiteListSanitizer.allowed_attributes
    Rails::Html::WhiteListSanitizer.allowed_attributes = attributes
    yield Rails::Html::WhiteListSanitizer.new
  ensure
    Rails::Html::WhiteListSanitizer.allowed_attributes = old_attributes
  end
//  [ruby]
  def scope_allowed_attributes(attributes)
    Rails::Html::WhiteListSanitizer.allowed_attributes = attributes
    yield Rails::Html::WhiteListSanitizer.new

  ensure
    Rails::Html::WhiteListSanitizer.allowed_attributes = nil
  end
//  [ruby]
      def mget(*keys)
        options = (keys.pop if keys.last.is_a? Hash) || {}
        if keys.any?
          # Serialization gets extended before Namespace does, so we need to pass options further
          if singleton_class.ancestors.include? Serialization
            super(*keys.map {|key| interpolate(key) }, options)
          else
            super(*keys.map {|key| interpolate(key) })
          end
        end
      end
//  [ruby]
      def mget(*keys)
        options = (keys.pop if keys.last.is_a? Hash) || {}
        if keys.any?
          # Marshalling gets extended before Namespace does, so we need to pass options further
          if singleton_class.ancestors.include? Marshalling
            super(*keys.map {|key| interpolate(key) }, options)
          else
            super(*keys.map {|key| interpolate(key) })
          end
        end
      end
//  [ruby]
  def test_sanitize_script
    assert_sanitized "a b c<script language=\"Javascript\">blah blah blah</script>d e f", "a b cblah blah blahd e f"
  end
//  [ruby]
  def test_sanitize_script
    assert_sanitized "a b c<script language=\"Javascript\">blah blah blah</script>d e f", "a b cd e f"
  end
//  [ruby]
  def test_should_allow_anchors
    assert_sanitized %(<a href="foo" onclick="bar"><script>baz</script></a>), %(<a href=\"foo\">baz</a>)
  end

  def test_video_poster_sanitization
    scope_allowed_tags(%w(video)) do
      scope_allowed_attributes %w(src poster) do
        assert_sanitized %(<video src="videofile.ogg" autoplay  poster="posterimage.jpg"></video>), %(<video src="videofile.ogg" poster="posterimage.jpg"></video>)
        assert_sanitized %(<video src="videofile.ogg" poster=javascript:alert(1)></video>), %(<video src="videofile.ogg"></video>)
      end
    end
  end

  # RFC 3986, sec 4.2
  def test_allow_colons_in_path_component
    assert_sanitized "<a href=\"./this:that\">foo</a>"
  end
//  [ruby]
  def test_should_allow_anchors
    assert_sanitized %(<a href="foo" onclick="bar"><script>baz</script></a>), %(<a href=\"foo\"></a>)
  end

  def test_video_poster_sanitization
    assert_sanitized %(<video src="videofile.ogg" autoplay  poster="posterimage.jpg"></video>), %(<video src="videofile.ogg" poster="posterimage.jpg"></video>)
    assert_sanitized %(<video src="videofile.ogg" poster=javascript:alert(1)></video>), %(<video src="videofile.ogg"></video>)
  end

  # RFC 3986, sec 4.2
  def test_allow_colons_in_path_component
    assert_sanitized "<a href=\"./this:that\">foo</a>"
  end