jiahuimbzuai/CoQuIR huggingface dataset:
// writeErrorResponse [go]
func writeErrorResponse(rw *http.ResponseWriter, status int, body string) {
	(*rw).WriteHeader(status)
	errTmpl.Execute(*rw, map[string]interface{}{
		"msg": body,
	})
}
// writeErrorResponse [go]
func writeErrorResponse(rw *http.ResponseWriter, status int, body string) {
	(*rw).WriteHeader(status)
	(*rw).Write([]byte(body))
}
// (anonymous) [javascript]
    jQuery('body').on('DOMNodeInserted', 'DIV.drop-popover', function (e) {
        var cssUrl = url+'lightbox/css/light.css'
        if (!cssLoaded) {
            var link = $('<link type="text/css" rel="stylesheet" />').attr("href", cssUrl);
            $('head').append(link);
            $.getScript(url+'lightbox/js/light.js', function(){});
            cssLoaded = true;
        }

        var box = $( e.currentTarget ).find( "DIV.sakuli-popup" );
        if (box.length > 0 ){
            $(box[0]).attr('class', 'sakuli-image');
            var sakuliUrl = site[1] + box[0].innerHTML;
            var svcoutput;
            var imagename;
            jQuery.when(
                // fetch Sakuli serviceoutput file
                $.get( sakuliUrl + "output.txt").always(function(data ,state) {
                    if (state != "success" ) {
                        data = "Could not find Sakuli service outputfile at " + sakuliUrl + "output.txt !"
                    }
                    console.log(data);
                    svcoutput = $("<div>").text(data).html().replace(/['"]+/g, '');
                    console.log("Sakuli service output: " + svcoutput);
                }) &&
                // fetch Sakuli screenshot (jpg/png)
                $.get( sakuliUrl ).always(function(imgdata ,state) {
                    if (state != "success" ) {
                        imgdata = "Could not access screenshot list page at " + sakuliUrl + "!"
                    }
                    // the 3rd href on the apache index page contains the img name
                    imagename = $(imgdata).find('a')[2].text.trim();
                    console.log("Sakuli screenshot image name: " + imagename);
                })
            ).then ( function() {
                box[0].innerHTML = '<a href="' + sakuliUrl  + imagename + '" data-lightbox="sakuli" data-title="'+ svcoutput +'"><img src="'+ sakuliUrl + imagename +'" alt="Sakuli error image" width=250px /></a>';
            });
        }
    });
// (anonymous) [javascript]
    jQuery('body').on('DOMNodeInserted', 'DIV.drop-popover', function (e) {
        var cssUrl = url+'lightbox/css/light.css'
        if (!cssLoaded) {
            $('head').append('<link rel="stylesheet" href="'+url+'lightbox/css/light.css" type="text/css" />');
            $.getScript(url+'lightbox/js/light.js', function(){});
            cssLoaded = true;
        }

        var box = $( e.currentTarget ).find( "DIV.sakuli-popup" );
        if (box.length > 0 ){
            $(box[0]).attr('class', 'sakuli-image');
            var sakuliUrl = site[1] + box[0].innerHTML;
            var svcoutput;
            var imagename;
            jQuery.when(
                // fetch Sakuli serviceoutput file
                $.get( sakuliUrl + "output.txt").always(function(data ,state) {
                    if (state != "success" ) {
                        data = "Could not find Sakuli service outputfile at " + sakuliUrl + "output.txt !"
                    }
                    console.log(data);
                    svcoutput = $("<div>").text(data).html().replace(/['"]+/g, '');
                    console.log("Sakuli service output: " + svcoutput);
                }) &&
                // fetch Sakuli screenshot (jpg/png)
                $.get( sakuliUrl ).always(function(imgdata ,state) {
                    if (state != "success" ) {
                        imgdata = "Could not access screenshot list page at " + sakuliUrl + "!"
                    }
                    // the 3rd href on the apache index page contains the img name
                    imagename = $(imgdata).find('a')[2].text.trim();
                    console.log("Sakuli screenshot image name: " + imagename);
                })
            ).then ( function() {
                box[0].innerHTML = '<a href="' + sakuliUrl  + imagename + '" data-lightbox="sakuli" data-title="'+ svcoutput +'"><img src="'+ sakuliUrl + imagename +'" alt="Sakuli error image" width=250px /></a>';
            });
        }
    });
// showLog [javascript]
function showLog(msg, data) {
    if (data) {
        console.log(msg, data);
        msg = msg + '<span class="strong">' + encodeHTML(JSON.stringify(data)) + '</span>';
    } else {
        console.log(msg);
    }
    var div = document.getElementById('print-wall');
    var p = document.createElement('p');
    p.innerHTML = msg;
    div.appendChild(p);
}
// showLog [javascript]
function showLog(msg, data) {
    if (data) {
        console.log(msg, data);
        msg = msg + '<span class="strong">' + JSON.stringify(data) + '</span>';
    } else {
        console.log(msg);
    }
    var div = document.getElementById('print-wall');
    var p = document.createElement('p');
    p.innerHTML = msg;
    div.appendChild(p);
}
// (anonymous) [javascript]
                setTimeout(function () {
                    updateScheduled = false;

                    var form = $('#mail-form-newsletter form'),
                        action = form.attr('action'),
                        target = form.attr('target');

                    form.attr('action', '/admin/newsletter/create_preview');
                    form.attr('target', 'mail-template-iframe');

                    form.submit();

                    form.attr('action', action ? action : '');
                    form.attr('target', target ? target : '');
                    updateButton.prop('disabled', false);

                    $('*#mail-template-iframe-panel .panel-heading').html(eHtml($("#newsletter_mail_subject").val()));
                }, 500);
// (anonymous) [javascript]
                setTimeout(function () {
                    updateScheduled = false;

                    var form = $('#mail-form-newsletter form'),
                        action = form.attr('action'),
                        target = form.attr('target');

                    form.attr('action', '/admin/newsletter/create_preview');
                    form.attr('target', 'mail-template-iframe');

                    form.submit();

                    form.attr('action', action ? action : '');
                    form.attr('target', target ? target : '');
                    updateButton.prop('disabled', false);

                    $('*#mail-template-iframe-panel .panel-heading').html($("#newsletter_mail_subject").val());
                }, 500);
// transvision [python]
def transvision(request):
    """Get Mozilla translations from Transvision service."""
    try:
        text = request.GET['text']
        locale = request.GET['locale']
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    try:
        text = quote(text.encode('utf-8'))
    except KeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    url = (
        u'https://transvision.mozfr.org/api/v1/tm/global/en-US/{locale}/{text}/'
        .format(locale=locale, text=text)
    )

    payload = {
        'max_results': 5,
        'min_quality': 70,
    }

    try:
        r = requests.get(url, params=payload)
        if 'error' in r.json():
            error = r.json()['error']
            log.error('Transvision error: {error}'.format(error=error))
            error = escape(error)
            return HttpResponseBadRequest('Bad Request: {error}'.format(error=error))

        return JsonResponse(r.json(), safe=False)

    except requests.exceptions.RequestException as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))
// transvision [python]
def transvision(request):
    """Get Mozilla translations from Transvision service."""
    try:
        text = request.GET['text']
        locale = request.GET['locale']
    except MultiValueDictKeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    try:
        text = quote(text.encode('utf-8'))
    except KeyError as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))

    url = (
        u'https://transvision.mozfr.org/api/v1/tm/global/en-US/{locale}/{text}/'
        .format(locale=locale, text=text)
    )

    payload = {
        'max_results': 5,
        'min_quality': 70,
    }

    try:
        r = requests.get(url, params=payload)
        if 'error' in r.json():
            error = r.json()['error']
            log.error('Transvision error: {error}'.format(error=error))
            return HttpResponseBadRequest('Bad Request: {error}'.format(error=error))

        return JsonResponse(r.json(), safe=False)

    except requests.exceptions.RequestException as e:
        return HttpResponseBadRequest('Bad Request: {error}'.format(error=e))
// tileRec [javascript]
function tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, invertZoom, quality) {
    var inPathMpc = tempDir + '/temp_level_' + zoom + '.mpc';
    var inPathCache = tempDir + '/temp_level_' + zoom + '.cache';
    execFileSync('convert', [inPath, inPathMpc]);
    return tileLevel(inPathMpc, outPath, zoomToDisplay, tileSize, pattern, quality)
        .then(function () {
            if (imageBiggerThanTile(inPath, tileSize)) {
                var newZoom = zoom + 1;
                var newZoomToDisplay = zoomToDisplay + 1;
                if (!invertZoom) {
                    newZoomToDisplay = zoomToDisplay - 1;
                }
                var newInPath = tempDir + '/temp_level_' + zoom + '.png';
                execFileSync('convert', [inPathMpc, '-resize', '50%', '-quality', quality, newInPath]);
                fs.unlinkSync(inPathMpc);
                fs.unlinkSync(inPathCache);
                return tileRec(newInPath, outPath, newZoom, tileSize, tempDir, pattern, newZoomToDisplay, invertZoom, quality);
            } else {
                fs.unlinkSync(inPathMpc);
                fs.unlinkSync(inPathCache);
            }
        });
}
// tileRec [javascript]
function tileRec(inPath, outPath, zoom, tileSize, tempDir, pattern, zoomToDisplay, invertZoom, quality) {
    var inPathMpc = tempDir + '/temp_level_' + zoom + '.mpc';
    var inPathCache = tempDir + '/temp_level_' + zoom + '.cache';
    execSync('convert ' + inPath + ' ' + inPathMpc);
    return tileLevel(inPathMpc, outPath, zoomToDisplay, tileSize, pattern, quality)
        .then(function () {
            if (imageBiggerThanTile(inPath, tileSize)) {
                var newZoom = zoom + 1;
                var newZoomToDisplay = zoomToDisplay + 1;
                if (!invertZoom) {
                    newZoomToDisplay = zoomToDisplay - 1;
                }
                var newInPath = tempDir + '/temp_level_' + zoom + '.png';
                execSync('convert ' + inPathMpc + ' -resize 50% -quality ' + quality + ' ' + newInPath);
                fs.unlinkSync(inPathMpc);
                fs.unlinkSync(inPathCache);
                return tileRec(newInPath, outPath, newZoom, tileSize, tempDir, pattern, newZoomToDisplay, invertZoom, quality);
            } else {
                fs.unlinkSync(inPathMpc);
                fs.unlinkSync(inPathCache);
            }
        });
}
// tileLevel [javascript]
function tileLevel(inPath, outPath, zoom, tileSize, pattern, quality) {
    var dotExtension = pattern.replace(/.*(\.[^.]+)$/, '$1');
    var patternedFilename = pattern.replace(/\{z\}/, '' + zoom)
        .replace(/\{x\}/, '%[fx:page.x/' + tileSize + ']')
        .replace(/\{y\}/, '%[fx:page.y/' + tileSize + ']')
        .replace(/\.[^.]+$/, '');
    var patternedFilenameWithoutTheFilename = '';
    if (pattern.indexOf(path.sep) > 0) {
        patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep + '[^' + path.sep + ']*$'), '')
            .replace(/\{z\}/, '' + zoom);
    }
    return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)
        .then(() => {
            var args = [inPath,
                '-crop', tileSize + 'x' + tileSize,
                '-set', 'filename:tile', patternedFilename,
                '-quality', quality, '+repage', '+adjoin',
                outPath + '/%[filename:tile]' + dotExtension];
            execFileSync('convert', args);
        });
}
// tileLevel [javascript]
function tileLevel(inPath, outPath, zoom, tileSize, pattern, quality) {
    var dotExtension = pattern.replace(/.*(\.[^.]+)$/, '$1');
    var patternedFilename = pattern.replace(/\{z\}/, '' + zoom)
        .replace(/\{x\}/, '%[fx:page.x/' + tileSize + ']')
        .replace(/\{y\}/, '%[fx:page.y/' + tileSize + ']')
        .replace(/\.[^.]+$/, '');
    var patternedFilenameWithoutTheFilename = '';
    if (pattern.indexOf(path.sep) > 0) {
        patternedFilenameWithoutTheFilename = pattern.replace(new RegExp(path.sep+'[^'+path.sep+']*$'), '')
        .replace(/\{z\}/, '' + zoom);
    }
    return mkdirp(outPath + path.sep + patternedFilenameWithoutTheFilename)
    .then(()=>{
        var command = 'convert ' + inPath +
            ' -crop ' + tileSize + 'x' + tileSize +
            ' -set filename:tile "' + patternedFilename + '"' +
            ' -quality ' + quality + ' +repage +adjoin' +
            ' "' + outPath + '/%[filename:tile]' + dotExtension + '"' ;
        execSync(command);
    });
}
// editor [python]
    def editor(self, filename):
        """Spawn the default editor ($EDITOR env var or editor configuration
        item)."""

        if not self.config_editor:
            raise exceptions.FatalError("no editor configured (EDITOR "
                                        "environment variable or editor "
                                        "configuration item)")

        if subprocess.call([self.config_editor, filename]) != 0:
            raise exceptions.FatalError("there was a problem running the "
                                        "editor")
// editor [python]
    def editor(self, filename):
        """Spawn the default editor ($EDITOR env var)."""

        if not os.getenv("EDITOR"):
            raise exceptions.FatalError("unable to get an EDITOR environment "
                                        "variable")

        os.system("$EDITOR '{}'".format(filename))
// crypt [ruby]
    def crypt(path: nil, password: nil, encrypt: true)
      if password.to_s.strip.length == 0 && encrypt
        UI.user_error!("No password supplied")
      end

      tmpfile = File.join(Dir.mktmpdir, "temporary")
      command = ["openssl aes-256-cbc"]
      command << "-k #{password.shellescape}"
      command << "-in #{path.shellescape}"
      command << "-out #{tmpfile.shellescape}"
      command << "-a"
      command << "-d" unless encrypt
      command << "&> /dev/null" unless $verbose # to show show an error message is something goes wrong
      success = system(command.join(' '))

      UI.crash!("Error decrypting '#{path}'") unless success
      FileUtils.mv(tmpfile, path)
    end
// crypt [ruby]
    def crypt(path: nil, password: nil, encrypt: true)
      if password.to_s.strip.length == 0 && encrypt
        UI.user_error!("No password supplied")
      end

      tmpfile = File.join(Dir.mktmpdir, "temporary")
      command = ["openssl aes-256-cbc"]
      command << "-k \"#{password}\""
      command << "-in \"#{path}\""
      command << "-out \"#{tmpfile}\""
      command << "-a"
      command << "-d" unless encrypt
      command << "&> /dev/null" unless $verbose # to show show an error message is something goes wrong
      success = system(command.join(' '))

      UI.crash!("Error decrypting '#{path}'") unless success
      FileUtils.mv(tmpfile, path)
    end
// open [ruby]
      def open(path, options = {})
        b = parse(File.read(path), options)
        b.path = path
        return b unless block_given?

        begin
          yield b
        ensure
          b.save_to(options[:out] || path)
        end
      end
// open [ruby]
      def open(path, options = {})
        b = parse(Kernel.open(path, 'r:UTF-8').read, options)
        b.path = path
        return b unless block_given?

        begin
          yield b
        ensure
          b.save_to(options[:out] || path)
        end
      end
// render [javascript]
    }

    buffer.push(EscapeHtml(content.substring(0, regexp.lastIndex - m[0].length)));
    buffer.push( '<em>' + EscapeHtml(m[0]) + '</em>');
    content = content.substring(regexp.lastIndex);
  }
  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>
        );
      });

      return (
        <div className="file">
          <div className="title">
            <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}
                target="_blank"
                rel="noopener noreferrer">
              {match.Filename}
            </a>
          </div>
          <div className="file-body">
            {matches}
          </div>
// render [javascript]
    }

    buffer.push(EscapeHtml(content.substring(0, regexp.lastIndex - m[0].length)));
    buffer.push( '<em>' + EscapeHtml(m[0]) + '</em>');
    content = content.substring(regexp.lastIndex);
  }
  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>
        );
      });

      return (
        <div className="file">
          <div className="title">
            <a href={Model.UrlToRepo(repo, match.Filename, null, rev)}>
              {match.Filename}
            </a>
          </div>
          <div className="file-body">
            {matches}
          </div>
//  [go]
	r.HandleFunc("/api/totals/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, end_of_day_total 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/totals/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, end_of_day_total 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)
	})
// (anonymous) [javascript]
    connection.query('SELECT * FROM Occupation WHERE soc = ?;', [soc], function(err, rows, fields) {
        if (err === null && rows.length == 1) {
            successNext(rows[0]);
        }
        else {
            errNext(err);
        };
    });
// (anonymous) [javascript]
    connection.query('SELECT * FROM Occupation WHERE soc = "' + soc + '";', function(err, rows, fields) {
        if (err === null && rows.length == 1) {
            successNext(rows[0]);
        }
        else {
            errNext(err);
        };
    });
// Database.prototype.register [javascript]
Database.prototype.register = function(attendee) {
    this.db.run(
      "INSERT INTO tb_events (uid, key, value, payload) VALUES ( ? , 'attendee', ? , ? );",
      [attendee.event, attendee.name, attendee.times]
    );
} // end of Database#register
// Database.prototype.register [javascript]
Database.prototype.register = function(attendee) {
    let query = "INSERT INTO tb_events (uid, key, value, payload) VALUES "
              + "("
              + "'" + attendee.event + "', "
              + "'attendee', "
              + "'" + attendee.name + "', "
              + "'" + attendee.times + "'"
              + " );";
    this.db.run(query);
} // end of Database#register
// forgot_passwd [python]
@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_passwd():
  """ Procedure to allow users to reset forgotten passwords. """
  if 'username' in session:
    flash("You're already logged in!")
    return redirect(url_for('home'))

  if request.method == 'POST':
    username = request.form['username']
    email = request.form['email']
    query = text("SELECT * FROM users NATURAL JOIN members WHERE username=:u")
    result = connection.execute(query, u=str(username))
    if result.returns_rows and result.rowcount != 0:
      result_cols = result.keys()
      row = result.first()
      q_dict = dict(zip(result_cols, row))
      if q_dict['email'] == email:
        reset_key = auth.reset_key(q_dict['passwd'], q_dict['salt'], username)
        msg = "We received a request to reset this account's password.\n" \
              "If you didn't request this change, disregard this email.\n" \
              "If you do want to change your password, please go to:\n" +\
              url_for('reset_passwd', u=q_dict['user_id'], r=reset_key,
                  _external=True) + \
              "\n\nThanks,\nThe Ruddock Website"
        sendEmail(str(email), msg, "[RuddWeb] Forgotten Password")
        flash("An email has been sent.")
        redirect(url_for('home'))
      else:
        flash("Incorrect email.")
        return render_template('forgot_password.html')
    else:
      flash("Incorrect username.")
      return render_template('forgot_password.html')
  return render_template('forgot_password.html')
// forgot_passwd [python]
@app.route('/forgot-password', methods=['GET', 'POST'])
def forgot_passwd():
  """ Procedure to allow users to reset forgotten passwords. """
  if request.method == 'POST':
    username = request.form['username']
    email = request.form['email']
    query = text("SELECT * FROM users NATURAL JOIN members WHERE username=:u")
    result = connection.execute(query, u=str(username))
    if result.returns_rows and result.rowcount != 0:
      result_cols = result.keys()
      row = result.first()
      q_dict = dict(zip(result_cols, row))
      if q_dict['email'] == email:
        reset_key = auth.reset_key(q_dict['passwd'], q_dict['salt'], username)
        msg = "We received a request to reset this account's password.\n" \
              "If you didn't request this change, disregard this email.\n" \
              "If you do want to change your password, please go to:\n" +\
              url_for('reset_passwd', u=q_dict['user_id'], r=reset_key,
                  _external=True) + \
              "\n\nThanks,\nThe Ruddock Website"
        sendEmail(str(email), msg, "[RuddWeb] Forgotten Password")
        flash("An email has been sent.")
        redirect(url_for('home'))
      else:
        flash("Incorrect email.")
        return render_template('forgot_password.html')
    else:
      flash("Incorrect username.")
      return render_template('forgot_password.html')
  return render_template('forgot_password.html')
// verify_token [python]
    async def verify_token(self, token):
        """ verify session token """
        try:
            async with aiopg.create_pool(self.dsn) as pool:
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        table = self.manager_type
                        query = f"""
                SELECT aio.{table}.id
                FROM aio.tokens JOIN aio.users ON aio.tokens.user_id = aio.users.id
                JOIN aio.{table} ON aio.{table}.user_id = aio.users.id
                WHERE aio.tokens.token = %s"""
                        await cur.execute(query, (token, ))
                        async for row in cur:
                            return row[0]
        except Exception as err:
            print(err)
            raise web.HTTPForbidden()
// verify_token [python]
    async def verify_token(self, token):
        """ verify session token """
        try:
            async with aiopg.create_pool(self.dsn) as pool:
                async with pool.acquire() as conn:
                    async with conn.cursor() as cur:
                        query = f"""
                SELECT aio.{self.manager_type}.id
                FROM aio.tokens JOIN aio.users ON aio.tokens.user_id = aio.users.id
                JOIN aio.{self.manager_type} ON aio.{self.manager_type}.user_id = aio.users.id
                WHERE aio.tokens.token = '{token}'"""
                        await cur.execute(query)
                        async for row in cur:
                            return row[0]
        except Exception as err:
            print(err)
            raise HTTPForbidden()
// sanitize [ruby]
  def sanitize(text)
    # Add \\ to escape special characters. Four \ to escape the backslashes.
    # Escape anything that isn't in "a-zA-Z0-9 ._|'/"
    text.gsub(%r{([^a-zA-Z0-9 ._|'\/])}, '\\\\\1') if text
  end
// sanitize [ruby]
  def sanitize(prefix)
    # Add \\ to escape special characters. Four \ to escape the backslashes.
    # Escape anything that isn't in "a-zA-Z0-9 ._|'/"
    prefix.gsub(%r{([^a-zA-Z0-9 ._|'\/])}, '\\\\\1') if prefix
  end
// check_in_interaction_ids [ruby]
      def check_in_interaction_ids
        access_token = Hackbot::Team
                       .find_by(team_id: team.team_id)
                       .bot_access_token

        im_id = SlackClient::Chat.open_im(slack_id, access_token)[:channel][:id]

        check_in_interactions = Hackbot::Interactions::CheckIn
                                .where("data->>'channel' = ?", im_id)
                                .where.not(state: 'finish')

        check_in_interactions.map(&:id)
      end
// check_in_interaction_ids [ruby]
      def check_in_interaction_ids
        access_token = Hackbot::Team
                       .find_by(team_id: team.team_id)
                       .bot_access_token

        im_id = SlackClient::Chat.open_im(slack_id, access_token)[:channel][:id]

        check_in_interactions = Hackbot::Interactions::CheckIn
                                .where("data->>'channel' = '#{im_id}'")
                                .where.not(state: 'finish')

        check_in_interactions.map(&:id)
      end
// set [javascript]
  set: function (key, val) {
    if (key.includes('__proto__') || key.includes('prototype') || key.includes('constructor')){
      return undefined;
    }
    if (val === undefined) {
      val = key;
      key = null;
    }
    var path = getPath(key);
    if (path.length === 0) {
      // root must be an object
      if (!val || typeof val !== 'object') {
        return false;
      } else {
        this.store = val;
        return true;
      }
    }

    var target = this.store;
    while (path.length > 1) {
      key = path.shift();
      if (!target[key] || typeof target[key] !== 'object') {
        target[key] = {};
      }

      target = target[key];
    }

    key = path.shift();
    target[key] = val;
    return true;
  },
// set [javascript]
  set: function (key, val) {
    if (val === undefined) {
      val = key;
      key = null;
    }
    var path = getPath(key);
    if (path.length === 0) {
      // root must be an object
      if (!val || typeof val !== 'object') {
        return false;
      } else {
        this.store = val;
        return true;
      }
    }

    var target = this.store;
    while (path.length > 1) {
      key = path.shift();
      if (!target[key] || typeof target[key] !== 'object') {
        target[key] = {};
      }

      target = target[key];
    }

    key = path.shift();
    target[key] = val;
    return true;
  },
// FileStorage::getResourceFile [java]
	File getResourceFile(String id, Location location) {
		id = new File(id).getName(); // make sure we're not doing any directory traversal
		// package level for migrators
		if (id==null) {
			throw new IllegalArgumentException("No ID provided for stored resource");
		}
		File file = new File(getObjectStoreDirectory(location),  id+".gz");
		if (file.exists()) {return file;}
		else {return new File(getObjectStoreDirectory(location),  id);}
	}
// FileStorage::getResourceFile [java]
	File getResourceFile(String id, Location location) {
		// package level for migrators
		if (id==null) {
			throw new IllegalArgumentException("No ID provided for stored resource");
		}
		File file = new File(getObjectStoreDirectory(location),  id+".gz");
		if (file.exists()) {return file;}
		else {return new File(getObjectStoreDirectory(location),  id);}
	}
// DefaultSampleFilesService::downloadAndUnpackResource [java]
	private void downloadAndUnpackResource(final Location source,
		final File targetFolder) throws InterruptedException, ExecutionException,
		IOException
	{
		// allocate array
		final ByteArray byteArray = new ByteArray(1024 * 1024);

		log.debug("Started download of " + source.getURI());
		// Download the zip file
		final BytesLocation bytes = new BytesLocation(byteArray);
		final Task task = //
			downloadService.download(source, bytes, sourceCache()).task();
		task.waitFor();

		// extract to cache dir
		final byte[] buf = new byte[64 * 1024];
		final ByteArrayInputStream bais = new ByteArrayInputStream(//
			byteArray.getArray(), 0, byteArray.size());
		targetFolder.mkdirs();
		log.debug("Unpacking files");
		try (final ZipInputStream zis = new ZipInputStream(bais)) {
			while (true) {
				final ZipEntry entry = zis.getNextEntry();
				if (entry == null) break; // All done!
				final String name = entry.getName();
				final File outFile = new File(targetFolder, name);
				if (!outFile.toPath().normalize().startsWith(targetFolder.toPath().normalize())) {
					throw new RuntimeException("Bad zip entry");
				}
				if (entry.isDirectory()) {
					outFile.mkdirs();
				}
				else {
					final int size = (int) entry.getSize();
					int len = 0;
					try (final FileOutputStream out = new FileOutputStream(outFile)) {
						while (true) {
							log.debug("Unpacking " + name + "; completion" + (double) len /
								size * 100 + "%");
							final int r = zis.read(buf);
							if (r < 0) break; // end of entry
							len += r;
							out.write(buf, 0, r);
						}
					}
				}
			}
		}
	}
// DefaultSampleFilesService::downloadAndUnpackResource [java]
	private void downloadAndUnpackResource(final Location source,
		final File targetFolder) throws InterruptedException, ExecutionException,
		IOException
	{
		// allocate array
		final ByteArray byteArray = new ByteArray(1024 * 1024);

		log.debug("Started download of " + source.getURI());
		// Download the zip file
		final BytesLocation bytes = new BytesLocation(byteArray);
		final Task task = //
			downloadService.download(source, bytes, sourceCache()).task();
		task.waitFor();

		// extract to cache dir
		final byte[] buf = new byte[64 * 1024];
		final ByteArrayInputStream bais = new ByteArrayInputStream(//
			byteArray.getArray(), 0, byteArray.size());
		targetFolder.mkdirs();
		log.debug("Unpacking files");
		try (final ZipInputStream zis = new ZipInputStream(bais)) {
			while (true) {
				final ZipEntry entry = zis.getNextEntry();
				if (entry == null) break; // All done!
				final String name = entry.getName();
				final File outFile = new File(targetFolder, name);
				if (entry.isDirectory()) {
					outFile.mkdirs();
				}
				else {
					final int size = (int) entry.getSize();
					int len = 0;
					try (final FileOutputStream out = new FileOutputStream(outFile)) {
						while (true) {
							log.debug("Unpacking " + name + "; completion" + (double) len /
								size * 100 + "%");
							final int r = zis.read(buf);
							if (r < 0) break; // end of entry
							len += r;
							out.write(buf, 0, r);
						}
					}
				}
			}
		}
	}
// (anonymous) [javascript]
	release.assets.forEach(function(asset) {
		var arch = parseName(asset.name);
		if (!arch) return;

		var dist = {
			name: asset.name,
			url: asset.browser_download_url,
			size: asset.size,
			os: arch && arch.os,
			arch: arch && arch.arch,
			download: function() {
				debug('download: ' + this.name);
				return request(dist.url);
			},
			extract: function(dest, options) {
				options = options || {};
				var filter = options.filter || [];
				if (!Array.isArray(filter)) {
					filter = [filter];
				}
				dest = dest || '.';

				debug('extract: %s -> %s', this.name, dest);

				// ensure that destination exists
				fs.ensureDirSync(dest);

				var stream = this.download();
				var zip = stream.pipe(unzip.Parse());
				zip.on('entry', function(entry) {
					// skip directories
					if (entry.type === 'Directory') {
						entry.autodrain();
						return;
					}

					var dest_file = path.join(dest, entry.path);
					// skip if path is filtered
					for (var i in filter) {
						if (minimatch(entry.path, filter[i], {dot: true})) {
							debug('  skip: %s', entry.path);
							entry.autodrain();
							return;
						}
					}
					debug('  write: %s -> %s', entry.path, dest_file);
					fs.ensureFileSync(dest_file);
					if (entry.path == 'atom') {
						// make 'atom' executable
						fs.chmodSync(dest_file, '755');
					}
					entry.pipe(fs.createWriteStream(dest_file));
				});
				return stream;
			}
		};
		dists[arch.os + '-' + arch.arch] = dist;
	});
// (anonymous) [javascript]
	release.assets.forEach(function(asset) {
		var arch = parseName(asset.name);
		if (!arch) return;
		
		var dist = {
			name: asset.name,
			url: asset.browser_download_url,
			size: asset.size,
			os: arch && arch.os,
			arch: arch && arch.arch,
			download: function() {
				debug('download: ' + this.name);
				return request(dist.url);
			},
			extract: function(dest, options) {
				options = options || {};
				var filter = options.filter || [];
				if (!Array.isArray(filter)) {
					filter = [filter];
				}
				dest = dest || '.';

				debug('extract: %s -> %s', this.name, dest);

				// ensure that destination exists
				fs.ensureDirSync(dest);

				var stream = this.download();
				var zip = stream.pipe(unzip.Parse());
				zip.on('entry', function(entry) {
					// skip directories
					if (entry.type === 'Directory') {
						entry.autodrain();
						return;
					}

					var dest_file = path.join(dest, entry.path);
					// skip if path is filtered
					for (var i in filter) {
						if (minimatch(entry.path, filter[i], {dot: true})) {
							debug('  skip: %s', entry.path);
							entry.autodrain();
							return;
						}
					}
					debug('  write: %s -> %s', entry.path, dest_file);
					fs.ensureFileSync(dest_file);
					if (entry.path == 'atom') {
						// make 'atom' executable
						fs.chmodSync(dest_file, '755');
					}
					entry.pipe(fs.createWriteStream(dest_file));
				});
				return stream;
			}
		};
		dists[arch.os + '-' + arch.arch] = dist;
	});
// _get_obj_absolute_path [python]
def _get_obj_absolute_path(obj_path):
    return safe_join(DATAROOT, obj_path)
// _get_obj_absolute_path [python]
def _get_obj_absolute_path(obj_path):
    return os.path.join(DATAROOT, obj_path)
// modname_normalize [c]
static inline char *modname_normalize(const char *modname, char buf[NAME_MAX],
								size_t *len)
{
	size_t s;

	for (s = 0; s < NAME_MAX - 1; s++) {
		const char c = modname[s];
		if (c == '-')
			buf[s] = '_';
		else if (c == '\0' || c == '.')
			break;
		else
			buf[s] = c;
	}
	buf[s] = '\0';

	if (len)
		*len = s;

	return buf;
}
// modname_normalize [c]
static inline char *modname_normalize(char *modname, char buf[NAME_MAX],
								size_t *len)
{
	char *c;
	size_t s;

	if (buf) {
		buf[NAME_MAX] = '\0';
		modname = strncpy(buf, modname, NAME_MAX - 1);
	}

	for (c = modname, s = 0; *c != '\0' && *c != '.'; c++) {
		if (*c == '-')
			*c = '_';
		s++;
	}

	if (len)
		*len = s;

	*c = '\0';

	return modname;
}
// SecurityConfiguration::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();

        // Person pages only for authenticated users.
        http.authorizeRequests()
                .antMatchers("/persons/**").hasAnyAuthority("USER");

        // Forum pages only for authenticated users.
        http.authorizeRequests()
                .antMatchers("/forums/**").hasAnyAuthority("USER");

        http.formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/main")
                .failureUrl("/invalidlogin")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/main");
    }
// SecurityConfiguration::configure [java]
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // Enable CSRF (for h2 console!). This is a vulnerability!
        http.csrf().disable();
        http.headers().frameOptions().sameOrigin();

        // Person pages only for authenticated users.
        http.authorizeRequests()
                .antMatchers("/persons/**").hasAnyAuthority("USER");

        // Forum pages only for authenticated users.
        http.authorizeRequests()
                .antMatchers("/forums/**").hasAnyAuthority("USER");

        http.formLogin()
                .loginPage("/login")
                .defaultSuccessUrl("/main")
                .failureUrl("/invalidlogin")
                .permitAll()
                .and()
                .logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/main");
    }
// testConstructWrapperWithExistingNonEmptyDumpRoot [python]
  def testConstructWrapperWithExistingNonEmptyDumpRoot(self):
    dir_path = os.path.join(self._tmp_dir, "foo")
    os.mkdir(dir_path)
    self.assertTrue(os.path.isdir(dir_path))

    with self.assertRaisesRegex(
        ValueError, "dump_root path points to a non-empty directory"):
      local_cli_wrapper.LocalCLIDebugWrapperSession(
          session.Session(), dump_root=self._tmp_dir, log_usage=False)
// testConstructWrapperWithExistingNonEmptyDumpRoot [python]
  def testConstructWrapperWithExistingNonEmptyDumpRoot(self):
    os.mkdir(self._tmp_dir)
    dir_path = os.path.join(self._tmp_dir, "foo")
    os.mkdir(dir_path)
    self.assertTrue(os.path.isdir(dir_path))

    with self.assertRaisesRegex(
        ValueError, "dump_root path points to a non-empty directory"):
      local_cli_wrapper.LocalCLIDebugWrapperSession(
          session.Session(), dump_root=self._tmp_dir, log_usage=False)
// try_compile_and_link [python]
def try_compile_and_link(compiler, source='', flags=[], verbose=False):
    ensure_tmp_dir_exists()
    with tempfile.NamedTemporaryFile() as sfile:
        ofd, ofile = tempfile.mkstemp()
        os.close(ofd)
        try:
            sfile.file.write(bytes(source, 'utf-8'))
            sfile.file.flush()
            ret = subprocess.run([compiler, '-x', 'c++', '-o', ofile, sfile.name] + args.user_cflags.split() + flags,
                                 capture_output=True)
            if verbose:
                print(f"Compilation failed: {compiler} -x c++ -o {ofile} {sfile.name} {args.user_cflags} {flags}")
                print(source)
                print(ret.stdout.decode('utf-8'))
                print(ret.stderr.decode('utf-8'))
            return ret.returncode == 0
        finally:
            if os.path.exists(ofile):
                os.unlink(ofile)
// try_compile_and_link [python]
def try_compile_and_link(compiler, source='', flags=[], verbose=False):
    ensure_tmp_dir_exists()
    with tempfile.NamedTemporaryFile() as sfile:
        ofile = tempfile.mktemp()
        try:
            sfile.file.write(bytes(source, 'utf-8'))
            sfile.file.flush()
            ret = subprocess.run([compiler, '-x', 'c++', '-o', ofile, sfile.name] + args.user_cflags.split() + flags,
                                 capture_output=True)
            if verbose:
                print(f"Compilation failed: {compiler} -x c++ -o {ofile} {sfile.name} {args.user_cflags} {flags}")
                print(source)
                print(ret.stdout.decode('utf-8'))
                print(ret.stderr.decode('utf-8'))
            return ret.returncode == 0
        finally:
            if os.path.exists(ofile):
                os.unlink(ofile)
// _make_asset [python]
  def _make_asset(self, contents):
    fd, filename = tempfile.mkstemp(prefix=self.get_temp_dir())
    with os.fdopen(fd, "w") as f:
      f.write(contents)
    return filename
// _make_asset [python]
  def _make_asset(self, contents):
    filename = tempfile.mktemp(prefix=self.get_temp_dir())
    with open(filename, "w") as f:
      f.write(contents)
    return filename
// testConstructWrapperWithExistingFileDumpRoot [python]
  def testConstructWrapperWithExistingFileDumpRoot(self):
    file_path = os.path.join(self._tmp_dir, "foo")
    open(file_path, "a").close()  # Create the file
    self.assertTrue(os.path.isfile(file_path))
    with self.assertRaisesRegex(ValueError, "dump_root path points to a file"):
      local_cli_wrapper.LocalCLIDebugWrapperSession(
          session.Session(), dump_root=file_path, log_usage=False)
// testConstructWrapperWithExistingFileDumpRoot [python]
  def testConstructWrapperWithExistingFileDumpRoot(self):
    os.mkdir(self._tmp_dir)
    file_path = os.path.join(self._tmp_dir, "foo")
    open(file_path, "a").close()  # Create the file
    self.assertTrue(os.path.isfile(file_path))
    with self.assertRaisesRegex(ValueError, "dump_root path points to a file"):
      local_cli_wrapper.LocalCLIDebugWrapperSession(
          session.Session(), dump_root=file_path, log_usage=False)
// check_inode [c]
static bool check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
{
	struct exfat *exfat = iter->exfat;
	struct exfat_dentry *dentry;
	bool ret = true;
	uint16_t checksum;

	if (check_clus_chain(exfat, node))
		return false;

	if (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *
				(uint64_t)exfat->clus_size) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("size %" PRIu64 " is greater than cluster heap: %s\n",
				node->size, path_resolve_ctx.local_path);
		ret = false;
	}

	if (node->size == 0 && node->is_contiguous) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("empty, but marked as contiguous: %s\n",
					path_resolve_ctx.local_path);
		ret = false;
	}

	if ((node->attr & ATTR_SUBDIR) &&
			node->size % exfat->clus_size != 0) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("directory size %" PRIu64 " is not divisible by %d: %s\n",
				node->size, exfat->clus_size,
				path_resolve_ctx.local_path);
		ret = false;
	}

	checksum = file_calc_checksum(iter);
	exfat_de_iter_get(iter, 0, &dentry);
	if (checksum != le16_to_cpu(dentry->file_checksum)) {
		if (repair_file_ask(iter, node, ER_DE_CHECKSUM,
				"the checksum of a file is wrong")) {
			exfat_de_iter_get_dirty(iter, 0, &dentry);
			dentry->file_checksum = cpu_to_le16(checksum);
		} else
			ret = false;
	}

	return ret;
}
// check_inode [c]
static bool check_inode(struct exfat_de_iter *iter, struct exfat_inode *node)
{
	struct exfat *exfat = iter->exfat;
	struct exfat_dentry *dentry;
	bool ret = true;
	uint16_t checksum;

	if (check_clus_chain(exfat, node))
		return false;

	if (node->size > le32_to_cpu(exfat->bs->bsx.clu_count) *
				exfat->clus_size) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("size %" PRIu64 " is greater than cluster heap: %s\n",
				node->size, path_resolve_ctx.local_path);
		ret = false;
	}

	if (node->size == 0 && node->is_contiguous) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("empty, but marked as contiguous: %s\n",
					path_resolve_ctx.local_path);
		ret = false;
	}

	if ((node->attr & ATTR_SUBDIR) &&
			node->size % exfat->clus_size != 0) {
		resolve_path_parent(&path_resolve_ctx, iter->parent, node);
		exfat_err("directory size %" PRIu64 " is not divisible by %d: %s\n",
				node->size, exfat->clus_size,
				path_resolve_ctx.local_path);
		ret = false;
	}

	checksum = file_calc_checksum(iter);
	exfat_de_iter_get(iter, 0, &dentry);
	if (checksum != le16_to_cpu(dentry->file_checksum)) {
		if (repair_file_ask(iter, node, ER_DE_CHECKSUM,
				"the checksum of a file is wrong")) {
			exfat_de_iter_get_dirty(iter, 0, &dentry);
			dentry->file_checksum = cpu_to_le16(checksum);
		} else
			ret = false;
	}

	return ret;
}
// VerifyMAC [go]
func (m *wrappedMAC) VerifyMAC(mac, data []byte) error {
	// This also rejects raw MAC with size of 4 bytes or fewer. Those MACs are
	// clearly insecure, thus should be discouraged.
	prefixSize := cryptofmt.NonRawPrefixSize
	if len(mac) <= prefixSize {
		return errInvalidMAC
	}

	// try non raw keys
	prefix := mac[:prefixSize]
	macNoPrefix := mac[prefixSize:]
	entries, err := m.ps.EntriesForPrefix(string(prefix))
	if err == nil {
		for i := 0; i < len(entries); i++ {
			entry := entries[i]
			p, ok := (entry.Primitive).(tink.MAC)
			if !ok {
				return fmt.Errorf("mac_factory: not an MAC primitive")
			}
			if entry.PrefixType == tinkpb.OutputPrefixType_LEGACY {
				d := data
				if len(d) >= maxInt {
					return fmt.Errorf("mac_factory: data too long")
				}
				data = make([]byte, 0, len(d)+1)
				data = append(data, d...)
				data = append(data, byte(0))
			}
			if err = p.VerifyMAC(macNoPrefix, data); err == nil {
				return nil
			}
		}
	}

	// try raw keys
	entries, err = m.ps.RawEntries()
	if err == nil {
		for i := 0; i < len(entries); i++ {
			p, ok := (entries[i].Primitive).(tink.MAC)
			if !ok {
				return fmt.Errorf("mac_factory: not an MAC primitive")
			}

			if err = p.VerifyMAC(mac, data); err == nil {
				return nil
			}
		}
	}

	// nothing worked
	return errInvalidMAC
}