jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def self.set_statistics_groups(group_ids)

    yaml = Research.get_config_yaml

    yaml = Hash.new if yaml.nil?

    if group_ids.nil?

      unless yaml[:statistics].nil?
        yaml[:statistics].delete :groups
      end

    else

      if yaml[:statistics].nil?
        yaml[:statistics] = Hash.new
      end

      yaml[:statistics][:groups] = group_ids.join('|')
    end

    Research.save_config_yaml yaml

    return ary
  end
//  [ruby]
  def install_location filename, destination_dir # :nodoc:
    raise Gem::Package::PathError.new(filename, destination_dir) if
      filename.start_with? '/'

    destination_dir = realpath destination_dir
    destination_dir = File.expand_path destination_dir

    destination = File.join destination_dir, filename
    destination = File.expand_path destination

    raise Gem::Package::PathError.new(destination, destination_dir) unless
      destination.start_with? destination_dir + '/'

    destination.untaint
    destination
  end
//  [ruby]
  def install_location filename, destination_dir # :nodoc:
    raise Gem::Package::PathError.new(filename, destination_dir) if
      filename.start_with? '/'

    destination_dir = File.realpath destination_dir if
      File.respond_to? :realpath
    destination_dir = File.expand_path destination_dir

    destination = File.join destination_dir, filename
    destination = File.realpath destination if
      File.respond_to? :realpath
    destination = File.expand_path destination

    raise Gem::Package::PathError.new(destination, destination_dir) unless
      destination.start_with? destination_dir + '/'

    destination.untaint
    destination
  end
//  [ruby]
  def self.get_for(mail_account_id, enabled=nil, trigger=nil)

    return [] if mail_account_id.nil?

    SqlHelper.validate_token([mail_account_id, trigger])

    con = []
    con << "(mail_account_id=#{mail_account_id.to_i})"
    con << "(enabled=#{(enabled)?(1):(0)})" unless enabled.nil?
    con << SqlHelper.get_sql_like([:triggers], "|#{trigger}|") unless trigger.nil?

    return MailFilter.where(con.join(' and ')).order('(xorder is null) ASC, xorder ASC, id ASC').to_a
  end
//  [ruby]
  def self.get_for(mail_account_id, enabled=nil, trigger=nil)

    return [] if mail_account_id.nil?

    SqlHelper.validate_token([mail_account_id, trigger])

    con = []
    con << "(mail_account_id=#{mail_account_id})"
    con << "(enabled=#{(enabled)?(1):(0)})" unless enabled.nil?
    con << SqlHelper.get_sql_like([:triggers], "|#{trigger}|") unless trigger.nil?

    return MailFilter.where(con.join(' and ')).order('(xorder is null) ASC, xorder ASC, id ASC').to_a
  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 send_password
    Log.add_info(request, params.inspect)

    begin
      users = User.where("email='#{params[:thetisBoxEdit]}'").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 self.get_account_roots_for(user)

    return nil if user.nil?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id])

    con = []
    con << "(user_id=#{user_id.to_i})"
    con << "(xtype='#{MailFolder::XTYPE_ACCOUNT_ROOT}')"

    order_by = 'xorder ASC, id ASC'

    return MailFolder.where(con.join(' and ')).order(order_by).to_a
  end
//  [ruby]
  def self.get_account_roots_for(user)

    return nil if user.nil?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id])

    con = []
    con << "(user_id=#{user_id})"
    con << "(xtype='#{MailFolder::XTYPE_ACCOUNT_ROOT}')"

    order_by = 'xorder ASC, id ASC'

    return MailFolder.where(con.join(' and ')).order(order_by).to_a
  end
//  [ruby]
  def save_page
    Log.add_info(request, params.inspect)

    # Next page
    pave_val = params[:page].to_i + 1
    @page = sprintf('%02d', pave_val)

    page_num = Dir.glob(File.join(Research.page_dir, "_q[0-9][0-9].html.erb")).length

    unless params[:research].nil?
      params[:research].each do |key, value|
        if value.instance_of?(Array)
          value.compact!
          value.delete('')
          if value.empty?
            params[:research][key] = nil
          else
            params[:research][key] = value.join("\n") + "\n"
          end
        end
      end
    end

    research_id = params[:research_id]
    SqlHelper.validate_token([research_id])
    if research_id.blank?
      @research = Research.new(params.require(:research).permit(Research::PERMIT_BASE))
      @research.status = Research::U_STATUS_IN_ACTON
      @research.update_attribute(:user_id, @login_user.id)
    else
      @research = Research.find(research_id)
      @research.update_attributes(params.require(:research).permit(Research::PERMIT_BASE))
    end

    if pave_val <= page_num

      render(:action => 'edit_page')

    else

      tmpl_folder, tmpl_q_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_RESEARCH)

      if tmpl_q_folder.nil?
        ary = TemplatesHelper.setup_tmpl_folder
        tmpl_q_folder = ary[4]
      end

      items = Folder.get_items_admin(tmpl_q_folder.id, 'xorder ASC')

      @q_caps_h = {}
      unless items.nil?
        items.each do |item|

          desc = item.description
          next if desc.nil? or desc.empty?

          hash = Research.select_q_caps(desc)
          hash.each do |key, val|
            @q_caps_h[key] = val
          end
        end
      end

      render(:action => 'confirm')
    end

  rescue => evar
    Log.add_error(request, evar)
    @page = '01'
    render(:action => 'edit_page')
  end
//  [ruby]
  def save_page
    Log.add_info(request, params.inspect)

    # Next page
    pave_val = params[:page].to_i + 1
    @page = sprintf('%02d', pave_val)

    page_num = Dir.glob(File.join(Research.page_dir, "_q[0-9][0-9].html.erb")).length

    unless params[:research].nil?
      params[:research].each do |key, value|
        if value.instance_of?(Array)
          value.compact!
          value.delete('')
          if value.empty?
            params[:research][key] = nil
          else
            params[:research][key] = value.join("\n") + "\n"
          end
        end
      end
    end

    if params[:research_id].nil? or params[:research_id].empty?
      @research = Research.new(params.require(:research).permit(Research::PERMIT_BASE))
      @research.status = Research::U_STATUS_IN_ACTON
      @research.update_attribute(:user_id, @login_user.id)
    else
      @research = Research.find(params[:research_id])
      @research.update_attributes(params.require(:research).permit(Research::PERMIT_BASE))
    end

    if pave_val <= page_num

      render(:action => 'edit_page')

    else

      tmpl_folder, tmpl_q_folder = TemplatesHelper.get_tmpl_subfolder(TemplatesHelper::TMPL_RESEARCH)

      if tmpl_q_folder.nil?
        ary = TemplatesHelper.setup_tmpl_folder
        tmpl_q_folder = ary[4]
      end

      items = Folder.get_items_admin(tmpl_q_folder.id, 'xorder ASC')

      @q_caps_h = {}
      unless items.nil?
        items.each do |item|

          desc = item.description
          next if desc.nil? or desc.empty?

          hash = Research.select_q_caps(desc)
          hash.each do |key, val|
            @q_caps_h[key] = val
          end
        end
      end

      render(:action => 'confirm')
    end

  rescue => evar
    Log.add_error(request, evar)
    @page = '01'
    render(:action => 'edit_page')
  end
//  [ruby]
  def edit_page

    # Saved contents of Login User
    begin
      @research = Research.where("user_id=#{@login_user.id}").first
    rescue
    end
    if @research.nil?
      @research = Research.new
    else
      # Already accepted?
      if !@research.status.nil? and @research.status != 0
        render(:action => 'show_receipt')
        return
      end
    end

    # Specifying page
    @page = '01'
    unless params[:page].blank?
      @page = params[:page]
      SqlHelper.validate_token([@page])
    end
  end
//  [ruby]
  def edit_page

    # Saved contents of Login User
    begin
      @research = Research.where("user_id=#{@login_user.id}").first
    rescue
    end
    if @research.nil?
      @research = Research.new
    else
      # Already accepted?
      if !@research.status.nil? and @research.status != 0
        render(:action => 'show_receipt')
        return
      end
    end

    # Specifying page
    @page = '01'
    unless params[:page].nil? or params[:page].empty?
      @page = params[:page]
    end
  end
//  [ruby]
  def self.get_for(user, mail_account_id, xtype)

    return nil if user.nil? or mail_account_id.blank?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id, mail_account_id, xtype])

    con = []
    con << "(user_id=#{user_id.to_i})"
    con << "(mail_account_id=#{mail_account_id.to_i})"
    con << "(xtype='#{xtype}')"

    return MailFolder.where(con.join(' and ')).first
  end
//  [ruby]
  def self.get_for(user, mail_account_id, xtype)

    return nil if user.nil? or mail_account_id.blank?

    if user.kind_of?(User)
      user_id = user.id
    else
      user_id = user.to_s
    end

    SqlHelper.validate_token([user_id, mail_account_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << "(mail_account_id=#{mail_account_id})"
    con << "(xtype='#{xtype}')"

    return MailFolder.where(con.join(' and ')).first
  end
//  [ruby]
  def get_group_users
    Log.add_info(request, params.inspect)

    SqlHelper.validate_token([params[:id]])
    begin
      @folder = Folder.find(params[:id])
    rescue => evar
      Log.add_error(request, evar)
    end

    @group_id = nil
    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].blank?
      @group_id = params[:group_id]
    end
    SqlHelper.validate_token([@group_id])

    @users = Group.get_users(@group_id)

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

    begin
      @folder = Folder.find(params[:id])
    rescue => evar
      Log.add_error(request, evar)
    end

    @group_id = nil
    if !params[:thetisBoxSelKeeper].nil?
      @group_id = params[:thetisBoxSelKeeper].split(':').last
    elsif !params[:group_id].nil? and !params[:group_id].empty?
      @group_id = params[:group_id]
    end

    @users = Group.get_users @group_id

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

    if !@login_user.nil? and @login_user.admin?(User::AUTH_FOLDER)

      @group_id = nil
      if !params[:thetisBoxSelKeeper].nil?
        @group_id = params[:thetisBoxSelKeeper].split(':').last
      elsif !params[:group_id].blank?
        @group_id = params[:group_id]
      end
      SqlHelper.validate_token([@group_id])

      @folder_tree = Folder.get_tree_by_group_for_admin(@group_id || '0')
    else
      @folder_tree = Folder.get_tree_for(@login_user)
    end
  end
//  [ruby]
  def show_tree
    Log.add_info(request, params.inspect)

    if !@login_user.nil? and @login_user.admin?(User::AUTH_FOLDER)

      @group_id = nil
      if !params[:thetisBoxSelKeeper].nil?
        @group_id = params[:thetisBoxSelKeeper].split(':').last
      elsif !params[:group_id].nil? and !params[:group_id].empty?
        @group_id = params[:group_id]
      end

      @folder_tree = Folder.get_tree_by_group_for_admin(@group_id || '0')
    else
      @folder_tree = Folder.get_tree_for(@login_user)
    end
  end
//  [ruby]
  def self.search_by_host(key, operator, value)
    conditions = sanitize_sql_for_conditions(["hosts.name #{operator} ?", value_to_sql(operator, value)])
    direct     = Puppetclass.joins(:hosts).where(conditions).select('puppetclasses.id').map(&:id).uniq
    hostgroup  = Hostgroup.joins(:hosts).where(conditions).first
    indirect   = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq
    return { :conditions => "1=0" } if direct.blank? && indirect.blank?

    puppet_classes = (direct + indirect).uniq
    { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" }
  end
//  [ruby]
  def self.search_by_host(key, operator, value)
    conditions = "hosts.name #{operator} '#{value_to_sql(operator, value)}'"
    direct     = Puppetclass.all(:conditions => conditions, :joins => :hosts, :select => 'puppetclasses.id').map(&:id).uniq
    hostgroup  = Hostgroup.joins(:hosts).where(conditions).first
    indirect   = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq
    return { :conditions => "1=0" } if direct.blank? && indirect.blank?

    puppet_classes = (direct + indirect).uniq
    { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" }
  end
//  [ruby]
    def initialize(image_path, colors=16, depth=8)
      output = `convert #{image_path.shellescape} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors.to_i} -depth #{depth.to_i} histogram:info:-`
      @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?)
    end
//  [ruby]
    def initialize(image_path, colors=16, depth=8)
      output = `convert #{image_path} -resize 400x400 -format %c -dither None -quantize YIQ -colors #{colors} -depth #{depth} histogram:info:-`
      @lines = output.lines.sort.reverse.map(&:strip).reject(&:empty?)
    end
//  [ruby]
  def update
    Log.add_info(request, params.inspect)

    return unless request.post?

    SqlHelper.validate_token([params[:groups], params[:teams]])

    @equipment = Equipment.find(params[:id])

    if params[:groups].blank?
      params[:equipment][:groups] = nil
    else
      params[:equipment][:groups] = '|' + params[:groups].join('|') + '|'
    end

    if params[:teams].blank?
      params[:equipment][:teams] = nil
    else
      params[:equipment][:teams] = '|' + params[:teams].join('|') + '|'
    end

    if @equipment.update_attributes(params.require(:equipment).permit(Equipment::PERMIT_BASE))
      flash[:notice] = t('msg.update_success')
      list
      render(:action => 'list')
    else
      render(:controller => 'equipment', :action => 'edit', :id => params[:id])
    end
  end
//  [ruby]
  def update
    Log.add_info(request, params.inspect)

    @equipment = Equipment.find(params[:id])

    if (params[:groups].nil? or params[:groups].empty?)
      params[:equipment][:groups] = nil
    else
      params[:equipment][:groups] = '|' + params[:groups].join('|') + '|'
    end

    if (params[:teams].nil? or params[:teams].empty?)
      params[:equipment][:teams] = nil
    else
      params[:equipment][:teams] = '|' + params[:teams].join('|') + '|'
    end

    if @equipment.update_attributes(params.require(:equipment).permit(Equipment::PERMIT_BASE))
      flash[:notice] = t('msg.update_success')
      list
      render(:action => 'list')
    else
      render(:controller => 'equipment', :action => 'edit', :id => params[:id])
    end
  end
//  [ruby]
  def schedule_all
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.blank?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    if @login_user.nil? or params[:display].nil? or params[:display] == 'all'
      params[:display] = 'all'
      con = EquipmentHelper.get_scope_condition_for(@login_user)
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      case display_type
       when 'group'
        if @login_user.get_groups_a(true).include?(display_id)
          con = SqlHelper.get_sql_like([:groups], "|#{display_id}|")
        end
       when 'team'
        if @login_user.get_teams_a.include?(display_id)
          con = SqlHelper.get_sql_like([:teams], "|#{display_id}|")
        end
      end
    end
//  [ruby]
  def schedule_all
    Log.add_info(request, params.inspect)

    date_s = params[:date]
    if date_s.nil? or date_s.empty?
      @date = Date.today
    else
      @date = Date.parse(date_s)
    end

    if @login_user.nil? or params[:display].nil? or params[:display] == 'all'
      params[:display] = 'all'
      con = EquipmentHelper.get_scope_condition_for(@login_user)
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      case display_type
       when 'group'
        if @login_user.get_groups_a(true).include?(display_id)
          con = SqlHelper.get_sql_like([:groups], "|#{display_id}|")
        end
       when 'team'
        if @login_user.get_teams_a.include?(display_id)
          con = SqlHelper.get_sql_like([:teams], "|#{display_id}|")
        end
      end
    end
//  [ruby]
    def index
      @applications = Doorkeeper.config.application_model.authorized_for(current_resource_owner)

      respond_to do |format|
        format.html
        format.json { render json: @applications, current_resource_owner: current_resource_owner }
      end
    end
//  [ruby]
    def index
      @applications = Doorkeeper.config.application_model.authorized_for(current_resource_owner)

      respond_to do |format|
        format.html
        format.json { render json: @applications }
      end
    end
//  [ruby]
  def timeline
    state = params[:state].to_s
    if %w(Collapsed Expanded).include?(state)
      if (model_type = params[:type].to_s).present?
        if %w(comment email).include?(model_type)
          model = model_type.camelize.constantize
          item = model.find(params[:id])
          item.update_attribute(:state, state)
        end
      else
        comments, emails = params[:id].split("+")
        Comment.where(:id => comments.split(',')).update_all(:state => state) unless comments.blank?
        Email.where(:id => emails.split(',')).update_all(:state => state) unless emails.blank?
      end
    end

    render :nothing => true
  end
//  [ruby]
  def timeline
    unless params[:type].empty?
      model = params[:type].camelize.constantize
      item = model.find(params[:id])
      item.update_attribute(:state, params[:state])
    else
      comments, emails = params[:id].split("+")
      Comment.update_all("state = '#{params[:state]}'", "id IN (#{comments})") unless comments.blank?
      Email.update_all("state = '#{params[:state]}'", "id IN (#{emails})") unless emails.blank?
    end

    render :nothing => true
  end
//  [ruby]
  def comment_link(uniqueid, data)
    comment = comment_for_type(data)
    i18n_key = data[:cutoff] ? 'truncated' : 'full'
    notification = t(
      "notifications.comment.#{i18n_key}",
      name: name_or_email(data),
      comment: strip_tags(data[:comment]),
      typename: data[:typename]
    )
    notification_link(uniqueid, comment[:path], notification)
  end
//  [ruby]
  def comment_link(uniqueid, data)
    comment = comment_for_type(data)
    i18n_key = data[:cutoff] ? 'truncated' : 'full'
    notification = t(
      "notifications.comment.#{i18n_key}",
      name: data[:user],
      comment: strip_tags(data[:comment]),
      typename: data[:typename]
    )
    notification_link(uniqueid, comment[:path], notification)
  end
//  [ruby]
    def get_data_center_from_api_key(api_key)
      # Return an empty string for invalid API keys so Gibbon hits the main endpoint
      data_center = ""

      if api_key && api_key["-"]
        # Remove all non-alphanumberic characters in case someone attempts to inject
        # a different domain into the API key (e.g. when consuming user form-provided keys)
        # This approach avoids assuming a 3 letter prefix (e.g. is MC were to create 
        # a us10 DC, this would continue to work), and will continue to hit MC's server
        # rather than a would-be attacker's servers.
        data_center = "#{api_key.split('-').last.gsub(/[^0-9a-z ]/i, '')}."
      end

      data_center
    end
//  [ruby]
    def get_data_center_from_api_key(api_key)
      # Return an empty string for invalid API keys so Gibbon hits the main endpoint
      data_center = ""

      if api_key && api_key["-"]
        # Add a period since the data_center is a subdomain and it keeps things dry
        data_center = "#{api_key.split('-').last}."
      end

      data_center
    end
//  [ruby]
  def meeting_link(uniqueid, data)
    notification = t(
      "notifications.meeting.#{data[:type]}",
      name: name_or_email(data),
      group_name: data[:group],
      meeting_name: data[:typename]
    )
    link = specific_meeting_link(data[:type], data[:typeid], data[:group_id])
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def meeting_link(uniqueid, data)
    notification = t(
      "notifications.meeting.#{data[:type]}",
      name: data[:user],
      group_name: data[:group],
      meeting_name: data[:typename]
    )
    link = specific_meeting_link(data[:type], data[:typeid], data[:group_id])
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def check_owner

    return if (params[:id].blank? or @login_user.nil?)

    mail_filter = MailFilter.find(params[:id])

    if !@login_user.admin?(User::AUTH_MAIL) and mail_filter.mail_account.user_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def check_owner

    return if (params[:id].nil? or params[:id].empty? or @login_user.nil?)

    mail_filter = MailFilter.find(params[:id])

    if !@login_user.admin?(User::AUTH_MAIL) and mail_filter.mail_account.user_id != @login_user.id
      Log.add_check(request, '[check_owner]'+request.to_s)

      flash[:notice] = t('msg.need_to_be_owner')
      redirect_to(:controller => 'desktop', :action => 'show')
    end
  end
//  [ruby]
  def group_link(uniqueid, data)
    notification = t(
      "notifications.group.#{data[:type]}",
      name: name_or_email(data),
      group_name: data[:group]
    )
    link = "/groups/#{data[:group_id]}"
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def group_link(uniqueid, data)
    notification = t(
      "notifications.group.#{data[:type]}",
      name: data[:user],
      group_name: data[:group]
    )
    link = "/groups/#{data[:group_id]}"
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def accepted_ally_link(uniqueid, data)
    notification = t(
      'notifications.ally.accepted',
      name: name_or_email(data)
    )
    link = "/profile?uid=#{data[:uid]}"
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def accepted_ally_link(uniqueid, data)
    notification = t(
      'notifications.ally.accepted',
      name: data[:user]
    )
    link = "/profile?uid=#{data[:uid]}"
    notification_link(uniqueid, link, notification)
  end
//  [ruby]
  def self.prepare_rdoc root
    debug, verbose = false, false

    prepare_script = Pathname.new(Rails.root) + "script/rdoc_prepare_script.rb"
    if prepare_script.executable?
      dirs = Environment.puppetEnvs.values.join(":").split(":").uniq.sort.join(" ")
      puts "Running #{prepare_script} #{dirs}" if debug
      location = %x{#{prepare_script} #{dirs}}
      if $? == 0
        root = location.chomp
        puts "Relocated modules to #{root}" if verbose
      end
    else
      puts "No executable #{prepare_script} found so using the uncopied module sources" if verbose
    end
    root
  end

  def as_json(options={})
    super({:only => [:name, :id], :include => [:lookup_keys]})
  end

  def self.search_by_host(key, operator, value)
    conditions = sanitize_sql_for_conditions(["hosts.name #{operator} ?", value_to_sql(operator, value)])
    direct     = Puppetclass.joins(:hosts).where(conditions).select('puppetclasses.id').map(&:id).uniq
    hostgroup  = Hostgroup.joins(:hosts).where(conditions).first
    indirect   = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq
    return { :conditions => "1=0" } if direct.blank? && indirect.blank?

    puppet_classes = (direct + indirect).uniq
    { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" }
  end


  def self.value_to_sql(operator, value)
    return value                 if operator !~ /LIKE/i
    return value.tr_s('%*', '%') if (value ~ /%|\*/)

    return "%#{value}%"
  end

end
//  [ruby]
  def self.prepare_rdoc root
    debug, verbose = false, false

    prepare_script = Pathname.new(Rails.root) + "script/rdoc_prepare_script.rb"
    if prepare_script.executable?
      dirs = Environment.puppetEnvs.values.join(":").split(":").uniq.sort.join(" ")
      puts "Running #{prepare_script} #{dirs}" if debug
      location = %x{#{prepare_script} #{dirs}}
      if $? == 0
        root = location.chomp
        puts "Relocated modules to #{root}" if verbose
      end
    else
      puts "No executable #{prepare_script} found so using the uncopied module sources" if verbose
    end
    root
  end

  def as_json(options={})
    super({:only => [:name, :id], :include => [:lookup_keys]})
  end

  def self.search_by_host(key, operator, value)
    conditions = "hosts.name #{operator} '#{value_to_sql(operator, value)}'"
    direct     = Puppetclass.all(:conditions => conditions, :joins => :hosts, :select => 'puppetclasses.id').map(&:id).uniq
    hostgroup  = Hostgroup.joins(:hosts).where(conditions).first
    indirect   = HostgroupClass.where(:hostgroup_id => hostgroup.path_ids).pluck(:puppetclass_id).uniq
    return { :conditions => "1=0" } if direct.blank? && indirect.blank?

    puppet_classes = (direct + indirect).uniq
    { :conditions => "puppetclasses.id IN(#{puppet_classes.join(',')})" }
  end


  def self.value_to_sql(operator, value)
    return value                 if operator !~ /LIKE/i
    return value.tr_s('%*', '%') if (value ~ /%|\*/)

    return "%#{value}%"
  end

end
//  [ruby]
  def new_ally_request_link(uniqueid, data)
    link = "/profile?uid=#{data[:uid]}"
    link_html = "<a href=\"#{link}\">#{name_or_email(data)}</a>"
    # rubocop:disable Layout/LineLength
    "<div id=\"#{uniqueid}\"><div>#{t('notifications.ally.sent_html', link_to_user: link_html)}</div>#{request_actions(data[:user_id])}</div>"
    # rubocop:enable Layout/LineLength
  end
//  [ruby]
  def new_ally_request_link(uniqueid, data)
    link = "/profile?uid=#{data[:uid]}"
    link_html = "<a href=\"#{link}\">#{data[:user]}</a>"
    # rubocop:disable Layout/LineLength
    "<div id=\"#{uniqueid}\"><div>#{t('notifications.ally.sent_html', link_to_user: link_html)}</div>#{request_actions(data[:user_id])}</div>"
    # rubocop:enable Layout/LineLength
  end
//  [ruby]
  def load_file(filename)
    Gem.load_yaml

    yaml_errors = [ArgumentError]
    yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)

    return {} unless filename and File.exist? filename

    begin
      content = Gem::SafeYAML.load(File.read(filename))
      unless content.kind_of? Hash
        warn "Failed to load #{filename} because it doesn't contain valid YAML hash"
        return {}
      end
      return content
    rescue *yaml_errors => e
      warn "Failed to load #{filename}, #{e}"
    rescue Errno::EACCES
      warn "Failed to load #{filename} due to permissions problem."
    end

    {}
  end
//  [ruby]
  def load_file(filename)
    Gem.load_yaml

    yaml_errors = [ArgumentError]
    yaml_errors << Psych::SyntaxError if defined?(Psych::SyntaxError)

    return {} unless filename and File.exist? filename

    begin
      content = YAML.load(File.read(filename))
      unless content.kind_of? Hash
        warn "Failed to load #{filename} because it doesn't contain valid YAML hash"
        return {}
      end
      return content
    rescue *yaml_errors => e
      warn "Failed to load #{filename}, #{e}"
    rescue Errno::EACCES
      warn "Failed to load #{filename} due to permissions problem."
    end

    {}
  end
//  [ruby]
  def self.get_for_group(group_id)

    SqlHelper.validate_token([group_id])
    if group_id.nil?
      con = 'group_id is null'
    else
      con = "group_id=#{group_id.to_i}"
    end

    Location.do_expire(con)

    return Location.where(con).to_a
  end
//  [ruby]
  def self.get_for_group(group_id)

    SqlHelper.validate_token([group_id])
    if group_id.nil?
      con = 'group_id is null'
    else
      con = "group_id=#{group_id}"
    end

    Location.do_expire(con)

    return Location.where(con).to_a
  end
//  [ruby]
  def self.trim_by_capacity(user_id, mail_account_id, capacity_mb)

# FEATURE_MAIL_STRICT_CAPACITY >>>
=begin
#    max_size = capacity_mb * 1024 * 1024
#    cur_size = MailAccount.get_using_size(mail_account_id)
#
#    if cur_size > max_size
#      over_size = cur_size - max_size
#      emails = []
#
#      # First, empty Trashbox
#      user = User.find(user_id)
#      trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
#      trash_nodes = [trashbox.id.to_s]
#      trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
#      con = "mail_folder_id in (#{trash_nodes.join(',')})"
#      emails = Email.where(con).order('updated_at ASC').to_a
#      emails.each do |email|
#        next if email.size.nil?
#
#        email.destroy
#        over_size -= email.size
#        break if over_size <= 0
#      end
#
#      # Now, remove others
#      if over_size > 0
#        emails = Email.where("mail_account_id=#{mail_account_id.to_i}").order('updated_at ASC').to_a
#        emails.each do |email|
#          next if email.size.nil?
#
#          email.destroy
#          over_size -= email.size
#          break if over_size <= 0
#        end
#      end
#    end
=end
# FEATURE_MAIL_STRICT_CAPACITY <<<
  end
//  [ruby]
  def self.trim_by_capacity(user_id, mail_account_id, capacity_mb)

# FEATURE_MAIL_STRICT_CAPACITY >>>
=begin
#    max_size = capacity_mb * 1024 * 1024
#    cur_size = MailAccount.get_using_size(mail_account_id)
#
#    if cur_size > max_size
#      over_size = cur_size - max_size
#      emails = []
#
#      # First, empty Trashbox
#      user = User.find(user_id)
#      trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
#      trash_nodes = [trashbox.id.to_s]
#      trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
#      con = "mail_folder_id in (#{trash_nodes.join(',')})"
#      emails = Email.where(con).order('updated_at ASC').to_a
#      emails.each do |email|
#        next if email.size.nil?
#
#        email.destroy
#        over_size -= email.size
#        break if over_size <= 0
#      end
#
#      # Now, remove others
#      if over_size > 0
#        emails = Email.where("mail_account_id=#{mail_account_id}").order('updated_at ASC').to_a
#        emails.each do |email|
#          next if email.size.nil?
#
#          email.destroy
#          over_size -= email.size
#          break if over_size <= 0
#        end
#      end
#    end
=end
# FEATURE_MAIL_STRICT_CAPACITY <<<
  end
//  [ruby]
  def self.trim(user_id, mail_account_id, max)

    SqlHelper.validate_token([user_id, mail_account_id])

    begin
      count = Email.where("mail_account_id=#{mail_account_id.to_i}").count
      if count > max
#logger.fatal("[INFO] Email.trim(user_id:#{user_id}, mail_account_id:#{mail_account_id}, max:#{max})")
        over_num = count - max
        emails = []

        # First, empty Trashbox
        user = User.find(user_id)
        trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
        trash_nodes = [trashbox.id.to_s]
        trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
        con = "mail_folder_id in (#{trash_nodes.join(',')})"
        emails = Email.where(con).order('updated_at ASC').limit(over_num).to_a

        # Now, remove others
        if emails.length < over_num
          over_num -= emails.length
          emails += Email.where("mail_account_id=#{mail_account_id.to_i}").order('updated_at ASC').limit(over_num).to_a
        end

        emails.each do |email|
          email.destroy
        end
      end
    rescue
    end
  end
//  [ruby]
  def self.trim(user_id, mail_account_id, max)

    SqlHelper.validate_token([user_id, mail_account_id])

    begin
      count = Email.where("mail_account_id=#{mail_account_id}").count
      if count > max
#logger.fatal("[INFO] Email.trim(user_id:#{user_id}, mail_account_id:#{mail_account_id}, max:#{max})")
        over_num = count - max
        emails = []

        # First, empty Trashbox
        user = User.find(user_id)
        trashbox = MailFolder.get_for(user, mail_account_id, MailFolder::XTYPE_TRASH)
        trash_nodes = [trashbox.id.to_s]
        trash_nodes += MailFolder.get_childs(trash_nodes.first, true, false)
        con = "mail_folder_id in (#{trash_nodes.join(',')})"
        emails = Email.where(con).order('updated_at ASC').limit(over_num).to_a

        # Now, remove others
        if emails.length < over_num
          over_num -= emails.length
          emails += Email.where("mail_account_id=#{mail_account_id}").order('updated_at ASC').limit(over_num).to_a
        end

        emails.each do |email|
          email.destroy
        end
      end
    rescue
    end
  end
//  [ruby]
  def self.destroy_by_user(user_id, add_con=nil)

    SqlHelper.validate_token([user_id])

    con = "(user_id=#{user_id.to_i})"
    con << " and (#{add_con})" unless add_con.nil? or add_con.empty?
    emails = Email.where(con).to_a

    emails.each do |email|
      email.destroy
    end
  end
//  [ruby]
  def self.destroy_by_user(user_id, add_con=nil)

    SqlHelper.validate_token([user_id])

    con = "user_id=#{user_id}"
    con << " and (#{add_con})" unless add_con.nil? or add_con.empty?
    emails = Email.where(con).to_a

    emails.each do |email|
      email.destroy
    end
  end
//  [ruby]
    def call(env)
      env[HTTP_ORIGIN] ||= env[HTTP_X_ORIGIN] if env[HTTP_X_ORIGIN]

      path = evaluate_path(env)

      add_headers = nil
      if env[HTTP_ORIGIN]
        debug(env) do
          [ 'Incoming Headers:',
            "  Origin: #{env[HTTP_ORIGIN]}",
            "  Path-Info: #{path}",
            "  Access-Control-Request-Method: #{env[HTTP_ACCESS_CONTROL_REQUEST_METHOD]}",
            "  Access-Control-Request-Headers: #{env[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]}"
            ].join("\n")
        end
        if env[REQUEST_METHOD] == OPTIONS and env[HTTP_ACCESS_CONTROL_REQUEST_METHOD]
          headers = process_preflight(env, path)
          debug(env) do
            "Preflight Headers:\n" +
                headers.collect{|kv| "  #{kv.join(': ')}"}.join("\n")
          end
          return [200, headers, []]
        else
          add_headers = process_cors(env, path)
        end
      else
        Result.miss(env, Result::MISS_NO_ORIGIN)
      end

      # This call must be done BEFORE calling the app because for some reason
      # env[PATH_INFO] gets changed after that and it won't match. (At least
      # in rails 4.1.6)
      vary_resource = resource_for_path(path)

      status, headers, body = @app.call env

      if add_headers
        headers = add_headers.merge(headers)
        debug(env) do
          add_headers.each_pair do |key, value|
            if headers.has_key?(key)
              headers["X-Rack-CORS-Original-#{key}"] = value
            end
          end
        end
      end

      # Vary header should ALWAYS mention Origin if there's ANY chance for the
      # response to be different depending on the Origin header value.
      # Better explained here: http://www.fastly.com/blog/best-practices-for-using-the-vary-header/
      if vary_resource
        vary = headers[VARY]
        cors_vary_headers = if vary_resource.vary_headers && vary_resource.vary_headers.any?
          vary_resource.vary_headers
        else
          DEFAULT_VARY_HEADERS
        end
        headers[VARY] = ((vary ? ([vary].flatten.map { |v| v.split(/,\s*/) }.flatten) : []) + cors_vary_headers).uniq.join(', ')
      end
//  [ruby]
    def call(env)
      env[HTTP_ORIGIN] ||= env[HTTP_X_ORIGIN] if env[HTTP_X_ORIGIN]

      add_headers = nil
      if env[HTTP_ORIGIN]
        debug(env) do
          [ 'Incoming Headers:',
            "  Origin: #{env[HTTP_ORIGIN]}",
            "  Access-Control-Request-Method: #{env[HTTP_ACCESS_CONTROL_REQUEST_METHOD]}",
            "  Access-Control-Request-Headers: #{env[HTTP_ACCESS_CONTROL_REQUEST_HEADERS]}"
            ].join("\n")
        end
        if env[REQUEST_METHOD] == OPTIONS and env[HTTP_ACCESS_CONTROL_REQUEST_METHOD]
          headers = process_preflight(env)
          debug(env) do
            "Preflight Headers:\n" +
                headers.collect{|kv| "  #{kv.join(': ')}"}.join("\n")
          end
          return [200, headers, []]
        else
          add_headers = process_cors(env)
        end
      else
        Result.miss(env, Result::MISS_NO_ORIGIN)
      end

      # This call must be done BEFORE calling the app because for some reason
      # env[PATH_INFO] gets changed after that and it won't match. (At least
      # in rails 4.1.6)
      vary_resource = resource_for_path(env[PATH_INFO])

      status, headers, body = @app.call env

      if add_headers
        headers = add_headers.merge(headers)
        debug(env) do
          add_headers.each_pair do |key, value|
            if headers.has_key?(key)
              headers["X-Rack-CORS-Original-#{key}"] = value
            end
          end
        end
      end

      # Vary header should ALWAYS mention Origin if there's ANY chance for the
      # response to be different depending on the Origin header value.
      # Better explained here: http://www.fastly.com/blog/best-practices-for-using-the-vary-header/
      if vary_resource
        vary = headers[VARY]
        cors_vary_headers = if vary_resource.vary_headers && vary_resource.vary_headers.any?
          vary_resource.vary_headers
        else
          DEFAULT_VARY_HEADERS
        end
        headers[VARY] = ((vary ? ([vary].flatten.map { |v| v.split(/,\s*/) }.flatten) : []) + cors_vary_headers).uniq.join(', ')
      end
//  [ruby]
      def match_resource(path, env)
        origin = env[HTTP_ORIGIN]

        origin_matched = false
        all_resources.each do |r|
          if r.allow_origin?(origin, env)
            origin_matched = true
            if found = r.match_resource(path, env)
              return [found, nil]
            end
          end
        end

        [nil, origin_matched ? Result::MISS_NO_PATH : Result::MISS_NO_ORIGIN]
      end
//  [ruby]
      def match_resource(env)
        path   = env[PATH_INFO]
        origin = env[HTTP_ORIGIN]

        origin_matched = false
        all_resources.each do |r|
          if r.allow_origin?(origin, env)
            origin_matched = true
            if found = r.match_resource(path, env)
              return [found, nil]
            end
          end
        end

        [nil, origin_matched ? Result::MISS_NO_PATH : Result::MISS_NO_ORIGIN]
      end
//  [ruby]
  def self.get_default_for(user_id, xtype=nil)

    SqlHelper.validate_token([user_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << '(is_default=1)'
    con << "(xtype='#{xtype}')" unless xtype.blank?

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

    mail_accounts = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')

    if mail_accounts.nil? or mail_accounts.empty?
      return nil
    else
      return mail_accounts.first
    end
  end
//  [ruby]
  def self.get_default_for(user_id, xtype=nil)

    SqlHelper.validate_token([user_id, xtype])

    con = []
    con << "(user_id=#{user_id})"
    con << '(is_default=1)'
    con << "(xtype='#{xtype}')" unless xtype.blank?

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

    account_ary = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')

    if account_ary.nil? or account_ary.empty?
      return nil
    else
      return account_ary.first
    end
  end
//  [ruby]
  def self.destroy_by_user(user_id, add_con=nil)

    SqlHelper.validate_token([user_id])

    con = "(user_id=#{user_id.to_i})"
    con << " and (#{add_con})" unless add_con.nil? or add_con.empty?
    mail_accounts = MailAccount.where(con).to_a

    mail_accounts.each do |mail_account|
      mail_account.destroy
    end
  end
//  [ruby]
  def self.destroy_by_user(user_id, add_con=nil)

    SqlHelper.validate_token([user_id])

    con = "user_id=#{user_id}"
    con << " and (#{add_con})" unless add_con.nil? or add_con.empty?
    mail_accounts = MailAccount.where(con).to_a

    mail_accounts.each do |mail_account|
      mail_account.destroy
    end
  end
//  [ruby]
      def process_preflight(env, path)
        result = Result.preflight(env)

        resource, error = match_resource(path, env)
        unless resource
          result.miss(error)
          return {}
        end

        return resource.process_preflight(env, result)
      end
//  [ruby]
      def process_preflight(env)
        result = Result.preflight(env)

        resource, error = match_resource(env)
        unless resource
          result.miss(error)
          return {}
        end

        return resource.process_preflight(env, result)
      end
//  [ruby]
  def test_execute_details_cleans_text
    spec_fetcher do |fetcher|
      fetcher.spec 'a', 2 do |s|
        s.summary = 'This is a lot of text. ' * 4
        s.authors = ["Abraham Lincoln \x01", "\x02 Hirohito"]
        s.homepage = "http://a.example.com/\x03"
      end

      fetcher.legacy_platform
    end

    @cmd.handle_options %w[-r -d]

    use_ui @ui do
      @cmd.execute
    end

    expected = <<-EOF

*** REMOTE GEMS ***

a (2)
    Authors: Abraham Lincoln ., . Hirohito
    Homepage: http://a.example.com/.

    This is a lot of text. This is a lot of text. This is a lot of text.
    This is a lot of text.

pl (1)
    Platform: i386-linux
    Author: A User
    Homepage: http://example.com

    this is a summary
    EOF

    assert_equal expected, @ui.output
    assert_equal '', @ui.error
  end
//  [ruby]
  def test_execute_details_cleans_text
    spec_fetcher do |fetcher|
      fetcher.spec 'a', 2 do |s|
        s.summary = 'This is a lot of text. ' * 4
        s.authors = ["Abraham Lincoln \u0001", "\u0002 Hirohito"]
        s.homepage = "http://a.example.com/\u0003"
      end

      fetcher.legacy_platform
    end

    @cmd.handle_options %w[-r -d]

    use_ui @ui do
      @cmd.execute
    end

    expected = <<-EOF

*** REMOTE GEMS ***

a (2)
    Authors: Abraham Lincoln ., . Hirohito
    Homepage: http://a.example.com/.

    This is a lot of text. This is a lot of text. This is a lot of text.
    This is a lot of text.

pl (1)
    Platform: i386-linux
    Author: A User
    Homepage: http://example.com

    this is a summary
    EOF

    assert_equal expected, @ui.output
    assert_equal '', @ui.error
  end
//  [ruby]
  def self.get_using_size(mail_account_id, add_con=nil)

    SqlHelper.validate_token([mail_account_id])

    con = []
    con << "(mail_account_id=#{mail_account_id.to_i})"
    con << "(#{add_con})" unless add_con.nil? or add_con.empty?

    return (Email.count_by_sql("select SUM(size) from emails where #{con.join(' and ')}") || 0)
  end
//  [ruby]
  def self.get_using_size(mail_account_id, add_con=nil)

    SqlHelper.validate_token([mail_account_id])

    con = []
    con << "(mail_account_id=#{mail_account_id})"
    con << "(#{add_con})" unless add_con.nil? or add_con.empty?

    return (Email.count_by_sql("select SUM(size) from emails where #{con.join(' and ')}") || 0)
  end
//  [ruby]
  def self.get_default_for(user_id, xtype=nil)

    SqlHelper.validate_token([user_id, xtype])

    con = []
    con << "(user_id=#{user_id.to_i})"
    con << '(is_default=1)'
    con << "(xtype='#{xtype}')" unless xtype.blank?

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

    mail_accounts = MailAccount.find_by_sql('select * from mail_accounts ' + where + ' order by xorder ASC, title ASC')

    if mail_accounts.nil? or mail_accounts.empty?
      return nil
    else
      return mail_accounts.first
    end
  end
//  [python]
def edit_user(user_id):
    content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()  # type: ub.User
    if not content or (not config.config_anonbrowse and content.name == "Guest"):
        flash(_(u"User not found"), category="error")
        return redirect(url_for('admin.admin'))
    languages = calibre_db.speaking_language(return_all_languages=True)
    translations = babel.list_translations() + [Locale('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if request.method == "POST":
        to_save = request.form.to_dict()
        resp = _handle_edit_user(to_save, content, languages, translations, kobo_support)
        if resp:
            return resp
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 languages=languages,
                                 new_user=0,
                                 content=content,
                                 config=config,
                                 registered_oauth=oauth_check,
                                 mail_configured=config.get_mail_server_configured(),
                                 kobo_support=kobo_support,
                                 title=_(u"Edit User %(nick)s", nick=content.name),
                                 page="edituser")
//  [python]
def edit_user(user_id):
    content = ub.session.query(ub.User).filter(ub.User.id == int(user_id)).first()  # type: ub.User
    if not content or (not config.config_anonbrowse and content.name == "Guest"):
        flash(_(u"User not found"), category="error")
        return redirect(url_for('admin.admin'))
    languages = calibre_db.speaking_language(return_all_languages=True)
    translations = babel.list_translations() + [LC('en')]
    kobo_support = feature_support['kobo'] and config.config_kobo_sync
    if request.method == "POST":
        to_save = request.form.to_dict()
        resp = _handle_edit_user(to_save, content, languages, translations, kobo_support)
        if resp:
            return resp
    return render_title_template("user_edit.html",
                                 translations=translations,
                                 languages=languages,
                                 new_user=0,
                                 content=content,
                                 config=config,
                                 registered_oauth=oauth_check,
                                 mail_configured=config.get_mail_server_configured(),
                                 kobo_support=kobo_support,
                                 title=_(u"Edit User %(nick)s", nick=content.name),
                                 page="edituser")