text:
require 'erb'
require 'uri'
require 'dropcaster/logging'

module Dropcaster
  #
  # Represents a podcast feed in the RSS 2.0 format
  #
  class Channel
    include Logging
    include ERB::Util # for h() in the ERB template

    STORAGE_UNITS = %w[Byte KB MB GB TB].freeze
    MAX_KEYWORD_COUNT = 12

    # Instantiate a new Channel object. +sources+ must be present and can be a String or Array
    # of Strings, pointing to a one or more directories or MP3 files.
    #
    # +attributes+ is a hash with all attributes for the channel. The following attributes are
    # mandatory when a new channel is created:
    #
    # * <tt>:title</tt> - Title (name) of the podcast
    # * <tt>:url</tt> - URL to the podcast
    # * <tt>:description</tt> - Short description of the podcast (a few words)
    #
    def initialize(sources, attributes)
      # Assert mandatory attributes
      %i[title url description].each { |attr|
        raise MissingAttributeError.new(attr) if attributes[attr].blank?
      }

      @attributes = attributes
      @attributes[:explicit] = yes_no_or_input(attributes[:explicit])
      @source_files = []

      # if (sources.respond_to?(:each)) # array
      if sources.is_a? Array
        sources.each do |src|
          add_files(src)
        end
      else
        # single file or directory
        add_files(sources)
      end

      # If not absolute, prepend the image URL with the channel's base to make an absolute URL
      unless @attributes[:image_url].blank? || @attributes[:image_url] =~ /^https?:/
        logger.info("Channel image URL '#{@attributes[:image_url]}' is relative, so we prepend it with the channel URL '#{@attributes[:url]}'")
        @attributes[:image_url] = (URI.parse(@attributes[:url]) + @attributes[:image_url]).to_s
      end

      # If enclosures_url is not given, take the channel URL as a base.
      if @attributes[:enclosures_url].blank?
        logger.info("No enclosure URL given, using the channel's enclosure URL")
        @attributes[:enclosures_url] = @attributes[:url]
      end

      # Warn if keyword count is larger than recommended
      assert_keyword_count(@attributes[:keywords])

      channel_template = @attributes[:channel_template] || File.join(File.dirname(__FILE__), '..', '..', 'templates', 'channel.rss.erb')

      begin
        @erb_template = ERB.new(IO.read(channel_template))
      rescue Errno::ENOENT => e
        raise TemplateNotFoundError.new(e.message)
      end
    end

    #
    # Returns this channel as an RSS representation. The actual rendering is done with the help
    # of an ERB template. By default, it is expected as ../../templates/channel.rss.erb (relative)
    # to channel.rb.
    #
    def to_rss
      @erb_template.result(binding)
    end

    #
    # Returns all items (episodes) of this channel, ordered by newest-first.
    #
    def items
      all_items = []
      @source_files.each { |src|
        item = Item.new(src)

        logger.debug("Adding new item from file #{src}")

        # set author and image_url from channel if empty
        if item.tag.artist.blank?
          logger.info("#{src} has no artist, using the channel's author")
          item.tag.artist = @attributes[:author]
        end

        if item.image_url.blank?
          logger.info("#{src} has no image URL set, using the channel's image URL")
          item.image_url = @attributes[:image_url]
        end

        # construct absolute URL, based on the channel's enclosures_url attribute
        item.url = URI.parse(enclosures_url) + item.file_path.each_filename.map { |p| url_encode(p) }.join('/')

        # Warn if keyword count is larger than recommended
        assert_keyword_count(item.keywords)

        all_items << item
      }

      all_items.sort { |x, y| y.pub_date <=> x.pub_date }
    end

    # from http://stackoverflow.com/questions/4136248
    def humanize_time(secs)
      [[60, :s], [60, :m], [24, :h], [1000, :d]].map { |count, name|
        if secs.positive?
          secs, n = secs.divmod(count)
          "#{n.to_i}#{name}"
        end
      }.compact.reverse.join(' ')
    end

    # Fixed version of https://gist.github.com/260184
    def humanize_size(number)
      return nil if number.nil?

      if number.to_i < 1024
        unit = number > 1 ? 'Bytes' : 'Byte'
      else
        max_exp  = STORAGE_UNITS.size - 1
        number   = Float(number)
        exponent = (Math.log(number) / Math.log(1024)).to_i # Convert to base 1024
        exponent = max_exp if exponent > max_exp # we need this to avoid overflow for the highest unit
        number  /= 1024**exponent
        unit = STORAGE_UNITS[exponent]
      end

      '%n %u'.gsub(/%n/, number.to_i.to_s).gsub(/%u/, unit)
    end

    #
    # Delegate all unknown methods to @attributes
    #
    # rubocop:disable Style/MethodMissing
    def method_missing(meth, *args)
      m = meth.id2name
      if m =~ /=$/
        @attributes[m.chop.to_sym] = (args.length < 2 ? args[0] : args)
      else
        @attributes[m.to_sym]
      end
    end
    # rubocop:enable Style/MethodMissing

    def respond_to_missing?(meth, *)
      (meth.id2name =~ /=$/) || super
    end

    private

    def add_files(src)
      if File.directory?(src)
        @source_files.concat(Dir.glob(File.join(src, '*.mp3'), File::FNM_CASEFOLD))
      else
        @source_files << src
      end
    end

    #
    # Deal with Ruby's autoboxing of Yes, No, true, etc values in YAML
    #
    def yes_no_or_input(flag)
      case flag
      when nil
        nil
      when true
        'Yes'
      when false
        'No'
      else
        flag
      end
    end

    #
    # http://snippets.dzone.com/posts/show/4578
    #
    def truncate(string, count=30)
      if string.length >= count
        shortened = string[0, count]
        splitted = shortened.split(/\s/)
        words = splitted.length
        splitted[0, words - 1].join(' ') + '...'
      else
        string
      end
    end

    def assert_keyword_count(keywords)
      if keywords && MAX_KEYWORD_COUNT < keywords.size
        logger.info("The list of keywords has #{keywords.size} entries, which exceeds the recommended maximum of #{MAX_KEYWORD_COUNT}.")
      end
    end
  end
end


text:
#region Copyright (c) 2003, newtelligence AG. All rights reserved.

#endregion

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;

namespace newtelligence.DasBlog.Web
{
	/// <summary>
	/// Summary description for PermaLink.
	/// </summary>
	public partial class PermaLink : SharedBasePage
	{

		public PermaLink()
		{
			showTrackingDetail = true;
			isAggregatedView = false;
		}

		protected override PlaceHolder ContentPlaceHolder
		{
			get { return contentPlaceHolder; }
		}

		public override string GetPageTemplate(string path)
		{
			return base.GetPageTemplate(path);
		}

		protected override Macros InitializeMacros()
		{
			return MacrosFactory.CreateMacrosInstance(this);
		}

		public override void ProcessItemTemplate(Entry item, Control ContentPlaceHolder)
		{
			base.ProcessItemTemplate(item, ContentPlaceHolder);

			// add the trackback and pingback information
			string metaData = "";

			if (!this.IsAggregatedView)
			{
				if (this.SiteConfig.EnablePingbackService)
				{
					metaData = string.Format("<link ref=\"pingback\" href=\"{0}\">\n", new Uri(new Uri(this.SiteConfig.Root), "pingback.aspx"));
				}

				if (this.SiteConfig.EnableTrackbackService)
				{
					// we need to ensure that the URL we use in the identifier
					// is the same one used by the remote server or they will
					// not post a trackback since dasBlog supports many url
					// formats.
					string link = Request.Url.GetLeftPart(UriPartial.Authority) + Request.RawUrl.ToString();

					metaData += "\n<!--\n<rdf:RDF xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\"\nxmlns:dc=\"http://purl.org/dc/elements/1.1/\"\nxmlns:trackback=\"http://madskills.com/public/xml/rss/module/trackback/\">\n";
					metaData += string.Format("<rdf:Description\nrdf:about=\"{0}\"\ndc:identifier=\"{1}\"\ndc:title=\"{2}\"\ntrackback:ping=\"{3}\" />\n</rdf:RDF>\n-->\n\n", link, link, item.Title, SiteUtilities.GetTrackbackUrl(item.EntryId));
				}
			}

			ContentPlaceHolder.Controls.Add(new LiteralControl(metaData));
		}

		public override string GetItemTemplate()
		{
			return base.GetItemTemplate();
		}

		protected override EntryCollection LoadEntries()
		{
			if (WeblogEntryId.Length == 0)
			{
				Response.StatusCode = 404;
				Response.SuppressContent = true;
				Response.End();
				return null; //save us all the time
			}

			EntryCollection entryCollection = new EntryCollection();
			Entry entry = DataService.GetEntry(WeblogEntryId);
            ILoggingDataService logService = this.LoggingService;
			if (entry != null)
			{
				entryCollection.Add(entry);

				if (NotModified(entryCollection))
				{
					Response.End();
					return null;
				}
			}

			return entryCollection;
		}

		#region Web Form Designer generated code
		protected override void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
		}
		#endregion
	}
}

redpajama_set_name: RedPajamaGithub


text:
import { Router } from 'express';
import * as Controller from '../controllers/semanticRule.controller';

const router = new Router();

router.route('/semanticRules').get((req, res, next) => {
  if (process.env.NODE_ENV === 'production') {
    res.set('Cache-Control', 'private, max-age=60');
  }
  next();
}, Controller.getSemanticRules);

export default router;


text:
namespace gandiva {

static const int DEFAULT_CACHE_SIZE = 500;

int GetCapacity() {
  int capacity;
  const char* env_cache_size = std::getenv("GANDIVA_CACHE_SIZE");
  if (env_cache_size != nullptr) {
    capacity = std::atoi(env_cache_size);
    if (capacity <= 0) {
      ARROW_LOG(WARNING) << "Invalid cache size provided. Using default cache size: "
                         << DEFAULT_CACHE_SIZE;
      capacity = DEFAULT_CACHE_SIZE;
    }
  } else {
    capacity = DEFAULT_CACHE_SIZE;
  }
  return capacity;
}

void LogCacheSize(size_t capacity) {
  ARROW_LOG(INFO) << "Creating gandiva cache with capacity: " << capacity;
}

}  // namespace gandiva


text:
**Alienstrap for Wordpress (Alienstrap)** is a [Wordpress](http://wordpress.org) theme based on [Twitter Bootstrap 3](http://getbootstrap.com).

# Requirements/Dependencies #

In order to apply **Alienstrap** to your website, those following applications, plugins and modules are required to install.

* [Wordpress](http://wordpress.org) 3.7.1 or later.
* [Options Framework](http://wordpress.org/plugins/options-framework) 1.7.1 or later.
* [Aqua Resizer](https://github.com/syamilmj/Aqua-Resizer) 1.2.0 or later.

_*NOTE*_: Previous versions of Wordpress, Options Framework and Aqua Resizer have not been tested. You can use earlier version of those with your own risk.

# Contribution #

Your contribution is always welcome! All your work should be done in the`dev` branch. Once you finish your work, please send us a pull request on `dev` for review.

# License #

**Alienstrap** is released under [MIT License](http://opensource.org/licenses/MIT).

> The MIT License (MIT)
>
> Copyright (c) 2013 [aliencube.org](http://aliencube.org)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
> furnished to do so, subject to the following conditions:
>
> The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
>
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.


text:
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */
/*
 *  Copyright (c) 1999 by Uros Bizjak <uros@kss-loka.si>
 *                        Takashi Iwai <tiwai@suse.de>
 *
 *  SB16ASP/AWE32 CSP control
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
 *
 */
#ifndef __SOUND_SB16_CSP_H
#define __SOUND_SB16_CSP_H

/* CSP modes */
#define SNDRV_SB_CSP_MODE_NONE		0x00
#define SNDRV_SB_CSP_MODE_DSP_READ	0x01	/* Record from DSP */
#define SNDRV_SB_CSP_MODE_DSP_WRITE	0x02	/* Play to DSP */
#define SNDRV_SB_CSP_MODE_QSOUND		0x04	/* QSound */

/* CSP load flags */
#define SNDRV_SB_CSP_LOAD_FROMUSER	0x01
#define SNDRV_SB_CSP_LOAD_INITBLOCK	0x02

/* CSP sample width */
#define SNDRV_SB_CSP_SAMPLE_8BIT		0x01
#define SNDRV_SB_CSP_SAMPLE_16BIT		0x02

/* CSP channels */
#define SNDRV_SB_CSP_MONO			0x01
#define SNDRV_SB_CSP_STEREO		0x02

/* CSP rates */
#define SNDRV_SB_CSP_RATE_8000		0x01
#define SNDRV_SB_CSP_RATE_11025		0x02
#define SNDRV_SB_CSP_RATE_22050		0x04
#define SNDRV_SB_CSP_RATE_44100		0x08
#define SNDRV_SB_CSP_RATE_ALL		0x0f

/* CSP running state */
#define SNDRV_SB_CSP_ST_IDLE		0x00
#define SNDRV_SB_CSP_ST_LOADED		0x01
#define SNDRV_SB_CSP_ST_RUNNING		0x02
#define SNDRV_SB_CSP_ST_PAUSED		0x04
#define SNDRV_SB_CSP_ST_AUTO		0x08
#define SNDRV_SB_CSP_ST_QSOUND		0x10

/* maximum QSound value (180 degrees right) */
#define SNDRV_SB_CSP_QSOUND_MAX_RIGHT	0x20

/* maximum microcode RIFF file size */
#define SNDRV_SB_CSP_MAX_MICROCODE_FILE_SIZE	0x3000

/* microcode header */
struct snd_sb_csp_mc_header {
	char codec_name[16];		/* id name of codec */
	unsigned short func_req;	/* requested function */
};

/* microcode to be loaded */
struct snd_sb_csp_microcode {
	struct snd_sb_csp_mc_header info;
	unsigned char data[SNDRV_SB_CSP_MAX_MICROCODE_FILE_SIZE];
};

/* start CSP with sample_width in mono/stereo */
struct snd_sb_csp_start {
	int sample_width;	/* sample width, look above */
	int channels;		/* channels, look above */
};

/* CSP information */
struct snd_sb_csp_info {
	char codec_name[16];		/* id name of codec */
	unsigned short func_nr;		/* function number */
	unsigned int acc_format;	/* accepted PCM formats */
	unsigned short acc_channels;	/* accepted channels */
	unsigned short acc_width;	/* accepted sample width */
	unsigned short acc_rates;	/* accepted sample rates */
	unsigned short csp_mode;	/* CSP mode, see above */
	unsigned short run_channels;	/* current channels  */
	unsigned short run_width;	/* current sample width */
	unsigned short version;		/* version id: 0x10 - 0x1f */
	unsigned short state;		/* state bits */
};

/* HWDEP controls */
/* get CSP information */
#define SNDRV_SB_CSP_IOCTL_INFO		_IOR('H', 0x10, struct snd_sb_csp_info)
/* load microcode to CSP */
/* NOTE: struct snd_sb_csp_microcode overflows the max size (13 bits)
 * defined for some architectures like MIPS, and it leads to build errors.
 * (x86 and co have 14-bit size, thus it's valid, though.)
 * As a workaround for skipping the size-limit check, here we don't use the
 * normal _IOW() macro but _IOC() with the manual argument.
 */
#define SNDRV_SB_CSP_IOCTL_LOAD_CODE	\
	_IOC(_IOC_WRITE, 'H', 0x11, sizeof(struct snd_sb_csp_microcode))
/* unload microcode from CSP */
#define SNDRV_SB_CSP_IOCTL_UNLOAD_CODE	_IO('H', 0x12)
/* start CSP */
#define SNDRV_SB_CSP_IOCTL_START		_IOW('H', 0x13, struct snd_sb_csp_start)
/* stop CSP */
#define SNDRV_SB_CSP_IOCTL_STOP		_IO('H', 0x14)
/* pause CSP and DMA transfer */
#define SNDRV_SB_CSP_IOCTL_PAUSE		_IO('H', 0x15)
/* restart CSP and DMA transfer */
#define SNDRV_SB_CSP_IOCTL_RESTART	_IO('H', 0x16)

#endif /* __SOUND_SB16_CSP_H */


text:
var path = require('path');
var fs = require('fs');

exports.init = function(grunt) {
  var exports = {};

  exports.casperjs = function(filepath, options, callback) {

    var command = "./node_modules/.bin/casperjs";
    if (!fs.existsSync(command)) {
      command = path.join(__dirname, '..', '..', 'node_modules', '.bin', 'casperjs');
      if (!fs.existsSync(command)) {
        command = path.join(__dirname, '..', '..', '..', 'casperjs', 'bin', 'casperjs');
      }
    }
    if (process.platform === 'win32') {
      command += ".cmd";
    }
    var args = ['test'],
        spawn = require('child_process').spawn,
        phantomBinPath = require('phantomjs').path;

    if (options.casperjsOptions && options.casperjsOptions.length > 0) {
        args = args.concat(options.casperjsOptions);
    }

    args.push(filepath);

    if (!options.silent) {
      grunt.log.writeln("Command: " + command);
    }

    process.env["PHANTOMJS_EXECUTABLE"] = phantomBinPath;

    if (!options.silent) {
      grunt.log.write('\nRunning tests from "' + filepath + '":\n');
    }

    grunt.util.spawn({
      cmd: command,
      args: args,
      opts: {
        // pipe stdout/stderr through
        stdio: 'inherit'
      }
    }, function(error, stdout, code) {
      callback(error);
    });

  };

  return exports;
};


text:
""" Example to demonstrate how to use queues
Author: Chip Huyen
Prepared for the class CS 20SI: "TensorFlow for Deep Learning Research"
cs20si.stanford.edu
"""
from __future__ import print_function
import tensorflow as tf
import numpy as np

N_SAMPLES = 1000
NUM_THREADS = 4
# Generating some simple data
# create 1000 random samples, each is a 1D array from the normal distribution (10, 1)
data = 10 * np.random.randn(N_SAMPLES, 4) + 1
# create 1000 random labels of 0 and 1
target = np.random.randint(0, 2, size=N_SAMPLES)

queue = tf.FIFOQueue(capacity=50, dtypes=[tf.float32, tf.int32], shapes=[[4], []])

enqueue_op = queue.enqueue_many([data, target])
data_sample, label_sample = queue.dequeue()

# create ops that do something with data_sample and label_sample

# create NUM_THREADS to do enqueue
qr = tf.train.QueueRunner(queue, [enqueue_op] * NUM_THREADS)
with tf.Session() as sess:
	# create a coordinator, launch the queue runner threads.
	coord = tf.train.Coordinator()
	enqueue_threads = qr.create_threads(sess, coord=coord, start=True)
	for step in xrange(100): # do to 100 iterations
		if coord.should_stop():
			break
		data_batch, label_batch = sess.run([data_sample, label_sample])
	coord.request_stop()
	coord.join(enqueue_threads)


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE190_Integer_Overflow__int64_t_fscanf_square_44.c
Label Definition File: CWE190_Integer_Overflow.label.xml
Template File: sources-sinks-44.tmpl.c
*/
/*
 * @description
 * CWE: 190 Integer Overflow
 * BadSource: fscanf Read data from the console using fscanf()
 * GoodSource: Set data to a small, non-zero number (two)
 * Sinks: square
 *    GoodSink: Ensure there will not be an overflow before squaring data
 *    BadSink : Square data, which can lead to overflow
 * Flow Variant: 44 Data/control flow: data passed as an argument from one function to a function in the same source file called via a function pointer
 *
 * */

#include "std_testcase.h"

#include <math.h>

#ifndef OMITBAD

static void badSink(int64_t data)
{
    {
        /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
        int64_t result = data * data;
        printLongLongLine(result);
    }
}

void CWE190_Integer_Overflow__int64_t_fscanf_square_44_bad()
{
    int64_t data;
    /* define a function pointer */
    void (*funcPtr) (int64_t) = badSink;
    data = 0LL;
    /* POTENTIAL FLAW: Use a value input from the console */
    fscanf (stdin, "%lld", &data);
    /* use the function pointer */
    funcPtr(data);
}

#endif /* OMITBAD */

#ifndef OMITGOOD

/* goodG2B() uses the GoodSource with the BadSink */
static void goodG2BSink(int64_t data)
{
    {
        /* POTENTIAL FLAW: if (data*data) > LLONG_MAX, this will overflow */
        int64_t result = data * data;
        printLongLongLine(result);
    }
}

static void goodG2B()
{
    int64_t data;
    void (*funcPtr) (int64_t) = goodG2BSink;
    data = 0LL;
    /* FIX: Use a small, non-zero value that will not cause an overflow in the sinks */
    data = 2;
    funcPtr(data);
}

/* goodB2G() uses the BadSource with the GoodSink */
static void goodB2GSink(int64_t data)
{
    /* FIX: Add a check to prevent an overflow from occurring */
    if (abs((long)data) <= (long)sqrt((double)LLONG_MAX))
    {
        int64_t result = data * data;
        printLongLongLine(result);
    }
    else
    {
        printLine("data value is too large to perform arithmetic safely.");
    }
}

static void goodB2G()
{
    int64_t data;
    void (*funcPtr) (int64_t) = goodB2GSink;
    data = 0LL;
    /* POTENTIAL FLAW: Use a value input from the console */
    fscanf (stdin, "%lld", &data);
    funcPtr(data);
}

void CWE190_Integer_Overflow__int64_t_fscanf_square_44_good()
{
    goodG2B();
    goodB2G();
}

#endif /* OMITGOOD */

/* Below is the main(). It is only used when building this testcase on
   its own for testing or for building a binary to use in testing binary
   analysis tools. It is not used when compiling all the testcases as one
   application, which is how source code analysis tools are tested. */
#ifdef INCLUDEMAIN

int main(int argc, char * argv[])
{
    /* seed randomness */
    srand( (unsigned)time(NULL) );
#ifndef OMITGOOD
    printLine("Calling good()...");
    CWE190_Integer_Overflow__int64_t_fscanf_square_44_good();
    printLine("Finished good()");
#endif /* OMITGOOD */
#ifndef OMITBAD
    printLine("Calling bad()...");
    CWE190_Integer_Overflow__int64_t_fscanf_square_44_bad();
    printLine("Finished bad()");
#endif /* OMITBAD */
    return 0;
}

#endif


text:
cask 'emacs' do
  version '26.2'
  sha256 '1c314b55d565330ed0a78ce183ebabf9936b56932ad58887c28f929241534822'

  url "https://emacsformacosx.com/emacs-builds/Emacs-#{version}-universal.dmg"
  appcast 'https://emacsformacosx.com/atom/release'
  name 'Emacs'
  homepage 'https://emacsformacosx.com/'

  conflicts_with formula: 'emacs'

  app 'Emacs.app'
  binary "#{appdir}/Emacs.app/Contents/MacOS/Emacs", target: 'emacs'
  binary "#{appdir}/Emacs.app/Contents/MacOS/bin/ebrowse"
  binary "#{appdir}/Emacs.app/Contents/MacOS/bin/emacsclient"
  binary "#{appdir}/Emacs.app/Contents/MacOS/bin/etags"

  zap trash: [
               '~/Library/Caches/org.gnu.Emacs',
               '~/Library/Preferences/org.gnu.Emacs.plist',
               '~/Library/Saved Application State/org.gnu.Emacs.savedState',
             ]
end


text:
  <TITLE>
  EMBOSS: inforesidue
  </TITLE>

inforesidue

Wiki

The master copies of EMBOSS documentation are available
at
http://emboss.open-bio.org/wiki/Appdocs
on the EMBOSS Wiki.

Please help by correcting and extending the Wiki pages.

    Function

Return information on a given amino acid residue

    Description

inforesidue reports the defined properties for all known residues, or
for any residues specified by the user.

    Usage

Here is a sample session with inforesidue

% inforesidue
Return information on a given amino acid residue
Amino acid residue code [ABCDEFGHIJKLMNOPQRSTUVWXYZ]:
Output file [outfile.inforesidue]:

Go to the output files for this example

    Command line arguments

Return information on a given amino acid residue
Version: EMBOSS:6.6.0.0

   Standard (Mandatory) qualifiers:
  [-code]              string     [ABCDEFGHIJKLMNOPQRSTUVWXYZ] Enter IUPAC
                                  amino acids codes, e.g. A, C, D, E etc. (Any
                                  string)
  [-outfile]           outfile    [*.inforesidue] Output file name

   Additional (Optional) qualifiers: (none)
   Advanced (Unprompted) qualifiers:
   -aadata             datafile   [Eamino.dat] Amino acid properties
   -mwdata             datafile   [Emolwt.dat] Molecular weight data for amino
                                  acids

   Associated qualifiers:

   "-outfile" associated qualifiers
   -odirectory2        string     Output directory

   General qualifiers:
   -auto               boolean    Turn off prompts
   -stdout             boolean    Write first file to standard output
   -filter             boolean    Read first file from standard input, write
                                  first file to standard output
   -options            boolean    Prompt for standard and additional values
   -debug              boolean    Write debug output to program.dbg
   -verbose            boolean    Report some/full command line options
   -help               boolean    Report command line options and exit. More
                                  information on associated and general
                                  qualifiers can be found with -help -verbose
   -warning            boolean    Report warnings
   -error              boolean    Report errors
   -fatal              boolean    Report fatal errors
   -die                boolean    Report dying program messages
   -version            boolean    Report version number and exit

Qualifier
Type
Description
Allowed values
Default

Standard (Mandatory) qualifiers

[-code]
(Parameter 1)
string
Enter IUPAC amino acids codes, e.g. A, C, D, E etc.
Any string
ABCDEFGHIJKLMNOPQRSTUVWXYZ

[-outfile]
(Parameter 2)
outfile
Output file name
Output file
<*>.inforesidue

Additional (Optional) qualifiers

(none)

Advanced (Unprompted) qualifiers

-aadata
datafile
Amino acid properties
Data file
Eamino.dat

-mwdata
datafile
Molecular weight data for amino acids
Data file
Emolwt.dat

Associated qualifiers

"-outfile" associated outfile qualifiers

 -odirectory2
-odirectory_outfile
string
Output directory
Any string

General qualifiers

 -auto
boolean
Turn off prompts
Boolean value Yes/No
N

 -stdout
boolean
Write first file to standard output
Boolean value Yes/No
N

 -filter
boolean
Read first file from standard input, write first file to standard output
Boolean value Yes/No
N

 -options
boolean
Prompt for standard and additional values
Boolean value Yes/No
N

 -debug
boolean
Write debug output to program.dbg
Boolean value Yes/No
N

 -verbose
boolean
Report some/full command line options
Boolean value Yes/No
Y

 -help
boolean
Report command line options and exit. More information on associated and general qualifiers can be found with -help -verbose
Boolean value Yes/No
N

 -warning
boolean
Report warnings
Boolean value Yes/No
Y

 -error
boolean
Report errors
Boolean value Yes/No
Y

 -fatal
boolean
Report fatal errors
Boolean value Yes/No
Y

 -die
boolean
Report dying program messages
Boolean value Yes/No
Y

 -version
boolean
Report version number and exit
Boolean value Yes/No
N

    Input file format

inforesidue uses a string of residue codes.

    Output file format

inforesidue
outputs a text table of residue properties.

Output files for usage example

File: outfile.inforesidue

Code Short Mnemonic             Charge     MolWt Properties                     Ambiguity
A    Ala   alanine                 0.0   71.0788 tiny,small,aliphatic,nonpolar  A
B    Asx   aspartate/asparagine   -0.5  114.5962 small                          DN
C    Cys   cysteine                0.0  103.1388 tiny,small,nonpolar            C
D    Asp   aspartate              -1.0  115.0886 small,polar                    D
E    Glu   glutamate              -1.0  129.1155 polar                          E
F    Phe   phenylalanine           0.0  147.1766 aromatic,nonpolar              F
G    Gly   glycine                 0.0   57.0519 tiny,small,nonpolar            G
H    His   histidine              +0.5  137.1411 aromatic,polar                 H
I    Ile   isoleucine              0.0  113.1594 aliphatic,nonpolar             I
J    ---   leucine/isoleucine      0.0  113.1594 aliphatic,nonpolar             IL
K    Lys   lysine                 +1.0  128.1741 polar                          K
L    Leu   leucine                 0.0  113.1594 aliphatic,nonpolar             L
M    Met   methionine              0.0  131.1926 nonpolar                       M
N    Asn   asparagine              0.0  114.1038 small,polar                    N
O    ---   pyrrolysine            +1.0  237.3018 polar                          O
P    Pro   proline                 0.0   97.1167 small,nonpolar                 P
Q    Gln   glutamine               0.0  128.1307 polar                          Q
R    Arg   arginine               +1.0  156.1875 polar                          R
S    Ser   serine                  0.0   87.0782 tiny,small,polar               S
T    Thr   threonine               0.0  101.1051 tiny,small,polar               T
U    ---   selenocysteine          0.0  150.0388 tiny,small,nonpolar            U
V    Val   valine                  0.0   99.1326 small,aliphatic,nonpolar       V
W    Trp   tryptophan              0.0  186.2132 aromatic,nonpolar              W
X    Xaa   unknown                 0.0  118.8860 (none)                         ACDEFGHIKLMNPQRSTVWY
Y    Tyr   tyrosine                0.0  163.1760 aromatic,nonpolar              Y
Z    Glx   glutamate/glutamine    -0.5  128.6231 polar                          EQ

    Data files

inforesidue reads the Eresidues.iub file to define IUB standard codes
for nucleotides and ambiguity codes, and files Eamino.dat and
Emolwt.dat to read other amino acid residue chemical proerties and
molecular weights.

EMBOSS data files are distributed with the application and stored
in the standard EMBOSS data directory, which is defined
by the EMBOSS environment variable EMBOSS_DATA.

To see the available EMBOSS data files, run:

% embossdata -showall

To fetch one of the data files (for example 'Exxx.dat') into your
current directory for you to inspect or modify, run:

% embossdata -fetch -file Exxx.dat

Users can provide their own data files in their own directories.
Project specific files can be put in the current directory, or for
tidier directory listings in a subdirectory called
".embossdata". Files for all EMBOSS runs can be put in the user's home
directory, or again in a subdirectory called ".embossdata".

The directories are searched in the following order:

 . (your current directory)

 .embossdata (under your current directory)

 ~/ (your home directory)

 ~/.embossdata

    Notes

None.

    References

None.

    Warnings

None.

    Diagnostic Error Messages

None.

    Exit status

It always exits with status 0.

    Known bugs

None.

See also

Program name
Description

infobase
Return information on a given nucleotide base

    Author(s)

Jon Ison

European Bioinformatics Institute, Wellcome Trust Genome Campus, Hinxton, Cambridge CB10 1SD, UK

Please report all bugs to the EMBOSS bug team (emboss-bug © emboss.open-bio.org) not to the original author.

    History

    Target users

This program is intended to be used by everyone and everything, from naive users to embedded scripts.

    Comments

None


text:
(function () {
	// HTML5 Shiv v3.6.2 | @afarkas @jdalton @jon_neal @rem | MIT/GPL2 Licensed (Suporte HTML5 para navegadores viejos, ejemplo IE8)
	var supportsUnknownElements = false;

	(function () {
		try {
			var a = document.createElement('a');
			a.innerHTML = '<xyz></xyz>';

			supportsUnknownElements = a.childNodes.length == 1 || (function () {
				(document.createElement)('a');
				var frag = document.createDocumentFragment();
				return (
					typeof frag.cloneNode == 'undefined' ||
						typeof frag.createDocumentFragment == 'undefined' ||
						typeof frag.createElement == 'undefined'
					);
			}());
		} catch (e) {
			supportsUnknownElements = true;
		}
	}());

	System
		.config(
			{
				map:
				{
					'jquery/jquery':	'jquery'
				,	'can':				'bower_components/canjs'
				}
			,	paths:
				{
					'jquery':			'bower_components/jquery/dist/jquery.js'
				,	'bootstrap':		'bower_components/bootstrap/dist/js/bootstrap.js'
				,	'bootstrap.css':	'bower_components/bootstrap/dist/css/bootstrap.css!css'
				}
			,	meta:
				{
					'jquery':
					{
						'exports':	'jQuery'
					,	'deps':		supportsUnknownElements ? undefined : ['can/lib/html5shiv.js']
					}
				}
			,	ext:
				{
					'ejs':		'can/view/ejs/system'
				,	'mustache':	'can/view/mustache/system'
				,	'stache':	'can/view/stache/system'
				}
			,	bundle:
				[
					"login.js"
				]
			}
		);
	}
)();

System.buildConfig
=	{
		map:
		{
			'can/util/util':	'can/util/domless/domless'
		}
	};


text:
package sample.boot.web;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MySampleController {

    @GetMapping("/js/*")
    public String js() {
        return "js!!";
    }

    @GetMapping("/css/*")
    public String css() {
        return "css!!";
    }

    @GetMapping("/images/*")
    public String images() {
        return "images!!";
    }

    @GetMapping("/webjars/*")
    public String webjars() {
        return "webjars!!";
    }

    @GetMapping("/favicon.ico")
    public String favicon() {
        return "favicon!!";
    }
}


text:
<resources>
    <string name="app_name">TextMeApp_fansfolio</string>
</resources>


text:
{{ _('Legend') }}

 frei

        {%- if manage_mode %}

 belegt durch ein nicht von dir verwaltetes Ticket

 belegt durch ein von dir verwaltetes Ticket

 belegt durch ein von dir verwaltetes und aktuell ausgewähltes Ticket

        {%- else %}

 belegt

        {%- endif %}


text:
/********************************************************************************
    Head First C, by
    David Griffiths and Dawn Griffiths
    ISBN: 978-1449399917

    Q. Develop a utility for substring searching lines in a file.
********************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAXLENGTH 100
#define IS_LINE 1
#define NOT_LINE 0

void parse_argv(int , char **, FILE *, char **, char **, FILE **);
void get_lines(int, char **,FILE *, FILE *, char *, FILE **);

int count = 0; /* reusable counter */
const int _offset = 2;
int state = NOT_LINE;

int main(int argc, char *argv[])
{
    char line[MAXLENGTH];
    char **search_for = (char **)malloc((argc - _offset) * sizeof(char *));
    char **arg = (char **)malloc(argc * sizeof(char *));
    FILE *log = fopen("splitter.log", "a");
    FILE *input;
    FILE **outputfiles = (FILE **)malloc((argc - _offset) * sizeof(FILE *));

    /* Check existence of logfile */
    if(!(input = fopen(argv[1], "r"))) {
        fprintf(stderr, "Can't open %s. No such file\n", argv[1]);
        return 1;
    }

    /* parse arg variables */
    parse_argv(argc, argv, log, arg, search_for, outputfiles);

    /* search lines in file for substring */
    get_lines(argc, search_for, log, input, line, outputfiles);

    return 0;
}

void parse_argv(int argc, char *argv[], FILE *log, char **arg, char **search_for, FILE **outputfiles)
{
    switch(argc) {
        case 1:
            /* fall through */
        case 2:
            printf("WARNING Usage: %s <logfile> search1, search2, search3.... search[n] -> where n is any natural number\n", argv[0]);
            fprintf(log, "Wrong number of arguments...\n");
            fclose(log);
            exit(EXIT_FAILURE);
        default:
            fprintf(log, "Setting up search array and opening output files...\n");
            for(arg = argv + _offset; *arg; ++arg) {
#ifdef DEBUG
                fprintf(stderr, "count = [%d]\n", count);
                fprintf(stderr, "arg[%d] = %s\n", count + _offset, *arg);
#endif /* DEBUG */

                search_for[count] = (char *)malloc(MAXLENGTH * sizeof(char));
                strcpy(search_for[count], *arg);
                outputfiles[count] = fopen(*arg, "w");
                ++count;
            }
            break;
        }
}

void get_lines(int argc, char **search_for, FILE * log, FILE *input, char line[], FILE **outputfiles)
{
    extern int state;
#ifdef DEBUG
    for(count = 0; count < (argc - _offset); ++count)
        fprintf(stderr, "DEBUG: search_for[%d]=%s\n", count, search_for[count]);
#endif /* DEBUG */

    fprintf(log, "Running search through logfile...\n");

    while(fscanf(input, "%100[^\n]\n", line) == 1)
        for(count = 0; count < (argc - _offset); ++count)
            if(strstr(line, search_for[count])) {
                fprintf(outputfiles[count], "%s\n", line);
                state = IS_LINE;
            };

    if(state)
       fprintf(log, "Substrings found in logfile...");
    else
        fprintf(log, "No instances of substrings found in logfile...");

    /* clean up */
    fclose(input);
    fclose(log);

    for(count = 0; count < (argc - _offset); ++count) {
        fclose(outputfiles[count]);
        free(search_for[count]) ;
    }
}


text:
package com.github.tomakehurst.wiremock.servlet;

import com.github.tomakehurst.wiremock.common.Gzip;
import com.github.tomakehurst.wiremock.http.*;
import com.github.tomakehurst.wiremock.jetty9.JettyUtils;
import com.google.common.collect.ImmutableMap;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

import static com.github.tomakehurst.wiremock.common.Encoding.encodeBase64;
import static com.github.tomakehurst.wiremock.common.Strings.stringFromBytes;
import static com.github.tomakehurst.wiremock.common.Urls.splitQuery;
import static com.google.common.base.MoreObjects.firstNonNull;
import static com.google.common.base.Strings.isNullOrEmpty;
import static com.google.common.collect.Lists.newArrayList;
import static com.google.common.io.ByteStreams.toByteArray;
import static java.util.Collections.list;

public class WireMockHttpServletRequestAdapter implements Request {

    private final HttpServletRequest request;
    private byte[] cachedBody;
    private String urlPrefixToRemove;

    public WireMockHttpServletRequestAdapter(HttpServletRequest request) {
        this.request = request;
    }

    public WireMockHttpServletRequestAdapter(HttpServletRequest request, String urlPrefixToRemove) {
        this.request = request;
        this.urlPrefixToRemove = urlPrefixToRemove;
    }

    @Override
    public String getUrl() {
        String url = request.getRequestURI();

        String contextPath = request.getContextPath();
        if (!isNullOrEmpty(contextPath) && url.startsWith(contextPath)) {
            url = url.substring(contextPath.length());
        }
        if (!isNullOrEmpty(urlPrefixToRemove) && url.startsWith(urlPrefixToRemove)) {
            url = url.substring(urlPrefixToRemove.length());
        }

        return withQueryStringIfPresent(url);
    }

    @Override
    public String getAbsoluteUrl() {
        return withQueryStringIfPresent(request.getRequestURL().toString());
    }

    private String withQueryStringIfPresent(String url) {
        return url + (isNullOrEmpty(request.getQueryString()) ? "" : "?" + request.getQueryString());
    }

    @Override
    public RequestMethod getMethod() {
        return RequestMethod.fromString(request.getMethod().toUpperCase());
    }

    @Override
    public String getClientIp() {
        String forwardedForHeader = this.getHeader("X-Forwarded-For");

        if (forwardedForHeader != null && forwardedForHeader.length() > 0) {
            return forwardedForHeader;
        }

        return  request.getRemoteAddr();
    }

    @Override
    public byte[] getBody() {
        if (cachedBody == null) {
            try {
                byte[] body = toByteArray(request.getInputStream());
                boolean isGzipped = hasGzipEncoding() || Gzip.isGzipped(body);
                cachedBody = isGzipped ? Gzip.unGzip(body) : body;
            } catch (IOException ioe) {
                throw new RuntimeException(ioe);
            }
        }

        return cachedBody;
    }

    private boolean hasGzipEncoding() {
        String encodingHeader = request.getHeader("Content-Encoding");
        return encodingHeader != null && encodingHeader.contains("gzip");
    }

    @Override
    public String getBodyAsString() {
        return stringFromBytes(getBody());
    }

    @Override
    public String getBodyAsBase64() {
        return encodeBase64(getBody());
    }

    @SuppressWarnings("unchecked")
    @Override
    public String getHeader(String key) {
        List<String> headerNames = list(request.getHeaderNames());
        for (String currentKey : headerNames) {
            if (currentKey.toLowerCase().equals(key.toLowerCase())) {
                return request.getHeader(currentKey);
            }
        }

        return null;
    }

    @Override
    @SuppressWarnings("unchecked")
    public HttpHeader header(String key) {
        List<String> headerNames = list(request.getHeaderNames());
        for (String currentKey : headerNames) {
            if (currentKey.toLowerCase().equals(key.toLowerCase())) {
                List<String> valueList = list(request.getHeaders(currentKey));
                if (valueList.isEmpty()) {
                    return HttpHeader.empty(key);
                }

                return new HttpHeader(key, valueList);
            }
        }

        return HttpHeader.absent(key);
    }

    @Override
    public ContentTypeHeader contentTypeHeader() {
        return getHeaders().getContentTypeHeader();
    }

    @Override
    public boolean containsHeader(String key) {
        return header(key).isPresent();
    }

    @Override
    public HttpHeaders getHeaders() {
        List<HttpHeader> headerList = newArrayList();
        for (String key : getAllHeaderKeys()) {
            headerList.add(header(key));
        }

        return new HttpHeaders(headerList);
    }

    @SuppressWarnings("unchecked")
    @Override
    public Set<String> getAllHeaderKeys() {
        LinkedHashSet<String> headerKeys = new LinkedHashSet<String>();
        for (Enumeration<String> headerNames = request.getHeaderNames(); headerNames.hasMoreElements(); ) {
            headerKeys.add(headerNames.nextElement());
        }

        return headerKeys;
    }

    @Override
    public Map<String, Cookie> getCookies() {
        ImmutableMap.Builder<String, Cookie> builder = ImmutableMap.builder();

        for (javax.servlet.http.Cookie cookie :
            firstNonNull(request.getCookies(), new javax.servlet.http.Cookie[0])) {
            builder.put(cookie.getName(), convertCookie(cookie));
        }

        return builder.build();
    }

    private static Cookie convertCookie(javax.servlet.http.Cookie servletCookie) {
        return new Cookie(servletCookie.getValue());
    }

    @Override
    public QueryParameter queryParameter(String key) {
        return firstNonNull((splitQuery(request.getQueryString())
                .get(key)),
            QueryParameter.absent(key));
    }

    @Override
    public boolean isBrowserProxyRequest() {
        if (!isJetty()) {
            return false;
        }
        if (request instanceof org.eclipse.jetty.server.Request) {
            org.eclipse.jetty.server.Request jettyRequest = (org.eclipse.jetty.server.Request) request;
            return JettyUtils.getUri(jettyRequest).isAbsolute();
        }

        return false;
    }

    private boolean isJetty() {
        try {
            getClass("org.eclipse.jetty.server.Request");
            return true;
        } catch (Exception e) {
        }
        return false;
    }

    private void getClass(String type) throws ClassNotFoundException {
        ClassLoader contextCL = Thread.currentThread().getContextClassLoader();
        ClassLoader loader = contextCL == null ? WireMockHttpServletRequestAdapter.class.getClassLoader() : contextCL;
        Class.forName(type, false, loader);
    }

    @Override
    public String toString() {
        return request.toString() + getBodyAsString();
    }
}


text:
test_description="Test ipfs blockstore repo read check."

. lib/test-lib.sh

rm -rf "$IPF_PATH/*"

test_init_ipfs

H_BLOCK1=$(echo "Block 1" | ipfs add -q)
H_BLOCK2=$(echo "Block 2" | ipfs add -q)

BS_BLOCK1="XZ/CIQPDDQH5PDJTF4QSNMPFC45FQZH5MBSWCX2W254P7L7HGNHW5MQXZA.data"
BS_BLOCK2="CK/CIQNYWBOKHY7TCY7FUOBXKVJ66YRMARDT3KC7PPY6UWWPZR4YA67CKQ.data"

test_expect_success 'blocks are swapped' '
  ipfs cat $H_BLOCK2 > noswap &&
  cp -f "$IPFS_PATH/blocks/$BS_BLOCK1" "$IPFS_PATH/blocks/$BS_BLOCK2" &&
  ipfs cat $H_BLOCK2 > swap &&
  test_must_fail test_cmp noswap swap
'

ipfs config --bool Datastore.HashOnRead true

test_check_bad_blocks() {
  test_expect_success 'getting modified block fails' '
    (test_must_fail ipfs cat $H_BLOCK2 2> err_msg) &&
    grep "block in storage has different hash than requested" err_msg
  '

  test_expect_success "block shows up in repo verify" '
    test_expect_code 1 ipfs repo verify > verify_out &&
    grep "$H_BLOCK2" verify_out
  '
}

test_check_bad_blocks

test_expect_success "can add and cat a raw-leaf file" '
  HASH=$(echo "stuff" | ipfs add -q --raw-leaves) &&
  ipfs cat $HASH > /dev/null
'

test_launch_ipfs_daemon
test_check_bad_blocks
test_kill_ipfs_daemon

test_done


text: export * from "./FairExhibitorRail"


text:
<?php

class rediscache {

	public static $class  = 'updated'; // class of admin notice: array('updated' => green, 'error' => 'red', 'update-nag' => 'yellow')
	public static $notice = null;      // admin notice message
	public static $status = null;      // Redis connection status
	public static $redis  = null;      // Redis extension class object
	public static $config = null;      // Redis configuration array
	public static $info   = array();   // Redis statistic info array

	/**
	 * check if required code snippet has been installed in WordPress index.php
	 *
	 */
	public static function check_snippet() {
		if (defined('_REDIS_LIGHT_CACHE_PREPEND')) {
			return true;
		}
	}

	/**
	 * load config
	 *
	 */
	public static function load_config()
	{
        self::$config = [
            'REDIS_STATUS'  => true,
            'REDIS_HOST'    => $_ENV['REDIS_HOST']    ?? '127.0.0.1',
            'REDIS_PORT'    => $_ENV['REDIS_PORT']    ?? 6379,
            'REDIS_AUTH'    => $_ENV['REDIS_AUTH']    ?? '',
            'REDIS_WAIT'    => $_ENV['REDIS_WAIT']    ?? 1,
            'REDIS_QUERY'   => $_ENV['REDIS_QUERY']   ?? 0,
            'REDIS_EXCLUDE' => $_ENV['REDIS_EXCLUDE'] ?? [],
        ];

        $file    = $_SERVER['DOCUMENT_ROOT'] . ($_ENV['REDIS_CONFIG_PATH'] ?? '/wp-content/uploads/redis-config.json');
        $options = @json_decode(@self::simple_crypt(@file_get_contents($file, true), 'd'), true);

        # echo '
pre-load'; print_r($options); # die(); // DEBUG LINE

        if (is_array($options)) {
	        foreach ($options as $key => $val) {
	        	// overwrite config defaults only if environment variable is not set
	        	if (isset(self::$config[ $key ]) and empty($_ENV[ $key ])) {
	        		self::$config[ $key ] = is_array($val) ? $val : trim($val);
	        		# printf("key: [ %s ], val: [ %s ]\n", $key, $val); // DEBUG LINE
	        	}
	        }
        }

		# echo '
post load'; print_r(self::$config); die(); // DEBUG LINE

        return self::$config;
	}

	/**
	 * connect to Redis
	 *
	 */
	public static function connect()
	{
		self::$config = self::load_config();

		if (! self::$config['REDIS_STATUS']) {
	        rediscache::$class  = 'error';
	        rediscache::$notice = 'Redis status set to OFF. You can change it here: configuration';

	        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);

	        return false;
		}

        try {
            require_once 'predis/autoload.php';

            self::$redis = new Predis\Client([
                'scheme'  => 'tcp',
                'host'    => self::$config['REDIS_HOST'],
                'port'    => self::$config['REDIS_PORT'],
                'timeout' => self::$config['REDIS_WAIT'],
            ]);

            // cannot for the love of God catch this exception - please HELP!
			if (trim(self::$config['REDIS_AUTH']) != '') {
				# self::$redis->auth( self::$config['REDIS_AUTH'] );
			}

			self::$redis->connect();
            self::$config['REDIS_STATUS'] = 1;
        }

        catch (Predis\Connection\ConnectionException $exception) {
	        // throw message - cannot connect with redis
	        rediscache::$class  = 'error';
	        rediscache::$notice = 'Cannot connect to Redis storage engine. Please check your configuration';

	        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);

	        self::$config['REDIS_STATUS'] = 0;
            self::logger($e);

            return false;
        }

	    // connect to Redis storage
        self::$redis->select(0);

        $domains = json_decode(self::$redis->get('domains'), true);

        // fetch redis database ID for current host
        if (isset($domains[ $_SERVER['HTTP_HOST'] ]['id'])) {
            $db = $domains[ $_SERVER['HTTP_HOST'] ]['id'];

            self::logger(sprintf('current domain [id: %d]: %s found in cache. Total hostname(s) stored: %d',
            	$db, $_SERVER['HTTP_HOST'], count($domains)));
        }

        // create new redis database if current host does not have one
        else {
            if (! is_array($domains)) {
                $domains = [];
            }

            $db = count($domains) + 1;

            $domains[ $_SERVER['HTTP_HOST'] ]['id'] = $db;

            self::logger(sprintf('current domain: %s does not exist in cache - creating. Total hostname(s) stored: %d',
            	$_SERVER['HTTP_HOST'], count($domains)));

            self::$redis->set('domains', json_encode($domains));
        }

        try {
            self::$redis->select($db);
			self::$info['pages'] = 0;
	        self::$info          = self::$redis->info();
	        self::$status        = self::$config['status'];
	        self::$info['pages'] = (int) self::$redis->dbSize();
        }

        catch (Exception $e) {
            self::logger(sprintf('ERROR: could not select database: %d for host: %s', $db, $_SERVER['HTTP_HOST']));
            return false;
        }
	}

    /*
     * system log
     *
     */
    public static function logger($message)
    {
        if (isset($_ENV['REDIS_LOG']) && $_ENV['REDIS_LOG'] == "true") {
            file_put_contents('php://stderr', sprintf("%s\n", $message), FILE_APPEND);
        }
    }

	/**
	 * render admin notice
	 *
	 */
	public static function admin_notice()
	{
	    if (trim(self::$notice) != '') {
	        printf('

%s

', self::$class, self::$notice);
	    }
	}

	/**
	 * process user POST actions
	 *
	 */
	public static function post_actions() {
        $file    = $_SERVER['DOCUMENT_ROOT'] . ($_ENV['REDIS_CONFIG_PATH'] ?? '/wp-content/uploads/redis-config.json');
        $options = @json_decode(@self::simple_crypt(@file_get_contents($file, true), 'd'), true);

		// ACTION: update configuration file
		//
	    if (isset($_POST['update'])) {
	        // create default options
	        foreach ($_POST as $key => $val) {
                $options[ $key ] = trim($val);
	        }

	        if (@file_put_contents($file, @self::simple_crypt(json_encode($options, JSON_PRETTY_PRINT), 'e'))) {
	            // throw message - redis config updated sucessfully
		        rediscache::$class  = 'updated';
		        rediscache::$notice = 'Configuration has been updated';

		        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);
	        } else {
	            // throw error - cannot save config file: redis-config.json
		        rediscache::$class  = 'error';
		        rediscache::$notice = 'Could not update configuration file.  Please make sure this file is writable:  ' . $file;

		        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);
	        }
	    }

		// ACTION: update URL exclusions
		//
	    if (isset($_POST['REDIS_EXCLUDE'])) {
	        $options['REDIS_QUERY']   = $_POST['REDIS_QUERY'];
	        $options['REDIS_EXCLUDE'] = explode("\r\n", $_POST['REDIS_EXCLUDE']);

	        if (@file_put_contents($file, @self::simple_crypt(json_encode($options), 'e'))) {
	            // throw message - redis config updated sucessfully
		        rediscache::$class  = 'updated';
		        rediscache::$notice = 'Exclusion URL list has been updated';

		        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);
	        } else {
	            // throw error - cannot save config file: redis-config.json
		        rediscache::$class  = 'error';
		        rediscache::$notice = 'Could not update configuration file.  Please make sure this file is writable:  ' . $file;

		        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);
	        }
	    }

		// ACTION: flush cache engine
		//
	    if (isset($_POST['flush'])) {
			if (self::$status != 'ON') {
		        rediscache::$class  = 'error';
		        rediscache::$notice = 'Redis connection error - cannot this operation';
			} else {
			    $domain = self::set_database();

				self::$redis->flushDb();

		        rediscache::$class  = 'updated';
		        rediscache::$notice = 'Domain cache flushed';
			}

	        add_action('admin_notices', [ 'rediscache', 'admin_notice' ]);
	    }

		// END of ACTIONS
		//
	}

	/**
	 * Flush page cache on post update action
	 *
	 */
	function flush_page($post_id)
	{
		global $wpdb;

		if (self::$status != 'ON') {
			return false;
		}

	    $permalink = get_permalink($post_id);
	    $domain    = self::set_database();
		$blog_id   = get_current_blog_id();
		$query     = 'SELECT path FROM '.TABLE_PREFIX.'blogs WHERE blog_id='.$blog_id;
		$path      = $wpdb->get_var($query);

	    // build URL key
	    $url = $domain.str_replace($path, '/', parse_url($permalink, PHP_URL_PATH));
	    $key = md5($url);

	    self::$redis->del($key); # die($key.' - '.$url); // DEBUG
	}

	/**
	 * Flush page cache on post update action
	 *
	 */
	function set_database()
	{
		global $wpdb;

		if (self::$status != 'ON') {
			return false;
		}

		// determine blog domain to flush
		$blog_id = get_current_blog_id();
		$query   = 'SELECT domain FROM '.TABLE_PREFIX.'domain_mapping WHERE blog_id='.$blog_id;
		$domain  = $wpdb->get_var($query);

		// fix for main blog domain flush domain selection
		if (trim($domain) == '')
		{
			$domain = $_SERVER['HTTP_HOST'];
		}

	    self::$redis->select(0);
	    $domains = json_decode(self::$redis->get('domains'), true);

	    // fetch redis database ID for current host
	    if (isset($domains[ $domain ]['id'])) {
	        $db = $domains[ $domain ]['id'];
	    }

	    // create new redis database if current host does not have one
	    else {
	        if (! is_array($domains)) {
	            $domains = [];
	        }

	        $db = count($domains) + 1;

	        $domains[ $domain ]['id'] = $db;

	        self::$redis->set('domains', json_encode($domains));
	    }

	    self::$redis->select($db);

	    return $domain;
	}

	/**
	 * Encrypt and decrypt
	 *
	 * @author Nazmul Ahsan <n.mukto@gmail.com>
	 * @link http://nazmulahsan.me/simple-two-way-function-encrypt-decrypt-string/
	 *
	 * @param string $string string to be encrypted/decrypted
	 * @param string $action what to do with this? e for encrypt, d for decrypt
	 */
	public static function simple_crypt( $string, $action = 'e' ) {
	    // you may change these values to your own
	    $secret_key = $_ENV['REDIS_ENCRYPT_KEY']    ?? 'simple_secret_key';
	    $secret_iv  = $_ENV['REDIS_ENCRYPT_SECRET'] ?? 'simple_secret_iv';

	    $output         = false;
	    $encrypt_method = "AES-256-CBC";
	    $key            = hash( 'sha256', $secret_key );
	    $iv             = substr( hash( 'sha256', $secret_iv ), 0, 16 );

	    if ( $action == 'e' ) {
	        $output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
	    }
	    else if( $action == 'd' ){
	        $output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
	    }

	    return $output;
	}
}


text:
<?php

?>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Edit Sertifikasi

                <form id="formEdit" class="form-horizontal" role="form" method="post" action="">

                        Tanggal :

                            <input id="tanggalEdit" class="form-control datepicker" type="text"
                                   data-date-format="dd-mm-yyyy" name="tanggal">

                        Nama :

                            <input id="namaEdit" type="text" class="form-control" name="nama"
                                   placeholder="Masukkan Nama Kegiatan" value="" required="true">

                        Kota :

                            <input id="kotaEdit" type="text" class="form-control" name="kota"
                                   placeholder="Masukkan Kota" value="" required="true">

                        Tahun Ajaran :

                            <input id="tahunAjaranEdit" type="number" class="form-control" name="tahun_ajaran"
                                   placeholder="Ex : 2015" value="" required="true">

                        Tempat :

                            <input id="tempatEdit" type="text" class="form-control" name="tempat"
                                   placeholder="Masukkan Lokasi" value="" required="true">

                            <button type="submit" class="btn btn-sm btn-primary">OK</button>
                            <button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Batal</button>

                </form>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Konfirmasi

                Apakah Anda Yakin Untuk Menghapus Data Sertifikasi?

                <button type="button" class="btn btn-default" data-dismiss="modal">Batal</button>
                OK


text:
Namespace Enums

    Public Enum UserEventAction As Integer

        Unknown = -1

        NoAction = 0

        FileDeleted = 1
        FileCopiedOut = 2
        Created = 3
        BookedOut = 4
        BookedIn = 5
        Checked = 6
        Approved = 7
        Released = 8
        Opened = 9
        ImportByCSV = 10
        AbandonedBookOut = 11
        Viewed = 12
        AddedToArchive = 13
        RestoredFromArchive = 14
        EditDataCard = 15
        ViewFailed = 16
        CreateFailed = 17
        BookOutFailed = 18
        BookInFailed = 19
        CheckFailed = 20
        ApproveFailed = 21
        ReleaseFailed = 22
        OpenFailed = 23
        AbandonBookOutFailed = 24
        FileDeleteFailed = 25
        AddToArchiveFailed = 26
        RestoreFromArchiveFailed = 27
        CreateCancelledByUser = 28
        SCSViewed = 29
        SCSDragDrop = 30
        SheetCreated = 31
        ChangeofSheetOf = 32
        CopyOutDragDrop = 33
        DWG2PDFPaperSizeList = 34
        DWG2PDFPaperSizeEdit = 35
        DWG2PDFPenStyleList = 36
        DWG2PDFPenStyleEdit = 37
        DWG2PDFLineColourList = 38
        DWG2PDFLineColourEdit = 39
        DWG2PDFPenSizeList = 40
        DWG2PDFPenSizeEdit = 41
        MessageSent = 42
        EmailAddedToQ = 43
        EmailQUserWarned = 44
        'TID491
        DocumentFieldList = 45
        DocumentFieldEdit = 46
        'TID536
        CreatedFromScannerOrCamera = 47
        CreateFailedFromScannerOrCamera = 48
        'TID653
        SearchAndReplaceFieldValues = 49
        'TID685
        CopyFileNotSuccessfulSourceFileNotFound = 50
        CopyFileNotSuccessful = 51
        CopyFileSizesDiffer = 52
        CopyFileSizesDifferTidyUpFails = 53
        CopyFileAttributeSetFailed = 54
        CopyFileAttributeSetFailedTidyUpFails = 55
        'TID805
        MoveFileNotSuccessfulSourceFileNotFound = 56
        MoveFileNotSuccessful = 57
        ' TIDXXX
        AccountLinked = 58
        AccountUnLinked = 59
        DocumentLinked = 60
        DocumentUnLinked = 61
        ' TIDXXX
        AccountEdited = 62
        ContactEdited = 63
        AccountCreated = 64
        ContactCreated = 65
        AccountDeleted = 66
        ContactDeleted = 67

        WorkFlowStepPerformed = 68

        DocumentNoteAdded = 69
        DocumentNoteEdited = 70
        DocumentNoteDeleted = 71

        Transmittal_Deleted = 72
        SCS_Deleted = 73

        SheetUpdated = 74

        MarkUp_Created = 75
        MarkUp_Deleted = 76
        MarkUp_Viewed = 77
        MarkUp_Edited = 78
        MarkUp_CreatedPDF = 79

        DocConvertedToDocx = 80
        DocConvertedToDocm = 81
        XlsConvertedToXlsx = 82
        XlsConvertedToXlsm = 83

        MarkUp_Completed = 84

        Transmittal_Created = 85
        Transmittal_Built = 86

        Transmittal_Transmitted = 87
        Transmittal_Re_Transmitted = 88

        DMSLinkCreated = 89
        WebLinkCreated = 90
        WorkFlowAssigned = 91

        Import_Email = 92

        DocumentIntegrityFixed = 93

        ReviewDateSet = 94
        Reviewed = 95

        ReviewDateCleared = 96

        SCSPrinted = 97
        SCSPrintFailed = 98

        SharePointAdded = 99
        SharePointRemoved = 100

    End Enum

End Namespace


text:
jupytext:
  formats: ipynb,md:myst
  text_representation:
    extension: .md
    format_name: myst
    format_version: '0.8'
    jupytext_version: 1.4.2
kernelspec:
  display_name: Python 3
  language: python
  name: python3
---

# srl

Semantic Role Labeling (SRL) is one shallow semantic parsing that produces predicate-argument structures which are semantic roles (or participants) such as agent, patient, and theme associated with verbs.

Inputs to SRL are tokenized sentences:

````{margin} Batching is Faster
```{hint}
Feed in multiple sentences at once for faster speed!
```
````

```{code-cell} ipython3
:tags: [output_scroll]
import hanlp

srl = hanlp.load(hanlp.pretrained.srl.CPB3_SRL_ELECTRA_SMALL)
srl(['男孩', '希望', '女孩', '相信', '他', '。'])
```

All the pre-trained labelers and their details are listed below.

```{eval-rst}

.. automodule:: hanlp.pretrained.srl
    :members:

```


text:
package de.tudarmstadt.ukp.clarin.webanno.api.annotation.preferences;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.markup.html.panel.Panel;

import de.tudarmstadt.ukp.clarin.webanno.api.annotation.page.AnnotationPageBase;
import de.tudarmstadt.ukp.clarin.webanno.support.lambda.LambdaAjaxLink;

public class PreferencesActionBarItem
    extends Panel
{
    private static final long serialVersionUID = 4139817495914347777L;

    private final AnnotationPreferencesDialog preferencesModal;
    private final AnnotationPageBase page;

    public PreferencesActionBarItem(String aId, AnnotationPageBase aPage)
    {
        super(aId);

        page = aPage;

        add(preferencesModal = new AnnotationPreferencesDialog("preferencesDialog",
                page.getModel()));
        preferencesModal.setOnChangeAction(this::actionCompletePreferencesChange);

        add(new LambdaAjaxLink("showPreferencesDialog", this::actionShowPreferencesDialog));
    }

    private void actionCompletePreferencesChange(AjaxRequestTarget aTarget)
    {
        page.actionLoadDocument(aTarget);
    }

    private void actionShowPreferencesDialog(AjaxRequestTarget aTarget)
    {
        page.getModelObject().getSelection().clear();
        preferencesModal.show(aTarget);
    }
}


text:
namespace chainerx {
namespace python {
namespace testing {
namespace testing_internal {

namespace py = pybind11;
using py::literals::operator""_a;

void InitChainerxTestingModule(pybind11::module& m) {
    InitChainerxDeviceBuffer(m);

    // Converts from NumPy array. It supports keepstrides option.
    m.def("_fromnumpy",
          [](py::array array, bool keepstrides, py::handle device) {
              if (keepstrides) {
                  return python_internal::MakeArrayFromNumpyArray(array, python_internal::GetDevice(device));
              }
              return python_internal::MakeArray(array, array.dtype(), true, device);
          },
          "array"_a,
          "keepstrides"_a = false,
          "device"_a = nullptr);
}

}  // namespace testing_internal
}  // namespace testing
}  // namespace python
}  // namespace chainerx


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<TITLE>
net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction (LicenseManager 1.0.0)
</TITLE>

<META NAME="date" CONTENT="2012-09-05">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../../../stylesheet.css" TITLE="Style">

net.nicholaswilliams.java.licensing.licensor.interfaces.text.abstraction

Interfaces

TextInterfaceDevice

Classes

AbstractTextInterfaceDevice

CliOptionsBuilder

ConsoleInterfaceDevice


text:
<?php

namespace VIPSoft\CodeCoverageBundle\Service;

use VIPSoft\CodeCoverageCommon\Model\Aggregate;

/**
 * Code coverage repository
 *
 * @author Anthon Pang <apang@softwaredevelopment.ca>
 */
class CodeCoverageRepository
{
    /**
     * @var string
     */
    private $databaseFile;

    /**
     * @var string
     */
    private $sqliteClassName;

    /**
     * Constructor
     *
     * @param array  $databaseConfig
     * @param string $databaseDirectory
     * @param string $sqliteClassName
     */
    public function __construct(array $databaseConfig, $databaseDirectory, $sqliteClassName = '\SQLite3')
    {
        $this->databaseFile    = $databaseDirectory . '/' . $databaseConfig['database'];
        $this->sqliteClassName = $sqliteClassName;
    }

    /**
     * Initialize
     *
     * @return boolean
     */
    public function initialize()
    {
        $this->drop();

        $sqlite = $this->newSQLiteInstance();
        $sqlite->exec('CREATE TABLE coverage (class TEXT, counts BLOB)');

        return (boolean) $sqlite;
    }

    /**
     * Is enabled?
     *
     * @return boolean
     */
    public function isEnabled()
    {
        return file_exists($this->databaseFile);
    }

    /**
     * Insert coverage
     *
     * @param array $coverage
     */
    public function addCoverage(array $coverage)
    {
        $sqlite = $this->newSQLiteInstance();

        foreach ($coverage as $className => $counts) {
            $counts = json_encode($counts);

            $sql = "INSERT INTO coverage (class, counts) VALUES ('$className', '$counts')";
            $sqlite->exec($sql);
        }
    }

    /**
     * Get coverage
     *
     * @return array
     */
    public function getCoverage()
    {
        $aggregate = new Aggregate();
        $resultSet = array();
        $sqlite    = $this->newSQLiteInstance();
        $result    = @$sqlite->query('SELECT class, counts FROM coverage');

        if ( ! $result) {
            return array();
        }

        while ($res = $result->fetchArray(SQLITE3_ASSOC)) {
            $resultSet[] = $res;
        }

        if ($resultSet !== false) {
            foreach ($resultSet as $result) {
                $counts = json_decode($result['counts'], true);

                $aggregate->update($result['class'], $counts);
            }
        }

        return $aggregate->getCoverage();
    }

    /**
     * Delete database file
     */
    public function drop()
    {
        if (file_exists($this->databaseFile)) {
            unlink($this->databaseFile);
        }
    }

    /**
     * Instantiate SQLite3 object
     *
     * @return \SQLite3
     */
    private function newSQLiteInstance()
    {
        $instance = new $this->sqliteClassName($this->databaseFile);

        return $instance;
    }
}


text:
`Home <index.html>`_ OpenStack-Ansible Installation Guide

Configuring RabbitMQ (optional)
===============================

RabbitMQ provides the messaging broker for various OpenStack services. The
OpenStack-Ansible project configures a plaintext listener on port 5672 and
a SSL/TLS encrypted listener on port 5671.

Customize your RabbitMQ deployment in ``/etc/openstack_deploy/user_variables.yml``.

Add a TLS encrypted listener to RabbitMQ
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The OpenStack-Ansible project provides the ability to secure RabbitMQ
communications with self-signed or user-provided SSL certificates. Refer to
`Securing services with SSL certificates`_ for available configuration
options.

.. _Securing services with SSL certificates: configure-sslcertificates.html

Enable encrypted connections to RabbitMQ
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The control of SSL communication between various OpenStack services and
RabbitMQ is via the Ansible variable ``rabbitmq_use_ssl``:

.. code-block:: yaml

    rabbitmq_use_ssl: true

Setting this variable to ``true`` adjusts the RabbitMQ port to 5671 (the
default SSL/TLS listener port) and enables SSL connectivity between each
OpenStack service and RabbitMQ.

Setting this variable to ``false`` disables SSL encryption between
OpenStack services and RabbitMQ. Use the plaintext port for RabbitMQ, 5672,
for all services.

--------------

.. include:: navigation.txt


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Rhino.Mocks.Impl.RemotingMock
{
    /// <summary>
    /// Operation on a remoting proxy
    /// </summary>
    /// <remarks>
    /// It is not possible to directly communicate to a real proxy via transparent proxy.
    /// Transparent proxy impersonates a user type and only methods of that user type are callable.
    /// The only methods that are guaranteed to exist on any transparent proxy are methods defined
    /// in Object: namely ToString(), GetHashCode(), and Equals()).
    ///
    /// These three methods are the only way to tell the real proxy to do something.
    /// Equals() is the most suitable of all, since it accepts an arbitrary object parameter.
    /// The RemotingProxy code is built so that if it is compared to an IRemotingProxyOperation,
    /// transparentProxy.Equals(operation) will call operation.Process(realProxy).
    /// This way we can retrieve a real proxy from transparent proxy and perform
    /// arbitrary operation on it.
    /// </remarks>
    internal interface IRemotingProxyOperation
    {
        void Process(RemotingProxy proxy);
    }
}


text:
using HDO2O.Infranstructure;
using HDO2O.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HDO2O.IRepository
{
    public interface IBarbershopHairDresserRespository : IBaseRepository<BarbershopHairDresser>
    {
    }
}


text:
module Data.BucketHistogram (
  BucketHistogram
  , bucketHistogram
  , bucketHistogramWithBounds
  , reset
  , quantile
  , insert
  ) where

import Data.Array

data BucketHistogram = BucketHistogram {
  numBuckets :: Int
  , buckets :: Array Int Int
  , lowerBounds :: Array Int Int
  , upperBounds :: Array Int Int
  , countElems :: Int
  } deriving Show

bucketHistogram :: Int -> Int -> BucketHistogram
bucketHistogram n s = BucketHistogram {
  numBuckets = n
  , buckets = mkBuckets n
  , lowerBounds = lowerBoundsArr
  , upperBounds = upperBoundsArr
  , countElems = 0
  }
  where
    lowerBoundsArr = listArray (0, n - 1) [i * s | i <- [0..(n - 1)]]
    upperBoundsArr = listArray (0, n - 1) [i * s | i <- [1..n]]

bucketHistogramWithBounds :: Int -> [Int] -> [Int] -> BucketHistogram
bucketHistogramWithBounds n lb ub = BucketHistogram {
  numBuckets = n
  , buckets = mkBuckets n
  , lowerBounds = listArray (0, n - 1) lb
  , upperBounds = listArray (0, n - 1) ub
  , countElems = 0
  }

mkBuckets :: Int -> Array Int Int
mkBuckets n = listArray (0, n - 1) (replicate n 0)

reset :: BucketHistogram -> BucketHistogram

reset h@BucketHistogram { numBuckets = n } = h {
  buckets = mkBuckets n
  , countElems = 0
  }

quantile :: (Fractional a, Ord a) => BucketHistogram -> a -> Int
quantile h@BucketHistogram { numBuckets = n
                           , buckets = bucketsArr
                           , countElems = cnt
                           , lowerBounds = lowerBoundsArr
                           } targetQuantile = loop 0 0
  where
    loop total i | i == n = 0
                 | currQuantile total >= targetQuantile = lowerBoundsArr ! i
                 | otherwise = loop (total + bucketsArr ! i) (i + 1)
    currQuantile total = fromIntegral total / fromIntegral cnt

insert :: BucketHistogram -> Int -> BucketHistogram
insert h@BucketHistogram { buckets = bucketsArr, countElems = cnt } datum = h {
  buckets = bucketsArr // [(idx, curr + 1)]
  , countElems = cnt + 1
  }
  where
    curr = bucketsArr ! idx
    idx = findBucket h datum

findBucket :: BucketHistogram -> Int -> Int
findBucket h@BucketHistogram { upperBounds = upperBoundsArr, numBuckets = nb } datum
  | datum > upperBoundsArr ! (nb - 1) = nb - 1
  | otherwise = loop 0 (nb - 1)
    where
      loop low high
        | low > high = -1
        | otherwise = case cmp of
          EQ -> mid
          GT -> loop low (mid - 1)
          LT -> loop (mid + 1) high
          where mid = (low + high) `div` 2
                cmp = compareBucket h mid datum

compareBucket :: BucketHistogram -> Int -> Int -> Ordering
compareBucket h bucket datum
  | low <= datum && high > datum = EQ
  | low > datum = GT
  | otherwise = LT
    where
      low = lowerBounds h ! bucket
      high = upperBounds h ! bucket


text:
module Wars
  class Npc
    include Fighter

    cattr_accessor :index
    self.index = 0

    DefaultStrength = 10
    DefaultDefense = 10
    DefaultLife = 50

    def self.all
      @@all ||= Data::Npcs
    end

    def self.find(id)
      all.detect{ |o| o.id == id.to_i }
    end

    attr_reader :id, :name, :strength, :defense
    attr_accessor :life

    def initialize(attributes = {})
      self.index += 1
      @id = attributes[:id] || self.index
      @name = attributes[:name] || 'Mystery Man'
      @strength = attributes[:strength] || DefaultStrength
      @defense = attributes[:defense] || DefaultDefense
      @life = @base_life = attributes[:life] || DefaultLife
      @rewards = attributes[:rewards]
      @condition = attributes[:condition] || nil
    end

    def eligible?(player)
      return true if @condition.blank?
      @condition.call(player)
    end

    # HACK: when class caching is on the NPC's health is still set to negatives from the
    # previous fight. this is just a bandaid
    def reset!
      @life = @base_life
    end

    def alive?
      life > 0
    end

    # returns [type, quantity] where type can be a +Product+, +Equipment+ or +:cash+
    def reward(player = nil)
      @rewards.call(player)
    end
  end
end