jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
      it "updates to a mongo advanced selector" do
        query.explain
        query.operation.selector.should eq(
          "$query" => selector,
          "$explain" => true,
          "$orderby" => { _id: 1 }
        )
      end
//  [ruby]
    def initialize(hosts, options)
      @options = {
        down_interval: 30,
        refresh_interval: 300
      }.merge(options)

      @seeds = hosts
      @nodes = hosts.map { |host| Node.new(host) }
    end
//  [ruby]
    def initialize(seeds, direct = false)
      @seeds  = seeds
      @direct = direct

      @servers = []
      @dynamic_seeds = []
    end
//  [ruby]
    it "should raise an error if the image fails to be processed when downloaded" do
      stub_request(:get, "http://www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))

      expect(running {
        @instance.remote_image_url = "http://www.example.com/test.jpg"
      }).to raise_error(CarrierWave::ProcessingError)
    end
//  [ruby]
    it "should raise an error if the image fails to be processed when downloaded" do
      stub_request(:get, "www.example.com/test.jpg").to_return(body: File.read(file_path("test.jpg")))

      expect(running {
        @instance.remote_image_url = "http://www.example.com/test.jpg"
      }).to raise_error(CarrierWave::ProcessingError)
    end
//  [ruby]
      def as_json(options = {})
        # if application belongs to some owner we need to check if it's the same as
        # the one passed in the options or check if we render the client as an owner
        if (respond_to?(:owner) && owner && owner == options[:current_resource_owner]) ||
           options[:as_owner]
          # Owners can see all the client attributes, fallback to ActiveModel serialization
          super
        else
          # if application has no owner or it's owner doesn't match one from the options
          # we render only minimum set of attributes that could be exposed to a public
          only = extract_serializable_attributes(options)
          super(options.merge(only: only))
        end
      end
//  [ruby]
      def as_json(options = {})
        hash = super

        hash["secret"] = plaintext_secret if hash.key?("secret")
        hash
      end
//  [ruby]
    def create
      @application = Doorkeeper.config.application_model.new(application_params)

      if @application.save
        flash[:notice] = I18n.t(:notice, scope: %i[doorkeeper flash applications create])
        flash[:application_secret] = @application.plaintext_secret

        respond_to do |format|
          format.html { redirect_to oauth_application_url(@application) }
          format.json { render json: @application, as_owner: true }
        end
      else
        respond_to do |format|
          format.html { render :new }
          format.json do
            errors = @application.errors.full_messages

            render json: { errors: errors }, status: :unprocessable_entity
          end
        end
      end
    end
//  [ruby]
    def create
      @application = Doorkeeper.config.application_model.new(application_params)

      if @application.save
        flash[:notice] = I18n.t(:notice, scope: %i[doorkeeper flash applications create])
        flash[:application_secret] = @application.plaintext_secret

        respond_to do |format|
          format.html { redirect_to oauth_application_url(@application) }
          format.json { render json: @application }
        end
      else
        respond_to do |format|
          format.html { render :new }
          format.json do
            errors = @application.errors.full_messages

            render json: { errors: errors }, status: :unprocessable_entity
          end
        end
      end
    end
//  [ruby]
    def show
      respond_to do |format|
        format.html
        format.json { render json: @application, as_owner: true }
      end
    end
//  [ruby]
    def show
      respond_to do |format|
        format.html
        format.json { render json: @application }
      end
    end
//  [ruby]
  def check_mail_owner
    return if params[:id].blank? or @login_user.nil?

    begin
      owner_id = Email.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_MAIL) and owner_id != @login_user.id
      Log.add_check(request, '[check_mail_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def check_mail_owner
    return if params[:id].nil? or params[:id].empty? or @login_user.nil?

    begin
      owner_id = Email.find(params[:id]).user_id
    rescue
      owner_id = -1
    end
    if !@login_user.admin?(User::AUTH_MAIL) and owner_id != @login_user.id
      Log.add_check(request, '[check_mail_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def create
    Log.add_info(request, params.inspect)

    return unless request.post?

    parent_id = params[:selectedFolderId]

    if params[:thetisBoxEdit].blank?
      @mail_folder = nil
    else
      @mail_folder = MailFolder.new
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.parent_id = parent_id
      @mail_folder.user_id = @login_user.id
      @mail_folder.xtype = nil
      @mail_folder.save!
    end
    render(:partial => 'ajax_folder_entry', :layout => false)
  end
//  [ruby]
  def create
    Log.add_info(request, params.inspect)

    parent_id = params[:selectedFolderId]

    if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @mail_folder = nil
    else
      @mail_folder = MailFolder.new
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.parent_id = parent_id
      @mail_folder.user_id = @login_user.id
      @mail_folder.xtype = nil
      @mail_folder.save!
    end
    render(:partial => 'ajax_folder_entry', :layout => false)
  end
//  [ruby]
  def empty
    Log.add_info(request, params.inspect)

    return unless request.post?

    @folder_id = params[:id]
    mail_account_id = params[:mail_account_id]
    SqlHelper.validate_token([@folder_id, mail_account_id])

    trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)

    mail_folder = MailFolder.find(@folder_id)
    emails = (MailFolder.get_mails(mail_folder.id, @login_user) || [])

    if mail_folder.id == trash_folder.id \
        or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
      emails.each do |email|
        email.destroy
      end
      flash[:notice] = t('msg.delete_success')
    else
      emails.each do |email|
        email.update_attribute(:mail_folder_id, trash_folder.id)
      end
      flash[:notice] = t('msg.moved_to_trash')
    end

    get_mails
  end
//  [ruby]
  def empty
    Log.add_info(request, params.inspect)

    @folder_id = params[:id]
    mail_account_id = params[:mail_account_id]
    SqlHelper.validate_token([mail_account_id])

    trash_folder = MailFolder.get_for(@login_user, mail_account_id, MailFolder::XTYPE_TRASH)

    mail_folder = MailFolder.find(@folder_id)
    emails = MailFolder.get_mails(mail_folder.id, @login_user) || []

    if mail_folder.id == trash_folder.id \
        or mail_folder.get_parents(false).include?(trash_folder.id.to_s)
      emails.each do |email|
        email.destroy
      end
      flash[:notice] = t('msg.delete_success')
    else
      emails.each do |email|
        email.update_attribute(:mail_folder_id, trash_folder.id)
      end
      flash[:notice] = t('msg.moved_to_trash')
    end

    get_mails
  end
//  [ruby]
    def update
      if @application.update(application_params)
        flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update))

        respond_to do |format|
          format.html { redirect_to oauth_application_url(@application) }
          format.json { render json: @application, as_owner: true }
        end
      else
        respond_to do |format|
          format.html { render :edit }
          format.json do
            errors = @application.errors.full_messages

            render json: { errors: errors }, status: :unprocessable_entity
          end
        end
      end
    end
//  [ruby]
    def update
      if @application.update(application_params)
        flash[:notice] = I18n.t(:notice, scope: i18n_scope(:update))

        respond_to do |format|
          format.html { redirect_to oauth_application_url(@application) }
          format.json { render json: @application }
        end
      else
        respond_to do |format|
          format.html { render :edit }
          format.json do
            errors = @application.errors.full_messages

            render json: { errors: errors }, status: :unprocessable_entity
          end
        end
      end
    end
//  [ruby]
  def get_mail_content
    Log.add_info(request, params.inspect)

    email_id = params[:id]

    begin
      @email = Email.find(email_id)
      render(:partial => 'ajax_mail_content', :layout => false)
    rescue => evar
      Log.add_error(nil, evar)
      render(:text => '')
    end
  end
//  [ruby]
  def get_mail_content
    Log.add_info(request, params.inspect)

    mail_id = params[:id]

    begin
      @email = Email.find(mail_id)
      render(:partial => 'ajax_mail_content', :layout => false)
    rescue => evar
      Log.add_error(nil, evar)
      render(:text => '')
    end
  end
//  [ruby]
  def get_folders_order
    Log.add_info(request, params.inspect)

    @folder_id = params[:id]
    SqlHelper.validate_token([@folder_id])

    if @folder_id == '0'
      @folders = MailFolder.get_account_roots_for(@login_user)
    else
      mail_folder = MailFolder.find(@folder_id)
      if mail_folder.user_id == @login_user.id
        @folders = MailFolder.get_childs(@folder_id, false, true)
      end
    end

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

    @folder_id = params[:id]

    if @folder_id == '0'
      @folders = MailFolder.get_account_roots_for(@login_user)
    else
      mail_folder = MailFolder.find(@folder_id)
      if mail_folder.user_id == @login_user.id
        @folders = MailFolder.get_childs(@folder_id, false, true)
      end
    end

    render(:partial => 'ajax_folders_order', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_folders_order', :layout => false)
  end
//  [ruby]
  def rename
    Log.add_info(request, params.inspect)

    return unless request.post?

    @mail_folder = MailFolder.find(params[:id])

    unless params[:thetisBoxEdit].blank?
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.save
    end
    render(:partial => 'ajax_folder_name', :layout => false)
  end
//  [ruby]
  def rename
    Log.add_info(request, params.inspect)

    @mail_folder = MailFolder.find(params[:id])

    unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @mail_folder.name = params[:thetisBoxEdit]
      @mail_folder.save
    end
    render(:partial => 'ajax_folder_name', :layout => false)
  end
//  [ruby]
    it "can set password" do
      user = InviteRedeemer.new(invite: invite, email: invite.email, username: username, name: name, password: password).redeem
      expect(user).to have_password
      expect(user.confirm_password?(password)).to eq(true)
      expect(user.approved).to eq(false)
    end
//  [ruby]
    it "can set password" do
      user = InviteRedeemer.new(invite: invite, email: invite.email, username: username, name: name, password: password).redeem
      expect(user).to have_password
      expect(user.confirm_password?(password)).to eq(true)
      expect(user.approved).to eq(true)
    end
//  [ruby]
  def get_mails
    if params[:action] == 'get_mails'
      Log.add_info(request, params.inspect)
    end

    if !params[:pop].nil? and params[:pop] == 'true'

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

      begin
        new_arrivals_h = {}

        if mail_account_id.blank?
          mail_accounts = MailAccount.find_all("user_id=#{@login_user.id}")
          mail_accounts.each do |mail_account|
            emails = Email.do_pop(mail_account)
            unless emails.empty?
              new_arrivals_h[mail_account.id] ||= []
              new_arrivals_h[mail_account.id] |= emails
            end
          end
        else
          mail_account = MailAccount.find(mail_account_id)
          emails = Email.do_pop(mail_account)
          unless emails.empty?
            new_arrivals_h[mail_account.id] ||= []
            new_arrivals_h[mail_account.id] |= emails
          end
        end

        unless new_arrivals_h.empty?
          flash[:notice] = t('mail.received', :count => new_arrivals_h.values.flatten.length)

        # FEATURE_MAIL_FILTERS >>>
          new_arrivals_h.each do |mail_account_id, emails|
            mail_filters = MailFilter.get_for(mail_account_id, true, MailFilter::TRIGGER_CHECKING)
            filter_next = true

            emails.each do |email|
              mail_filters.each do |filter|
                filter_next = filter.execute(email)
                break unless filter_next
              end
              break unless filter_next
            end
          end
        # FEATURE_MAIL_FILTERS <<<
        end
      rescue => evar
        if evar.to_s.starts_with?('ERROR:')
          flash[:notice] = evar.to_s
        else
          flash[:notice] = 'ERROR:' + t('mail.receive_error') + '<br/>' + evar.to_s
        end
        Log.add_error(nil, evar)
      end
    end

    @folder_id = params[:id]
    SqlHelper.validate_token([@folder_id])

    if @folder_id == TreeElement::ROOT_ID.to_s
      @emails = nil
    else
=begin
#      @emails = MailFolder.get_mails_to_show(@folder_id, @login_user)
=end
# FEATURE_PAGING_IN_TREE >>>
      @sort_col = (params[:sort_col] || 'sent_at')
      @sort_type = (params[:sort_type] || 'DESC')
      SqlHelper.validate_token([@sort_col, @sort_type])

      sql = EmailsHelper.get_list_sql(@login_user, params[:keyword], [@folder_id], @sort_col, @sort_type, 0, nil)
      @email_pages, @emails, @total_num = paginate_by_sql(Email, sql, 10)
# FEATURE_PAGING_IN_TREE <<<
    end

    session[:mailfolder_id] = @folder_id

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

    if !params[:pop].nil? and params[:pop] == 'true'
      begin
        new_arrivals_h = {}

        mail_account_id = params[:mail_account_id]
        if mail_account_id.blank?
          mail_accounts = MailAccount.find_all("user_id=#{@login_user.id}")
          mail_accounts.each do |mail_account|
            emails = Email.do_pop(mail_account)
            unless emails.empty?
              new_arrivals_h[mail_account.id] ||= []
              new_arrivals_h[mail_account.id] |= emails
            end
          end
        else
          mail_account = MailAccount.find(mail_account_id)
          emails = Email.do_pop(mail_account)
          unless emails.empty?
            new_arrivals_h[mail_account.id] ||= []
            new_arrivals_h[mail_account.id] |= emails
          end
        end

        unless new_arrivals_h.empty?
          flash[:notice] = t('mail.received', :count => new_arrivals_h.values.flatten.length)

        # FEATURE_MAIL_FILTERS >>>
          new_arrivals_h.each do |mail_account_id, emails|
            mail_filters = MailFilter.get_for(mail_account_id, true, MailFilter::TRIGGER_CHECKING)
            filter_next = true

            emails.each do |email|
              mail_filters.each do |filter|
                filter_next = filter.execute(email)
                break unless filter_next
              end
              break unless filter_next
            end
          end
        # FEATURE_MAIL_FILTERS <<<
        end
      rescue => evar
        if evar.to_s.starts_with?('ERROR:')
          flash[:notice] = evar.to_s
        else
          flash[:notice] = 'ERROR:' + t('mail.receive_error') + '<br/>' + evar.to_s
        end
        Log.add_error(nil, evar)
      end
    end

    @folder_id = params[:id]
    if @folder_id == TreeElement::ROOT_ID.to_s
      @emails = nil
    else
=begin
#      @emails = MailFolder.get_mails_to_show(@folder_id, @login_user)
=end
# FEATURE_PAGING_IN_TREE >>>
      @sort_col = (params[:sort_col] || 'sent_at')
      @sort_type = (params[:sort_type] || 'DESC')

      folder_ids = nil
      add_con = nil

      folder_ids = [@folder_id]

      sql = EmailsHelper.get_list_sql(@login_user, params[:keyword], folder_ids, @sort_col, @sort_type, 0, add_con)
      @email_pages, @emails, @total_num = paginate_by_sql(Email, sql, 10)
# FEATURE_PAGING_IN_TREE <<<
    end

    session[:mailfolder_id] = @folder_id

    render(:partial => 'ajax_folder_mails', :layout => false)
  end
//  [ruby]
    it "activates user invited via email with a token" do
      invite = Fabricate(:invite, invited_by: Fabricate(:admin), email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:sent])
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', email_token: invite.email_token)

      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(false)
      expect(user.active).to eq(true)
    end
//  [ruby]
    it "activates user invited via email with a token" do
      invite = Fabricate(:invite, invited_by: Fabricate(:admin), email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:sent])
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', email_token: invite.email_token)

      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(true)
      expect(user.active).to eq(true)
    end
//  [ruby]
      def validate_each(record, attribute, value)
        adapter = Paperclip.io_adapters.for(value)
        if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename, value.content_type).spoofed?
          record.errors.add(attribute, :spoofed_media_type)
        end
      end
//  [ruby]
      def validate_each(record, attribute, value)
        adapter = Paperclip.io_adapters.for(value)
        if Paperclip::MediaTypeSpoofDetector.using(adapter, value.original_filename).spoofed?
          record.errors.add(attribute, :spoofed_media_type)
        end
      end
//  [ruby]
  def private_message_reset_new
    topic_query = TopicQuery.new(current_user)

    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_query.options[:limit] = false
      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]
    it "can set the password and ip_address" do
      password = 's3cure5tpasSw0rD'
      ip_address = '192.168.1.1'
      invite = Fabricate(:invite, email: 'walter.white@email.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', password: password, ip_address: ip_address)
      expect(user).to have_password
      expect(user.confirm_password?(password)).to eq(true)
      expect(user.approved).to eq(false)
      expect(user.ip_address).to eq(ip_address)
      expect(user.registration_ip_address).to eq(ip_address)
    end
//  [ruby]
    it "can set the password and ip_address" do
      password = 's3cure5tpasSw0rD'
      ip_address = '192.168.1.1'
      invite = Fabricate(:invite, email: 'walter.white@email.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White', password: password, ip_address: ip_address)
      expect(user).to have_password
      expect(user.confirm_password?(password)).to eq(true)
      expect(user.approved).to eq(true)
      expect(user.ip_address).to eq(ip_address)
      expect(user.registration_ip_address).to eq(ip_address)
    end
//  [ruby]
    it "does not activate user invited via links" do
      invite = Fabricate(:invite, email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:not_required])
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')

      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(false)
      expect(user.active).to eq(false)
    end
//  [ruby]
    it "does not activate user invited via links" do
      invite = Fabricate(:invite, email: 'walter.white@email.com', emailed_status: Invite.emailed_status_types[:not_required])
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')

      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(true)
      expect(user.active).to eq(false)
    end
//  [ruby]
      it "removes the first matching document" do
        users.insert(documents)
        users.find(scope: scope).remove
        users.find(scope: scope).count.should eq 1
      end
//  [ruby]
    it "removes the first matching document" do
      session.should_receive(:with, :consistency => :strong).
        and_yield(session)

      session.should_receive(:execute).with do |delete|
        delete.flags.should eq [:remove_first]
        delete.selector.should eq query.operation.selector
      end

      query.remove
    end
//  [ruby]
    it "should be created correctly" do
      invite = Fabricate(:invite, email: 'walter.white@email.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')
      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(false)
      expect(user.active).to eq(false)
    end
//  [ruby]
    it "should be created correctly" do
      invite = Fabricate(:invite, email: 'walter.white@email.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')
      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.email).to eq('walter.white@email.com')
      expect(user.approved).to eq(true)
      expect(user.active).to eq(false)
    end
//  [ruby]
    it "should redeem the invite if invited by non staff and approve if staff not required to approve" do
      inviter = invite.invited_by
      user = invite_redeemer.redeem

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.invited_by).to eq(inviter)
      expect(inviter.notifications.count).to eq(1)
      expect(user.approved).to eq(false)
    end
//  [ruby]
    it "should redeem the invite if invited by non staff and approve if staff not required to approve" do
      inviter = invite.invited_by
      user = invite_redeemer.redeem

      expect(user.name).to eq(name)
      expect(user.username).to eq(username)
      expect(user.invited_by).to eq(inviter)
      expect(inviter.notifications.count).to eq(1)
      expect(user.approved).to eq(true)
    end
//  [ruby]
    it 'supports passing read options to RMagick' do
      expect_any_instance_of(::Magick::Image::Info).to receive(:density=).with(10)
      expect_any_instance_of(::Magick::Image::Info).to receive(:size=).with("200x200")

      instance.manipulate! :read => {
          :density => 10,
          :size => "200x200"
        }
    end
//  [ruby]
    it 'supports passing read options to RMagick' do
      expect_any_instance_of(::Magick::Image::Info).to receive(:density=).with(10)
      expect_any_instance_of(::Magick::Image::Info).to receive(:size=).with("200x200")

      instance.manipulate! :read => {
          :density => 10,
          :size => %{"200x200"}
        }
    end
//  [ruby]
    it "renders email addresses in the body" do
      comment = build_stubbed(:comment, body: "foo@example.com")
      expect(comment.html).to match(/mailto:/)
    end
//  [ruby]
    it "renders email addresses in the body" do
      comment = build_stubbed(:comment, body: "foo@example.com")
      expect(comment.generate_html(:body)).to match(/mailto:/)
    end
//  [ruby]
  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    return unless request.post?

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    attachment_id = params[:attachment_id]
    SqlHelper.validate_token([user_id, zeptair_id, attachment_id])

    unless user_id.blank?
      if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == user_id.to_s
        target_user = User.find(user_id)
      end
    end

    unless zeptair_id.blank?

      target_user = User.where("zeptair_id=#{zeptair_id.to_i}").first

      unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id
        target_user = nil
      end
    end

    if target_user.nil?
      if attachment_id.blank?
        query
        unless @post_items.nil?
          @post_items.each do |post_item|
            post_item.attachments_without_content.each do |attach|
              attach.destroy
            end
            post_item.update_attribute(:updated_at, Time.now)
          end
        end

      else
        attach = Attachment.find(attachment_id)

        item = Item.find(attach.item_id)

        if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id
          raise t('msg.need_to_be_owner')
        end

        if item.xtype != Item::XTYPE_ZEPTAIR_POST
          raise t('msg.system_error')
        end

        attach.destroy

        item.update_attribute(:updated_at, Time.now)
      end
    else

      post_item = ZeptairPostHelper.get_item_for(target_user)
      post_item.attachments_without_content.each do |attach|
        attach.destroy
      end
      post_item.update_attribute(:updated_at, Time.now)
    end

    render(:text => t('msg.delete_success'))

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
  def delete_attachment
    Log.add_info(request, '')   # Not to show passwords.

    return unless request.post?

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    attachment_id = params[:attachment_id]
    SqlHelper.validate_token([user_id, zeptair_id, attachment_id])

    unless user_id.blank?
      if @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id.to_s == user_id.to_s
        target_user = User.find(user_id)
      end
    end

    unless zeptair_id.blank?

      target_user = User.where("zeptair_id=#{zeptair_id}").first

      unless @login_user.admin?(User::AUTH_ZEPTAIR) or @login_user.id == target_user.id
        target_user = nil
      end
    end

    if target_user.nil?
      if attachment_id.blank?
        query
        unless @post_items.nil?
          @post_items.each do |post_item|
            post_item.attachments_without_content.each do |attach|
              attach.destroy
            end
            post_item.update_attribute(:updated_at, Time.now)
          end
        end

      else
        attach = Attachment.find(attachment_id)

        item = Item.find(attach.item_id)

        if !@login_user.admin?(User::AUTH_ZEPTAIR) and item.user_id != @login_user.id
          raise t('msg.need_to_be_owner')
        end

        if item.xtype != Item::XTYPE_ZEPTAIR_POST
          raise t('msg.system_error')
        end

        attach.destroy

        item.update_attribute(:updated_at, Time.now)
      end
    else

      post_item = ZeptairPostHelper.get_item_for(target_user)
      post_item.attachments_without_content.each do |attach|
        attach.destroy
      end
      post_item.update_attribute(:updated_at, Time.now)
    end

    render(:text => t('msg.delete_success'))

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
  def query
    Log.add_info(request, '')   # Not to show passwords.

    unless @login_user.admin?(User::AUTH_ZEPTAIR)
      render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
      return
    end

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    group_id = params[:group_id]
    SqlHelper.validate_token([user_id, zeptair_id, group_id])

    unless user_id.blank?
      target_user = User.find(user_id)
    end

    unless zeptair_id.blank?
      target_user = User.where("zeptair_id=#{zeptair_id.to_i}").first
    end

    if target_user.nil?

      if group_id.blank?
        sql = 'select distinct Item.* from items Item, attachments Attachment'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << ' order by Item.user_id ASC'
      else
        group_ids = [group_id]

        if params[:recursive] == 'true'
          group_ids += Group.get_childs(group_id, true, false)
        end

        groups_con = []
        group_ids.each do |grp_id|
          groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{grp_id}|")
        end
        sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
        sql << ' order by Item.user_id ASC'
      end

      @post_items = Item.find_by_sql(sql)
    else
      @post_item = ZeptairPostHelper.get_item_for(target_user)
    end

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
  def query
    Log.add_info(request, '')   # Not to show passwords.

    unless @login_user.admin?(User::AUTH_ZEPTAIR)
      render(:text => 'ERROR:' + t('msg.need_to_be_admin'))
      return
    end

    target_user = nil

    user_id = params[:user_id]
    zeptair_id = params[:zeptair_id]
    group_id = params[:group_id]
    SqlHelper.validate_token([user_id, zeptair_id, group_id])

    unless user_id.blank?
      target_user = User.find(user_id)
    end

    unless zeptair_id.blank?
      target_user = User.where("zeptair_id=#{zeptair_id}").first
    end

    if target_user.nil?

      if group_id.blank?
        sql = 'select distinct Item.* from items Item, attachments Attachment'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << ' order by Item.user_id ASC'
      else
        group_ids = [group_id]

        if params[:recursive] == 'true'
          group_ids += Group.get_childs(group_id, true, false)
        end

        groups_con = []
        group_ids.each do |grp_id|
          groups_con << SqlHelper.get_sql_like(['User.groups'], "|#{grp_id}|")
        end
        sql = 'select distinct Item.* from items Item, attachments Attachment, users User'
        sql << " where Item.xtype='#{Item::XTYPE_ZEPTAIR_POST}' and Item.id=Attachment.item_id"
        sql << " and (Item.user_id=User.id and (#{groups_con.join(' or ')}))"
        sql << ' order by Item.user_id ASC'
      end

      @post_items = Item.find_by_sql(sql)
    else
      @post_item = ZeptairPostHelper.get_item_for(target_user)
    end

  rescue => evar
    Log.add_error(request, evar)
    render(:text => 'ERROR:' + t('msg.system_error'))
  end
//  [ruby]
    it "should unstage user" do
      staged_user = Fabricate(:staged, email: 'staged@account.com', active: true, username: 'staged1', name: 'Stage Name')
      invite = Fabricate(:invite, email: 'staged@account.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')

      expect(user.id).to eq(staged_user.id)
      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.staged).to eq(false)
      expect(user.email).to eq('staged@account.com')
      expect(user.approved).to eq(false)
    end
//  [ruby]
    it "should unstage user" do
      staged_user = Fabricate(:staged, email: 'staged@account.com', active: true, username: 'staged1', name: 'Stage Name')
      invite = Fabricate(:invite, email: 'staged@account.com')
      user = InviteRedeemer.create_user_from_invite(invite: invite, email: invite.email, username: 'walter', name: 'Walter White')

      expect(user.id).to eq(staged_user.id)
      expect(user.username).to eq('walter')
      expect(user.name).to eq('Walter White')
      expect(user.staged).to eq(false)
      expect(user.email).to eq('staged@account.com')
      expect(user.approved).to eq(true)
    end
//  [ruby]
  def show
    filename = Rails.root.join("attachments", @attachment.filename)
    unless File.exist?(filename)
      COURSE_LOGGER.log("Cannot find the file '#{@attachment.filename}' for"\
                        " attachment #{@attachment.name}")

      flash[:error] = "Error loading #{@attachment.name} from #{@attachment.filename}"
      redirect_to([@course, :attachments]) && return
    end
    # Set to application/octet-stream to force download
    send_file(filename, disposition: "inline",
                        type: "application/octet-stream", filename: @attachment.filename) && return
  end
//  [ruby]
  def show
    filename = Rails.root.join("attachments", @attachment.filename)
    unless File.exist?(filename)
      COURSE_LOGGER.log("Cannot find the file '#{@attachment.filename}' for"\
                        " attachment #{@attachment.name}")

      flash[:error] = "Error loading #{@attachment.name} from #{@attachment.filename}"
      redirect_to([@course, :attachments]) && return
    end
    send_file(filename, disposition: "inline",
                        type: @attachment.mime_type, filename: @attachment.filename) && return
  end
//  [ruby]
    def command(command)
      session.context.command name, command
    end
//  [ruby]
    def command(command)
      operation = Protocol::Command.new(name, command)

      result = session.with(consistency: :strong) do |session|
        session.simple_query(operation)
      end

      raise Errors::OperationFailure.new(
        operation, result
      ) unless result["ok"] == 1.0

      result
    end
//  [ruby]
    def drop
      session.with(consistency: :strong) do |session|
        session.context.command name, dropDatabase: 1
      end
    end
//  [ruby]
    def drop
      command dropDatabase: 1
    end
//  [ruby]
    def logout
      session.context.logout(name)
    end
//  [ruby]
    def logout
      session.cluster.logout(name)
    end
//  [ruby]
    def login(username, password)
      session.context.login(name, username, password)
    end
//  [ruby]
    def login(username, password)
      session.cluster.login(name, username, password)
    end
//  [ruby]
  def check_import(mode, user_names)    #, user_emails

    err_msgs = []

    # Existing Users
    unless self.id.nil? or self.id == 0 or self.id == ''
      if mode == 'add'
        err_msgs << I18n.t('user.import.dont_specify_id')
      else
        begin
          org_user = User.find(self.id)
        rescue
        end
        if org_user.nil?
          err_msgs << I18n.t('user.import.not_found')
        end
      end
    end

    # Required
    if self.name.nil? or self.name.empty?
      err_msgs <<  User.human_attribute_name('name') + I18n.t('msg.is_required')
    end
    if self.pass_md5.nil? or self.pass_md5.empty?
      if mode == 'update' and !org_user.nil?
        self.pass_md5 = org_user.pass_md5
      end
    end
    if self.pass_md5.nil? or self.pass_md5.empty?
      err_msgs << I18n.t('password.name') + I18n.t('msg.is_required')
    end
    if self.email.nil? or self.email.empty?
      err_msgs <<  User.human_attribute_name('email') + I18n.t('msg.is_required')
    end

    # Duplicated
    if user_names.include?(self.name)
      err_msgs << User.human_attribute_name('name') + I18n.t('msg.is_duplicated')
    elsif !self.name.nil? and !self.name.empty?
      user_names << self.name
    end
# Comment out considering about administrative users.
#    if user_emails.include?(self.email)
#      err_msgs << User.human_attribute_name('email') + I18n.t('msg.is_duplicated')
#    elsif !self.email.nil? and !self.email.empty?
#      user_emails << self.email
#    end

    # Characters
    if (/^[01-9a-zA-Z]+$/ =~ self.name).nil?
      err_msgs << User.human_attribute_name('name') + I18n.t('activerecord.errors.models.user.attributes.name.invalid', :attribute => User.human_attribute_name('name'))
    end

    # Authority
    unless self.auth.nil? or self.auth.empty? or self.auth == User::AUTH_ALL

      if (/^|([a-z]+|)+$/ =~ self.auth) == 0

        keys = User.get_auth_names.keys()
        keys.delete(User::AUTH_ALL)

        self.get_auth_a.each do |auth|
          unless keys.include?(auth)
            err_msgs << I18n.t('user.import.not_valid_auth') + ': '+auth.to_s
            break
          end
        end

      else
        err_msgs << I18n.t('user.import.invalid_auth_format')
      end
    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('user.import.not_valid_groups') + ': '+group_id.to_s
            break
          end
        end
      else
        err_msgs << I18n.t('user.import.invalid_groups_format')
      end
    end

    return err_msgs
  end
//  [ruby]
  def check_import(mode, user_names)    #, user_emails

    err_msgs = []

    # Existing Users
    unless self.id.nil? or self.id == 0 or self.id == ''
      if mode == 'add'
        err_msgs << I18n.t('user.import.dont_specify_id')
      else
        begin
          org_user = User.find(self.id)
        rescue
        end
        if org_user.nil?
          err_msgs << I18n.t('user.import.not_found')
        end
      end
    end

    # Required
    if self.name.nil? or self.name.empty?
      err_msgs <<  User.human_attribute_name('name') + I18n.t('msg.is_required')
    end
    if self.pass_md5.nil? or self.pass_md5.empty?
      if mode == 'update' and !org_user.nil?
        self.pass_md5 = org_user.pass_md5
      end
    end
    if self.pass_md5.nil? or self.pass_md5.empty?
      err_msgs << I18n.t('password.name') + I18n.t('msg.is_required')
    end
    if self.email.nil? or self.email.empty?
      err_msgs <<  User.human_attribute_name('email') + I18n.t('msg.is_required')
    end

    # Duplicated
    if user_names.include?(self.name)
      err_msgs << User.human_attribute_name('name') + I18n.t('msg.is_duplicated')
    elsif !self.name.nil? and !self.name.empty?
      user_names << self.name
    end
# Comment out considering about administrative users.
#    if user_emails.include?(self.email)
#      err_msgs << User.human_attribute_name('email') + I18n.t('msg.is_duplicated')
#    elsif !self.email.nil? and !self.email.empty?
#      user_emails << self.email
#    end

    # Characters
    if (/^[01-9a-zA-Z]+$/ =~ self.name).nil?
      err_msgs << User.human_attribute_name('name') + I18n.t('activerecord.errors.models.user.attributes.name.invalid', :attribute => User.human_attribute_name('name'))
    end

    # Authority
    unless self.auth.nil? or self.auth.empty? or self.auth == User::AUTH_ALL

      if (/^|([a-z]+|)+$/ =~ self.auth) == 0

        keys = User.get_auth_names.keys()
        keys.delete(User::AUTH_ALL)

        self.get_auth_a.each do |auth|
          unless keys.include?(auth)
            err_msgs << I18n.t('user.import.not_valid_auth') + ': '+auth.to_s
            break
          end
        end

      else
        err_msgs << I18n.t('user.import.invalid_auth_format')
      end
    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('user.import.not_valid_groups') + ': '+group_id.to_s
            break
          end
        end
      else
        err_msgs << I18n.t('user.import.invalid_groups_format')
      end
    end

    return err_msgs
  end
//  [ruby]
  def nofollowify_links(string)
    raise ArgumentError, "string", "must be html_safe" unless string.html_safe?

    if this_blog.dofollowify
      string
    else
      followify_scrubber = Loofah::Scrubber.new do |node|
        node.set_attribute "rel", "nofollow" if node.name == "a"
      end
      sanitize h(string), scrubber: followify_scrubber
    end
  end
//  [ruby]
  def nofollowify_links(string)
    if this_blog.dofollowify
      string
    else
      string.gsub(/<a(.*?)>/i, '<a\1 rel="nofollow">')
    end
  end
//  [ruby]
  def create
    Log.add_info(request, params.inspect)

    return unless request.post?

    if params[:thetisBoxEdit].blank?
      @group = nil
    else
      @group = Group.new
      @group.name = params[:thetisBoxEdit]
      @group.parent_id = params[:selectedGroupId]
      @group.save!

      @group.create_group_folder
    end
    render(:partial => 'ajax_group_entry', :layout => false)
  end
//  [ruby]
  def create
     Log.add_info(request, params.inspect)

    if params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @group = nil
    else
      @group = Group.new
      @group.name = params[:thetisBoxEdit]
      @group.parent_id = params[:selectedGroupId]
      @group.save!

      @group.create_group_folder
    end
    render(:partial => 'ajax_group_entry', :layout => false)
  end
//  [ruby]
  def send_password
    Log.add_info(request, params.inspect)

    mail_addr = params[:thetisBoxEdit]
    SqlHelper.validate_token([mail_addr])
    begin
      users = User.where("email='#{mail_addr}'").to_a
    rescue => evar
    end

    if users.nil? or users.empty?
      Log.add_error(request, evar)
      flash[:notice] = 'ERROR:' + t('email.address_not_found')
    else
      user_passwords_h = {}
      users.each do |user|
        newpass = UsersHelper.generate_password
        user.update_attribute(:pass_md5, UsersHelper.generate_digest_pass(user.name, newpass))

        user_passwords_h[user] = newpass
      end

      NoticeMailer.password(user_passwords_h, ApplicationHelper.root_url(request)).deliver;
      flash[:notice] = t('email.sent')
    end

    render(:controller => 'login', :action => 'index')
  end
//  [ruby]
  def get_path
    Log.add_info(request, params.inspect)

    if params[:thetisBoxSelKeeper].blank?
      @group_path = '/' + t('paren.unknown')
      render(:partial => 'ajax_group_path', :layout => false)
      return
    end

    @selected_id = params[:thetisBoxSelKeeper].split(':').last
    SqlHelper.validate_token([@selected_id])

    @group_path = Group.get_path(@selected_id)

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

    if params[:thetisBoxSelKeeper].nil? or params[:thetisBoxSelKeeper].empty?
      @group_path = '/' + t('paren.unknown')
      render(:partial => 'ajax_group_path', :layout => false)
      return
    end

    @selected_id = params[:thetisBoxSelKeeper].split(':').last

    @group_path = Group.get_path(@selected_id)

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

    return unless request.post?

    @group = Group.find(params[:id])
    unless params[:thetisBoxEdit].blank?
      @group.rename(params[:thetisBoxEdit])
    end
    render(:partial => 'ajax_group_name', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_group_name', :layout => false)
  end
//  [ruby]
  def rename
    Log.add_info(request, params.inspect)

    @group = Group.find(params[:id])
    unless params[:thetisBoxEdit].nil? or params[:thetisBoxEdit].empty?
      @group.rename params[:thetisBoxEdit]
    end
    render(:partial => 'ajax_group_name', :layout => false)

  rescue => evar
    Log.add_error(request, evar)
    render(:partial => 'ajax_group_name', :layout => false)
  end
//  [ruby]
  def self.get_tmpl_folder

    tmpl_folder = Folder.where(name: TMPL_ROOT).first

    if tmpl_folder.nil?

      ary = self.setup_tmpl_folder

      unless ary.nil? or ary.empty?
        tmpl_folder = ary[0]
        tmpl_system_folder = ary[1]
        tmpl_workflows_folder = ary[2]
        tmpl_local_folder = ary[3]
        tmpl_q_folder = ary[4]
      end

    else

      folders = Folder.where("parent_id=#{tmpl_folder.id}").to_a
      unless folders.nil?
        folders.each do |child|
          case child.name
            when TMPL_SYSTEM
              tmpl_system_folder = child
            when TMPL_WORKFLOWS
              tmpl_workflows_folder = child
            when TMPL_LOCAL
              tmpl_local_folder = child
            when TMPL_RESEARCH
              tmpl_q_folder = child
          end
        end
      end
    end
//  [ruby]
  def self.get_tmpl_folder

    tmpl_folder = Folder.where("folders.name='#{TMPL_ROOT}'").first

    if tmpl_folder.nil?

      ary = self.setup_tmpl_folder

      unless ary.nil? or ary.empty?
        tmpl_folder = ary[0]
        tmpl_system_folder = ary[1]
        tmpl_workflows_folder = ary[2]
        tmpl_local_folder = ary[3]
        tmpl_q_folder = ary[4]
      end

    else

      folders = Folder.where("parent_id=#{tmpl_folder.id}").to_a
      unless folders.nil?
        folders.each do |child|
          case child.name
            when TMPL_SYSTEM
              tmpl_system_folder = child
            when TMPL_WORKFLOWS
              tmpl_workflows_folder = child
            when TMPL_LOCAL
              tmpl_local_folder = child
            when TMPL_RESEARCH
              tmpl_q_folder = child
          end
        end
      end
    end