jiahuimbzuai/CoQuIR huggingface dataset:
// command_flags [ruby]
    def command_flags(options)
      options.flat_map do |key, value|
        next if key == 'execute'
        flag_options = self.class.percona_flags[key]

        # Satisfy version requirements
        if flag_options.try(:key?, :version)
          next unless Gem::Requirement.new(flag_options[:version]).satisfied_by? self.class.tool_version
        end

        # Mutate the value if needed
        if flag_options.try(:key?, :mutator)
          value = send(flag_options[:mutator], value, { all_options: options, flag_name: key }.merge(flag_options[:arguments] || {}))
          next if value.nil? # Allow a mutator to determine the flag shouldn't be used
        end

        # Handle boolean flags
        if flag_options.try(:[], :boolean)
          key = "no-#{key}" unless value
          value = nil
        end

        ["--#{key}", value]
      end.compact
    end
// command_flags [ruby]
    def command_flags(options)
      options.map do |key, value|
        next if key == 'execute'
        flag_options = self.class.percona_flags[key]

        # Satisfy version requirements
        if flag_options.try(:key?, :version)
          next unless Gem::Requirement.new(flag_options[:version]).satisfied_by? self.class.tool_version
        end

        # Mutate the value if needed
        if flag_options.try(:key?, :mutator)
          value = send(flag_options[:mutator], value, { all_options: options, flag_name: key }.merge(flag_options[:arguments] || {}))
          next if value.nil? # Allow a mutator to determine the flag shouldn't be used
        end

        # Handle boolean flags
        if flag_options.try(:[], :boolean)
          key = "no-#{key}" unless value
          value = nil
        end

        " --#{key} #{value}"
      end.join('')
    end
// read_plist [ruby]
    def read_plist(pathname)
      out, err, status = Open3.capture3('plutil', '-convert', 'json', '-o', '-', pathname)
      raise "#{out}\n\n#{err}" unless status.success?

      JSON.parse(out)
    end
// read_plist [ruby]
    def read_plist(pathname)
      transformed_pathname = pathname.gsub!(%r{[^0-9A-Za-z. \-'/]}, '')
      transformed_pathname = pathname if transformed_pathname.nil?
      JSON.parse(`plutil -convert json -o - '#{transformed_pathname}'`)
    end
// audit [ruby]
  def audit
    audit_args.parse

    Homebrew.auditing = true
    inject_dump_stats!(FormulaAuditor, /^audit_/) if args.audit_debug?

    formula_count = 0
    problem_count = 0
    corrected_problem_count = 0
    new_formula_problem_count = 0
    new_formula = args.new_formula?
    strict = new_formula || args.strict?
    online = new_formula || args.online?
    git = args.git?
    skip_style = args.skip_style? || args.no_named?

    ENV.activate_extensions!
    ENV.setup_build_environment

    audit_formulae = args.no_named? ? Formula : args.resolved_formulae
    style_files = args.formulae_paths unless skip_style

    only_cops = args.only_cops
    except_cops = args.except_cops
    options = { fix: args.fix? }

    if only_cops
      options[:only_cops] = only_cops
    elsif args.new_formula?
      nil
    elsif except_cops
      options[:except_cops] = except_cops
    elsif !strict
      options[:except_cops] = [:FormulaAuditStrict]
    end

    # Check style in a single batch run up front for performance
    style_results = Style.check_style_json(style_files, options) if style_files
    # load licenses
    spdx = HOMEBREW_LIBRARY_PATH/"data/spdx.json"
    spdx_data = File.open(spdx, "r") do |file|
      JSON.parse(file.read)
    end
    new_formula_problem_lines = []
    audit_formulae.sort.each do |f|
      only = only_cops ? ["style"] : args.only
      options = {
        new_formula: new_formula,
        strict:      strict,
        online:      online,
        git:         git,
        only:        only,
        except:      args.except,
        spdx_data:   spdx_data,
      }
      options[:style_offenses] = style_results.file_offenses(f.path) if style_results
      options[:display_cop_names] = args.display_cop_names?

      fa = FormulaAuditor.new(f, options)
      fa.audit
      next if fa.problems.empty? && fa.new_formula_problems.empty?

      fa.problems
      formula_count += 1
      problem_count += fa.problems.size
      problem_lines = format_problem_lines(fa.problems)
      corrected_problem_count = options[:style_offenses].count(&:corrected?) if options[:style_offenses]
      new_formula_problem_lines = format_problem_lines(fa.new_formula_problems)
      if args.display_filename?
        puts problem_lines.map { |s| "#{f.path}: #{s}" }
      else
        puts "#{f.full_name}:", problem_lines.map { |s| "  #{s}" }
      end
// audit [ruby]
  def audit
    audit_args.parse

    Homebrew.auditing = true
    inject_dump_stats!(FormulaAuditor, /^audit_/) if args.audit_debug?

    formula_count = 0
    problem_count = 0
    corrected_problem_count = 0
    new_formula_problem_count = 0
    new_formula = args.new_formula?
    strict = new_formula || args.strict?
    online = new_formula || args.online?
    git = args.git?
    skip_style = args.skip_style? || args.no_named?

    ENV.activate_extensions!
    ENV.setup_build_environment

    audit_formulae = args.no_named? ? Formula : args.resolved_formulae
    style_files = args.formulae_paths unless skip_style

    only_cops = args.only_cops
    except_cops = args.except_cops
    options = { fix: args.fix? }

    if only_cops
      options[:only_cops] = only_cops
    elsif args.new_formula?
      nil
    elsif except_cops
      options[:except_cops] = except_cops
    elsif !strict
      options[:except_cops] = [:FormulaAuditStrict]
    end

    # Check style in a single batch run up front for performance
    style_results = Style.check_style_json(style_files, options) if style_files
    # load licenses
    spdx = HOMEBREW_LIBRARY_PATH/"data/spdx.json"
    spdx_data = open(spdx, "r") do |file|
      JSON.parse(file.read)
    end
    new_formula_problem_lines = []
    audit_formulae.sort.each do |f|
      only = only_cops ? ["style"] : args.only
      options = {
        new_formula: new_formula,
        strict:      strict,
        online:      online,
        git:         git,
        only:        only,
        except:      args.except,
        spdx_data:   spdx_data,
      }
      options[:style_offenses] = style_results.file_offenses(f.path) if style_results
      options[:display_cop_names] = args.display_cop_names?

      fa = FormulaAuditor.new(f, options)
      fa.audit
      next if fa.problems.empty? && fa.new_formula_problems.empty?

      fa.problems
      formula_count += 1
      problem_count += fa.problems.size
      problem_lines = format_problem_lines(fa.problems)
      corrected_problem_count = options[:style_offenses].count(&:corrected?) if options[:style_offenses]
      new_formula_problem_lines = format_problem_lines(fa.new_formula_problems)
      if args.display_filename?
        puts problem_lines.map { |s| "#{f.path}: #{s}" }
      else
        puts "#{f.full_name}:", problem_lines.map { |s| "  #{s}" }
      end
// read_body [ruby]
  def read_body
    raise Mechanize::ResponseCodeError.new(self) unless
      File.exist? @file_path

    if directory?
      yield dir_body
    else
      ::File.open(@file_path, 'rb') do |io|
        yield io.read
      end
    end
  end
// read_body [ruby]
  def read_body
    raise Mechanize::ResponseCodeError.new(self) unless
      File.exist? @file_path

    if directory?
      yield dir_body
    else
      open @file_path, 'rb' do |io|
        yield io.read
      end
    end
  end
// add_rpmmd_repo [ruby]
    def add_rpmmd_repo(primary_xml, name)
      repo = pool.add_repo(name)
      File.open(primary_xml) do |gz|
        fd = Solv.xfopen_fd(primary_xml, gz.fileno)
        repo.add_rpmmd(fd, nil, 0)
        pool.createwhatprovides
      end
    end
// add_rpmmd_repo [ruby]
    def add_rpmmd_repo(primary_xml, name)
      repo = pool.add_repo(name)
      gz = open(primary_xml)
      fd = Solv.xfopen_fd(primary_xml, gz.fileno)
      repo.add_rpmmd(fd, nil, 0)
      pool.createwhatprovides
    ensure
      gz&.close
    end
// self.read [ruby]
  def self.read(path=default_path)
    perm = File.stat(path).mode & 0777
    if perm != 0600 && !(WINDOWS)
      raise Error, "Permission bits for '#{path}' should be 0600, but are "+perm.to_s(8)
    end
    new(path, parse(lex(File.readlines(path))))
  rescue Errno::ENOENT
    new(path, parse(lex([])))
  end
// self.read [ruby]
  def self.read(path=default_path)
    perm = File.stat(path).mode & 0777
    if perm != 0600 && !(WINDOWS)
      raise Error, "Permission bits for '#{path}' should be 0600, but are "+perm.to_s(8)
    end
    new(path, parse(lex(IO.readlines(path))))
  rescue Errno::ENOENT
    new(path, parse(lex([])))
  end
// load [ruby]
    def load(input, *options)
      input.respond_to?(:write) or
        return ::File.open(input, 'r') { |io| load(io, *options) }

      opthash = {
        :format => :yaml,
        :session => false,
      }
      case options.size
      when 0
      when 1
        case options = options.first
        when Symbol
          opthash[:format] = options
        else
          if hash = Hash.try_convert(options)
            opthash.update(hash)
          end
        end
// load [ruby]
    def load(input, *options)
      input.respond_to?(:write) or
        return open(input, 'r') { |io| load(io, *options) }

      opthash = {
        :format => :yaml,
        :session => false,
      }
      case options.size
      when 0
      when 1
        case options = options.first
        when Symbol
          opthash[:format] = options
        else
          if hash = Hash.try_convert(options)
            opthash.update(hash)
          end
        end
// self.version [ruby]
    def self.version
      File.read(File.expand_path('../../../version', __FILE__))
    end
// self.version [ruby]
    def self.version
      IO.read(File.expand_path('../../../version', __FILE__))
    end
// run_mode_flag [ruby]
    def run_mode_flag(options)
      options[:execute] ? '--execute' : '--dry-run'
    end
// run_mode_flag [ruby]
    def run_mode_flag(options)
      options[:execute] ? ' --execute' : ' --dry-run'
    end
// load_yaml [ruby]
  def load_yaml(model_name)
    raise(ArgumentError, "No fixture_path set. Use FixtureDependencies.fixture_path = ...") unless fixture_path

    filename = model_name.camelize.constantize.table_name
    yaml_path = File.join(fixture_path, "#{filename}.yml")

    if File.exist?(yaml_path)
      yaml = YAML.load(File.read(yaml_path))
    elsif File.exist?("#{yaml_path}.erb")
      yaml = YAML.load(ERB.new(File.read("#{yaml_path}.erb")).result)
    else
      raise(ArgumentError, "No valid fixture found at #{yaml_path}[.erb]")
    end

    yaml.each do |name, attributes|
      symbol_attrs = {}
      attributes.each{|k,v| symbol_attrs[k.to_sym] = v}
      add(model_name.to_sym, name, symbol_attrs)
    end
    loaded[model_name.to_sym] = true
  end
// load_yaml [ruby]
  def load_yaml(model_name)
    raise(ArgumentError, "No fixture_path set. Use FixtureDependencies.fixture_path = ...") unless fixture_path

    filename = model_name.camelize.constantize.table_name
    yaml_path = File.join(fixture_path, "#{filename}.yml")

    if File.exist?(yaml_path)
      yaml = YAML.load(File.read(yaml_path))
    elsif File.exist?("#{yaml_path}.erb")
      yaml = YAML.load(ERB.new(IO.read("#{yaml_path}.erb")).result)
    else
      raise(ArgumentError, "No valid fixture found at #{yaml_path}[.erb]")
    end

    yaml.each do |name, attributes|
      symbol_attrs = {}
      attributes.each{|k,v| symbol_attrs[k.to_sym] = v}
      add(model_name.to_sym, name, symbol_attrs)
    end
    loaded[model_name.to_sym] = true
  end
// percona_command [ruby]
    def percona_command(execute_sql, database_name, table_name, options = {})
      command = ['pt-online-schema-change', '--alter', execute_sql || '', "D=#{database_name},t=#{table_name}"]

      # Whitelist
      options = HashWithIndifferentAccess.new(options)
      options = options.slice(*self.class.percona_flags.keys)

      # Merge config
      config = percona_config
      if config
        config.slice(*self.class.percona_flags.keys).each do |key, value|
          options[key] ||= value
        end
      end

      # Set defaults
      self.class.percona_flags.each do |flag, flag_config|
        options[flag] = flag_config[:default] if flag_config.key?(:default) && !options.key?(flag)
      end

      command_parts = command + [run_mode_flag(options)] + command_flags(options)

      command_parts.shelljoin
    end
// percona_command [ruby]
    def percona_command(execute_sql, database_name, table_name, options = {})
      command = "pt-online-schema-change --alter '#{execute_sql}' D=#{database_name},t=#{table_name}"

      # Whitelist
      options = HashWithIndifferentAccess.new(options)
      options = options.slice(*self.class.percona_flags.keys)

      # Merge config
      config = percona_config
      if config
        config.slice(*self.class.percona_flags.keys).each do |key, value|
          options[key] ||= value
        end
      end

      # Set defaults
      self.class.percona_flags.each do |flag, flag_config|
        options[flag] = flag_config[:default] if flag_config.key?(:default) && !options.key?(flag)
      end

      "#{command}#{run_mode_flag(options)}#{command_flags(options)}"
    end
// self.open [ruby]
    def self.open(path_or_url, ext = nil, options = {})
      options, ext = ext, nil if ext.is_a?(Hash)

      uri = URI(path_or_url.to_s)

      ext ||= File.extname(uri.path)
      ext.sub!(/:.*/, '') # hack for filenames or URLs that include a colon

      if uri.is_a?(URI::HTTP) || uri.is_a?(URI::FTP)
        uri.open(options) { |file| read(file, ext) }
      else
        File.open(uri.to_s, "rb", options) { |file| read(file, ext) }
      end
    end
// self.open [ruby]
    def self.open(path_or_url, ext = nil, options = {})
      options, ext = ext, nil if ext.is_a?(Hash)

      ext ||=
        if File.exist?(path_or_url)
          File.extname(path_or_url)
        else
          File.extname(URI(path_or_url).path)
        end

      ext.sub!(/:.*/, '') # hack for filenames or URLs that include a colon

      Kernel.open(path_or_url, "rb", options) do |file|
        read(file, ext)
      end
    end
// save [ruby]
    def save(output, *options)
      output.respond_to?(:write) or
        return ::File.open(output, 'w') { |io| save(io, *options) }

      opthash = {
        :format => :yaml,
        :session => false,
      }
      case options.size
      when 0
      when 1
        case options = options.first
        when Symbol
          opthash[:format] = options
        else
          opthash.update(options) if options
        end
// save [ruby]
    def save(output, *options)
      output.respond_to?(:write) or
        return open(output, 'w') { |io| save(io, *options) }

      opthash = {
        :format => :yaml,
        :session => false,
      }
      case options.size
      when 0
      when 1
        case options = options.first
        when Symbol
          opthash[:format] = options
        else
          opthash.update(options) if options
        end
// yaml_file [ruby]
    def yaml_file
      file = Rails.root.join('config', 'performance_platform.yml')
      YAML.safe_load(ERB.new(File.read(file)).result, [Symbol])
    end
// yaml_file [ruby]
    def yaml_file
      file = Rails.root.join('config', 'performance_platform.yml')
      YAML.safe_load(ERB.new(IO.read(file)).result, [Symbol])
    end
// download [ruby]
  def download uri, io_or_filename, parameters = [], referer = nil, headers = {}
    page = transact do
      get uri, parameters, referer, headers
    end

    io = if io_or_filename.respond_to? :write then
           io_or_filename
         else
           ::File.open(io_or_filename, 'wb')
         end

    case page
    when Mechanize::File then
      io.write page.body
    else
      body_io = page.body_io

      until body_io.eof? do
        io.write body_io.read 16384
      end
    end
// download [ruby]
  def download uri, io_or_filename, parameters = [], referer = nil, headers = {}
    page = transact do
      get uri, parameters, referer, headers
    end

    io = if io_or_filename.respond_to? :write then
           io_or_filename
         else
           open io_or_filename, 'wb'
         end

    case page
    when Mechanize::File then
      io.write page.body
    else
      body_io = page.body_io

      until body_io.eof? do
        io.write body_io.read 16384
      end
    end
// render [javascript]
  render () {
    const shareText = this.getSharingMessage()
    const twitterLink = 'https://twitter.com/intent/tweet' +
      '?text=' + encodeURIComponent(shareText) +
      '&url=' + encodeURIComponent(this.state.shareUrl)

    const facebookLink = 'https://www.facebook.com/dialog/feed' +
      '?app_id=' + encodeURIComponent(FACEBOOK_APP_ID) +
      '&redirect_uri=' + encodeURIComponent(this.state.shareUrl) +
      '&link=' + encodeURIComponent(this.state.shareUrl) +
      '&name=' + encodeURIComponent(getPageTitle(this.props.street)) +
      '&description=' + encodeURIComponent(shareText)

    const signInPromo = (!this.props.signedIn)
      ? (
        <div className="share-sign-in-promo">
          <FormattedHTMLMessage
            id="menu.share.sign-in"
            defaultMessage="<a href='/twitter-sign-in?redirectUri=/just-signed-in'>Sign in with Twitter</a> for nicer links to your streets and your personal street gallery"
          />
        </div>
      ) : null

    return (
      <Menu alignment="right" onShow={this.onShow} className="share-menu" {...this.props}>
        {signInPromo}
        <div className="share-via-link-container">
          <FormattedMessage id="menu.share.link" defaultMessage="Copy and paste this link to share:" />
          <input
            className="share-via-link"
            type="text"
            value={this.state.shareUrl}
            spellCheck="false"
            ref={(ref) => { this.shareViaLinkInput = ref }}
          />
        </div>
        <a
          className="share-via-twitter"
          href={twitterLink}
          target="_blank"
          rel="noopener noreferrer"
          onClick={this.onClickShareViaTwitter}
        >
          <svg className="icon">
            <use xlinkHref="#icon-twitter" />
          </svg>
          <FormattedMessage id="menu.share.twitter" defaultMessage="Share using Twitter" />
        </a>
        <a
          className="share-via-facebook"
          href={facebookLink}
          target="_blank"
          rel="noopener noreferrer"
          onClick={this.onClickShareViaFacebook}
        >
          <svg className="icon">
            <use xlinkHref="#icon-facebook" />
          </svg>
          <FormattedMessage id="menu.share.facebook" defaultMessage="Share using Facebook" />
        </a>
        <a href="#" onClick={printImage}>
          <FormattedMessage id="menu.share.print" defaultMessage="Print…" />
        </a>
        <a id="save-as-image" href="#" onClick={this.onClickSaveAsImage}>
          <FormattedMessage id="menu.share.save" defaultMessage="Save as image…" />
          <span className="menu-item-subtext">
            <FormattedMessage id="menu.share.save-byline" defaultMessage="For including in a report, blog, etc." />
          </span>
// render [javascript]
  render () {
    const shareText = this.getSharingMessage()
    const twitterLink = 'https://twitter.com/intent/tweet' +
      '?text=' + encodeURIComponent(shareText) +
      '&url=' + encodeURIComponent(this.state.shareUrl)

    const facebookLink = 'https://www.facebook.com/dialog/feed' +
      '?app_id=' + encodeURIComponent(FACEBOOK_APP_ID) +
      '&redirect_uri=' + encodeURIComponent(this.state.shareUrl) +
      '&link=' + encodeURIComponent(this.state.shareUrl) +
      '&name=' + encodeURIComponent(getPageTitle(this.props.street)) +
      '&description=' + encodeURIComponent(shareText)

    const signInPromo = (!this.props.signedIn)
      ? (
        <div className="share-sign-in-promo">
          <FormattedHTMLMessage
            id="menu.share.sign-in"
            defaultMessage="<a href='/twitter-sign-in?redirectUri=/just-signed-in'>Sign in with Twitter</a> for nicer links to your streets and your personal street gallery"
          />
        </div>
      ) : null

    return (
      <Menu alignment="right" onShow={this.onShow} className="share-menu" {...this.props}>
        {signInPromo}
        <div className="share-via-link-container">
          <FormattedMessage id="menu.share.link" defaultMessage="Copy and paste this link to share:" />
          <input
            className="share-via-link"
            type="text"
            value={this.state.shareUrl}
            spellCheck="false"
            ref={(ref) => { this.shareViaLinkInput = ref }}
          />
        </div>
        <a
          className="share-via-twitter"
          href={twitterLink}
          target="_blank"
          onClick={this.onClickShareViaTwitter}
        >
          <svg className="icon">
            <use xlinkHref="#icon-twitter" />
          </svg>
          <FormattedMessage id="menu.share.twitter" defaultMessage="Share using Twitter" />
        </a>
        <a
          className="share-via-facebook"
          href={facebookLink}
          target="_blank"
          onClick={this.onClickShareViaFacebook}
        >
          <svg className="icon">
            <use xlinkHref="#icon-facebook" />
          </svg>
          <FormattedMessage id="menu.share.facebook" defaultMessage="Share using Facebook" />
        </a>
        <a href="#" onClick={printImage}>
          <FormattedMessage id="menu.share.print" defaultMessage="Print…" />
        </a>
        <a id="save-as-image" href="#" onClick={this.onClickSaveAsImage}>
          <FormattedMessage id="menu.share.save" defaultMessage="Save as image…" />
          <span className="menu-item-subtext">
            <FormattedMessage id="menu.share.save-byline" defaultMessage="For including in a report, blog, etc." />
          </span>
// (anonymous) [javascript]
  return buffer.join('');
};

var FilesView = React.createClass({
  onLoadMore: function(event) {
    Model.LoadMore(this.props.repo);
  },

  render: function() {
    var rev = this.props.rev,
        repo = this.props.repo,
        regexp = this.props.regexp,
        matches = this.props.matches,
        totalMatches = this.props.totalMatches;
    var files = matches.map(function(match, index) {
      var filename = match.Filename,
          blocks = CoalesceMatches(match.Matches);
      var matches = blocks.map(function(block) {
        var lines = block.map(function(line) {
          var content = ContentFor(line, regexp);
          return (
            <div className="line">
              <a href={Model.UrlToRepo(repo, filename, line.Number, rev)}
                  className="lnum"
                  target="_blank"
                  rel="noopener noreferrer">{line.Number}</a>
              <span className="lval" dangerouslySetInnerHTML={{__html:content}} />
            </div>
          );
        });

        return (
          <div className="match">{lines}</div>
        );
      });
// (anonymous) [javascript]
  return buffer.join('');
};

var FilesView = React.createClass({
  onLoadMore: function(event) {
    Model.LoadMore(this.props.repo);
  },

  render: function() {
    var rev = this.props.rev,
        repo = this.props.repo,
        regexp = this.props.regexp,
        matches = this.props.matches,
        totalMatches = this.props.totalMatches;
    var files = matches.map(function(match, index) {
      var filename = match.Filename,
          blocks = CoalesceMatches(match.Matches);
      var matches = blocks.map(function(block) {
        var lines = block.map(function(line) {
          var content = ContentFor(line, regexp);
          return (
            <div className="line">
              <a href={Model.UrlToRepo(repo, filename, line.Number, rev)}
                  className="lnum"
                  target="_blank">{line.Number}</a>
              <span className="lval" dangerouslySetInnerHTML={{__html:content}} />
            </div>
          );
        });

        return (
          <div className="match">{lines}</div>
// render [javascript]
    render()
    {
        const rows = [];
        if (this.props.story)
        {
            const hasBackgrounds = this.props.story.backgrounds.length > 0;
            const classesHeaderPicture = cs(
                "article-header-picture",
                {
                    "radius-all": !hasBackgrounds,
                    "radius-top": hasBackgrounds
                }
            );

            const classesHeaderCaption = cs(
                "article-header-caption",
                {
                    "radius-bottom": !hasBackgrounds
                }
            );

            // 没有图片版权信息时隐藏。
            const classesImageSource = cs(
                {
                    "hide": !this.props.story.imageSource
                }
            );

            const titleRow = (
                <div className="article-header-title" key="article-header">
                    <button type="button" className="close" data-dismiss="modal">
                        <span>&times;</span>
                    </button>
                    <div className={classesHeaderPicture} style={{ backgroundImage: `url(${this.props.story.image})` }}>
                        <div className={classesHeaderCaption}>
                            <a href={this.props.story.shareURL} target="_blank">
                                <h3>{this.props.story.title}</h3>
                            </a>
                            <a
                                className={classesImageSource}
                                href={`https://www.google.com/search?q=${this.props.story.imageSource}`}
                                target="_blank"
                            >
                                <span className="glyphicon glyphicon-copyright-mark" />
                                    {this.props.story.imageSource}
                            </a>
                        </div>
                    </div>
                </div>
            );
            rows.push(titleRow);

            if (hasBackgrounds)
                                    {
                const backgroundRows = map(this.props.story.backgrounds, (value, index) =>
                                    {
                    return (
                        <a
                            className="article-backgrounds-content"
                            href={value.href}
                            target="_blank"
                            key={`background-${index}`}
                        >
                            <h4>{`${value.title}：${value.text}`}</h4>
                        </a>
                    );
                });

                rows.push(
                    <div className="article-backgrounds" key="article-backgrounds">
                        {backgroundRows}
                        <span className="article-backgrounds-arrow glyphicon glyphicon-chevron-right" />
                    </div>
                );
            }
        }

        return (
            <div className="ArticleHeader modal-header">
                {rows}
            </div>
// render [javascript]
    render()
    {
        let item = null;
        const story = this.state.story;
        if (story)
        {
            // 如果没有 img 要处理，否则不好看。
            item = (
                <div
                    id={`story${story.id}`}
                    className="flex-tile"
                >
                    <div className="flex-tile-content">
                        <div
                            className="flex-tile-picture"
                            style={{ backgroundImage: `url(${story.image})` }}
                            onClick={this.handleClick}
                        />
                        <div className="flex-tile-title">
                            <a
                                className="flex-tile-link"
                                href="javascript:;"
                                onClick={this.handleClick}
                            >
                                {story.title}
                            </a>
                        </div>
                    </div>
                    <div className="flex-tile-stripe" />
                    <div className="flex-tile-footer">
                        <div className="flex-tile-footer-right-buttons">
                            <a href={story.shareURL} target="_blank" rel="noopener noreferrer">
                                <span
                                    className="glyphicon glyphicon-new-window"
                                    title="在新标签页中打开原文"
                                />
                            </a>
                        </div>
                    </div>
                </div>
            );
// render [javascript]
    render()
    {
        let item = null;
        const story = this.state.story;
        if (story)
        {
            // 如果没有 img 要处理，否则不好看。
            item = (
                <div
                    id={`story${story.id}`}
                    className="flex-tile"
                    ref="self"
                >
                    <div className="flex-tile-content">
                        <div
                            className="flex-tile-picture"
                            style={{ backgroundImage: `url(${story.image})` }}
                            onClick={this.handleClick.bind(this)}
                        />
                        <div className="flex-tile-title">
                            <a
                                className="flex-tile-link"
                                href="javascript:;"
                                onClick={this.handleClick.bind(this)}
                            >
                                {story.title}
                            </a>
                        </div>
                    </div>
                    <div className="flex-tile-stripe" />
                    <div className="flex-tile-footer">
                        <div className="flex-tile-footer-right-buttons">
                            <a href={story.shareURL} target="_blank">
                                <span
                                    className="glyphicon glyphicon-new-window"
                                    title="在新标签页中打开原文"
                                />
                            </a>
                        </div>
                    </div>
                </div>
            );
// (anonymous) [javascript]
            // 2、答案。
            const answers = map(item.answers, (value, index) =>
            {
                // 没有作者图片时隐藏。
                const classesAvatar = cs(
                    "avatar",
                    {
                        "hide": isEmpty(value.avatar)
                    }
                );

                return (
                    <div className="question-answer" key={`question-answer-${i}-${index}`}>
                        <div className="question-answer-meta">
                            <img className={classesAvatar} src={value.avatar} />
                            <span className="author">{value.name}</span>
                            <span className="bio">{value.bio}</span>
                        </div>
                        <div className="question-answer-content" dangerouslySetInnerHTML={{ __html: value.content }} />
                    </div>
                );
            });
            innerRows.push(...answers);

            // 3、外链。
            if (item.link)
            {
                innerRows.push(
                    <div className="view-more" key={`view-more-${i}`}>
                        <a href={item.link.href} target="_blank" rel="noopener noreferrer"><b>{item.link.text}</b></a>
                    </div>
                );
            }

            questions.push(
                <div className="question" key={`question-${i}`}>
                    {innerRows}
                </div>
            );

            // 分隔符。
            if (i < length - 1)
            {
                questions.push(<hr className="question-separator" key={`question-separator-${i}`} />);
            }
        }

        return (
// (anonymous) [javascript]
            // 2、答案。
            const answers = map(item.answers, (value, index) =>
            {
                // 没有作者图片时隐藏。
                const classesAvatar = cs(
                    "avatar",
                    {
                        "hide": isEmpty(value.avatar)
                    }
                );

                return (
                    <div className="question-answer" key={`question-answer-${i}-${index}`}>
                        <div className="question-answer-meta">
                            <img className={classesAvatar} src={value.avatar} />
                            <span className="author">{value.name}</span>
                            <span className="bio">{value.bio}</span>
                        </div>
                        <div className="question-answer-content" dangerouslySetInnerHTML={{ __html: value.content }} />
                    </div>
                );
            });
            innerRows.push(...answers);

            // 3、外链。
            if (item.link)
            {
                innerRows.push(
                    <div className="view-more" key={`view-more-${i}`}>
                        <a href={item.link.href} target="_blank"><b>{item.link.text}</b></a>
                    </div>
                );
            }

            questions.push(
                <div className="question" key={`question-${i}`}>
                    {innerRows}
                </div>
            );

            // 分隔符。
            if (i < length - 1)
            {
                questions.push(<hr className="question-separator" key={`question-separator-${i}`} />);
            }
        }

        return (
// ToolbarLink [javascript]
function ToolbarLink(props) {
  return <a
    className={classnames('maputnik-toolbar-link', props.className)}
    href={props.href}
    rel="noopener noreferrer"
    target={"_blank"}
  >
    {props.children}
  </a>
}
// ToolbarLink [javascript]
function ToolbarLink(props) {
  return <a
    className={classnames('maputnik-toolbar-link', props.className)}
    href={props.href}
    target={"blank"}
  >
    {props.children}
  </a>
}
// renderPreviewLink [javascript]
  renderPreviewLink() {
    const gist = this.state.latestGist;
    const user = gist.user || 'anonymous';
    const preview = !!gist.files['index.html'];
    if(preview) {
      return <span><a target="_blank" rel="noopener noreferrer" href={"https://bl.ocks.org/"+user+"/"+gist.id}>Preview</a>,{' '}</span>
    }
    return null;
  }
// renderPreviewLink [javascript]
  renderPreviewLink() {
    const gist = this.state.latestGist;
    const user = gist.user || 'anonymous';
    const preview = !!gist.files['index.html'];
    if(preview) {
      return <span><a target="_blank" href={"https://bl.ocks.org/"+user+"/"+gist.id}>Preview</a>,{' '}</span>
    }
    return null;
  }
// (anonymous) [javascript]
				{actionList.map((action) => {
					return <a href={action.url} class="btn btn-default btn-sm" target="_blank" rel="noopener noreferrer"><i class={`fa fa-${action.icon}`} /> {action.name}</a>;
				})}
// (anonymous) [javascript]
				{actionList.map((action) => {
					return <a href={action.url} class={`btn btn-default btn-sm`} target="_blank"><i class={`fa fa-${action.icon}`} /> {action.name}</a>;
				})}
//  [go]
	r.HandleFunc("/api/diffs/last/{num}", func(w http.ResponseWriter, r *http.Request) {
		// Grab vars
		vars := mux.Vars(r)

		var output string
		// This is bad... don't do this.... omg
		query := `SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, up_count, down_count, finished_count from trello.dailytallies order by day DESC limit $1) r;`
		err := db.QueryRow(query, vars["num"]).Scan(&output)

		if err != nil {
			log.Println("Error retriving from DB, ", err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(w, "Error retriving from DB, ", err)
			return
		}

		// Print out returned
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, output)
	})
//  [go]
	r.HandleFunc("/api/diffs/last/{num}", func(w http.ResponseWriter, r *http.Request) {
		// Grab vars
		vars := mux.Vars(r)

		var output string
		// This is bad... don't do this.... omg
		query := fmt.Sprintf(`SELECT json_agg(r) FROM (select EXTRACT(epoch FROM day) as day, up_count, down_count, finished_count from trello.dailytallies order by day DESC limit %s) r;`, vars["num"])
		err := db.QueryRow(query).Scan(&output)

		if err != nil {
			log.Println("Error retriving from DB, ", err)
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprintln(w, "Error retriving from DB, ", err)
			return
		}

		// Print out returned
		w.Header().Set("Content-Type", "application/json")
		fmt.Fprint(w, output)
	})
// GetHostsFromGroup [go]
func GetHostsFromGroup(grpName string) map[string]int {
	hosts := make(map[string]int)

	now := time.Now().Unix()
	sqlStatement := "SELECT host.id, host.hostname FROM grp_host AS gh " +
		" INNER JOIN host ON host.id=gh.host_id AND (host.maintain_begin > ? OR host.maintain_end < ?)" +
		" INNER JOIN grp ON grp.id=gh.grp_id AND grp.grp_name=?"

	dbConn, err := GetDbConn("nodata.host")
	if err != nil {
		log.Println("db.get_conn error, host", err)
		return hosts
	}

	rows, err := dbConn.Query(sqlStatement, now, now, grpName)
	if err != nil {
		log.Println("[ERROR]", err)
		return hosts
	}

	defer rows.Close()
	for rows.Next() {
		hid := -1
		hostname := ""
		err = rows.Scan(&hid, &hostname)
		if err != nil {
			log.Println("[ERROR]", err)
			continue
		}
		if hid < 0 || hostname == "" {
			continue
		}

		hosts[hostname] = hid
	}

	return hosts
}
// GetHostsFromGroup [go]
func GetHostsFromGroup(grpName string) map[string]int {
	hosts := make(map[string]int)

	now := time.Now().Unix()
	q := fmt.Sprintf("SELECT host.id, host.hostname FROM grp_host AS gh "+
		" INNER JOIN host ON host.id=gh.host_id AND (host.maintain_begin > %d OR host.maintain_end < %d)"+
		" INNER JOIN grp ON grp.id=gh.grp_id AND grp.grp_name='%s'", now, now, grpName)

	dbConn, err := GetDbConn("nodata.host")
	if err != nil {
		log.Println("db.get_conn error, host", err)
		return hosts
	}

	rows, err := dbConn.Query(q)
	if err != nil {
		log.Println("[ERROR]", err)
		return hosts
	}

	defer rows.Close()
	for rows.Next() {
		hid := -1
		hostname := ""
		err = rows.Scan(&hid, &hostname)
		if err != nil {
			log.Println("[ERROR]", err)
			continue
		}
		if hid < 0 || hostname == "" {
			continue
		}

		hosts[hostname] = hid
	}

	return hosts
}
// Action [go]
func (admin *Admin) Action(context *Context) {
	var err error
	name := strings.Split(context.Request.URL.Path, "/")[4]
	if action := context.Resource.actions[name]; action != nil {
		ids := context.Request.Form.Get("ids")
		scope := context.GetDB().Where(fmt.Sprintf("%v IN (?)", context.Resource.PrimaryKey()), ids)
		err = action.Handle(scope, context.Context)
	}

	responder.With("html", func() {
		http.Redirect(context.Writer, context.Request, context.Request.Referer(), http.StatusFound)
	}).With("json", func() {
		if err == nil {
			context.Writer.Write([]byte("OK"))
		} else {
			context.Writer.Write([]byte(err.Error()))
		}
	}).Respond(context.Writer, context.Request)
}
// Action [go]
func (admin *Admin) Action(context *Context) {
	var err error
	name := strings.Split(context.Request.URL.Path, "/")[4]
	if action := context.Resource.actions[name]; action != nil {
		ids := context.Request.Form.Get("ids")
		scope := context.GetDB().Where(ids)
		err = action.Handle(scope, context.Context)
	}

	responder.With("html", func() {
		http.Redirect(context.Writer, context.Request, context.Request.Referer(), http.StatusFound)
	}).With("json", func() {
		if err == nil {
			context.Writer.Write([]byte("OK"))
		} else {
			context.Writer.Write([]byte(err.Error()))
		}
	}).Respond(context.Writer, context.Request)
}
// dumprecord [go]
func dumprecord(w http.ResponseWriter, r *http.Request, parray []string) {

	database := parray[0]
	table := parray[1]
	rec, err := strconv.Atoi(parray[2])
	checkY(err)

	user, pw := getCredentials(r)
	conn, err := sql.Open("mysql", dsn(user, pw, database))
	checkY(err)
	defer conn.Close()

	statement, err := conn.Prepare("select * from ?")
	checkY(err)

	rows, err := statement.Query(table)
	checkY(err)
	defer rows.Close()

	columns, err := rows.Columns()
	checkY(err)

	raw := make([]interface{}, len(columns))
	val := make([]interface{}, len(columns))

	for i := range val {
		raw[i] = &val[i]
	}

	var n int = 1

rowLoop:
	for rows.Next() {

		// unfortunately we have to iterate up to row of interest
		if n == rec {
			err = rows.Scan(raw...)
			checkY(err)

			fmt.Fprintln(w, "<p>")
			for i, col := range val {
				if col != nil {
					fmt.Fprintln(w, columns[i], ":", string(col.([]byte)), "<br>")
				}
			}
			fmt.Fprintln(w, "</p>")
			break rowLoop
		}
		n = n + 1
	}
}
// dumprecord [go]
func dumprecord(w http.ResponseWriter, r *http.Request, parray []string) {

	database := parray[0]
	table := parray[1]
	rec, err := strconv.Atoi(parray[2])
	checkY(err)

	user, pw := getCredentials(r)
	conn, err := sql.Open("mysql", dsn(user, pw, database))
	checkY(err)
	defer conn.Close()

	statement, err := conn.Prepare("select * from " + table)
	checkY(err)

	rows, err := statement.Query()
	checkY(err)
	defer rows.Close()

	columns, err := rows.Columns()
	checkY(err)

	raw := make([]interface{}, len(columns))
	val := make([]interface{}, len(columns))

	for i := range val {
		raw[i] = &val[i]
	}

	var n int = 1

rowLoop:
	for rows.Next() {

		// unfortunately we have to iterate up to row of interest
		if n == rec {
			err = rows.Scan(raw...)
			checkY(err)

			fmt.Fprintln(w, "<p>")
			for i, col := range val {
				if col != nil {
					fmt.Fprintln(w, columns[i], ":", string(col.([]byte)), "<br>")
				}
			}
			fmt.Fprintln(w, "</p>")
			break rowLoop
		}
		n = n + 1
	}
}
// dumptable [go]
func dumptable(w http.ResponseWriter, r *http.Request, parray []string) {

	user, pw := getCredentials(r)
	database := parray[0]
	table := parray[1]

	conn, err := sql.Open("mysql", dsn(user, pw, database))
	checkY(err)
	defer conn.Close()

	statement, err := conn.Prepare("select * from ?")
	checkY(err)

	rows, err := statement.Query(table)
	checkY(err)
	defer rows.Close()

	cols, err := rows.Columns()
	checkY(err)
	fmt.Fprintln(w, "<p>"+"# "+strings.Join(cols, " ")+"</p>")

	/*  credits:
	 * 	http://stackoverflow.com/questions/19991541/dumping-mysql-tables-to-json-with-golang
	 * 	http://go-database-sql.org/varcols.html
	 */

	raw := make([]interface{}, len(cols))
	val := make([]interface{}, len(cols))

	for i := range val {
		raw[i] = &val[i]
	}

	var n int = 1
	for rows.Next() {

		fmt.Fprint(w, linkDeeper(r.URL.Path, strconv.Itoa(n), strconv.Itoa(n)))
		err = rows.Scan(raw...)
		checkY(err)

		for _, col := range val {
			if col != nil {
				fmt.Fprintf(w, "%s ", string(col.([]byte)))
			}
		}
		fmt.Fprintln(w, "<br>")
		n = n + 1
	}
}
// dumptable [go]
func dumptable(w http.ResponseWriter, r *http.Request, parray []string) {

	user, pw := getCredentials(r)
	database := parray[0]
	table := parray[1]

	conn, err := sql.Open("mysql", dsn(user, pw, database))
	checkY(err)
	defer conn.Close()

	statement, err := conn.Prepare("select * from " + table)
	checkY(err)

	rows, err := statement.Query()
	checkY(err)
	defer rows.Close()

	cols, err := rows.Columns()
	checkY(err)
	fmt.Fprintln(w, "<p>"+"# "+strings.Join(cols, " ")+"</p>")

	/*  credits:
	 * 	http://stackoverflow.com/questions/19991541/dumping-mysql-tables-to-json-with-golang
	 * 	http://go-database-sql.org/varcols.html
	 */

	raw := make([]interface{}, len(cols))
	val := make([]interface{}, len(cols))

	for i := range val {
		raw[i] = &val[i]
	}

	var n int = 1
	for rows.Next() {

		fmt.Fprint(w, linkDeeper(r.URL.Path, strconv.Itoa(n), strconv.Itoa(n)))
		err = rows.Scan(raw...)
		checkY(err)

		for _, col := range val {
			if col != nil {
				fmt.Fprintf(w, "%s ", string(col.([]byte)))
			}
		}
		fmt.Fprintln(w, "<br>")
		n = n + 1
	}
}
// (anonymous) [javascript]
app.get('/api/search', function (req, res) {
  // WARNING: this API pattern should be revisited and potentially rewritten as its probably bad!
  var zip = req.query.zip,
      last_name = req.query.last_name,
      where = '',
      params = [];
  if (zip) { 
    where += "provider_business_practice_location_address_postal_code=$1";
    params.push(zip);
  }

  if (last_name && zip) {
    where += " AND provider_last_name_legal_name=$2";
    params.push(last_name);
  }

  if (last_name && !zip) { 
    where += "provider_last_name_legal_name=$1";
    params.push(last_name);
  }

  if (where === '') {
    // TODO: return error
    res.json([]);
    return
  }

  pg.query("SELECT * FROM npis WHERE " + where, params, function (err, result) {
    res.json(result.rows);
  });
});
// (anonymous) [javascript]
app.get('/api/search', function (req, res) {
  // WARNING: this API pattern should be revisited and potentially rewritten as its probably bad!
  var zip = req.query.zip,
      last_name = req.query.last_name,
      where = '';
  if (zip) where += "provider_business_practice_location_address_postal_code = '" + zip + "' ";
  if (last_name && zip) where += "AND provider_last_name_legal_name = '" + last_name + "' ";
  if (last_name && !zip) where += "provider_last_name_legal_name = '" + last_name + "' ";
  if (where === '') {
    // TODO: return error
  }

  pg.query("SELECT * FROM npis WHERE " + where, function (err, result) {
    res.json(result.rows);
  });
});
// (anonymous) [javascript]
    connection.query('SELECT soc FROM Occupation ORDER BY RAND() LIMIT 1;', function(err, rows, fields) {
        if (err === null && rows.length == 1) {
            successNext(rows[0].soc);
        }
        else {
            errNext(err);
        }
    });
// (anonymous) [javascript]
    connection.query('SELECT soc FROM occupation ORDER BY RAND() LIMIT 1;', function(err, rows, fields) {
        if (err === null && rows.length == 1) {
            successNext(rows[0].soc);
        }
        else {
            errNext(err);
        }
    });
// module.exports.searchOccupationNames [javascript]
module.exports.searchOccupationNames = function(query, successNext, errNext) {
    // Split query string into words
    var keywords = query.split(/[,\s]+/);

    if (keywords.length == 0) {
        errNext('No keywords');
        return;
    }

    // Add % to the beginning and end of each keyword
    for (var i = 0; i < keywords.length; i++) {
        keywords[i] = '%' + keywords[i] + '%';
    }

    // Build a series of nested queries to get all job titles that match each keyword
    var sqlQuery = 'SELECT * FROM Occupation WHERE title LIKE ?';
    for (var i = 1; i < keywords.length; i++) {
        sqlQuery += ' AND soc IN (SELECT soc FROM Occupation WHERE title LIKE ?';
    }
    for (var i = 1; i < keywords.length; i++) {
        sqlQuery += ')';
    }
    sqlQuery += ';';

    var connection = mysql.createConnection(config);
    connection.connect();

    connection.query(sqlQuery, keywords, function(err, rows, fields) {
        if (err === null) {
            successNext(rows);
        }
        else {
            errNext(err);
        };
    });

    connection.end();
}
// module.exports.searchOccupationNames [javascript]
module.exports.searchOccupationNames = function(query, successNext, errNext) {
    var connection = mysql.createConnection(config);
    connection.connect();

    // TECH DEBT: Beware SQL injection! Consider validating query
    connection.query('SELECT * FROM Occupation WHERE title LIKE "%' + query + '%";', function(err, rows, fields) {
        if (err === null) {
            successNext(rows);
        }
        else {
            errNext(err);
        };
    });

    connection.end();
}
// updateConsent [javascript]
function updateConsent(database){
  //Still need to grab emails from a sensitive data file
  const emails = JSON.parse(fs.readFileSync('./tmp/consented-latest.json'))
  const emailString = emails.consented.map(x => "'" + x + "'").toString();
  const pool = new Pool({database});
  const sql = `
    INSERT INTO consented_email (email,audio,permission,consent) 
    SELECT x,TRUE,TRUE,TRUE 
    FROM unnest(ARRAY[$1]) x;`;
  const values = [emailString]
  return pool.query(sql, values);
}