text:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

from astropy.io import fits
from astropy.table import Table, join
from astropy.coordinates import SkyCoord
from astropy import units as u
from astropy.wcs import WCS
from photutils import aperture_photometry
from photutils import SkyCircularAperture
from photutils import SkyCircularAnnulus

import os
import subprocess
import shlex
import sys
# edited 5/9/17
# ------

#v1.1: add background subtraction from the annulus aroud the point source
# also add seeing (FWHM) look up for sextractor

def write_ds9_region_sky(table, allcol, color, fname):
    """
    write_ds9_region_sky: write out a ds9 region file
    INPUT:
    - table: the table that we are interested in plotting
    - allcol: the column name for the celestial coordinates
    - color: the color for the region in ds9 (usually 'green', 'red', 'blue')
    - fname: the output filename (should be 'xxx.reg')
    OUTPUT:
    - create a fname reg file for ds9 to see on the celestial coordinates
    """
    dir = "region/"
    if not os.path.exists(dir):
        os.makedirs(dir)
    text_file = open(os.path.join(dir, fname), "w")
    text_file.write("# Region file format: CIAO version 1.0\n")
    for i in range(0, len(table)):
        ra = table[allcol][i].ra.to_string(unit=u.hr, sep=':')
        dec = table[allcol][i].dec.to_string(unit=u.degree, sep=':')
        text_file.write("j2000; circle(%s,%s,0.1') # color=%s\n" %
                        (ra, dec, color))
    text_file.close()

def list_file_name_seeing(dir, name, end=0, startdir=0):
    names=[]
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.startswith(name):
                if end == 0:
                    if startdir == 0:
                        names.append(os.path.join(root, file))
                    else:
                        if root.split('/')[-1][:2]==startdir:
                            names.append(os.path.join(root, file))
                else:
                    if file.endswith(end):
                        if startdir == 0:
                            names.append(os.path.join(root, file))
                        else:
                            if root.split('/')[-1][:2]==startdir:
                                names.append(os.path.join(root, file))
    if len(names) == 0:
        print 'Cannot find the files'
    return names

def sex_band(field, band):
    """
    sex_band: running sextractor in order to use its position for photometry (mainly using i band)
    INPUT:
    - field: our field of interest 'Field026'
    - band: our band of interest
        - in this software, we are only interested in 'i' band since it is the best band to get
        all the objects, but the function is flexible enough to be able to run for other bands
    OUTPUT:
    - create sextractor output file (e.g., posField026_i.fits) which have all the location of
    objects that we are interested in.
    """
    see=float(fits.open(list_file_name_seeing('/Users/taweewat/Documents/pisco_code/',field,startdir='ut')[0])[0].header['FWHM1'])
    # see=1.45
    print 'seeing =', see
    outname=os.path.join('final','pos%s_%s.fits'%(field,band))
    cmd="sex %s -c pisco_pipeline/config_slr.sex -CATALOG_NAME %s -SEEING_FWHM %s" %\
     (os.path.join('final','coadd_c%s_%s.fits'%(field,band)),outname,str(see))
    print cmd
    sub=subprocess.check_call(shlex.split(cmd))
    return outname

def cut(x):
    if x>0:
        return x
    else:
        return 0.

def aperature_f(field, band, aper_rad=2.2, annu_in=3., annu_out=6.):
    """
    aperature_f: running "photutils: aperture_photometry" to get the number of count within
    a radius 'aper_rad', comparing with the background annulus with inner radius 'annu_in' and
    outer radius 'annu_out'
    note about the algorithm: since we already subtracted the background count so that on average,
    the background count is roughly zero, we calculate SNR = N*/sqtr(N*+npix(N_bg)) where N_bg~0.
    INPUT:
    - field: object of interset e.g., 'Field026'
    - band: str for the name of the band that we are interested in.
    - aper_rad: the circular radius (in arcsec) for the photometry
    - annu_in: the inner radius (in arcsec) of the annulus for the background counts
    - annu_out: the outer radius (in arcsec) of the annulus for the background counts
    OUTPUT:
    - a new table with the photometry for the number of count for a specific 'band'
    """
    hdu = fits.open("final/coadd_c%s_%s.fits" % (field, band))
    w = WCS("final/coadd_c%s_%s.fits" % (field, band))
    # vfunc = np.vectorize(cut)
    # hdu[0].data=vfunc(hdu[0].data)

    pos_filename = os.path.join('final', 'pos%s_%s.fits' % (field, 'i'))
    if not os.path.isfile(pos_filename):
        print 'sextracting the i band position for %s' % field
    pos_filename = sex_band(field, 'i')

    t7 = Table.read(pos_filename)
    positions = SkyCoord(t7['ALPHA_J2000'], t7['DELTA_J2000'], frame='icrs')
    apertures = SkyCircularAperture(positions, r=aper_rad * u.arcsec)
    annulus_apertures = SkyCircularAnnulus(
        positions, r_in=annu_in * u.arcsec, r_out=annu_out * u.arcsec)
    apers = [apertures, annulus_apertures]

    phot_table = aperture_photometry(hdu[0], apers)
    # phot_table2 = phot_table[np.isfinite(phot_table['aperture_sum_0'])]
    # phot_table3 = phot_table2[np.where(phot_table2['aperture_sum_0'] > 0)]

    bkg_per_px = phot_table['aperture_sum_1']/apers[1].to_pixel(w).area()
    bkg_per_star = bkg_per_px*apers[0].to_pixel(w).area()
    phot_table['aperture_sum_2']=map(cut,phot_table['aperture_sum_0']-bkg_per_star)
    phot_table['snr'] = phot_table['aperture_sum_2'] / (np.sqrt(phot_table['aperture_sum_2'])+1e-3)

    phot_table3 = phot_table

    for name in phot_table3.colnames[1:]:
        phot_table3.rename_column(name, name + '_%s' % band)
    return phot_table3

def create_star_fits_slr(field, g, r, i, z):
    """
    create_star_fits_slr: convert the count to magnitude value and combine all four bands (g,r,i,z)
    together into one big table with magnitude and its uncertainty
    INPUT:
    - field: object of interset e.g., 'Field026'
    - g, r, i, z:
    OUTPUT:
    - a new table with celestial coordinates (ALPHA_J2000, DELTA_J2000) and magnitude from g, r, i, z band
    """
    pos_filename = os.path.join('final', 'pos%s_%s.fits' % (field, 'i'))
    if not os.path.isfile(pos_filename):
        print 'sextracting the i band position for %s' % field
    pos_filename = sex_band(field, 'i')
    t7 = Table.read(pos_filename)

    print 'joining g,r,i,z band together for %s...' % field
    total = join(join(join(i, g, keys='id'), r, keys='id'), z, keys='id')
    total["CLASS_STAR"] = t7[total['id'] - 1]["CLASS_STAR"]
    total["FLAGS"] = t7[total['id'] - 1]["FLAGS"]

    total=total[total['aperture_sum_2_g']>0]; print 'after remove zero g', len(total)
    total=total[total['aperture_sum_2_r']>0]; print 'after remove zero r', len(total)
    total=total[total['aperture_sum_2_i']>0]; print 'after remove zero i', len(total)
    total=total[total['aperture_sum_2_z']>0]; print 'after remove zero z', len(total)

    total['magg'] = -2.5 * np.array(map(np.log10, total['aperture_sum_2_g']))
    total['magr'] = -2.5 * np.array(map(np.log10, total['aperture_sum_2_r']))
    total['magi'] = -2.5 * np.array(map(np.log10, total['aperture_sum_2_i']))
    total['magz'] = -2.5 * np.array(map(np.log10, total['aperture_sum_2_z']))

    total['maggerr'] = 1.0857 / total["snr_g"]
    total['magrerr'] = 1.0857 / total["snr_r"]
    total['magierr'] = 1.0857 / total["snr_i"]
    total['magzerr'] = 1.0857 / total["snr_z"]

    total["ALPHA_J2000"] = total["celestial_center_i"].ra.degree
    total["DELTA_J2000"] = total["celestial_center_i"].dec.degree

    star = total[(total["CLASS_STAR"] > 0.9) & (total['magi']>-13.4)]
    #magnitude cut for saturated stars (pix~1400 for the whole aperature of radius 7.5 px => mag~-13.4)
    gal = total[total["CLASS_STAR"] < 0.75]
    # write_ds9_region_sky(star, "celestial_center_i",
    #                      'red', 'star_%s.reg' % field)
    # write_ds9_region_sky(gal, "celestial_center_i",
    #                      'green', 'gal_%s.reg' % field)
    starr = star[['id', 'ALPHA_J2000', 'DELTA_J2000', 'magg', 'magr', 'magi',
                  'magz', 'maggerr', 'magrerr', 'magierr', 'magzerr', 'CLASS_STAR','FLAGS']]
    starr.meta={'name':'Aperture'}
    # starr.meta['aperture_photometry_args'] = u"method='exact'"
    starr.write('star_%s.fits' % field, overwrite=True)
    print "writeout 'star_%s.fits' file for slr to run" % field
    return total[['id', 'ALPHA_J2000', 'DELTA_J2000', 'magg', 'magr', 'magi', 'magz',
                  'maggerr', 'magrerr', 'magierr', 'magzerr', 'CLASS_STAR','FLAGS']]

def slr_running(field, bigmacs="pisco_pipeline/big-macs-calibrate-master"):
    """
    slr_running: running SLR script from github.com/patkel/big-macs-calibrate to get a calibrated magnitude
    INPUT:
    - field: object of interset e.g., 'Field026'
    - bigmacs: the location for "big-macs-calibrate" directoty
    OUTPUT:
    - a new table with added columns with name MAG_g,...,MAGERR_g,...
    """
    infile = 'star_%s.fits' % field
    pyfile = os.path.join(bigmacs, 'fit_locus.py')
    cmd = "python %s --file %s --columns %s --extension 1 --bootstrap 5 -l -r ALPHA_J2000 -d DELTA_J2000 -j --plot=PLOTS_%s" \
        % (pyfile, infile, os.path.join(bigmacs, "coadd_mag.columns"), field)
    print cmd
    sub = subprocess.check_call(shlex.split(cmd))
    # if sub == 0:
    #     print 'finish slr_file and return starr.fits.offsets.list'
    # else:
    #     print 'slr stops working.'

def update_color(fname, table):
    """
    update_color: using the output from SLR, update to the correct magnitude
    INPUT:
    - fname: input file from SLR output (...offsets.list)
    - table: the table that we want to update the value (from column magg,etc to MAG_g,etc)
    OUTPUT:
    - a new table with added columns with name MAG_g,...,MAGERR_g,...
    """
    with open(fname) as f:
        content = f.readlines()
    content = [x.strip() for x in content]
    band = [x.split(' ')[0][-1] for x in content[5:-1]]
    corr = [float(x.split(' ')[1]) for x in content[5:-1]]
    ecorr = [float(x.split(' ')[3]) for x in content[5:-1]]
    print 'bands = ', band

    table['MAG_' + band[0]] = table['mag' + band[0]] + corr[0]
    table['MAG_' + band[1]] = table['mag' + band[1]] + corr[1]
    table['MAG_' + band[2]] = table['mag' + band[2]] + corr[2]
    table['MAG_' + band[3]] = table['mag' + band[3]] + corr[3]
    table['MAGERR_' + band[0]] = table['mag' + band[0] + 'err'] + ecorr[0]
    table['MAGERR_' + band[1]] = table['mag' + band[1] + 'err'] + ecorr[1]
    table['MAGERR_' + band[2]] = table['mag' + band[2] + 'err'] + ecorr[2]
    table['MAGERR_' + band[3]] = table['mag' + band[3] + 'err'] + ecorr[3]
    return table

"""
pisco_photometry: run pisco output data from pisco_combine to correct for the photometry of each object
and determine which objects are stars/galaxies.
The pipeline is a combination of SLR algorithm (cite: https://github.com/patkel/big-macs-calibrate)
and Photutils for photometry aperatures

ARGUMENTS:
1. fieldname for object (e.g., 'Field027')

EXAMPLES:
python pisco_pipeline/pisco_photometry.py Field026
"""

if __name__ == "__main__":
    print 'Number of arguments:', len(sys.argv), 'arguments.'
    print 'Argument List:', str(sys.argv)

    slrdir = 'slr_output'
    if not os.path.exists(slrdir):
        os.makedirs(slrdir)

    field = str(sys.argv[1])
    r = aperature_f(field, 'r')
    i = aperature_f(field, 'i')
    z = aperature_f(field, 'z')
    g = aperature_f(field, 'g')
    print 'len in g, r, i, z bands:', len(g), len(r), len(i), len(z)

    total = create_star_fits_slr(field, g, r, i, z)
    slr_running(field)
    ntotal = update_color('star_%s.fits.offsets.list' % field, total)
    ntotal.write(os.path.join(slrdir, 'ntotal_%s.csv' % field), overwrite=True)

    cmd = 'mv star_%s.fits slr_output/' % field
    try:
        sub = subprocess.check_call(shlex.split(cmd))
    except (ValueError, RuntimeError, TypeError, NameError):
        pass

    cmd = 'mv star_%s.fits.offsets.list slr_output/' % field
    try:
        sub = subprocess.check_call(shlex.split(cmd))
    except (ValueError, RuntimeError, TypeError, NameError):
        pass


text:
import hashlib
import random

from django.contrib.auth.models import User

def generate_username(email):
    def random_username():
        h = hashlib.sha1(email).hexdigest()[:25]
        # don't ask
        n = random.randint(1, (10 ** (5 - 1)) - 1)
        return "%s%d" % (h, n)
    while True:
        try:
            username = random_username()
            User.objects.get(username=username)
        except User.DoesNotExist:
            break
    return username

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace GrahamCampbell\Exceptions;

use Illuminate\Contracts\Container\Container;
use Illuminate\Foundation\Exceptions\Handler;

/**
 * This is the exception handler class.
 *
 * @author Graham Campbell <graham@alt-three.com>
 */
class NewExceptionHandler extends Handler
{
    use ExceptionHandlerTrait;

    /**
     * The exception config.
     *
     * @var array
     */
    protected $config;

    /**
     * A list of the exception types that should not be reported.
     *
     * @var string[]
     */
    protected $dontReport = [];

    /**
     * Create a new exception handler instance.
     *
     * @param \Illuminate\Contracts\Container\Container $container
     *
     * @return void
     */
    public function __construct(Container $container)
    {
        $this->config = $container->config->get('exceptions', []);

        parent::__construct($container);
    }
}


text:
'use strict';

const makeComputedArtifact = require('./computed-artifact.js');
const ByteEfficiencyAudit = require('../audits/byte-efficiency/byte-efficiency-audit.js');
const NetworkRecords = require('./network-records.js');

const PREVIEW_LENGTH = 100;

/** @typedef {LH.Artifacts.CSSStyleSheetInfo & {networkRecord: LH.Artifacts.NetworkRequest, usedRules: Array<LH.Crdp.CSS.RuleUsage>}} StyleSheetInfo */

class UnusedCSS {
  /**
   * @param {Array<LH.Artifacts.CSSStyleSheetInfo>} styles The output of the Styles gatherer.
   * @param {Array<LH.Artifacts.NetworkRequest>} networkRecords
   * @return {Object<string, StyleSheetInfo>} A map of styleSheetId to stylesheet information.
   */
  static indexStylesheetsById(styles, networkRecords) {
    const indexedNetworkRecords = networkRecords
        // Some phantom network records appear with a 0 resourceSize that aren't real.
        // A network record that has no size data is just as good as no network record at all for our
        // purposes, so we'll just filter them out. https://github.com/GoogleChrome/lighthouse/issues/9684#issuecomment-532381611
        .filter(record => record.resourceSize > 0)
        .reduce((indexed, record) => {
          indexed[record.url] = record;
          return indexed;
        }, /** @type {Object<string, LH.Artifacts.NetworkRequest>} */ ({}));

    return styles.reduce((indexed, stylesheet) => {
      indexed[stylesheet.header.styleSheetId] = Object.assign({
        usedRules: [],
        networkRecord: indexedNetworkRecords[stylesheet.header.sourceURL],
      }, stylesheet);
      return indexed;
    }, /** @type {Object<string, StyleSheetInfo>} */ ({}));
  }

  /**
   * Adds used rules to their corresponding stylesheet.
   * @param {Array<LH.Crdp.CSS.RuleUsage>} rules The output of the CSSUsage gatherer.
   * @param {Object<string, StyleSheetInfo>} indexedStylesheets Stylesheet information indexed by id.
   */
  static indexUsedRules(rules, indexedStylesheets) {
    rules.forEach(rule => {
      const stylesheetInfo = indexedStylesheets[rule.styleSheetId];

      if (!stylesheetInfo) {
        return;
      }

      if (rule.used) {
        stylesheetInfo.usedRules.push(rule);
      }
    });
  }

  /**
   * @param {StyleSheetInfo} stylesheetInfo
   * @return {{wastedBytes: number, totalBytes: number, wastedPercent: number}}
   */
  static computeUsage(stylesheetInfo) {
    let usedUncompressedBytes = 0;
    const totalUncompressedBytes = stylesheetInfo.content.length;

    for (const usedRule of stylesheetInfo.usedRules) {
      usedUncompressedBytes += usedRule.endOffset - usedRule.startOffset;
    }

    const totalTransferredBytes = ByteEfficiencyAudit.estimateTransferSize(
        stylesheetInfo.networkRecord, totalUncompressedBytes, 'Stylesheet');
    const percentUnused = (totalUncompressedBytes - usedUncompressedBytes) / totalUncompressedBytes;
    const wastedBytes = Math.round(percentUnused * totalTransferredBytes);

    return {
      wastedBytes,
      wastedPercent: percentUnused * 100,
      totalBytes: totalTransferredBytes,
    };
  }

  /**
   * Trims stylesheet content down to the first rule-set definition.
   * @param {string=} content
   * @return {string}
   */
  static determineContentPreview(content) {
    let preview = (content || '')
        .slice(0, PREVIEW_LENGTH * 5)
        .replace(/( {2,}|\t)+/g, '  ') // remove leading indentation if present
        .replace(/\n\s+}/g, '\n}') // completely remove indentation of closing braces
        .trim(); // trim the leading whitespace

    if (preview.length > PREVIEW_LENGTH) {
      const firstRuleStart = preview.indexOf('{');
      const firstRuleEnd = preview.indexOf('}');

      if (firstRuleStart === -1 || firstRuleEnd === -1
          || firstRuleStart > firstRuleEnd
          || firstRuleStart > PREVIEW_LENGTH) {
        // We couldn't determine the first rule-set or it's not within the preview
        preview = preview.slice(0, PREVIEW_LENGTH) + '...';
      } else if (firstRuleEnd < PREVIEW_LENGTH) {
        // The entire first rule-set fits within the preview
        preview = preview.slice(0, firstRuleEnd + 1) + ' ...';
      } else {
        // The first rule-set doesn't fit within the preview, just show as many as we can
        const lastSemicolonIndex = preview.slice(0, PREVIEW_LENGTH).lastIndexOf(';');
        preview = lastSemicolonIndex < firstRuleStart ?
            preview.slice(0, PREVIEW_LENGTH) + '... } ...' :
            preview.slice(0, lastSemicolonIndex + 1) + ' ... } ...';
      }
    }

    return preview;
  }

  /**
   * @param {StyleSheetInfo} stylesheetInfo The stylesheetInfo object.
   * @param {string} pageUrl The URL of the page, used to identify inline styles.
   * @return {LH.Audit.ByteEfficiencyItem}
   */
  static mapSheetToResult(stylesheetInfo, pageUrl) {
    let url = stylesheetInfo.header.sourceURL;
    if (!url || url === pageUrl) {
      const contentPreview = UnusedCSS.determineContentPreview(stylesheetInfo.content);
      url = contentPreview;
    }

    const usage = UnusedCSS.computeUsage(stylesheetInfo);
    return {url, ...usage};
  }

  /**
   * @param {{CSSUsage: LH.Artifacts['CSSUsage'], URL: LH.Artifacts['URL'], devtoolsLog: LH.DevtoolsLog}} data
   * @param {LH.Audit.Context} context
   * @return {Promise<LH.Audit.ByteEfficiencyItem[]>}
  */
  static async compute_(data, context) {
    const {CSSUsage, URL, devtoolsLog} = data;
    const networkRecords = await NetworkRecords.request(devtoolsLog, context);
    const indexedSheets = UnusedCSS.indexStylesheetsById(CSSUsage.stylesheets, networkRecords);
    UnusedCSS.indexUsedRules(CSSUsage.rules, indexedSheets);

    const items = Object.keys(indexedSheets)
      .map(sheetId => UnusedCSS.mapSheetToResult(indexedSheets[sheetId], URL.finalUrl));
    return items;
  }
}

module.exports = makeComputedArtifact(UnusedCSS);


text:
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;

namespace Amazon.AWSSupport.Model
{
    /// <summary>
    /// <para>JSON-formatted object that lists details about AWS resources that were analyzed in a call to Trusted Advisor
    /// DescribeTrustedAdvisorCheckSummaries. </para>
    /// </summary>
    public class TrustedAdvisorResourcesSummary
    {

        private long? resourcesProcessed;
        private long? resourcesFlagged;
        private long? resourcesIgnored;
        private long? resourcesSuppressed;

        /// <summary>
        /// Reports the number of AWS resources that were analyzed in your Trusted Advisor check.
        ///
        /// </summary>
        public long ResourcesProcessed
        {
            get { return this.resourcesProcessed ?? default(long); }
            set { this.resourcesProcessed = value; }
        }

        /// <summary>
        /// Sets the ResourcesProcessed property
        /// </summary>
        /// <param name="resourcesProcessed">The value to set for the ResourcesProcessed property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public TrustedAdvisorResourcesSummary WithResourcesProcessed(long resourcesProcessed)
        {
            this.resourcesProcessed = resourcesProcessed;
            return this;
        }

        // Check to see if ResourcesProcessed property is set
        internal bool IsSetResourcesProcessed()
        {
            return this.resourcesProcessed.HasValue;
        }

        /// <summary>
        /// Reports the number of AWS resources that were flagged in your Trusted Advisor check.
        ///
        /// </summary>
        public long ResourcesFlagged
        {
            get { return this.resourcesFlagged ?? default(long); }
            set { this.resourcesFlagged = value; }
        }

        /// <summary>
        /// Sets the ResourcesFlagged property
        /// </summary>
        /// <param name="resourcesFlagged">The value to set for the ResourcesFlagged property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public TrustedAdvisorResourcesSummary WithResourcesFlagged(long resourcesFlagged)
        {
            this.resourcesFlagged = resourcesFlagged;
            return this;
        }

        // Check to see if ResourcesFlagged property is set
        internal bool IsSetResourcesFlagged()
        {
            return this.resourcesFlagged.HasValue;
        }

        /// <summary>
        /// Indicates the number of resources ignored by Trusted Advisor due to unavailability of information.
        ///
        /// </summary>
        public long ResourcesIgnored
        {
            get { return this.resourcesIgnored ?? default(long); }
            set { this.resourcesIgnored = value; }
        }

        /// <summary>
        /// Sets the ResourcesIgnored property
        /// </summary>
        /// <param name="resourcesIgnored">The value to set for the ResourcesIgnored property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public TrustedAdvisorResourcesSummary WithResourcesIgnored(long resourcesIgnored)
        {
            this.resourcesIgnored = resourcesIgnored;
            return this;
        }

        // Check to see if ResourcesIgnored property is set
        internal bool IsSetResourcesIgnored()
        {
            return this.resourcesIgnored.HasValue;
        }

        /// <summary>
        /// Indicates whether the specified AWS resource has had its participation in Trusted Advisor checks suppressed.
        ///
        /// </summary>
        public long ResourcesSuppressed
        {
            get { return this.resourcesSuppressed ?? default(long); }
            set { this.resourcesSuppressed = value; }
        }

        /// <summary>
        /// Sets the ResourcesSuppressed property
        /// </summary>
        /// <param name="resourcesSuppressed">The value to set for the ResourcesSuppressed property </param>
        /// <returns>this instance</returns>
        [Obsolete("The With methods are obsolete and will be removed in version 2 of the AWS SDK for .NET. See http://aws.amazon.com/sdkfornet/#version2 for more information.")]
        public TrustedAdvisorResourcesSummary WithResourcesSuppressed(long resourcesSuppressed)
        {
            this.resourcesSuppressed = resourcesSuppressed;
            return this;
        }

        // Check to see if ResourcesSuppressed property is set
        internal bool IsSetResourcesSuppressed()
        {
            return this.resourcesSuppressed.HasValue;
        }
    }
}


text:
import configureStore from 'redux-mock-store';

// $ExpectError
const mockStoreContainingInvalidMiddlware = configureStore(['middlewares']);

const mockStore = configureStore();

const store = mockStore({ todos: [{ title: 'thing', done: false, id: 1 }] });

// $ExpectError
store.getState().somethingNotHere;

store.getState().todos;


text:
var express = require('express');
var request = require('request');
var router = express.Router();

/* GET home page. */
router.get('/', function(req, res, next) {
    url = req.originalUrl;

    if(url.indexOf("?") >= 0){
        url = url.substring(0, url.indexOf("?")).replace('/view','');
    }
    endType = /mobile/.test(req.headers['user-agent'])?"mobile":"desktop";

    res.render('login', {
        path : url,
        endType : "",
        title : '走在nodeJs的路上',
        redirect : "",
        data:{},
        session:{}
    });
});

router.post('/', function(req, res, next){
    var bodyData = req.body,
        redirect, url;
    var data = {};
    data.code = bodyData.code;
    data.password = bodyData.password;
    request({
        method: 'post',
        uri: global.config.service['sym']+'/account/checkPassword',
        json: data,
        headers: {
            "Content-Type": "application/json",
            "Accept": "application/json"
        }
    }, function (error, response, body) {
        //判断body
        if(body && body.id > 0){
            req.session.userCode=bodyData.code;
            req.session.userId=body.id;
            req.session.userName=body.name;
            req.session.userOrg=body.orgId;
            req.session.userRoles=body.roles;
            req.session.job=body.job;

            res.send({success : true});
        }else{
            res.send({success : false, msg : body.remark});
        }
    });
});

router.get('/logout', function(req, res, next) {
    delete req.session.userId;
    res.render('login', {
        path : '/login',
        endType : "",
        title : '登录',
        redirect : '',
        session:{},
        data:{}
    });
});

module.exports = router;


text:
"""
Python functions to facilitate interacting with the dataset from Koumura and
Okanoya 2016 [1].

The original code was released under the GNU license:
https://github.com/cycentum/birdsong-recognition/blob/master/
birdsong-recognition/src/computation/ViterbiSequencer.java

Note that the Python implementations are not based directly on the Java code but
they have been tested to see whether they produce the same results.

data: https://figshare.com/articles/BirdsongRecognition/3470165

[1] Koumura T, Okanoya K (2016) Automatic Recognition of Element Classes and
Boundaries in the Birdsong with Variable Sequences. PLoS ONE 11(7): e0159188.
doi:10.1371/journal.pone.0159188
"""
import os
import glob
import xml.etree.ElementTree as ET

import numpy as np

class Syllable:
    """
    Object that represents a syllable.

    Properties
    ----------
    position : int
        starting sample number ("frame") within .wav file
        *** relative to start of sequence! ***
    length : int
        duration given as number of samples
    label : char
        text representation of syllable as classified by a human
        or a machine learning algorithm
    """

    def __init__(self, position, length, label):
        self.position = position
        self.length = length
        self.label = label

    def __repr__(self):
        rep_str = "Syllable labeled {} at position {} with length {}".format(
            self.label, self.position, self.length
        )
        return rep_str

class Sequence:
    """
    Object that represents a sequence of syllables.

    Properties
    ----------
    wavFile : string
        file name of .wav file in which sequence occurs
    position : int
        starting sample number within .wav file
    length : int
        duration given as number of samples
    syls : list
        list of syllable objects that make up sequence
    seqSpect : spectrogram object
    """

    def __init__(self, wav_file, position, length, syl_list):
        self.wavFile = wav_file
        self.position = position
        self.length = length
        self.numSyls = len(syl_list)
        self.syls = syl_list
        self.seqSpect = None

    def __repr__(self):
        rep_str = "Sequence from {} with position {} and length {}".format(
            self.wavFile, self.position, self.length
        )
        return rep_str

def parse_xml(xml_file, concat_seqs_into_songs=False):
    """
    parses Annotation.xml files.

    Parameters
    ----------
    xml_file : string
        filename of .xml file, e.g. 'Annotation.xml'
    concat_seqs_into_songs : Boolean
        if True, concatenate sequences into songs, where each wav file is a
        song. Default is False.

    Returns
    -------
    seq_list : list of Sequence objects
    """

    tree = ET.ElementTree(file=xml_file)
    seq_list = []
    for seq in tree.iter(tag="Sequence"):
        wav_file = seq.find("WaveFileName").text
        position = int(seq.find("Position").text)
        length = int(seq.find("Length").text)
        syl_list = []
        for syl in seq.iter(tag="Note"):
            syl_position = int(syl.find("Position").text)
            syl_length = int(syl.find("Length").text)
            label = syl.find("Label").text

            syl_obj = Syllable(position=syl_position, length=syl_length, label=label)
            syl_list.append(syl_obj)
        seq_obj = Sequence(
            wav_file=wav_file, position=position, length=length, syl_list=syl_list
        )
        seq_list.append(seq_obj)

    if concat_seqs_into_songs:
        song_list = []
        curr_wavFile = seq_list[0].wavFile
        new_seq_obj = seq_list[0]
        for syl in new_seq_obj.syls:
            syl.position += new_seq_obj.position

        for seq in seq_list[1:]:
            if seq.wavFile == curr_wavFile:
                new_seq_obj.length += seq.length
                new_seq_obj.numSyls += seq.numSyls
                for syl in seq.syls:
                    syl.position += seq.position
                new_seq_obj.syls += seq.syls

            else:
                song_list.append(new_seq_obj)
                curr_wavFile = seq.wavFile
                new_seq_obj = seq
                for syl in new_seq_obj.syls:
                    syl.position += new_seq_obj.position

        song_list.append(new_seq_obj)  # to append last song

        return song_list

    else:
        return seq_list

def load_song_annot(filename, annot_file=None):
    """load annotation for specific song from Koumura dataset

    Parameters
    ----------
    filename : str
        filename of .wav file from Koumura dataset
    annotation_file : str
        absolute path to 'Annotation.xml' file that
        contains annotation for 'songfile'.
        Default is None, in which case the function
        searchs for Annotation.xml in the parent directory
        of songfile (if a full path is given) or the
        parent of the current working directory.

    Returns
    -------
    songfile_dict :
        with keys onsets, offsets, and labels
    """

    if annot_file is None:
        dirname, songfile = os.path.split(filename)
        if dirname == "":
            annot_file = glob.glob("../Annotation.xml")
        else:
            annot_file = glob.glob(os.path.join(dirname, "../Annotation.xml"))

        if len(annot_file) < 1:
            raise ValueError(
                "Can't open {}, Annotation.xml file not found in parent of current directory".format(
                    songfile
                )
            )
        elif len(annot_file) > 1:
            raise ValueError(
                "Can't open {}, found more than one Annotation.xml file "
                "in parent of current directory".format(songfile)
            )
        else:
            annot_file = annot_file[0]

    seq_list = parse_xml(annot_file, concat_seqs_into_songs=True)
    wav_files = [seq.wavFile for seq in seq_list]
    ind = wav_files.index(songfile)
    this_seq = seq_list[ind]
    onsets_Hz = np.asarray([syl.position for syl in this_seq.syls])
    offsets_Hz = np.asarray([syl.position + syl.length for syl in this_seq.syls])
    labels = [syl.label for syl in this_seq.syls]
    annotation_dict = {
        "filename": filename,
        "onsets_Hz": onsets_Hz,
        "offsets_Hz": offsets_Hz,
        "onsets_s": None,
        "offsets_s": None,
        "labels": labels,
    }
    return annotation_dict

def determine_unique_labels(annotation_file):
    """given an annotation.xml file
    from a bird in BirdsongRecognition dataset,
    determine unique set of labels applied to syllables from that bird"""
    annotation = parse_xml(annotation_file, concat_seqs_into_songs=True)
    lbls = [syl.label for seq in annotation for syl in seq.syls]
    unique_lbls = np.unique(lbls).tolist()
    unique_lbls = "".join(unique_lbls)  # convert from list to string
    return unique_lbls

class resequencer:
    """
    Computes most likely sequence of labels given observation probabilities
    at each time step in sequence and a second-order transition probability
    matrix taken from training data.

    Uses a Viterbi-like dynamic programming algorithm. (Viterbi-like because
    the observation probabilities are not strictly speaking the emission
    probabilities from hidden states but instead are outputs from some machine
    learning model, e.g., the softmax layer of a DCNN that assigns a probability
    to each label at each time step.)

    This is a Python implementation of the algorithm from Koumura Okanoya 2016.
    See "compLabelSequence" in:
        https://github.com/cycentum/birdsong-recognition/blob/master/
        birdsong-recognition/src/computation/ViterbiSequencer.java

    Parameters
    ----------
    sequences : list of strings
        Each string represents a sequence of syllables
    observation_prob : ndarray
        n x m x p matrix, n sequences of m estimated probabilities for p classes
    transition_prob : ndarray
        second-order transition matrix, n x m x p matrix where the value at
        [n,m,p] is the probability of transitioning to labels[p] at time step
        t given that labels[m] was observed at t-1 and labels[n] was observed
        at t-2
    labels : list of chars
        Contains all unique labels used to label songs being resequenced

    Returns
    -------
    resequenced : list of strings
        Each string represents the sequence of syllables after resequencing. So
        e.g. resequenced[0] is sequences[0] after running through the algorithm.
    """

    def __init__(self, transition_probs, labels):
        self.transition_probs = transition_probs
        self.labels = labels
        self.num_labels = len(labels)
        self.destination_label_ind = range(0, self.num_labels)

        # num_states calculation: +1 for 'e' state at beginning of initial states
        # number of labels (now without 'e') and + 1 for the final 'tail' state
        self.num_states = (self.num_labels + 1) * self.num_labels + 1
        # create dict of lists used to determine 'destination' state
        # given source state (key) and emitted label (index into each list)
        # i..e if source state is 5, destination_state{5} will return a list as
        # long as the number of labels, indexing into that list w/ e.g. index 4
        # will return some state number that then becomes the destination state
        # so len(destination_states.keys()) == num_states
        self.destination_states = {}
        dst_state_ctr = 0
        for label_one in range(0, self.num_labels + 1):  # +1 for 'e' state
            for label_two in range(0, self.num_labels):  # now without e
                dest_label_one = label_two
                dest_state_list = []
                for dest_label_two in range(0, self.num_labels):
                    dest_state_list.append(
                        dest_label_one * self.num_labels + dest_label_two
                    )
                self.destination_states[dst_state_ctr] = dest_state_list
                dst_state_ctr += 1
        # + 1 for the final tail states
        dest_label_one = self.num_labels
        dest_state_list = []
        for dest_label_two in range(0, self.num_labels):
            dest_state_list.append(dest_label_one * self.num_labels + dest_label_two)
        self.destination_states[dst_state_ctr] = dest_state_list
        # number of tail states = num_states because any state can transition to
        # a tail state and the tail state is non-emitting
        self.tail_states = list(range(0, self.num_states))

        self.head_state = self.num_states - 1  # last state in list is head
        # prob. of tranisitioning from head state 'e' to any state
        #'e1)','e2',...'e(N-1)' where N is number of labels is equal for all
        # initial states.
        self.initial_transition_prob = 1.0 / self.num_labels

    def resequence(self, observation_probs):
        num_time_steps = observation_probs.shape[0] - 1
        source_states = []
        for time_step in range(num_time_steps):
            source_states.append(np.zeros((self.num_states,), dtype=int))

        # initial inductive step of Viterbi
        current_score = np.ones((self.num_states,)) * -np.inf

        # use dest_labl_id to index into observation_prob array
        for dest_labl_id in self.destination_label_ind:
            # need destination state to assign it a score in the
            # next_score array
            dest_state = self.destination_states[self.head_state][dest_labl_id]
            obsv_prob = observation_probs[0, dest_labl_id]  # row 0 = 1st t step
            current_score[dest_state] = np.log(self.initial_transition_prob) + np.log(
                obsv_prob
            )

        # main loop for Viterbi
        for time_step in range(num_time_steps):
            next_score = np.ones((self.num_states,)) * -np.inf
            for source_state in range(self.num_states):
                for dest_label_ind in self.destination_label_ind:
                    # need destination state to assign it a score in the
                    # next_score array
                    dest_state = self.destination_states[source_state][dest_label_ind]

                    label_one = source_state // self.num_labels  # floor div
                    if label_one == self.num_labels or source_state == self.head_state:
                        trans_prob = self.initial_transition_prob
                    else:
                        label_two = source_state % self.num_labels
                        trans_prob = self.transition_probs[
                            label_one, label_two, dest_label_ind
                        ]
                    ob_prob = observation_probs[time_step + 1][dest_label_ind]
                    tmp_next_score = (
                        current_score[source_state]
                        + np.log(trans_prob)
                        + np.log(ob_prob)
                    )
                    if tmp_next_score >= next_score[dest_state]:
                        next_score[dest_state] = tmp_next_score
                        source_states[time_step][dest_state] = source_state
            tmp = current_score
            current_score = next_score
            next_score = tmp

        # retrieve best state sequence in reverse using scores directly
        current_state = -1

        # initial step to get best state
        for state in self.tail_states:
            if (
                current_state == -1
                or current_score[state] > current_score[current_state]
            ):
                current_state = state
        resequenced = []
        # loop through len-2 because we already figured out last element at -1
        for time_step in range((len(observation_probs) - 2), -1, -1):
            previous_state = source_states[time_step][current_state]
            source_label = -1

            possible_dest_states = self.destination_states[previous_state]
            for d in range(len(possible_dest_states)):
                if possible_dest_states[d] == current_state:
                    source_label_ind = self.destination_label_ind[d]
                    source_label = self.labels[source_label_ind]
                    break
            resequenced.append(source_label)
            current_state = previous_state

        previous_state = self.head_state
        source_label = -1
        possible_dest_states = self.destination_states[previous_state]
        for d in range(len(possible_dest_states)):
            if possible_dest_states[d] == current_state:
                source_label_ind = self.destination_label_ind[d]
                source_label = self.labels[source_label_ind]
                break
        resequenced.append(source_label)
        resequenced.reverse()
        return resequenced

def get_trans_mat(seqs, smoothing_constant=1e-4):
    """
    calculate second-order transition matrix given sequences of syllable labels

    Parameters
    ----------
    seqs : list of Sequence objects

    smoothing_constant : float
        default is 1e-4. Added to all probabilities so that none are zero.
        Mathematically convenient for computing Viterbi algorithm with
        exponential.

    Returns
    -------
    labels : 1-d array of ints
        set of unique labels across all Sequences.

    trans_mat : 3-d array
        Shape is n * n * n where n is the number of labels.
        trans_mat[i,j,k] is the probability of transitioning to labels[k]
        at time step t, given that label at time step t-1 was labels[k]
        and the label at time step t-2 was labels[i].
    """

    all_syls = [syl.label for seq in seqs for syl in seq.syls]
    labels = np.unique(all_syls)

    all_label_seqs = []
    for seq in seqs:
        all_label_seqs.append([syl.label for syl in seq.syls])

    num_labels = labels.shape[0]
    counts = np.zeros((num_labels, num_labels, num_labels))
    for label_seq in all_label_seqs:
        for ind in range(2, len(label_seq)):
            k = np.where(labels == label_seq[ind])
            j = np.where(labels == label_seq[ind - 1])
            i = np.where(labels == label_seq[ind - 2])
            counts[i, j, k] += 1
    trans_mat = np.zeros(counts.shape)
    for i in range(num_labels):
        for j in range(num_labels):
            num_ij_occurences = np.sum(counts[i, j, :])
            if num_ij_occurences > 0:
                for k in range(num_labels):
                    trans_mat[i, j, k] = counts[i, j, k] / num_ij_occurences

    if smoothing_constant:
        for i in range(num_labels):
            for j in range(num_labels):
                trans_mat[i, j, :] += smoothing_constant
                trans_mat[i, j, :] /= np.sum(trans_mat[i, j, :])

    return trans_mat


text:
import React from 'react';
import classNames from 'classnames';

class AvatarItem extends React.Component {
  static propTypes = {
    className: React.PropTypes.string,
    image: React.PropTypes.string,
    placeholder: React.PropTypes.string.isRequired,
    size: React.PropTypes.string,
    title: React.PropTypes.string.isRequired
  };

  constructor(props) {
    super(props);
  }

  render() {
    const { title, className, image, size, placeholder } = this.props;

    const placeholderClassName = classNames('avatar__placeholder', `avatar__placeholder--${placeholder}`);
    const avatarClassName = classNames('avatar', {
      'avatar--tiny': size === 'tiny',
      'avatar--small': size === 'small',
      'avatar--medium': size === 'medium',
      'avatar--large': size === 'large',
      'avatar--big': size === 'big',
      'avatar--huge': size === 'huge'
    }, className);

    const avatar = image ?  : null;

    return (

        {avatar}
        {title[0]}

    );
  }
}

export default AvatarItem;


text:
from django.shortcuts import render

from common.models import ReleaseNotes

def releasenotes(request):
    """Get release notes"""
    context = {}
    context['release_notes'] = ReleaseNotes.objects.all()
    return render(request, 'pages/releasenotes.html', context)


text:
namespace Econom.Services.Data.Contracts
{
    using Econom.Data.Models;
    using System.Linq;

    public interface ICategoryService
    {
        IQueryable<Category> GetByName(string name);

        Category GetByGS1(string gs1);
    }
}


text:
package org.gwtbootstrap3.extras.bootbox.client;

import com.google.gwt.core.client.GWT;
import com.google.gwt.resources.client.ClientBundle;
import com.google.gwt.resources.client.TextResource;

/**
 * @author Sven Jacobs
 */
interface BootboxClientBundle extends ClientBundle {

    static final BootboxClientBundle INSTANCE = GWT.create(BootboxClientBundle.class);

    @Source("resource/js/bootbox.min.js")
    TextResource bootbox();
}


text:
package net.starbs.antipleurdawn.events;

public interface EventInterface
{
    //
}


text:
from django.conf.urls.defaults import patterns, url
from django.contrib.auth import views as auth_views

from users.views import login, profile, register

urlpatterns = patterns('',
    url(r'^login/$', login, name='users.login'),
    url(r'^logout/$', auth_views.logout, {'next_page': '/'},
        name='users.logout'),
    url(r'^profile/$', profile, name='users.profile'),
    url(r'^register/$', register, name='users.register'),
)


text:
import styled from 'styled-components';

const anim = {
  entering: 'scale(0.75)',
  entered: 'none',
  exiting: 'scale(0.75)',
};

const opac = {
  entering: 0,
  entered: 1,
  exiting: 0,
};

export const InnerMenu = styled.div`
  top: 0;
`;

export const ContainerPositioning = styled.div<{ state: string }>`
  transition: transform 0.2s, opacity 0.2s;
  transform-origin: 50% 0;
  transform: ${props => anim[props.state]};
  opacity: ${props => opac[props.state]};
`;

export const Container = styled.div`
  padding: 50px;
  height: 300px;
  position: relative;
  overflow: hidden;
`;

export const Header = styled.header`
  display: flex;
  position: relative;
  align-items: center;

  > :first-child {
    margin-right: auto;
    color: white;
    font-size: 30px;
    flex-shrink: 0;
  }
`;

export const Background = styled.div`
  width: 100%;
  height: 100%;
  overflow: hidden;
  background: linear-gradient(150deg, #53f 15%, #05d5ff 70%, #a6ffcb 94%);
  position: absolute;
  top: 0;
  left: 0;
`;

export const MenuLink = styled.a`
  font-weight: 500;
  padding: 0 25px;
  height: 50px;
  font-size: 17px;
  line-height: 50px;
  outline: none;
  color: #fff;
  transition: color 0.1s ease;
  text-decoration: none;

  &:hover,
  &:focus {
    color: hsla(0, 0%, 100%, 0.5);
  }
`;

export const Menu = styled.ul`
  position: relative;
  padding: 0 20px;
  margin: 0;
`;

export const MenuItem = styled.li`
  display: block;
  padding: 9px 0;
  outline: none;
  position: relative;
  list-style: none;
  transition: color 0.1s;
  color: #6772e5;
  margin: 0;
  text-transform: uppercase;

  &:hover,
  &:focus {
    color: #32325d;
  }

  small {
    display: block;
    color: #6b7c93;
    text-transform: none;
  }
`;


text:
namespace ChilliSource
{
    //------------------------------------------------------------------------------
    DirectionalRenderLight::DirectionalRenderLight() noexcept
        : m_colour(Colour::k_black), m_direction(Vector3::k_unitNegativeY)
    {
    }

    //------------------------------------------------------------------------------
    DirectionalRenderLight::DirectionalRenderLight(const Colour& colour, const Vector3& direction) noexcept
        : m_colour(colour), m_direction(direction)
    {
    }

    //------------------------------------------------------------------------------
    DirectionalRenderLight::DirectionalRenderLight(const Colour& colour, const Vector3& direction, const Matrix4& lightWorldMatrix, const Matrix4& lightProjectionMatrix, const Quaternion& lightOrientation,
                                                   f32 shadowTolerance, const RenderTargetGroup* shadowMapTarget) noexcept
        : m_colour(colour), m_direction(direction), m_lightWorldMatrix(lightWorldMatrix), m_lightProjectionMatrix(lightProjectionMatrix), m_lightOrientation(lightOrientation),
          m_shadowTolerance(shadowTolerance), m_shadowMapTarget(shadowMapTarget)
    {
        CS_ASSERT(m_shadowMapTarget, "Shadow map target cannot be null.");
    }
}


text:
The Keyboard-Oriented File & Folder Explorer for Efficiency, or Koffee, is a no-nonsense alternative to Windows Explorer focused on VIM-style keyboard shortcuts, speed, and simplicity. It is built on .NET WPF, written in F#.

### Why would I want to use this?
**The goal of this application is to allow users to navigate and manipulate files and folders very quickly**, almost at the speed of thought -- a speed only achievable via keyboard. If you've ever experienced the productivity boost that comes from learning and using all the keyboard shortcuts in an application (or learned to use the text editor [VIM](http://www.vim.org/)), you understand what a big difference it makes.

![Screenshot](screenshot.png)

## Installation
Koffee depends on **Microsoft .NET Framework 4.5.1**. It is installed by default on Windows 8.1 or newer. Even on older versions of windows, you may already have it installed; look for it in the list of installed programs in "Programs and Features" (Windows 7 or Vista) or "Add or Remove Programs" (Windows XP). If you don't see it, head to [Microsoft's download page](https://www.microsoft.com/en-us/download/details.aspx?id=40773) to download and install it.

### From [Chocolatey](https://chocolatey.org/)

    choco install koffee

### From [Scoop](https://scoop.sh/)
Koffee is part of the "extras" bucket. If you haven't already, add this bucket with `scoop bucket add extras`.

    scoop install koffee

### From Installer or Zip
Go to the [releases page](https://github.com/mattstermiller/koffee/releases). From there, you can download and run **Koffee-Setup.exe**, which will guide you through the installation with a wizard. Or, if you prefer to install it yourself, you can download the zip file, unzip the app wherever you want and create your own shortcuts.

### From Source
You will need to have installed:
- [Visual Studio or VS Build Tools 2019](https://visualstudio.microsoft.com/downloads/)
  - Make sure to select the components ".NET Core SDK", ".NET Framework 4.5.1 targeting pack" and "F# compiler"

Steps:
- Clone this repository
- Open a terminal to the folder and run `.\fake.cmd build -t install`

## Using Koffee
First of all, take your hand off of the mouse because this is a keyboard tool! Once you're familiar with the hotkeys, you'll be navigating your files more quickly than you ever could with a mouse. If you're familiar with the text editor [VIM](http://www.vim.org/) which is popular among programmers, you should feel at home.

#### The Basics
_A capital letter indicates that the letter key is combined with Shift._
- `j` to move the cursor down
- `k` to move the cursor up
- `h` to go up to the parent folder
- `l` or `Enter` to open the selected file or folder
- `Shift + Enter` to open the "Open With" dialog for the selected file
- `H` to go back in navigation history
- `L` to go forward in navigation history
- `gr` to go to the root directory (Drives)
- `Tab` to switch between the main view and the path box
- `?` to open the Settings window, which displays the hotkeys for all commands.
- `Esc` to cancel actions, searches, path input, etc.
- `Ctrl + w` to exit

#### Advanced Navigation
- **Scroll quickly**
    - `Ctrl + j` and `Ctrl + k` move the cursor by half-pages at a time.
    - `gg` (press `g` twice) jumps to the first item, and `G` jumps to the last item.
- **Find / Jump to item**:
    - Press `f` then the beginning of a file or folder name. The cursor will jump to the first matching item as you type (not case-sensitive).
        - Press `;` during or after a Find to jump to the next matching item.
        - Press `Enter` to open the selected item and close Find.
        - Press `Esc` to close Find.
    - Press `F` to start a "multi" Find, which stays open when opening folders.
- **Search**:
    - Press `/` to start a search. This will move your cursor to a search input at the bottom of the window where you can enter space-separated search terms. The list will be filtered to matching items as you type.
    - Press `Ctrl + i` to toggle whether the search is case-sensitive.
    - Press `Ctrl + r` to toggle regular expression mode instead of term matching.
    - Press `Ctrl + s` to toggle sub-folder searching. A progress bar will show while results are loaded in the background.
    - Press `Up` to go back through previous searches and `Down` to go forward.
    - Press `Shift + Delete` when the previous searches are shown to delete the selected search history
    - Press `Enter` to close the search input and navigate the results. The current search filter will be shown at the bottom of the window.
    - Press `Esc` when the search input is open or when a search filter is active to cancel the search.
    - Press `n` to repeat the previous search when no search is active.
- **Bookmarks**
    - Set a bookmark by pressing `m`. The existing bookmarks are shown. Enter any character to set a bookmark to that character. Upper-case letters are distinct from lower-case letters.
    - Go to a bookmark by pressing `'`. The bookmarks are shown. Enter a character to activate the bookmark set to that character.
    - When viewing bookmarks, press `Delete` then a character to delete the bookmark set to that character.
- **Saved Searches**
    - To save an active search (the search input must be closed), press `m`. The existing saved searches are shown. Enter any character to set a saved search to that character. Upper-case letters are distinct from lower-case letters.
    - Activate a saved search by pressing `` ` ``. The saved searches are shown. Enter a character to activate the saved search set to that character.
    - When viewing saved searches, press `Delete` then a character to delete the saved search set to that character.
- **Sorting**
    - Press `sn` to sort by name, ascending then descending.
    - Press `sm` to sort by modified date, descending then ascending.
    - Press `ss` to sort by size, ascending then descending.
- **Path Box Suggestions** will appear when typing in the path box.
    - When no slashes are in the path box, folders that you have visited before are searched. Folders starting with the first search term are shown first, then other matches sorted by most recently visited.
    - When a path is in the path box, everything after the last slash is used to search the folder before the last slash. For example, typing "C:\Windows\sy 32" would suggest "C:\Windows\System32".
    - When suggestions are shown, use the up and down arrow keys to select a suggestion. When there is only one suggestion, it is selected automatically.
    - Press `Tab` to fill in the path box with the selected suggestion and continue typing, or press `Enter` to open the selected suggestion.
    - When suggestions from history are shown, pressing `Delete` will remove it from the list and history.

#### File & Folder Manipulation
- **Create File or Folder**: Press `o` to create a file or `O` to create a folder. Type in the name of the new item and press `Enter`.
- **Rename**: There are several ways to start renaming the currently selected file or folder.
    - Press `i` to start with the cursor at the beginning of the name
    - Press `a` to start with the cursor at the end of the name, before the extension
    - Press `A` to start with the cursor at the end of the extension
    - Press `c` to start with the name (without extension) selected so that typing will replace the name
    - Press `C` to start with the full name selected
    - When you are done editing the name, press `Enter`
- **Move / Copy / Shortcut**
    1. Press `d` to start a move, `y` to start a copy, or `Y` to start a shortcut of the selected file or folder. The item and operation will be displayed in the lower-right corner of the window.
    2. Navigate to the destination folder and press `p` to move, copy, or create a shortcut of the item there.
        - A copy to the same folder will append "(copy)" to the name.
        - If an item with the same name already exists, you will be prompted to overwrite it. If you choose to overwrite a folder, the contents will be merged (existing files in the destination with the same name will be overwritten, but the others will remain).
- **Delete**
    - Press `Delete` to send the currently selected item to the Recycle Bin. If the item cannot be recycled, an error message will be shown instead.
    - Press `Shift + Delete` to delete it permanently. You will be prompted to make sure this is what you want to do; press `y` to proceed with deletion or press `n` to cancel.
- **Undo / Redo Action**
    - Press `u` to undo the last file or folder action (this includes creating, renaming, moving, copying and deleting). The status bar will report the action that was undone. Since deletions cannot be undone, the status bar will simply report the deletion that cannot be undone.
    - Press `U` to redo the last action that was undone. Note that performing any action after an undo will clear the redo list.
    - Press `gu` to display undo / redo history.

- **Copy to Clipboard**: Press `Ctrl + c` to copy the selected item to the Windows Clipboard.
    - Paste in Windows Explorer or another app that accepts files to copy the file or folder there.
    - Paste in any text editor or text input to insert the file or folder's path there.

#### Other
- Repeat cursor, navigation and undo/redo commands by pressing numbers before the command. For example, pressing `4H` will go back 4 times.
- Display navigation history for Back/Forward with `gh`
- Display status message history with `gs`
- Open the selected file and exit with `Ctrl + Enter`
- Open the selected file or folder's properties with `Alt + Enter`
- Open a second window for easier file comparison or moves with `Ctrl + n`
- Open Windows Explorer at your current location with `Ctrl + Shift + e`
- Open the commandline tool (configured in the Settings window) at your current location with `Ctrl + Shift + c`
- Open the currently selected file with your text editor (configured in the Settings window) with `Ctrl + Shift + t`
- Show/hide hidden files and folders with `F9`

There are more commands at your disposal. Open the Settings window with `?` for the full list of commands and their key bindings!

## Contributing
If you want to contribute to Koffee, thank you! Head to the [issues page](https://github.com/mattstermiller/koffee/issues).
- Did you find a bug or issue in Koffee? Please create a new issue!
- Do you have an idea for a cool new feature? Please create an issue and detail your idea and how it would work!
- Do you want to contribute but not sure where to start? Look for issues that you might be interested in working on.
    The `help wanted` tag is used for issues that are easier for newcomers to pick up. Bonus if the issue is part of the
    next milestone, but that's not necessary!
- Still not sure? [Email me](mailto:miller.mattster@gmail.com) and we can discuss it!

Please read the [Development Guide](DEVGUIDE.md) to get started on Koffee code.

## Future Planned Features
- Select multiple items
- Configurable hotkeys
- Theme selection and editor
- And more... check out the [issues list](https://github.com/mattstermiller/koffee/issues) and please add your own ideas and contributions!