jiahuimbzuai/CoQuIR huggingface dataset:
//  [ruby]
  def group
    Log.add_info(request, params.inspect)

    date_s = params[:date]

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

    if params[:display] == 'mine'
      redirect_to(:action => 'month')
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last
      SqlHelper.validate_token([display_id])

      @selected_users = Group.get_users(display_id)
      @group_id = display_id

      if !@login_user.get_groups_a.include?(@group_id.to_s) and !@login_user.admin?(User::AUTH_TIMECARD)
        Log.add_check(request, '[User.get_groups_a.include?]'+request.to_s)
        redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
        return
      end
    end
  end
//  [ruby]
  def group
    Log.add_info(request, params.inspect)

    date_s = params[:date]

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

    if params[:display] == 'mine'
      redirect_to(:action => 'month')
    else
      display_type = params[:display].split('_').first
      display_id = params[:display].split('_').last

      @selected_users = Group.get_users(display_id)
      @group_id = display_id

      if !@login_user.get_groups_a.include?(@group_id.to_s) and !@login_user.admin?(User::AUTH_TIMECARD)
        Log.add_check(request, '[User.get_groups_a.include?]'+request.to_s)
        redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
        return
      end
    end
  end
//  [ruby]
  def month
    if params[:action] == 'month'
      Log.add_info(request, params.inspect)
    end

    if !params[:display].nil? and params[:display].split('_').first == 'group'
      @group_id = params[:display].split('_').last
    end

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

      if @selected_user.id != @login_user.id and !@login_user.admin?(User::AUTH_TIMECARD)
        if (@selected_user.get_groups_a & @login_user.get_groups_a).empty?
          Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
          redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
          return
        end
      end
    end

    year_begins_from, month_begins_at = TimecardsHelper.get_fiscal_params

    date_s = params[:date]

    if date_s.blank?
      date = Date.today
    else
      date_params = date_s.split('-')
      if date_params.length == 2
        @year = date_params.first.to_i
        @month = date_params.last.to_i
        date = TimecardsHelper.get_first_day_in_fiscal_month(@year, @month, month_begins_at)
      else
        date = Date.parse(date_s)
      end
    end

    @fiscal_year = TimecardsHelper.get_fiscal_year(date, year_begins_from, month_begins_at)
    fiscal_month = TimecardsHelper.get_fiscal_month(date, month_begins_at)

    if @year.nil? or @month.nil?
      @month = fiscal_month

      if fiscal_month < date.month and fiscal_month == 1
        @year = date.year + 1
      elsif fiscal_month > date.month and fiscal_month == 12
        @year = date.year - 1
      else
        @year = date.year
      end
    end

    @start_date, @end_date = TimecardsHelper.get_month_span(date, month_begins_at)

    @timecards = Timecard.find_term(@selected_user.id, @start_date, @end_date)

    @paid_holiday = PaidHoliday.get_for(@selected_user.id, @fiscal_year)

    year_start, year_end = TimecardsHelper.get_year_span(@fiscal_year, year_begins_from, month_begins_at)
    @applied_paid_hlds = Timecard.applied_paid_hlds(@selected_user.id, year_start, @start_date - 1)
  end
//  [ruby]
  def month
    if params[:action] == 'month'
      Log.add_info(request, params.inspect)
    end

    if !params[:display].nil? and params[:display].split('_').first == 'group'
      @group_id = params[:display].split('_').last
    end

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

      if @selected_user.id != @login_user.id and !@login_user.admin?(User::AUTH_TIMECARD)
        if (@selected_user.get_groups_a & @login_user.get_groups_a).empty?
          Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
          redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
          return
        end
      end
    end

    year_begins_from, month_begins_at = TimecardsHelper.get_fiscal_params

    date_s = params[:date]

    if date_s.nil? or date_s.empty?
      date = Date.today
    else
      date_params = date_s.split('-')
      if date_params.length == 2
        @year = date_params.first.to_i
        @month = date_params.last.to_i
        date = TimecardsHelper.get_first_day_in_fiscal_month(@year, @month, month_begins_at)
      else
        date = Date.parse date_s
      end
    end

    @fiscal_year = TimecardsHelper.get_fiscal_year(date, year_begins_from, month_begins_at)
    fiscal_month = TimecardsHelper.get_fiscal_month(date, month_begins_at)

    if @year.nil? or @month.nil?
      @month = fiscal_month

      if fiscal_month < date.month and fiscal_month == 1
        @year = date.year + 1
      elsif fiscal_month > date.month and fiscal_month == 12
        @year = date.year - 1
      else
        @year = date.year
      end
    end

    @start_date, @end_date = TimecardsHelper.get_month_span(date, month_begins_at)

    @timecards = Timecard.find_term(@selected_user.id, @start_date, @end_date)

    @paid_holiday = PaidHoliday.get_for(@selected_user.id, @fiscal_year)

    year_start, year_end = TimecardsHelper.get_year_span(@fiscal_year, year_begins_from, month_begins_at)
    @applied_paid_hlds = Timecard.applied_paid_hlds(@selected_user.id, year_start, @start_date - 1)
  end
//  [ruby]
      def process_cors(env, path)
        resource, error = match_resource(path, env)
        if resource
          Result.hit(env)
          cors = resource.to_headers(env)
          cors

        else
          Result.miss(env, error)
          nil
        end
      end
//  [ruby]
      def process_cors(env)
        resource, error = match_resource(env)
        if resource
          Result.hit(env)
          cors = resource.to_headers(env)
          cors

        else
          Result.miss(env, error)
          nil
        end
      end
//  [ruby]
    it 'is possible to return hash errors in jsonapi format' do
      get '/'
      expect(['{&quot;error&quot;:&quot;rain!&quot;,&quot;detail&quot;:&quot;missing widget&quot;}',
              '{&quot;detail&quot;:&quot;missing widget&quot;,&quot;error&quot;:&quot;rain!&quot;}']).to include(last_response.body)
    end
//  [ruby]
    it 'is possible to return hash errors in jsonapi format' do
      get '/'
      expect(['{"error":"rain!","detail":"missing widget"}',
              '{"detail":"missing widget","error":"rain!"}']).to include(last_response.body)
    end
//  [ruby]
    def within_bounding_box(sw_lat, sw_lng, ne_lat, ne_lng, lat_attr, lon_attr)
      spans = "#{lat_attr} BETWEEN #{sw_lat.to_f} AND #{ne_lat.to_f} AND "
      # handle box that spans 180 longitude
      if sw_lng.to_f > ne_lng.to_f
        spans + "(#{lon_attr} BETWEEN #{sw_lng.to_f} AND 180 OR " +
        "#{lon_attr} BETWEEN -180 AND #{ne_lng.to_f})"
      else
        spans + "#{lon_attr} BETWEEN #{sw_lng.to_f} AND #{ne_lng.to_f}"
      end
    end
//  [ruby]
    def within_bounding_box(sw_lat, sw_lng, ne_lat, ne_lng, lat_attr, lon_attr)
      spans = "#{lat_attr} BETWEEN #{sw_lat} AND #{ne_lat} AND "
      # handle box that spans 180 longitude
      if sw_lng.to_f > ne_lng.to_f
        spans + "(#{lon_attr} BETWEEN #{sw_lng} AND 180 OR " +
        "#{lon_attr} BETWEEN -180 AND #{ne_lng})"
      else
        spans + "#{lon_attr} BETWEEN #{sw_lng} AND #{ne_lng}"
      end
    end
//  [ruby]
    it 'is possible to return errors in jsonapi format' do
      get '/'
      expect(last_response.body).to eq('{&quot;error&quot;:&quot;rain!&quot;}')
    end
//  [ruby]
    it 'is possible to return errors in jsonapi format' do
      get '/'
      expect(last_response.body).to eq('{"error":"rain!"}')
    end
//  [ruby]
  def self.get_for_group(group_id, incl_img_content=false)

    SqlHelper.validate_token([group_id])

    if group_id.nil?
      office_map = nil
    else
      if incl_img_content
        office_map = OfficeMap.where("group_id=#{group_id.to_i}").first
      else
        sql = 'select id, group_id, img_enabled, img_name, img_size, img_content_type, created_at, updated_at from office_maps'
        sql << " where group_id=#{group_id.to_i}"
        begin
          office_map = OfficeMap.find_by_sql(sql).first
        rescue
        end
      end
    end

    if office_map.nil?
      office_map = OfficeMap.new
      office_map.group_id = group_id.to_i unless group_id.nil?
      office_map.img_enabled = false
    end

    return office_map
  end
//  [ruby]
  def self.get_for_group(group_id, incl_img_content=false)

    SqlHelper.validate_token([group_id])

    if group_id.nil?
      office_map = nil
    else
      if incl_img_content
        office_map = OfficeMap.where("group_id=#{group_id}").first
      else
        sql = 'select id, group_id, img_enabled, img_name, img_size, img_content_type, created_at, updated_at from office_maps'
        sql << " where group_id=#{group_id}"
        begin
          office_map = OfficeMap.find_by_sql(sql).first
        rescue
        end
      end
    end

    if office_map.nil?
      office_map = OfficeMap.new
      office_map.group_id = group_id.to_i unless group_id.nil?
      office_map.img_enabled = false
    end

    return office_map
  end
//  [ruby]
  def update
    Log.add_info(request, params.inspect)

    return unless request.post?

    if params[:id].blank?
      @timecard = Timecard.new
    else
      @timecard = Timecard.find(params[:id])
    end

    options = params[:timecard]['options']
    if options.nil?
      params[:timecard]['options'] = nil
    else
      params[:timecard]['options'] = '|' + options.join('|') + '|'
    end

    if params[:user_id].blank?
      @selected_user = @login_user
    elsif (@login_user.id.to_s == params[:user_id])
      @selected_user = @login_user
    else
      unless @login_user.admin?(User::AUTH_TIMECARD)
        Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
        redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
        return
      end

      @selected_user = User.find(params[:user_id])
    end

    if Timecard.off?(params[:timecard]['workcode'])
      params[:timecard]['start'] = nil
      params[:timecard]['end'] = nil
      params[:timecard]['options'] = nil
    else

      breaks = @timecard.get_breaks_a
      unless breaks.empty?
        check_error = false

        unless params[:timecard]['start'].blank?
          start_t = UtilDateTime.parse(params[:timecard]['start']).to_time
          check_error = true if breaks.first.first < start_t
        end

        unless params[:timecard]['end'].blank?
          end_t = UtilDateTime.parse(params[:timecard]['end']).to_time
          check_error = true if end_t < breaks.last.last
        end

        if check_error
          flash[:notice] = 'ERROR:' + t('timecard.break_out_of_labor')
          render(:partial => 'ajax_update_break', :layout => false)
          return
        end
      end
    end

    if (@login_user.id.to_s != params[:timecard][:user_id] and !@login_user.admin?(User::AUTH_TIMECARD)) \
        or (!@timecard.user_id.nil? and @timecard.user_id.to_s != params[:timecard][:user_id])
      Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
      redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
      return
    end

    if @timecard.update_attributes(params.require(:timecard).permit(Timecard::PERMIT_BASE))

      if @timecard.off? and !@timecard.get_breaks_a.empty?
        @timecard.update_breaks(nil)
      end

      flash[:notice] = t('msg.update_success')

      unless @timecard.start.nil? or @timecard.end.nil?
        @timecard.set_default_breaks
      end
    end
//  [ruby]
  def update
    Log.add_info(request, params.inspect)

    if params[:id].nil? or params[:id].empty?
      @timecard = Timecard.new
    else
      @timecard = Timecard.find(params[:id])
    end

    options = params[:timecard]['options']
    if options.nil?
      params[:timecard]['options'] = nil
    else
      params[:timecard]['options'] = '|' + options.join('|') + '|'
    end

    if params[:user_id].nil? or params[:user_id].empty?
      @selected_user = @login_user
    elsif @login_user.id.to_s == params[:user_id]
      @selected_user = @login_user
    else
      unless @login_user.admin?(User::AUTH_TIMECARD)
        Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
        redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
        return
      end

      @selected_user = User.find(params[:user_id])
    end

    if Timecard.off?(params[:timecard]['workcode'])
      params[:timecard]['start'] = nil
      params[:timecard]['end'] = nil
      params[:timecard]['options'] = nil
    else

      breaks = @timecard.get_breaks_a
      unless breaks.empty?
        check_error = false

        unless params[:timecard]['start'].nil? or params[:timecard]['start'].empty?
          start_t = UtilDateTime.parse(params[:timecard]['start']).to_time
          check_error = true if breaks.first.first < start_t
        end

        unless params[:timecard]['end'].nil? or params[:timecard]['end'].empty?
          end_t = UtilDateTime.parse(params[:timecard]['end']).to_time
          check_error = true if end_t < breaks.last.last
        end

        if check_error
          flash[:notice] = 'ERROR:' + t('timecard.break_out_of_labor')
          render(:partial => 'ajax_update_break', :layout => false)
          return
        end
      end
    end

    if (@login_user.id.to_s != params[:timecard][:user_id] and !@login_user.admin?(User::AUTH_TIMECARD)) \
        or (!@timecard.user_id.nil? and @timecard.user_id.to_s != params[:timecard][:user_id])
      Log.add_check(request, '[User::AUTH_TIMECARD]'+request.to_s)
      redirect_to(:controller => 'frames', :action => 'http_error', :id => '401')
      return
    end

    if @timecard.update_attributes(params.require(:timecard).permit(Timecard::PERMIT_BASE))

      if @timecard.off? and !@timecard.get_breaks_a.empty?
        @timecard.update_breaks(nil)
      end

      flash[:notice] = t('msg.update_success')

      unless @timecard.start.nil? or @timecard.end.nil?
        @timecard.set_default_breaks
      end
    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.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.expand_path destination

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

    destination.untaint
    destination
  end
//  [ruby]
    def remove
      session.with(consistency: :strong) do |session|
        session.context.remove operation.database,
          operation.collection,
          operation.selector,
          flags: [:remove_first]
      end
    end
//  [ruby]
    def remove
      delete = Protocol::Delete.new(
        operation.database,
        operation.collection,
        operation.selector,
        flags: [:remove_first]
      )

      session.with(consistency: :strong) do |session|
        session.execute delete
      end
    end
//  [ruby]
    it 'is possible to specify a custom formatter' do
      get '/'
      expect(last_response.body).to eq('{:custom_formatter=&gt;&quot;rain!&quot;}')
    end
//  [ruby]
    it 'is possible to specify a custom formatter' do
      get '/'
      expect(last_response.body).to eq('{:custom_formatter=>"rain!"}')
    end
//  [ruby]
    def each
      cursor = Cursor.new(session, operation)
      cursor.to_enum.tap do |enum|
        enum.each do |document|
          yield document
        end if block_given?
      end
    end
//  [ruby]
    def each
      cursor = Cursor.new(session.with(retain_socket: true), operation)
      cursor.to_enum.tap do |enum|
        enum.each do |document|
          yield document
        end if block_given?
      end
    end
//  [ruby]
    def update(change, flags = nil)
      session.with(consistency: :strong) do |session|
        session.context.update operation.database,
          operation.collection,
          operation.selector,
          change,
          flags: flags
      end
    end
//  [ruby]
    def update(change, flags = nil)
      update = Protocol::Update.new(
        operation.database,
        operation.collection,
        operation.selector,
        change,
        flags: flags
      )

      session.with(consistency: :strong) do |session|
        session.execute update
      end
    end
//  [ruby]
    def first
      limit(-1).each.first
    end
//  [ruby]
    def first
      session.simple_query(operation)
    end
//  [ruby]
    def remove_all
      session.with(consistency: :strong) do |session|
        session.context.remove operation.database,
          operation.collection,
          operation.selector
      end
    end
//  [ruby]
    def remove_all
      delete = Protocol::Delete.new(
        operation.database,
        operation.collection,
        operation.selector
      )

      session.with(consistency: :strong) do |session|
        session.execute delete
      end
    end
//  [ruby]
    def include_allowed?(target, reader)
      doc = reader.document

      return false if doc.safe >= ::Asciidoctor::SafeMode::SECURE
      return false if doc.attributes.fetch('max-include-depth', 64).to_i < 1
      return false if target_http?(target) && !doc.attributes.key?('allow-uri-read')
      true
    end
//  [ruby]
    def include_allowed?(target, reader)
      doc = reader.document

      return false if doc.safe >= ::Asciidoctor::SafeMode::SECURE
      return false if doc.attributes.fetch('max-include-depth', 64).to_i < 1
      return false if target_uri?(target) && !doc.attributes.key?('allow-uri-read')
      true
    end
//  [ruby]
      def parse(parent, line, pos, content, strict=true)
        if content !~ /^<\S/
          Text.new(parent, line, pos, content)
        else
          scanner = StringScanner.new(content)

          unless scanner.skip(/</)
            if strict
              raise "expected <"
            else
              return Text.new(parent, line, pos, content)
            end
          end

          if scanner.skip(/!\[CDATA\[/)
            unless scanner.skip_until(/\]\]>/)
              if strict
                raise "expected ]]> (got #{scanner.rest.inspect} for #{content})"
              else
                scanner.skip_until(/\Z/)
              end
            end

            return CDATA.new(parent, line, pos, scanner.pre_match.gsub(/<!\[CDATA\[/, ''))
          end

          closing = ( scanner.scan(/\//) ? :close : nil )
          return Text.new(parent, line, pos, content) unless name = scanner.scan(/[^\s!>\/]+/)
          name.downcase!

          unless closing
            scanner.skip(/\s*/)
            attributes = {}
            while attr = scanner.scan(/[-\w:]+/)
              value = true
              if scanner.scan(/\s*=\s*/)
                if delim = scanner.scan(/['"]/)
                  value = ""
                  while text = scanner.scan(/[^#{delim}\\]+|./)
                    case text
                      when "\\" then
                        value << text
                        break if scanner.eos?
                        value << scanner.getch
                      when delim
                        break
                      else value << text
                    end
                  end
                else
                  value = scanner.scan(/[^\s>\/]+/)
                end
              end
              attributes[attr.downcase] = value
              scanner.skip(/\s*/)
            end

            closing = ( scanner.scan(/\//) ? :self : nil )
          end

          unless scanner.scan(/\s*>/)
            if strict
              raise "expected > (got #{scanner.rest.inspect} for #{content}, #{attributes.inspect})"
            else
              # throw away all text until we find what we're looking for
              scanner.skip_until(/>/) or scanner.terminate
            end
          end

          Tag.new(parent, line, pos, name, attributes, closing)
        end
//  [ruby]
      def parse(parent, line, pos, content, strict=true)
        if content !~ /^<\S/
          Text.new(parent, line, pos, content)
        else
          scanner = StringScanner.new(content)

          unless scanner.skip(/</)
            if strict
              raise "expected <"
            else
              return Text.new(parent, line, pos, content)
            end
          end

          if scanner.skip(/!\[CDATA\[/)
            unless scanner.skip_until(/\]\]>/)
              if strict
                raise "expected ]]> (got #{scanner.rest.inspect} for #{content})"
              else
                scanner.skip_until(/\Z/)
              end
            end

            return CDATA.new(parent, line, pos, scanner.pre_match.gsub(/<!\[CDATA\[/, ''))
          end

          closing = ( scanner.scan(/\//) ? :close : nil )
          return Text.new(parent, line, pos, content) unless name = scanner.scan(/[\w:-]+/)
          name.downcase!

          unless closing
            scanner.skip(/\s*/)
            attributes = {}
            while attr = scanner.scan(/[-\w:]+/)
              value = true
              if scanner.scan(/\s*=\s*/)
                if delim = scanner.scan(/['"]/)
                  value = ""
                  while text = scanner.scan(/[^#{delim}\\]+|./)
                    case text
                      when "\\" then
                        value << text
                        break if scanner.eos?
                        value << scanner.getch
                      when delim
                        break
                      else value << text
                    end
                  end
                else
                  value = scanner.scan(/[^\s>\/]+/)
                end
              end
              attributes[attr.downcase] = value
              scanner.skip(/\s*/)
            end

            closing = ( scanner.scan(/\//) ? :self : nil )
          end

          unless scanner.scan(/\s*>/)
            if strict
              raise "expected > (got #{scanner.rest.inspect} for #{content}, #{attributes.inspect})"
            else
              # throw away all text until we find what we're looking for
              scanner.skip_until(/>/) or scanner.terminate
            end
          end

          Tag.new(parent, line, pos, name, attributes, closing)
        end
//  [ruby]
    def read_lines(path, selector)
      if selector
        IO.foreach(path).select.with_index(1, &selector)
      else
        URI.open(path, &:read)
      end
    end
//  [ruby]
    def read_lines(filename, selector)
      if selector
        IO.foreach(filename).select.with_index(1, &selector)
      else
        URI.open(filename, &:read)
      end
    end
//  [ruby]
    def resolve_target_path(target, reader)
      return target if target_http? target

      # Include file is resolved relative to dir of the current include,
      # or base_dir if within original docfile.
      path = reader.document.normalize_system_path(target, reader.dir, nil,
                                                   target_name: 'include file')
      path if ::File.file?(path)
    end
//  [ruby]
    def resolve_target_path(target, reader)
      return target if target_uri? target

      # Include file is resolved relative to dir of the current include,
      # or base_dir if within original docfile.
      path = reader.document.normalize_system_path(target, reader.dir, nil,
                                                   target_name: 'include file')
      path if ::File.file?(path)
    end
//  [ruby]
  def destroy
    Log.add_info(request, params.inspect)

    return unless request.post?

    begin
      OfficialTitle.destroy(params[:id])
    rescue => evar
      Log.add_error(nil, evar)
    end

    @group_id = params[:group_id]
    SqlHelper.validate_token([@group_id])

    if @group_id.blank?
      @group_id = '0'   # '0' for ROOT
    end

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

    begin
      OfficialTitle.destroy(params[:id])
    rescue => evar
      Log.add_error(nil, evar)
    end

    @group_id = params[:group_id]

    if @group_id.nil? or @group_id.empty?
      @group_id = '0'   # '0' for ROOT
    end

    render(:partial => 'groups/ajax_group_official_titles', :layout => false)
  end
//  [ruby]
  def index
    respond_to do |format|
      format.json do
        dir = params[:dir]
        dir = 'DESC' unless SORT_DIRECTIONS.include?(dir.try(:upcase))

        @occurrences = @bug.occurrences.order("occurred_at #{dir}").limit(50)

        last = params[:last].present? ? @bug.occurrences.find_by_number(params[:last]) : nil
        @occurrences = @occurrences.where(infinite_scroll_clause('occurred_at', dir, last, 'occurrences.number')) if last

        render json: decorate(@occurrences)
      end
      format.atom { @occurrences = @bug.occurrences.order('occurred_at DESC').limit(100) } # index.atom.builder
    end
  end
//  [ruby]
  def index
    respond_to do |format|
      format.json do
        dir = params[:dir]
        dir = 'desc' unless SORT_DIRECTIONS.include?(dir.try(:upcase))

        @occurrences = @bug.occurrences.order("occurred_at #{dir}").limit(50)

        last = params[:last].present? ? @bug.occurrences.find_by_number(params[:last]) : nil
        @occurrences = @occurrences.where(infinite_scroll_clause('occurred_at', dir, last, 'occurrences.number')) if last

        render json: decorate(@occurrences)
      end
      format.atom { @occurrences = @bug.occurrences.order('occurred_at DESC').limit(100) } # index.atom.builder
    end
  end
//  [ruby]
  def show
    Log.add_info(request, params.inspect)

    @group_id = params[:group_id]
    official_title_id = params[:id]
    SqlHelper.validate_token([@group_id, official_title_id])

    unless official_title_id.blank?
      @official_title = OfficialTitle.find(official_title_id)
    end

    render(:layout => (!request.xhr?))
  end
//  [ruby]
  def show
    Log.add_info(request, params.inspect)

    @group_id = params[:group_id]
    official_title_id = params[:id]

    unless official_title_id.nil? or official_title_id.empty?
      @official_title = OfficialTitle.find(official_title_id)
    end

    render(:layout => (!request.xhr?))
  end
//  [ruby]
  def self.validate_token(tokens, extra_chars=nil)

    extra_chars ||= []
    regexp = Regexp.new("^\s*[a-zA-Z0-9_.#{extra_chars.join()}]+\s*$")

    [tokens].flatten.each do |token|
      next if token.blank?

      if token.to_s.match(regexp).nil?
        raise("[ERROR] SqlHelper.validate_token failed: #{token}")
      end
    end
  end
//  [ruby]
  def update_config
    Log.add_info(request, params.inspect)

    return unless request.post?

    yaml = ApplicationHelper.get_config_yaml

    unless params[:timecard].blank?
      yaml[:timecard] = Hash.new if yaml[:timecard].nil?
      
      params[:timecard].each do |key, val|
        yaml[:timecard][key] = val
      end
      ApplicationHelper.save_config_yaml(yaml)
    end

    @yaml_timecard = yaml[:timecard]
    @yaml_timecard = Hash.new if @yaml_timecard.nil?

    flash[:notice] = t('msg.update_success')
    render(:action => 'configure')
  end
//  [ruby]
  def update_config
    Log.add_info(request, params.inspect)

    yaml = ApplicationHelper.get_config_yaml

    unless params[:timecard].nil? or params[:timecard].empty?
      yaml[:timecard] = Hash.new if yaml[:timecard].nil?
      
      params[:timecard].each do |key, val|
        yaml[:timecard][key] = val
      end
      ApplicationHelper.save_config_yaml(yaml)
    end

    @yaml_timecard = yaml[:timecard]
    @yaml_timecard = Hash.new if @yaml_timecard.nil?

    flash[:notice] = t('msg.update_success')
    render(:action => 'configure')
  end
//  [ruby]
      it "fails when user is suspended" do
        user.update!(
          suspended_till: 2.days.from_now,
          suspended_at: Time.zone.now
        )

        post "/session/email-login/#{email_token.token}.json"

        expect(response.status).to eq(200)

        expect(JSON.parse(response.body)["error"]).to eq(
          I18n.t("login.suspended", date: I18n.l(user.suspended_till, format: :date_only)
        ))
        expect(session[:current_user_id]).to eq(nil)
      end
//  [ruby]
      it "fails when user is suspended" do
        user.update!(
          suspended_till: 2.days.from_now,
          suspended_at: Time.zone.now
        )

        get "/session/email-login/#{email_token.token}"

        expect(response.status).to eq(200)

        expect(CGI.unescapeHTML(response.body)).to include(I18n.t("login.suspended",
          date: I18n.l(user.suspended_till, format: :date_only)
        ))
      end
//  [ruby]
  def edit
    Log.add_info(request, params.inspect)

    @group_id = params[:group_id]
    official_title_id = params[:id]
    SqlHelper.validate_token([@group_id, official_title_id])

    unless official_title_id.blank?
      @official_title = OfficialTitle.find(official_title_id)
    end

    render(:partial => 'ajax_official_title_form', :layout => (!request.xhr?))
  end
//  [ruby]
  def edit
    Log.add_info(request, params.inspect)

    @group_id = params[:group_id]
    official_title_id = params[:id]

    unless official_title_id.nil? or official_title_id.empty?
      @official_title = OfficialTitle.find(official_title_id)
    end

    render(:partial => 'ajax_official_title_form', :layout => (!request.xhr?))
  end
//  [ruby]
      it "doesn't log in the user when not approved" do
        SiteSetting.must_approve_users = true

        post "/session/email-login/#{email_token.token}.json"

        expect(response.status).to eq(200)

        expect(JSON.parse(response.body)["error"]).to eq(I18n.t("login.not_approved"))
        expect(session[:current_user_id]).to eq(nil)
      end
//  [ruby]
      it "doesn't log in the user when not approved" do
        SiteSetting.must_approve_users = true

        get "/session/email-login/#{email_token.token}"

        expect(response.status).to eq(200)

        expect(CGI.unescapeHTML(response.body)).to include(
          I18n.t("login.not_approved")
        )
      end
//  [ruby]
  def self.get_from_name(user_name)

    SqlHelper.validate_token([user_name])

    begin
      user = User.where(name: user_name).first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return user
  end
//  [ruby]
  def self.get_from_name(user_name)

    SqlHelper.validate_token([user_name])

    begin
      user = User.where("name='#{user_name}'").first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return user
  end
//  [ruby]
            it 'does not log in with incorrect backup code' do
              post "/session/email-login/#{email_token.token}.json", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:backup_codes]
              }

              expect(response.status).to eq(200)
              expect(JSON.parse(response.body)["error"]).to eq(
                I18n.t("login.invalid_second_factor_code")
              )
              expect(session[:current_user_id]).to eq(nil)
            end
//  [ruby]
            it 'does not log in with incorrect backup code' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:backup_codes]
              }

              expect(response.status).to eq(200)
              expect(CGI.unescapeHTML(response.body)).to include(I18n.t(
                "login.invalid_second_factor_code"
              ))
            end
//  [ruby]
      it 'returns success' do
        post "/session/email-login/#{email_token.token}.json"

        expect(JSON.parse(response.body)["success"]).to eq("OK")
        expect(session[:current_user_id]).to eq(user.id)
      end
//  [ruby]
      it 'returns success' do
        get "/session/email-login/#{email_token.token}"

        expect(response).to redirect_to("/")
      end
//  [ruby]
      it 'fails when local logins is disabled' do
        SiteSetting.enable_local_logins = false

        get "/session/email-login/#{email_token.token}.json"

        expect(response.status).to eq(500)
      end
//  [ruby]
      it 'fails when local logins is disabled' do
        SiteSetting.enable_local_logins = false

        get "/session/email-login/#{email_token.token}"

        expect(response.status).to eq(500)
      end
//  [ruby]
      it 'fails when local logins via email is disabled' do
        SiteSetting.enable_local_logins_via_email = false

        get "/session/email-login/#{email_token.token}.json"

        expect(response.status).to eq(404)
      end
//  [ruby]
      it 'fails when local logins via email is disabled' do
        SiteSetting.enable_local_logins_via_email = false

        get "/session/email-login/#{email_token.token}"

        expect(response.status).to eq(404)
      end
//  [ruby]
            it 'does not log in with incorrect two factor' do
              post "/session/email-login/#{email_token.token}.json", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(response.status).to eq(200)

              expect(JSON.parse(response.body)["error"]).to eq(
                I18n.t("login.invalid_second_factor_code")
              )
              expect(session[:current_user_id]).to eq(nil)
            end
//  [ruby]
            it 'does not log in with incorrect two factor' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: "0000",
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(response.status).to eq(200)

              expect(CGI.unescapeHTML(response.body)).to include(I18n.t(
                "login.invalid_second_factor_code"
              ))
            end
//  [ruby]
      it 'returns the right response' do
        post "/session/email-login"
        expect(response.status).to eq(404)
      end
//  [ruby]
      it 'returns the right response' do
        get "/session/email-login/adasdad"

        expect(response.status).to eq(200)

        expect(CGI.unescapeHTML(response.body)).to match(
          I18n.t('email_login.invalid_token')
        )
      end
//  [ruby]
            it 'logs in correctly' do
              post "/session/email-login/#{email_token.token}.json", params: {
                second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(JSON.parse(response.body)["success"]).to eq("OK")
              expect(session[:current_user_id]).to eq(user.id)
            end
//  [ruby]
            it 'logs in correctly' do
              post "/session/email-login/#{email_token.token}", params: {
                second_factor_token: ROTP::TOTP.new(user_second_factor.data).now,
                second_factor_method: UserSecondFactor.methods[:totp]
              }

              expect(response).to redirect_to("/")
            end
//  [ruby]
        it 'should return the right response' do
          email_token.update!(created_at: 999.years.ago)

          post "/session/email-login/#{email_token.token}.json"

          expect(response.status).to eq(200)

          expect(JSON.parse(response.body)["error"]).to eq(
            I18n.t('email_login.invalid_token')
          )
        end
//  [ruby]
        it 'should return the right response' do
          email_token.update!(created_at: 999.years.ago)

          get "/session/email-login/#{email_token.token}"

          expect(response.status).to eq(200)

          expect(CGI.unescapeHTML(response.body)).to match(
            I18n.t('email_login.invalid_token')
          )
        end
//  [ruby]
  def self.on_desktop?(user, xtype, target_id)

    return false if user.nil? or xtype.nil? or target_id.nil?

    SqlHelper.validate_token([xtype, target_id])

    con = "(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id.to_i})"

    begin
      toy = Toy.where(con).first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return (!toy.nil?)
  end
//  [ruby]
  def self.on_desktop?(user, xtype, target_id)

    return false if user.nil? or xtype.nil? or target_id.nil?

    SqlHelper.validate_token([xtype, target_id])

    con = "(user_id=#{user.id}) and (xtype='#{xtype}') and (target_id=#{target_id})"

    begin
      toy = Toy.where(con).first
    rescue => evar
      Log.add_error(nil, evar)
    end

    return (!toy.nil?)
  end
//  [ruby]
    def filter_archived(list, user, archived: true)
      # Executing an extra query instead of a sub-query because it is more
      # efficient for the PG planner. Caution should be used when changing the
      # query here as it can easily lead to an inefficient query.
      group_ids = group_with_messages_ids(user)

      if group_ids.present?
        list = list.joins(<<~SQL)
          LEFT JOIN group_archived_messages gm
            ON gm.topic_id = topics.id
            AND gm.group_id IN (#{group_ids.join(",")})
          LEFT JOIN user_archived_messages um
            ON um.user_id = #{user.id.to_i}
            AND um.topic_id = topics.id
        SQL

        if archived
          list.where("um.user_id IS NOT NULL OR gm.topic_id IS NOT NULL")
        else
          list.where("um.user_id IS NULL AND gm.topic_id IS NULL")
        end
      else
        list = list.joins(<<~SQL)
          LEFT JOIN user_archived_messages um
          ON um.user_id = #{user.id.to_i}
          AND um.topic_id = topics.id
        SQL

        list.where("um.user_id IS #{archived ? "NOT NULL" : "NULL"}")
      end
    end
//  [ruby]
  def actions
    if params[:media_action] != 'crop_url'
      authorize! :manage, :media
    end
    params[:folder] = params[:folder].gsub("//", "/") if params[:folder].present?
    case params[:media_action]
      when "new_folder"
        params[:folder] = slugify_folder(params[:folder])
        render partial: "render_file_item", locals: {files: [cama_uploader.add_folder(params[:folder])]}
      when "del_folder"
        cama_uploader.delete_folder(params[:folder])
        render inline: ""
      when "del_file"
        cama_uploader.delete_file(params[:folder].gsub("//", "/"))
        render inline: ""
      when 'crop_url'
        unless params[:url].start_with?('data:')
          params[:url] = (params[:url].start_with?('http') ? '' : current_site.the_url(locale: nil)) + params[:url]
        end
        r = if local_url?(params[:url])
              { error: t("camaleon_cms.admin.media.local_upload_denied") }
            else
              cama_tmp_upload( params[:url], formats: params[:formats], name: params[:name])
            end
//  [ruby]
  def actions
    if params[:media_action] != 'crop_url'
      authorize! :manage, :media
    end
    params[:folder] = params[:folder].gsub("//", "/") if params[:folder].present?
    case params[:media_action]
      when "new_folder"
        params[:folder] = slugify_folder(params[:folder])
        render partial: "render_file_item", locals: {files: [cama_uploader.add_folder(params[:folder])]}
      when "del_folder"
        cama_uploader.delete_folder(params[:folder])
        render inline: ""
      when "del_file"
        cama_uploader.delete_file(params[:folder].gsub("//", "/"))
        render inline: ""
      when 'crop_url'
        unless params[:url].start_with?('data:')
          params[:url] = (params[:url].start_with?('http') ? '' : current_site.the_url(locale: nil)) + params[:url]
        end
        r = cama_tmp_upload( params[:url], formats: params[:formats], name: params[:name])
        unless r[:error].present?
          params[:file_upload] = r[:file_path]
          sett = {remove_source: true}
          sett[:same_name] = true if params[:same_name].present?
          sett[:name] = params[:name] if params[:name].present?
          upload(sett)
        else
          render inline: r[:error]
        end
    end
//  [ruby]
  def remove_application(user_ids)

    return if user_ids.nil? or user_ids.empty?

    SqlHelper.validate_token([user_ids])

    con = ["(xtype='#{Comment::XTYPE_APPLY}')"]
    con << "(item_id=#{self.item_id})"

    user_con_a = []
    user_ids.each do |user_id|
      user_con_a << "(user_id=#{user_id.to_i})"
    end

    con << '(' + user_con_a.join(' or ') + ')'

    Comment.destroy_all(con.join(' and '))
 end
//  [ruby]
  def remove_application(user_ids)

    return if user_ids.nil? or user_ids.empty?

    SqlHelper.validate_token([user_ids])

    con = ["(xtype='#{Comment::XTYPE_APPLY}')"]
    con << "(item_id=#{self.item_id})"

    user_con_a = []
    user_ids.each do |user_id|
      user_con_a << "(user_id=#{user_id})"
    end

    con << '(' + user_con_a.join(' or ') + ')'

    Comment.destroy_all(con.join(' and '))
 end
//  [ruby]
  def self.get_for(user_id, category=nil)

    SqlHelper.validate_token([user_id, category])

    con = []
    con << "(user_id=#{user_id.to_i})"
    con << "(category='#{category}')" unless category.nil?

    settings = Setting.where(con.join(' and ')).to_a

    return nil if settings.nil? or settings.empty?

    hash = Hash.new

    settings.each do |setting|
      hash[setting.xkey] = setting.xvalue
    end

    return hash
  end
//  [ruby]
  def self.get_for(user_id, category=nil)

    SqlHelper.validate_token([user_id, category])

    con = []
    con << "(user_id=#{user_id})"
    con << "(category='#{category}')" unless category.nil?

    settings = Setting.where(con.join(' and ')).to_a

    return nil if settings.nil? or settings.empty?

    hash = Hash.new

    settings.each do |setting|
      hash[setting.xkey] = setting.xvalue
    end

    return hash
  end
//  [ruby]
  def self.get_team_folder(team_id)

    SqlHelper.validate_token([team_id])
    begin
      return Folder.where("(owner_id=#{team_id.to_i}) and (xtype='#{Folder::XTYPE_TEAM}')").first
    rescue => evar
      Log.add_error(nil, evar)
      return nil
    end
  end
//  [ruby]
  def self.get_team_folder(team_id)

    SqlHelper.validate_token([team_id])
    begin
      return Folder.where("(owner_id=#{team_id}) and (xtype='#{Folder::XTYPE_TEAM}')").first
    rescue => evar
      Log.add_error(nil, evar)
      return nil
    end
  end
//  [ruby]
  def self.get_for_group(group_id, category=nil)

    SqlHelper.validate_token([group_id, category])

    con = []
    con << "(group_id=#{group_id.to_i})"
    con << "(category='#{category}')" unless category.nil?

    settings = Setting.where(con.join(' and ')).to_a

    return nil if settings.nil? or settings.empty?

    hash = Hash.new

    settings.each do |setting|
      hash[setting.xkey] = setting.xvalue
    end

    return hash
  end
//  [ruby]
  def self.get_for_group(group_id, category=nil)

    SqlHelper.validate_token([group_id, category])

    con = []
    con << "(group_id=#{group_id})"
    con << "(category='#{category}')" unless category.nil?

    settings = Setting.where(con.join(' and ')).to_a

    return nil if settings.nil? or settings.empty?

    hash = Hash.new

    settings.each do |setting|
      hash[setting.xkey] = setting.xvalue
    end

    return hash
  end
//  [ruby]
    def private_messages_for(user, type)
      options = @options
      options.reverse_merge!(per_page: per_page_setting)

      result = Topic.includes(:allowed_users)
      result = result.includes(:tags) if SiteSetting.tagging_enabled

      if type == :group
        result = result.joins(
          "INNER JOIN topic_allowed_groups tag ON tag.topic_id = topics.id AND tag.group_id IN (SELECT id FROM groups WHERE LOWER(name) = '#{PG::Connection.escape_string(@options[:group_name].downcase)}')"
        )

        unless user.admin?
          result = result.joins("INNER JOIN group_users gu ON gu.group_id = tag.group_id AND gu.user_id = #{user.id.to_i}")
        end
      elsif type == :user
        result = result.where("topics.id IN (SELECT topic_id FROM topic_allowed_users WHERE user_id = #{user.id.to_i})")
      elsif type == :all
        group_ids = group_with_messages_ids(user)

        result =
        if group_ids.present?
          result.where(<<~SQL)
            topics.id IN (
              SELECT topic_id
              FROM topic_allowed_users
              WHERE user_id = #{user.id.to_i}
              UNION ALL
              SELECT topic_id FROM topic_allowed_groups
              WHERE group_id IN (#{group_ids.join(",")})
            )
          SQL
        else
          result.joins(<<~SQL)
          INNER JOIN topic_allowed_users tau
            ON tau.topic_id = topics.id
            AND tau.user_id = #{user.id.to_i}
          SQL
        end
      end

      result = result.joins("LEFT OUTER JOIN topic_users AS tu ON (topics.id = tu.topic_id AND tu.user_id = #{user.id.to_i})")
        .order("topics.bumped_at DESC")
        .private_messages

      result = result.limit(options[:per_page]) unless options[:limit] == false
      result = result.visible if options[:visible] || @user.nil? || @user.regular?

      if options[:page]
        offset = options[:page].to_i * options[:per_page]
        result = result.offset(offset) if offset > 0
      end
      result
    end
//  [ruby]
  def self.get_value(user_id, category, key)

    SqlHelper.validate_token([user_id, category, key])

    con = []
    con << "(user_id=#{user_id.to_i})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end
//  [ruby]
  def self.get_value(user_id, category, key)

    SqlHelper.validate_token([user_id, category, key])

    con = []
    con << "(user_id=#{user_id})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end
//  [ruby]
  def self.get_group_value(group_id, category, key)

    SqlHelper.validate_token([group_id, category, key])

    con = []
    con << "(group_id=#{group_id.to_i})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end
//  [ruby]
  def self.get_group_value(group_id, category, key)

    SqlHelper.validate_token([group_id, category, key])

    con = []
    con << "(group_id=#{group_id})"
    con << "(category='#{category}')"
    con << "(xkey='#{key}')"

    setting = Setting.where(con.join(' and ')).first

    return setting.xvalue unless setting.nil?

    return nil
  end
//  [ruby]
      def quote_column_name(name) #:nodoc:
        %Q("#{name.to_s.gsub('"', '""')}")
//  [ruby]
      def quote_column_name(name) #:nodoc:
        %Q("#{name}")
      end