text:
package io.skysail.server;

import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.service.StatusService;

public class SkysailStatusService extends StatusService {

    @Override
    public Representation toRepresentation(Status status, Request request, Response response) {
        String msg = "Sorry, there was a problem processing your request:

";
        msg += status.toString() + "

";
        msg += "Proceed here to get back to the application.";
        return new StringRepresentation(msg, MediaType.TEXT_HTML);
    }
}


text:
class InterventionBuilderSweeper < ActionController::Caching::Sweeper
  observe GoalDefinition,ObjectiveDefinition,InterventionCluster,InterventionDefinition,RecommendedMonitor,ProbeDefinition

  def after_create(obj)
    expire_cache_for(obj)
  end

  def after_update(obj)
    expire_cache_for(obj)
  end

  def after_destroy(obj)
    expire_cache_for(obj)
  end

  private
  def expire_cache_for(obj)
    if obj.respond_to?(:objective_definitions)
      return nil if obj.district.blank?
      obj.objective_definitions.each{|o| expire_cache_for_objective_definition(o)}
      obj.district.touch
    elsif obj.respond_to?(:objective_definition)
      return nil if obj.try(:objective_definition).try(:district).blank?
      expire_cache_for_objective_definition(obj.objective_definition)
      obj.objective_definition.district.touch
    elsif obj.is_a?(ObjectiveDefinition)
      return nil if obj.district.blank?
      expire_cache_for_objective_definition(obj)
      obj.district.touch
    end
  end

  def expire_cache_for_objective_definition(objective_definition)
    district = objective_definition.district
    FileUtils.rm(Dir.glob(Rails.root.join("public","system","district_generated_docs",district.id.to_s,"#{objective_definition.filename}.*")))
  end

end

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.siberiadante.utilsample.activity.util.SDDateUtilActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:padding="@dimen/page_padding_16">

        <TextView
            android:id="@+id/tv_time"
            android:minHeight="50dp"
            android:layout_width="match_parent"
            android:gravity="center"
            android:layout_height="wrap_content"
            android:textColor="@color/colorContentText"
            android:textSize="@dimen/sd_font_16" />

        <TextView
            android:id="@+id/tv_date"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textColor="@color/colorContentText"
            android:textSize="@dimen/sd_font_16" />

    </LinearLayout>

</ScrollView>


text:
static struct gpio gpio0;
static struct uart uart0;
static struct timer timer0;
static struct timer timer1;
static struct icerror icerror0;

static uint8_t led_status = 0x01;
static volatile unsigned int hashes_per_second = 0;
static volatile bool reset_counter = true;

// Converts an integer to a string:
static void int2string(int i, char * s);
// Converts an unsigned 32 bit integer to a hexadecimal string:
static void int2hex32(uint32_t i, char * s);

void exception_handler(uint32_t mcause, uint32_t mepc, uint32_t sp)
{
	if((mcause & (1 << POTATO_MCAUSE_INTERRUPT_BIT)) && (mcause & (1 << POTATO_MCAUSE_IRQ_BIT)))
	{
		uint8_t irq = mcause & 0x0f;

		switch(irq)
		{
			case PLATFORM_IRQ_TIMER0:
			{
				// Print the number of hashes since last interrupt:
				char hps_dec[11];
				int2string(hashes_per_second, hps_dec);
				uart_tx_string(&uart0, hps_dec);
				uart_tx_string(&uart0, " H/s\n\r");
				reset_counter = true;

				timer_clear(&timer0);
				break;
			}
			case PLATFORM_IRQ_TIMER1:
			{
				led_status >>= 1;
				if((led_status & 0xf) == 0)
					led_status = 0x8;

				// Read the switches to determine which LEDs should be used:
				uint32_t switch_mask = (gpio_get_input(&gpio0) >> 4) & 0xf;

				// Read the buttons and turn on the corresponding LED regardless of the switch settings:
				uint32_t button_mask = gpio_get_input(&gpio0) & 0xf;

				// Set the LEDs:
				gpio_set_output(&gpio0, ((led_status & switch_mask) | button_mask) << 8);
				timer_clear(&timer1);
				break;
			}
			case PLATFORM_IRQ_BUS_ERROR:
			{
				uart_tx_string(&uart0, "Bus error!\n\r");

				enum icerror_access_type access = icerror_get_access_type(&icerror0);
				switch(access)
				{
					case ICERROR_ACCESS_READ:
					{
						uart_tx_string(&uart0, "\tType: read\n\r");

						uart_tx_string(&uart0, "\tAddress: ");
						char address_buffer[5];
						int2hex32(icerror_get_read_address(&icerror0), address_buffer);
						uart_tx_string(&uart0, address_buffer);
						uart_tx_string(&uart0, "\n\r");
						break;
					}
					case ICERROR_ACCESS_WRITE:
					{
						uart_tx_string(&uart0, "\tType: write\n\r");

						char address_buffer[5];
						int2hex32(icerror_get_write_address(&icerror0), address_buffer);
						uart_tx_string(&uart0, address_buffer);
						uart_tx_string(&uart0, "\n\r");
						break;
					}
					case ICERROR_ACCESS_NONE:
						// fallthrough
					default:
						break;
				}

				potato_disable_interrupts();
				while(1) potato_wfi();

				break;
			}
			default:
				potato_disable_irq(irq);
				break;
		}
	}
}

int main(void)
{
	// Configure GPIOs:
	gpio_initialize(&gpio0, (volatile void *) PLATFORM_GPIO_BASE);
	gpio_set_direction(&gpio0, 0xf00);	// Set LEDs to output, buttons and switches to input
	gpio_set_output(&gpio0, 0x100);		// Turn LED0 on.

	// Configure the UART:
	uart_initialize(&uart0, (volatile void *) PLATFORM_UART0_BASE);
	uart_set_divisor(&uart0, uart_baud2divisor(115200, PLATFORM_SYSCLK_FREQ));
	uart_tx_string(&uart0, "--- SHA256 Benchmark Application ---\r\n\n");

	// Set up timer0 at 1 Hz:
	timer_initialize(&timer0, (volatile void *) PLATFORM_TIMER0_BASE);
	timer_reset(&timer0);
	timer_set_compare(&timer0, PLATFORM_SYSCLK_FREQ);
	timer_start(&timer0);

	// Set up timer1 at 4 Hz:
	timer_initialize(&timer1, (volatile void *) PLATFORM_TIMER1_BASE);
	timer_reset(&timer1);
	timer_set_compare(&timer1, PLATFORM_SYSCLK_FREQ >> 2);
	timer_start(&timer1);

	// Set up the interconnect error module for detecting invalid bus accesses:
	icerror_initialize(&icerror0, (volatile void *) PLATFORM_ICERROR_BASE);
	icerror_reset(&icerror0);

	// Enable interrupts:
	potato_enable_irq(PLATFORM_IRQ_TIMER0);
	potato_enable_irq(PLATFORM_IRQ_TIMER1);
	potato_enable_irq(PLATFORM_IRQ_BUS_ERROR);
	potato_enable_interrupts();

	struct sha256_context context;

	// Prepare a block for hashing:
	uint32_t block[16];
	uint8_t * block_ptr = (uint8_t *) block;
	block_ptr[0] = 'a';
	block_ptr[1] = 'b';
	block_ptr[2] = 'c';
	sha256_pad_le_block(block_ptr, 3, 3);

	// Repeatedly hash the same data over and over again:
	while(true)
	{
		uint8_t hash[32];

		sha256_reset(&context);
		sha256_hash_block(&context, block);
		sha256_get_hash(&context, hash);

		potato_disable_interrupts();
		if(reset_counter)
		{
			hashes_per_second = 1;
			reset_counter = false;
		} else
			++hashes_per_second;
		potato_enable_interrupts();
	}

	return 0;
}

static void int2string(int n, char * s)
{
	bool first = true;

	if(n == 0)
	{
		s[0] = '0';
		s[1] =  0;
		return;
	}

	if(n & (1u << 31))
	{
		n = ~n + 1;
		*(s++) = '-';
	}

	for(int i = 1000000000; i > 0; i /= 10)
	{
		if(n / i == 0 && !first)
			*(s++) = '0';
		else if(n / i != 0)
		{
			*(s++) = '0' + n / i;
			n %= i;
			first = false;
		}
	}
	*s = 0;
}

static void int2hex32(uint32_t n, char * s)
{
	static const char * hex_digits = "0123456789abcdef";

	int index = 0;
	for(int i = 28; i >= 0; i -= 4)
		s[index++] = hex_digits[(n >> (32 - i)) & 0xf];
	s[index] = 0;
}


text:
using System;
namespace MessagingToolkit.QRCode.Codec.Util
{

	public class ContentConverter
	{

		internal static char n = '\n';

		public static String convert(String targetString)
		{
			if (targetString == null)
				return targetString;
			if (targetString.IndexOf("MEBKM:") > - 1)
				targetString = convertDocomoBookmark(targetString);
			if (targetString.IndexOf("MECARD:") > - 1)
				targetString = convertDocomoAddressBook(targetString);
			if (targetString.IndexOf("MATMSG:") > - 1)
				targetString = convertDocomoMailto(targetString);
			if (targetString.IndexOf("http\\://") > - 1)
				targetString = replaceString(targetString, "http\\://", "\nhttp://");
			return targetString;
		}

		private static String convertDocomoBookmark(String targetString)
		{
			targetString = removeString(targetString, "MEBKM:");
			targetString = removeString(targetString, "TITLE:");
			targetString = removeString(targetString, ";");
			targetString = removeString(targetString, "URL:");
			return targetString;
		}

		private static String convertDocomoAddressBook(String targetString)
		{

			targetString = removeString(targetString, "MECARD:");
			targetString = removeString(targetString, ";");
			targetString = replaceString(targetString, "N:", "NAME1:");
			targetString = replaceString(targetString, "SOUND:", n + "NAME2:");
			targetString = replaceString(targetString, "TEL:", n + "TEL1:");
			targetString = replaceString(targetString, "EMAIL:", n + "MAIL1:");
			targetString = targetString + n;
			return targetString;
		}

		private static String convertDocomoMailto(String s)
		{
			String s1 = s;
			char c = '\n';
			s1 = removeString(s1, "MATMSG:");
			s1 = removeString(s1, ";");
			s1 = replaceString(s1, "TO:", "MAILTO:");
			s1 = replaceString(s1, "SUB:", c + "SUBJECT:");
			s1 = replaceString(s1, "BODY:", c + "BODY:");
			s1 = s1 + c;
			return s1;
		}

		private static String replaceString(String s, String s1, String s2)
		{
			String s3 = s;
			for (int i = s3.IndexOf(s1, 0); i > - 1; i = s3.IndexOf(s1, i + s2.Length))
				s3 = s3.Substring(0, (i) - (0)) + s2 + s3.Substring(i + s1.Length);

			return s3;
		}

		private static String removeString(String s, String s1)
		{
			return replaceString(s, s1, "");
		}
	}
}


text:
template <typename Point, typename LatitudePolicy>
void test_distance(
            typename bg::coordinate_type<Point>::type const& lon1,
            typename bg::coordinate_type<Point>::type const& lat1,
            typename bg::coordinate_type<Point>::type const& lon2,
            typename bg::coordinate_type<Point>::type const& lat2,
            typename bg::coordinate_type<Point>::type const& lon3,
            typename bg::coordinate_type<Point>::type const& lat3,
            typename bg::coordinate_type<Point>::type const& radius,
            typename bg::coordinate_type<Point>::type const& expected,
            typename bg::coordinate_type<Point>::type const& tolerance)
{
    typedef bg::strategy::distance::cross_track
        <
            typename bg::coordinate_type<Point>::type
        > strategy_type;

    typedef typename bg::strategy::distance::services::return_type
        <
            strategy_type,
            Point,
            Point
        >::type return_type;

    {
        // compile-check if there is a strategy for this type
        typedef typename bg::strategy::distance::services::default_strategy
            <
                bg::point_tag, bg::segment_tag, Point, Point
            >::type cross_track_strategy_type;

        typedef typename bg::strategy::distance::services::default_strategy
            <
                bg::segment_tag, bg::point_tag, Point, Point
            >::type reversed_tags_cross_track_strategy_type;

        boost::ignore_unused<cross_track_strategy_type,
                             reversed_tags_cross_track_strategy_type>();
    }

    BOOST_CONCEPT_ASSERT
        (
            (bg::concepts::PointSegmentDistanceStrategy<strategy_type, Point, Point>)
        );

    Point p1, p2, p3;
    bg::assign_values(p1, lon1, LatitudePolicy::apply(lat1));
    bg::assign_values(p2, lon2, LatitudePolicy::apply(lat2));
    bg::assign_values(p3, lon3, LatitudePolicy::apply(lat3));

    strategy_type strategy;
    return_type d = strategy.apply(p1, p2, p3);

    BOOST_CHECK_CLOSE(radius * d, expected, tolerance);

    // The strategy should return the same result if we reverse the parameters
    d = strategy.apply(p1, p3, p2);
    BOOST_CHECK_CLOSE(radius * d, expected, tolerance);

    // Test specifying radius explicitly
    strategy_type strategy_radius(radius);
    d = strategy_radius.apply(p1, p2, p3);
    BOOST_CHECK_CLOSE(d, expected, tolerance);

    // Test the "default strategy" registration
    bg::model::referring_segment<Point const> segment(p2, p3);
    d = bg::distance(p1, segment);
    BOOST_CHECK_CLOSE(radius * d, expected, tolerance);
}

template <typename Point>
void test_case_boost_geometry_list_20120625()
{
    // This function tests the bug submitted by Karsten Ahnert
    // on Boost.Geometry list at 2012-06-25, and wherefore he
    // submitted a patch a few days later.

    Point p1, p2;
    bg::model::segment<Point> s1, s2;

    bg::read_wkt("POINT(1 1)", p1);
    bg::read_wkt("POINT(5 1)", p2);
    bg::read_wkt("LINESTRING(0 2,2 2)", s1);
    bg::read_wkt("LINESTRING(2 2,4 2)", s2);

    BOOST_CHECK_CLOSE(boost::geometry::distance(p1, s1), 0.0174586, 0.0001);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p1, s2), 0.0246783, 0.0001);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p2, s1), 0.0551745, 0.0001);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p2, s2), 0.0246783, 0.0001);

    // Check degenerated segments
    bg::model::segment<Point> s3;
    bg::read_wkt("LINESTRING(2 2,2 2)", s3);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p1, s3), 0.0246783, 0.0001);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p2, s3), 0.0551745, 0.0001);

    // Point/Point distance should be identical:
    Point p3;
    bg::read_wkt("POINT(2 2)", p3);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p1, p3), 0.0246783, 0.0001);
    BOOST_CHECK_CLOSE(boost::geometry::distance(p2, p3), 0.0551745, 0.0001);
}

template <typename Point, typename LatitudePolicy>
void test_all()
{
    typename bg::coordinate_type<Point>::type const average_earth_radius = 6372795.0;

    // distance (Paris <-> Amsterdam/Barcelona),
    // with coordinates rounded as below ~87 km
    // is equal to distance (Paris <-> Barcelona/Amsterdam)
    typename bg::coordinate_type<Point>::type const p_to_ab = 86.798321 * 1000.0;
    test_distance<Point, LatitudePolicy>(2, 48, 4, 52, 2, 41, average_earth_radius, p_to_ab, 0.1);
    test_distance<Point, LatitudePolicy>(2, 48, 2, 41, 4, 52, average_earth_radius, p_to_ab, 0.1);

    test_case_boost_geometry_list_20120625<Point>();
}

int test_main(int, char* [])
{
    test_all<bg::model::point<double, 2, bg::cs::spherical_equatorial<bg::degree> >, geographic_policy >();

    // NYI: haversine for mathematical spherical coordinate systems
    // test_all<bg::model::point<double, 2, bg::cs::spherical<bg::degree> >, mathematical_policya >();

    return 0;
}


text:
layout:     post
title:      sq 0.51.0
date:       2017-06-01
categories: sq golang
---

After yet another hiatus, `sq 0.51.0` is available. This release adds basic notification functionality
(Slack, HipChat). This is useful for long-running jobs.
Download [here](https://github.com/neilotoole/sq-manual/wiki).


text:
from setuptools import setup, find_packages
from os import path
import re

# Get current path
here = path.abspath(path.dirname(__file__))

# Get version from strikepackage.py
with open(path.join(here, 'clancy/clancy.py')) as f:
    version_file = f.read()
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                          version_file, re.M)
if version_match:
    version = version_match.group(1)
else:
    raise RuntimeError("Unable to find version string.")

# Get long description from README and HISTORY
with open(path.join(here, 'README.rst')) as f:
    readme = f.read()
with open(path.join(here, 'HISTORY.rst')) as f:
    history = f.read()

# Dependencies
requires = [
    'docopt',
    'kaptan',
    'requests',
    'schema',
]

# Setup
setup(
    name='clancy',
    version=version,
    description='A command line client for Red October.',
    long_description=readme + '\n\n' + history,
    author='Paul Liu',
    author_email='paul@ferociouspings.com',
    url='https://github.com/pwyliu/clancy',
    license='MIT',
    zip_safe=False,  # fuck you egg
    classifiers=[
        'Development Status :: 3 - Alpha',
        'Intended Audience :: System Administrators',
        'Topic :: System :: Systems Administration',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 2.7',
        'Programming Language :: Python :: 2 :: Only',
        'Operating System :: POSIX :: Linux',
    ],
    keywords='Red October encryption security two man rule',
    install_requires=requires,
    include_package_data=True,
    packages=find_packages(),
    entry_points={
        'console_scripts': ['clancy = clancy.clancy:main']
    },
)


text:
https://d396qusza40orc.cloudfront.net/getdata%2Fprojectfiles%2FUCI%20HAR%20Dataset.zip

###########
get_data.R is for downloading data from the link above.
it will download the data and unzip all files into 'dataset' directory.
if the directory is existed, or it will creats a directory named 'dataset', then put data file into it.

##########
run_analysis.R

###########


text:
namespace DockSample
{
    partial class DummyOutputWindow
    {
        /// <summary>
        /// Required designer variable.
        /// </summary>
        private System.ComponentModel.IContainer components = null;

        /// <summary>
        /// Clean up any resources being used.
        /// </summary>
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
        protected override void Dispose(bool disposing)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }
            base.Dispose(disposing);
        }

        #region Windows Form Designer generated code
        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(DummyOutputWindow));
            this.comboBox = new System.Windows.Forms.ComboBox();
            this.textBox1 = new System.Windows.Forms.TextBox();
            this.SuspendLayout();
            //
            // comboBox
            //
            this.comboBox.Dock = System.Windows.Forms.DockStyle.Top;
            this.comboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
            this.comboBox.Items.AddRange(new object[] {
            "Build"});
            this.comboBox.Location = new System.Drawing.Point(0, 2);
            this.comboBox.Name = "comboBox";
            this.comboBox.Size = new System.Drawing.Size(255, 21);
            this.comboBox.TabIndex = 1;
            //
            // textBox1
            //
            this.textBox1.Dock = System.Windows.Forms.DockStyle.Fill;
            this.textBox1.Location = new System.Drawing.Point(0, 23);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ScrollBars = System.Windows.Forms.ScrollBars.Both;
            this.textBox1.Size = new System.Drawing.Size(255, 340);
            this.textBox1.TabIndex = 2;
            this.textBox1.Text = resources.GetString("textBox1.Text");
            this.textBox1.WordWrap = false;
            //
            // DummyOutputWindow
            //
            this.ClientSize = new System.Drawing.Size(255, 365);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.comboBox);
            this.DockAreas = ((WeifenLuo.WinFormsUI.Docking.DockAreas)(((((WeifenLuo.WinFormsUI.Docking.DockAreas.Float | WeifenLuo.WinFormsUI.Docking.DockAreas.DockLeft)
                        | WeifenLuo.WinFormsUI.Docking.DockAreas.DockRight)
                        | WeifenLuo.WinFormsUI.Docking.DockAreas.DockTop)
                        | WeifenLuo.WinFormsUI.Docking.DockAreas.DockBottom)));
            this.HideOnClose = true;
            this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
            this.Name = "DummyOutputWindow";
            this.Padding = new System.Windows.Forms.Padding(0, 2, 0, 2);
            this.ShowHint = WeifenLuo.WinFormsUI.Docking.DockState.DockBottomAutoHide;
            this.TabText = "Output";
            this.Text = "Output";
            this.ResumeLayout(false);
            this.PerformLayout();

        }
        #endregion

        private System.Windows.Forms.ComboBox comboBox;
        private System.Windows.Forms.TextBox textBox1;
    }
}


text:
package com.infrarch.engine.constants;

public interface Cmd {

	// query parameters
	public static final String Q_COMMAND = "command";
	public static final String Q_DIR = "dir";
	public static final String Q_FILE_NAME = "file_name";
	public static final String Q_USER = "name";
	public static final String Q_PASSWORD = "pass";
	public static final String Q_PROPERTY = "property";
	public static final String Q_VALUE = "value";
	public static final String Q_COMMENT = "comment";
	public static final String Q_SRC_DIR = "src_dir";
	public static final String Q_DEST_DIR = "dest_dir";
	public static final String Q_OVERWRITE = "overwrite";

	// commands
	public static final String LIST_CONTENTS = "list_contents";
	public static final String LIST_DIRS = "list_dirs";
	public static final String LIST_FILES = "list_files";
	public static final String FILE_INFO = "file_info";
	public static final String PING = "ping";
	public static final String DOWNLOAD = "download";
	public static final String UPLOAD = "upload";
	public static final String RECYCLE_FILE = "recycle_file";
	public static final String RECYCLE_DIRECTORY = "recycle_dir";
	public static final String LOGIN = "login";
	public static final String LOGOUT = "logout";
	public static final String CHANGE_PASSWORD = "change_pass";
	public static final String USER_INFO = "user_info";
	public static final String SERVER_INFO = "server_info";
	public static final String SETTINGS_GET = "settings_get";
	public static final String SETTINGS_SET = "settings_set";
	public static final String LIST_SETTINGS = "list_settings";
	public static final String LIST_USERS = "list_users";
	public static final String MAKE_DIR = "make_dir";
	public static final String DELETE_USER = "delete_user";
	public static final String ADD_USER = "add_user";
	public static final String EDIT_USER = "edit_user";
	public static final String COPY_FILE = "copy_file";
	public static final String MOVE_FILE = "move_file";
}


text:
.. _config:

Configuration Handling
======================

Applications need some kind of configuration.  There are different settings
you might want to change depending on the application environment like
toggling the debug mode, setting the secret key, and other such
environment-specific things.

The way Flask is designed usually requires the configuration to be
available when the application starts up.  You can hardcode the
configuration in the code, which for many small applications is not
actually that bad, but there are better ways.

Independent of how you load your config, there is a config object
available which holds the loaded configuration values:
The :attr:`~flask.Flask.config` attribute of the :class:`~flask.Flask`
object.  This is the place where Flask itself puts certain configuration
values and also where extensions can put their configuration values.  But
this is also where you can have your own configuration.

Configuration Basics
--------------------

The :attr:`~flask.Flask.config` is actually a subclass of a dictionary and
can be modified just like any dictionary::

    app = Flask(__name__)
    app.config['DEBUG'] = True

Certain configuration values are also forwarded to the
:attr:`~flask.Flask` object so you can read and write them from there::

    app.debug = True

To update multiple keys at once you can use the :meth:`dict.update`
method::

    app.config.update(
        DEBUG=True,
        SECRET_KEY='...'
    )

.. admonition:: Debug Mode with the ``flask`` Script

   If you use the :command:`flask` script to start a local development
   server, to enable the debug mode, you need to export the ``FLASK_DEBUG``
   environment variable before running the server::

    $ export FLASK_DEBUG=1
    $ flask run

   (On Windows you need to use ``set`` instead of ``export``).

   ``app.debug`` and ``app.config['DEBUG']`` are not compatible with
   the :command:`flask` script. They only worked when using ``Flask.run()``
   method.

Builtin Configuration Values
----------------------------

The following configuration values are used internally by Flask:

.. py:data:: DEBUG

    Enable debug mode. When using the development server with ``flask run`` or
    ``app.run``, an interactive debugger will be shown for unhanlded
    exceptions, and the server will be reloaded when code changes.

    **Do not enable debug mode in production.**

    Default: ``False``

.. py:data:: TESTING

    Enable testing mode. Exceptions are propagated rather than handled by the
    the app's error handlers. Extensions may also change their behavior to
    facilitate easier testing. You should enable this in your own tests.

    Default: ``False``

.. py:data:: PROPAGATE_EXCEPTIONS

    Exceptions are re-raised rather than being handled by the app's error
    handlers. If not set, this is implicitly true if ``TESTING`` or ``DEBUG``
    is enabled.

    Default: ``None``

.. py:data:: PRESERVE_CONTEXT_ON_EXCEPTION

    Don't pop the request context when an exception occurs. If not set, this
    is true if ``DEBUG`` is true. This allows debuggers to introspect the
    request data on errors, and should normally not need to be set directly.

    Default: ``None``

.. py:data:: TRAP_HTTP_EXCEPTIONS

    If there is no handler for an ``HTTPException``-type exception, re-raise it
    to be handled by the interactive debugger instead of returning it as a
    simple error response.

    Default: ``False``

.. py:data:: TRAP_BAD_REQUEST_ERRORS``

    Trying to access a key that doesn't exist from request dicts like ``args``
    and ``form`` will return a 400 Bad Request error page. Enable this to treat
    the error as an unhandled exception instead so that you get the interactive
    debugger. This is a more specific version of ``TRAP_HTTP_EXCEPTIONS``. If
    unset, it is enabled in debug mode.

    Default: ``None``

.. py:data:: SECRET_KEY

    A secret key that will be used for securely signing the session cookie
    and can be used for any other security related needs by extensions or your
    application. It should be a long random string of bytes, although unicode
    is accepted too. For example, copy the output of this to your config::

        python -c 'import os; print(os.urandom(32))'

    **Do not reveal the secret key when posting questions or committing code.**

    Default: ``None``

.. py:data:: SESSION_COOKIE_NAME

    The name of the session cookie. Can be changed in case you already have a
    cookie with the same name.

    Default: ``'session'``

.. py:data:: SESSION_COOKIE_DOMAIN

    The domain match rule that the session cookie will be valid for. If not
    set, the cookie will be valid for all subdomains of ``SERVER_NAME``. If
    ``False``, the cookie's domain will not be set.

    Default: ``None``

.. py:data:: SESSION_COOKIE_PATH

    The path that the session cookie will be valid for. If not set, the cookie
    will be valid underneath ``APPLICATION_ROOT`` or ``/`` if that is not set.

    Default: ``None``

.. py:data:: SESSION_COOKIE_HTTPONLY

    Browsers will not allow JavaScript access to cookies marked as "HTTP only"
    for security.

    Default: ``True``

.. py:data:: SESSION_COOKIE_SECURE

    Browsers will only send cookies with requests over HTTPS if the cookie is
    marked "secure". The application must be served over HTTPS for this to make
    sense.

    Default: ``False``

.. py:data:: PERMANENT_SESSION_LIFETIME

    If ``session.permanent`` is true, the cookie's max age will be set to this
    number of seconds. Can either be a :class:`datetime.timedelta` or an
    ``int``.

    Default: ``timedelta(days=31)`` (``2678400`` seconds)

.. py:data:: SESSION_REFRESH_EACH_REQUEST

    Control whether the cookie is sent with every response when
    ``session.permanent`` is true. Sending the cookie every time (the default)
    can more reliably keep the session from expiring, but uses more bandwidth.
    Non-permanent sessions are not affected.

    Default: ``True``

.. py:data:: USE_X_SENDFILE

    When serving files, set the ``X-Sendfile`` header instead of serving the
    data with Flask. Some web servers, such as Apache, recognize this and serve
    the data more efficiently. This only makes sense when using such a server.

    Default: ``False``

.. py:data:: SEND_FILE_MAX_AGE_DEFAULT

    When serving files, set the cache control max age to this number of
    seconds.  Can either be a :class:`datetime.timedelta` or an ``int``.
    Override this value on a per-file basis using
    :meth:`~flask.Flask.get_send_file_max_age` on the application or blueprint.

    Default: ``timedelta(hours=12)`` (``43200`` seconds)

.. py:data:: LOGGER_NAME

    The name of the logger that the Flask application sets up. If not set,
    it will take the import name passed to ``Flask.__init__``.

    Default: ``None``

.. py:data:: LOGGER_HANDLER_POLICY

    When to activate the application's logger handler. ``'always'`` always
    enables it, ``'debug'`` only activates it in debug mode, ``'production'``
    only activates it when not in debug mode, and ``'never'`` never enables it.

    Default: ``'always'``

.. py:data:: SERVER_NAME

    Inform the application what host and port it is bound to. Required for
    subdomain route matching support.

    If set, will be used for the session cookie domain if
    ``SESSION_COOKIE_DOMAIN`` is not set. Modern web browsers will not allow
    setting cookies for domains without a dot. To use a domain locally,
    add any names that should route to the app to your ``hosts`` file. ::

        127.0.0.1 localhost.dev

    If set, ``url_for`` can generate external URLs with only an application
    context instead of a request context.

    Default: ``None``

.. py:data:: APPLICATION_ROOT

    Inform the application what path it is mounted under by the application /
    web server.

    Will be used for the session cookie path if ``SESSION_COOKIE_PATH`` is not
    set.

    Default: ``'/'``

.. py:data:: PREFERRED_URL_SCHEME

    Use this scheme for generating external URLs when not in a request context.

    Default: ``'http'``

.. py:data:: MAX_CONTENT_LENGTH

    Don't read more than this many bytes from the incoming request data. If not
    set and the request does not specify a ``CONTENT_LENGTH``, no data will be
    read for security.

    Default: ``None``

.. py:data:: JSON_AS_ASCII

    Serialize objects to ASCII-encoded JSON. If this is disabled, the JSON
    will be returned as a Unicode string, or encoded as ``UTF-8`` by
    ``jsonify``. This has security implications when rendering the JSON in
    to JavaScript in templates, and should typically remain enabled.

    Default: ``True``

.. py:data:: JSON_SORT_KEYS

    Sort the keys of JSON objects alphabetically. This is useful for caching
    because it ensures the data is serialized the same way no matter what
    Python's hash seed is. While not recommended, you can disable this for a
    possible performance improvement at the cost of caching.

    Default: ``True``

.. py:data:: JSONIFY_PRETTYPRINT_REGULAR

    ``jsonify`` responses will be output with newlines, spaces, and indentation
    for easier reading by humans. Always enabled in debug mode.

    Default: ``False``

.. py:data:: JSONIFY_MIMETYPE

    The mimetype of ``jsonify`` responses.

    Default: ``'application/json'``

.. py:data:: TEMPLATES_AUTO_RELOAD

    Reload templates when they are changed. If not set, it will be enabled in
    debug mode.

    Default: ``None``

.. py:data:: EXPLAIN_TEMPLATE_LOADING

    Log debugging information tracing how a template file was loaded. This can
    be useful to figure out why a template was not loaded or the wrong file
    appears to be loaded.

    Default: ``False``

.. versionadded:: 0.4
   ``LOGGER_NAME``

.. versionadded:: 0.5
   ``SERVER_NAME``

.. versionadded:: 0.6
   ``MAX_CONTENT_LENGTH``

.. versionadded:: 0.7
   ``PROPAGATE_EXCEPTIONS``, ``PRESERVE_CONTEXT_ON_EXCEPTION``

.. versionadded:: 0.8
   ``TRAP_BAD_REQUEST_ERRORS``, ``TRAP_HTTP_EXCEPTIONS``,
   ``APPLICATION_ROOT``, ``SESSION_COOKIE_DOMAIN``,
   ``SESSION_COOKIE_PATH``, ``SESSION_COOKIE_HTTPONLY``,
   ``SESSION_COOKIE_SECURE``

.. versionadded:: 0.9
   ``PREFERRED_URL_SCHEME``

.. versionadded:: 0.10
   ``JSON_AS_ASCII``, ``JSON_SORT_KEYS``, ``JSONIFY_PRETTYPRINT_REGULAR``

.. versionadded:: 0.11
   ``SESSION_REFRESH_EACH_REQUEST``, ``TEMPLATES_AUTO_RELOAD``,
   ``LOGGER_HANDLER_POLICY``, ``EXPLAIN_TEMPLATE_LOADING``

Configuring from Files
----------------------

Configuration becomes more useful if you can store it in a separate file,
ideally located outside the actual application package. This makes
packaging and distributing your application possible via various package
handling tools (:ref:`distribute-deployment`) and finally modifying the
configuration file afterwards.

So a common pattern is this::

    app = Flask(__name__)
    app.config.from_object('yourapplication.default_settings')
    app.config.from_envvar('YOURAPPLICATION_SETTINGS')

This first loads the configuration from the
`yourapplication.default_settings` module and then overrides the values
with the contents of the file the :envvar:`YOURAPPLICATION_SETTINGS`
environment variable points to.  This environment variable can be set on
Linux or OS X with the export command in the shell before starting the
server::

    $ export YOURAPPLICATION_SETTINGS=/path/to/settings.cfg
    $ python run-app.py
     * Running on http://127.0.0.1:5000/
     * Restarting with reloader...

On Windows systems use the `set` builtin instead::

    >set YOURAPPLICATION_SETTINGS=\path\to\settings.cfg

The configuration files themselves are actual Python files.  Only values
in uppercase are actually stored in the config object later on.  So make
sure to use uppercase letters for your config keys.

Here is an example of a configuration file::

    # Example configuration
    DEBUG = False
    SECRET_KEY = '?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'

Make sure to load the configuration very early on, so that extensions have
the ability to access the configuration when starting up.  There are other
methods on the config object as well to load from individual files.  For a
complete reference, read the :class:`~flask.Config` object's
documentation.

Configuring from Environment Variables
--------------------------------------

In addition to pointing to configuration files using environment variables, you
may find it useful (or necessary) to control your configuration values directly
from the environment.

Environment variables can be set on Linux or OS X with the export command in
the shell before starting the server::

    $ export SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
    $ export DEBUG=False
    $ python run-app.py
     * Running on http://127.0.0.1:5000/
     * Restarting with reloader...

On Windows systems use the `set` builtin instead::

    >set SECRET_KEY='?\xbf,\xb4\x8d\xa3"<\x9c\xb0@\x0f5\xab,w\xee\x8d$0\x13\x8b83'
    >set DEBUG=False

While this approach is straightforward to use, it is important to remember that
environment variables are strings -- they are not automatically deserialized
into Python types.

Here is an example of a configuration file that uses environment variables::

    # Example configuration
    import os

    ENVIRONMENT_DEBUG = os.environ.get("DEBUG", default=False)
    if ENVIRONMENT_DEBUG.lower() in ("f", "false"):
        ENVIRONMENT_DEBUG = False

    DEBUG = ENVIRONMENT_DEBUG
    SECRET_KEY = os.environ.get("SECRET_KEY", default=None)
    if not SECRET_KEY:
        raise ValueError("No secret key set for Flask application")

Notice that any value besides an empty string will be interpreted as a boolean
``True`` value in Python, which requires care if an environment explicitly sets
values intended to be ``False``.

Make sure to load the configuration very early on, so that extensions have the
ability to access the configuration when starting up.  There are other methods
on the config object as well to load from individual files.  For a complete
reference, read the :class:`~flask.Config` class documentation.

Configuration Best Practices
----------------------------

The downside with the approach mentioned earlier is that it makes testing
a little harder.  There is no single 100% solution for this problem in
general, but there are a couple of things you can keep in mind to improve
that experience:

1.  Create your application in a function and register blueprints on it.
    That way you can create multiple instances of your application with
    different configurations attached which makes unittesting a lot
    easier.  You can use this to pass in configuration as needed.

2.  Do not write code that needs the configuration at import time.  If you
    limit yourself to request-only accesses to the configuration you can
    reconfigure the object later on as needed.

.. _config-dev-prod:

Development / Production
------------------------

Most applications need more than one configuration.  There should be at
least separate configurations for the production server and the one used
during development.  The easiest way to handle this is to use a default
configuration that is always loaded and part of the version control, and a
separate configuration that overrides the values as necessary as mentioned
in the example above::

    app = Flask(__name__)
    app.config.from_object('yourapplication.default_settings')
    app.config.from_envvar('YOURAPPLICATION_SETTINGS')

Then you just have to add a separate :file:`config.py` file and export
``YOURAPPLICATION_SETTINGS=/path/to/config.py`` and you are done.  However
there are alternative ways as well.  For example you could use imports or
subclassing.

What is very popular in the Django world is to make the import explicit in
the config file by adding ``from yourapplication.default_settings
import *`` to the top of the file and then overriding the changes by hand.
You could also inspect an environment variable like
``YOURAPPLICATION_MODE`` and set that to `production`, `development` etc
and import different hardcoded files based on that.

An interesting pattern is also to use classes and inheritance for
configuration::

    class Config(object):
        DEBUG = False
        TESTING = False
        DATABASE_URI = 'sqlite://:memory:'

    class ProductionConfig(Config):
        DATABASE_URI = 'mysql://user@localhost/foo'

    class DevelopmentConfig(Config):
        DEBUG = True

    class TestingConfig(Config):
        TESTING = True

To enable such a config you just have to call into
:meth:`~flask.Config.from_object`::

    app.config.from_object('configmodule.ProductionConfig')

There are many different ways and it's up to you how you want to manage
your configuration files.  However here a list of good recommendations:

-   Keep a default configuration in version control.  Either populate the
    config with this default configuration or import it in your own
    configuration files before overriding values.
-   Use an environment variable to switch between the configurations.
    This can be done from outside the Python interpreter and makes
    development and deployment much easier because you can quickly and
    easily switch between different configs without having to touch the
    code at all.  If you are working often on different projects you can
    even create your own script for sourcing that activates a virtualenv
    and exports the development configuration for you.
-   Use a tool like `fabric`_ in production to push code and
    configurations separately to the production server(s).  For some
    details about how to do that, head over to the
    :ref:`fabric-deployment` pattern.

.. _fabric: http://www.fabfile.org/

.. _instance-folders:

Instance Folders
----------------

.. versionadded:: 0.8

Flask 0.8 introduces instance folders.  Flask for a long time made it
possible to refer to paths relative to the application's folder directly
(via :attr:`Flask.root_path`).  This was also how many developers loaded
configurations stored next to the application.  Unfortunately however this
only works well if applications are not packages in which case the root
path refers to the contents of the package.

With Flask 0.8 a new attribute was introduced:
:attr:`Flask.instance_path`.  It refers to a new concept called the
"instance folder".  The instance folder is designed to not be under
version control and be deployment specific.  It's the perfect place to
drop things that either change at runtime or configuration files.

You can either explicitly provide the path of the instance folder when
creating the Flask application or you can let Flask autodetect the
instance folder.  For explicit configuration use the `instance_path`
parameter::

    app = Flask(__name__, instance_path='/path/to/instance/folder')

Please keep in mind that this path *must* be absolute when provided.

If the `instance_path` parameter is not provided the following default
locations are used:

-   Uninstalled module::

        /myapp.py
        /instance

-   Uninstalled package::

        /myapp
            /__init__.py
        /instance

-   Installed module or package::

        $PREFIX/lib/python2.X/site-packages/myapp
        $PREFIX/var/myapp-instance

    ``$PREFIX`` is the prefix of your Python installation.  This can be
    ``/usr`` or the path to your virtualenv.  You can print the value of
    ``sys.prefix`` to see what the prefix is set to.

Since the config object provided loading of configuration files from
relative filenames we made it possible to change the loading via filenames
to be relative to the instance path if wanted.  The behavior of relative
paths in config files can be flipped between "relative to the application
root" (the default) to "relative to instance folder" via the
`instance_relative_config` switch to the application constructor::

    app = Flask(__name__, instance_relative_config=True)

Here is a full example of how to configure Flask to preload the config
from a module and then override the config from a file in the config
folder if it exists::

    app = Flask(__name__, instance_relative_config=True)
    app.config.from_object('yourapplication.default_settings')
    app.config.from_pyfile('application.cfg', silent=True)

The path to the instance folder can be found via the
:attr:`Flask.instance_path`.  Flask also provides a shortcut to open a
file from the instance folder with :meth:`Flask.open_instance_resource`.

Example usage for both::

    filename = os.path.join(app.instance_path, 'application.cfg')
    with open(filename) as f:
        config = f.read()

    # or via open_instance_resource:
    with app.open_instance_resource('application.cfg') as f:
        config = f.read()


text:
namespace Caliburn.PresentationFramework.Actions
{
    using System;
    using System.Collections.Generic;
    using Filters;
    using RoutedMessaging;

    /// <summary>
    /// Represents a single action.
    /// </summary>
    public interface IAction : IActionHandler
    {
        /// <summary>
        /// Gets the name.
        /// </summary>
        /// <value>The name.</value>
        string Name { get; }

        /// <summary>
        /// Gets the requirements.
        /// </summary>
        /// <value>The requirements.</value>
        IList<RequiredParameter> Requirements { get; }

        /// <summary>
        /// Occurs when action has completed.
        /// </summary>
        event EventHandler Completed;

        /// <summary>
        /// Gets the filters.
        /// </summary>
        /// <value>The filters.</value>
        IFilterManager Filters { get; }

        /// <summary>
        /// Determines whether this action matches the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <returns></returns>
        bool Matches(ActionMessage message);
    }
}


text:
package net.opengis.citygml.impl;

import java.util.List;

import net.opengis.citygml.CitygmlPackage;
import net.opengis.citygml.ImplicitGeometryType;
import net.opengis.gml.GeometryPropertyType;
import net.opengis.gml.PointPropertyType;
import net.opengis.gml.impl.AbstractGMLTypeImpl;

import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;

/**
 *
 * An implementation of the model object 'Implicit Geometry Type'.
 *
 *

 * The following features are implemented:
 *

 *
{@link net.opengis.citygml.impl.ImplicitGeometryTypeImpl#getMimeType Mime Type}

 *
{@link net.opengis.citygml.impl.ImplicitGeometryTypeImpl#getTransformationMatrix Transformation Matrix}

 *
{@link net.opengis.citygml.impl.ImplicitGeometryTypeImpl#getLibraryObject Library Object}

 *
{@link net.opengis.citygml.impl.ImplicitGeometryTypeImpl#getRelativeGMLGeometry Relative GML Geometry}

 *
{@link net.opengis.citygml.impl.ImplicitGeometryTypeImpl#getReferencePoint Reference Point}

 *

 *

 *
 * @generated
 */
public class ImplicitGeometryTypeImpl extends AbstractGMLTypeImpl implements ImplicitGeometryType {
	/**
	 * The default value of the '{@link #getMimeType() Mime Type}' attribute.
	 *
	 *
	 * @see #getMimeType()
	 * @generated
	 * @ordered
	 */
	protected static final String MIME_TYPE_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getMimeType() Mime Type}' attribute.
	 *
	 *
	 * @see #getMimeType()
	 * @generated
	 * @ordered
	 */
	protected String mimeType = MIME_TYPE_EDEFAULT;

	/**
	 * The default value of the '{@link #getTransformationMatrix() Transformation Matrix}' attribute.
	 *
	 *
	 * @see #getTransformationMatrix()
	 * @generated
	 * @ordered
	 */
	protected static final List<Double> TRANSFORMATION_MATRIX_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getTransformationMatrix() Transformation Matrix}' attribute.
	 *
	 *
	 * @see #getTransformationMatrix()
	 * @generated
	 * @ordered
	 */
	protected List<Double> transformationMatrix = TRANSFORMATION_MATRIX_EDEFAULT;

	/**
	 * The default value of the '{@link #getLibraryObject() Library Object}' attribute.
	 *
	 *
	 * @see #getLibraryObject()
	 * @generated
	 * @ordered
	 */
	protected static final String LIBRARY_OBJECT_EDEFAULT = null;

	/**
	 * The cached value of the '{@link #getLibraryObject() Library Object}' attribute.
	 *
	 *
	 * @see #getLibraryObject()
	 * @generated
	 * @ordered
	 */
	protected String libraryObject = LIBRARY_OBJECT_EDEFAULT;

	/**
	 * The cached value of the '{@link #getRelativeGMLGeometry() Relative GML Geometry}' containment reference.
	 *
	 *
	 * @see #getRelativeGMLGeometry()
	 * @generated
	 * @ordered
	 */
	protected GeometryPropertyType relativeGMLGeometry;

	/**
	 * The cached value of the '{@link #getReferencePoint() Reference Point}' containment reference.
	 *
	 *
	 * @see #getReferencePoint()
	 * @generated
	 * @ordered
	 */
	protected PointPropertyType referencePoint;

	/**
	 *
	 *
	 * @generated
	 */
	protected ImplicitGeometryTypeImpl() {
		super();
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	protected EClass eStaticClass() {
		return CitygmlPackage.Literals.IMPLICIT_GEOMETRY_TYPE;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getMimeType() {
		return mimeType;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setMimeType(String newMimeType) {
		String oldMimeType = mimeType;
		mimeType = newMimeType;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__MIME_TYPE, oldMimeType, mimeType));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public List<Double> getTransformationMatrix() {
		return transformationMatrix;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setTransformationMatrix(List<Double> newTransformationMatrix) {
		List<Double> oldTransformationMatrix = transformationMatrix;
		transformationMatrix = newTransformationMatrix;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__TRANSFORMATION_MATRIX, oldTransformationMatrix, transformationMatrix));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public String getLibraryObject() {
		return libraryObject;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setLibraryObject(String newLibraryObject) {
		String oldLibraryObject = libraryObject;
		libraryObject = newLibraryObject;
		if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__LIBRARY_OBJECT, oldLibraryObject, libraryObject));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public GeometryPropertyType getRelativeGMLGeometry() {
		return relativeGMLGeometry;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetRelativeGMLGeometry(GeometryPropertyType newRelativeGMLGeometry, NotificationChain msgs) {
		GeometryPropertyType oldRelativeGMLGeometry = relativeGMLGeometry;
		relativeGMLGeometry = newRelativeGMLGeometry;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY, oldRelativeGMLGeometry, newRelativeGMLGeometry);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setRelativeGMLGeometry(GeometryPropertyType newRelativeGMLGeometry) {
		if (newRelativeGMLGeometry != relativeGMLGeometry) {
			NotificationChain msgs = null;
			if (relativeGMLGeometry != null)
				msgs = ((InternalEObject)relativeGMLGeometry).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY, null, msgs);
			if (newRelativeGMLGeometry != null)
				msgs = ((InternalEObject)newRelativeGMLGeometry).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY, null, msgs);
			msgs = basicSetRelativeGMLGeometry(newRelativeGMLGeometry, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY, newRelativeGMLGeometry, newRelativeGMLGeometry));
	}

	/**
	 *
	 *
	 * @generated
	 */
	public PointPropertyType getReferencePoint() {
		return referencePoint;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public NotificationChain basicSetReferencePoint(PointPropertyType newReferencePoint, NotificationChain msgs) {
		PointPropertyType oldReferencePoint = referencePoint;
		referencePoint = newReferencePoint;
		if (eNotificationRequired()) {
			ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT, oldReferencePoint, newReferencePoint);
			if (msgs == null) msgs = notification; else msgs.add(notification);
		}
		return msgs;
	}

	/**
	 *
	 *
	 * @generated
	 */
	public void setReferencePoint(PointPropertyType newReferencePoint) {
		if (newReferencePoint != referencePoint) {
			NotificationChain msgs = null;
			if (referencePoint != null)
				msgs = ((InternalEObject)referencePoint).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT, null, msgs);
			if (newReferencePoint != null)
				msgs = ((InternalEObject)newReferencePoint).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT, null, msgs);
			msgs = basicSetReferencePoint(newReferencePoint, msgs);
			if (msgs != null) msgs.dispatch();
		}
		else if (eNotificationRequired())
			eNotify(new ENotificationImpl(this, Notification.SET, CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT, newReferencePoint, newReferencePoint));
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
		switch (featureID) {
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY:
				return basicSetRelativeGMLGeometry(null, msgs);
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT:
				return basicSetReferencePoint(null, msgs);
		}
		return super.eInverseRemove(otherEnd, featureID, msgs);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public Object eGet(int featureID, boolean resolve, boolean coreType) {
		switch (featureID) {
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__MIME_TYPE:
				return getMimeType();
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__TRANSFORMATION_MATRIX:
				return getTransformationMatrix();
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__LIBRARY_OBJECT:
				return getLibraryObject();
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY:
				return getRelativeGMLGeometry();
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT:
				return getReferencePoint();
		}
		return super.eGet(featureID, resolve, coreType);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@SuppressWarnings("unchecked")
	@Override
	public void eSet(int featureID, Object newValue) {
		switch (featureID) {
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__MIME_TYPE:
				setMimeType((String)newValue);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__TRANSFORMATION_MATRIX:
				setTransformationMatrix((List<Double>)newValue);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__LIBRARY_OBJECT:
				setLibraryObject((String)newValue);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY:
				setRelativeGMLGeometry((GeometryPropertyType)newValue);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT:
				setReferencePoint((PointPropertyType)newValue);
				return;
		}
		super.eSet(featureID, newValue);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public void eUnset(int featureID) {
		switch (featureID) {
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__MIME_TYPE:
				setMimeType(MIME_TYPE_EDEFAULT);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__TRANSFORMATION_MATRIX:
				setTransformationMatrix(TRANSFORMATION_MATRIX_EDEFAULT);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__LIBRARY_OBJECT:
				setLibraryObject(LIBRARY_OBJECT_EDEFAULT);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY:
				setRelativeGMLGeometry((GeometryPropertyType)null);
				return;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT:
				setReferencePoint((PointPropertyType)null);
				return;
		}
		super.eUnset(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public boolean eIsSet(int featureID) {
		switch (featureID) {
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__MIME_TYPE:
				return MIME_TYPE_EDEFAULT == null ? mimeType != null : !MIME_TYPE_EDEFAULT.equals(mimeType);
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__TRANSFORMATION_MATRIX:
				return TRANSFORMATION_MATRIX_EDEFAULT == null ? transformationMatrix != null : !TRANSFORMATION_MATRIX_EDEFAULT.equals(transformationMatrix);
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__LIBRARY_OBJECT:
				return LIBRARY_OBJECT_EDEFAULT == null ? libraryObject != null : !LIBRARY_OBJECT_EDEFAULT.equals(libraryObject);
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__RELATIVE_GML_GEOMETRY:
				return relativeGMLGeometry != null;
			case CitygmlPackage.IMPLICIT_GEOMETRY_TYPE__REFERENCE_POINT:
				return referencePoint != null;
		}
		return super.eIsSet(featureID);
	}

	/**
	 *
	 *
	 * @generated
	 */
	@Override
	public String toString() {
		if (eIsProxy()) return super.toString();

		StringBuffer result = new StringBuffer(super.toString());
		result.append(" (mimeType: ");
		result.append(mimeType);
		result.append(", transformationMatrix: ");
		result.append(transformationMatrix);
		result.append(", libraryObject: ");
		result.append(libraryObject);
		result.append(')');
		return result.toString();
	}

} //ImplicitGeometryTypeImpl


text:
package kml2xml;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StringReader;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import kml.feature.Features;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 *
 * @author marty
 */
public class Kml2Xml {

    static String helpText = "\n\tKml2Xml"
            + "\n\tConverts a KML file to a Command Web XML file for import as an Effort into"
            + "\n\tthe Manuever Widget."
            + "\n"
            + "\n\tOptions"
            + "\n\t\t? or help: Print this message"
            + "\n\t\tIN=path/to/input/filename (required)"
            + "\n\t\tOUT=path/to/output/filename (optional)"
            + "\n\t\tTITLE=TITLE OF EFFORT/OVERLAY (optional, use quotes if the title has spaces)"
            + "\n\t\tFORMAT=the output schema, default is MNVR XML, use OVL to obtain GCCS-J OVL [MNVR,OVL,CSV](optional)";

    public static void main(String[] args) throws IOException, SAXException {
        String inFile = "";
        String outFile = "";
        SimpleDateFormat ft = new SimpleDateFormat("E MMM dd hh:mm:ss zzz yyyy");
        Date date = new Date();
        String owner = "USAREUR";
        String effortName = "KML to XML " + ft.format(date);
        boolean titleSet = false;
        boolean skip = false;
        String format = "MNVR";
        try {
            if (args.length == 0) {
                System.out.println(helpText);
                System.exit(0);
            }
            for (String s : args) {
                if (s.toUpperCase().equals("HELP") || s.equals("?")) {
                    System.out.println(helpText);
                    System.exit(0);
                }
                String[] arg = s.split("=");
                if (arg[0].toUpperCase().startsWith("IN")) {
                    inFile = arg[1];
                    System.out.println("INPUT FILE SET TO: " + inFile);
                }
                if (arg[0].toUpperCase().startsWith("OUT")) {
                    outFile = arg[1];
                    System.out.println("OUTPUT FILE SET TO: " + outFile);
                }
                if (arg[0].toUpperCase().startsWith("T")) {
                    effortName = arg[1];
                    System.out.println("EFFORT TITLE SET TO: " + effortName);
                    titleSet = true;
                }
                if (arg[0].toUpperCase().startsWith("F")) {
                    String value = arg[1];
                    if (value.toUpperCase().startsWith("M")) {
                        format = "MNVR";
                    }
                    if (value.toUpperCase().startsWith("G")) {
                        format = "OVL";
                    }
                    if (value.toUpperCase().startsWith("O")) {
                        format = "OVL";
                    }
                    if (value.toUpperCase().startsWith("C")) {
                        format = "CSV";
                    }
                    System.out.println("OUT FORMAT SET TO: " + format);
                }
                if (arg[0].toUpperCase().startsWith("S")) {
                    skip = true;
                    System.out.println("Skipping output file generation ");
                }
            }
        } catch (Exception e) {
            System.out.println("ERROR reading arguments: " + e.getMessage());
        }// try catch reading arguments
        if (!titleSet) {
            effortName = inFile.toUpperCase().replaceAll(".KML", "").replaceAll(".KMZ", "");
            effortName = effortName.replaceAll("_", " ") + " " + ft.format(date);
        }
        if (outFile.length() < 1) {
            String ext = ".xml";
            if (format.toUpperCase().startsWith("O")) {
                ext = ".ovl";
            }
            if (format.toUpperCase().startsWith("C")) {
                ext = ".csv";
            }
            outFile = inFile + ext;
            outFile = outFile.replace(" ", "_");
        }
        //======================================================================
        // Build string representing input file
        StringBuilder sbXml = new StringBuilder();
        String line = null;
        File fin = new File(inFile);
        File fout = new File(outFile);
        if (!fout.exists()) {
            fout.createNewFile();
        }
        BufferedWriter bw = new BufferedWriter(new FileWriter(fout.getAbsoluteFile()));
        try {
            //    ==============================================================
            long start_ms = System.currentTimeMillis();

            if (ZipUtils.isZip(fin)) {
                System.out.println("Zip file detected.");
                //get the zip file content
                ZipInputStream zis = new ZipInputStream(new FileInputStream(fin));
                //get the zipped file list entry
                ZipEntry ze;
                while ((ze = zis.getNextEntry()) != null) {
                    String fileName = ze.getName();
                    System.out.println("Zipped file: " + fileName);
                    String extension = fileName.substring(fileName.lastIndexOf(".") + 1);
                    if (extension.equalsIgnoreCase("kml")) { // ================
                        System.out.println("Extension: " + extension);
                        int bufferSize = 1;
                        int knt;
                        StringBuilder kml = new StringBuilder();
                        byte kmlBytes[] = new byte[bufferSize];
                        while ((knt = zis.read(kmlBytes, 0, bufferSize)) != -1) {
                            //Read in all the kml files bytes in data
                            kml.append(new String(kmlBytes));
                            kmlBytes = new byte[bufferSize];
                        }

                        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                        dbf.setNamespaceAware(true); //necessary if you want to getLocalName
                        DocumentBuilder db;
                        db = dbf.newDocumentBuilder();
                        Document doc = db.parse(new InputSource(new StringReader(kml.toString())));
                        Features features = new Features(doc);
                        features.setTitle(effortName);

                        if (format.toUpperCase().startsWith("O")) {
                            bw.write(features.getOvlXml());
                        } else if (format.toUpperCase().startsWith("C")) {
                            bw.write(features.getCsvHeader());
                            bw.write(features.toCsv());
                        } else {
                            bw.write(features.getMnvrXml());
                        }
                        //bw.flush();
                    } // =======================================================
                }
                zis.closeEntry();
                zis.close();
            } else {
                DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
                dbf.setNamespaceAware(true); //necessary if you want to getLocalName
                DocumentBuilder db = dbf.newDocumentBuilder();
                Document doc = db.parse(fin);
                Features features = new Features(doc);
                features.setTitle(effortName);

                if (format.toUpperCase().startsWith("O")) {
                    bw.write(features.getOvlXml());
                } else if (format.toUpperCase().startsWith("C")) {
                    bw.write(features.getCsvHeader());
                    bw.write(features.toCsv());
                } else {
                    bw.write(features.getMnvrXml());
                }
                //bw.flush();
            }
            //
            long end_ms = System.currentTimeMillis();
            double processing_s = (end_ms - start_ms) / 1000.0;
            System.out.println("\nProcessing time: " + processing_s + " (s)");
        } catch (FileNotFoundException ex) {
            Logger.getLogger(Kml2Xml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Kml2Xml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParserConfigurationException ex) {
            Logger.getLogger(Kml2Xml.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SAXException ex) {
            String error = ex.getMessage();
            if (error.indexOf("is not bound") > -1) {
                String prefix = error.substring(error.indexOf("prefix") + 8, error.indexOf("for attribute") - 2);
                System.out.println("Namespace prefix not defined:" + prefix + " in " + inFile);
            } else {
                Logger.getLogger(Kml2Xml.class.getName()).log(Level.SEVERE, null, ex);
            }

        }// try catch file input
        finally {
            bw.flush();
            bw.close();
            System.out.println("KML parsed to " + outFile);
        }
    }//main

}


text:
package com.rong.xposed.headsoff.adapter;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v7.widget.AppCompatImageButton;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.rong.xposed.headsoff.R;
import com.rong.xposed.headsoff.utils.SettingValues;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WhiteListAdapter extends RecyclerView.Adapter<WhiteListAdapter.ViewHolder> {

	private List<String> regexRuleList = null;
	private Context mContext = null;
	private final String packageName;
	private SharedPreferences prefs = null;
	private OnRegexRemoveListener listener = null;

	@SuppressLint("WorldReadableFiles")
	@SuppressWarnings("deprecation")
	public WhiteListAdapter(Context context, String pkg, List<String> list) {
		mContext = context;
		regexRuleList = list;
		packageName = pkg;
		prefs = context.getSharedPreferences(SettingValues.PREF_FILE, Context.MODE_WORLD_READABLE);
	}

	@Override
	public WhiteListAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
		View v = LayoutInflater.from(mContext).inflate(R.layout.list_item_regex_rules, parent, false);
		return new ViewHolder(v);
	}

	@Override
	public void onBindViewHolder(WhiteListAdapter.ViewHolder holder, int position) {
		String regex = getItem(position);

		if (!TextUtils.isEmpty(regex)) {
			holder.txtRule.setText(regex);
		}
	}

	@Override
	public int getItemCount() {
		return (regexRuleList == null) ? 0 : regexRuleList.size();
	}

	public String getItem(int position) {
		if (regexRuleList == null || regexRuleList.size() == 0)
			return null;
		else
			return regexRuleList.get(position);
	}

	public void setItemList(List<String> list) {
		regexRuleList = list;
	}

	protected void onDelete(int position) {
		SharedPreferences.Editor editor = prefs.edit();
		String key;
		int newCount = getItemCount() - 1;

		key = packageName + SettingValues.KEY_SUFFIX_WHITELIST_COUNT;
		editor.putInt(key, newCount);
		editor.apply();

		Set<String> newList = new HashSet<>();
		for (int i = 0; i <= newCount; i++) {
			if (i == position)
				continue;
			newList.add(regexRuleList.get(i));
		}

		key = packageName + SettingValues.KEY_SUFFIX_WHITELIST;
		editor.putStringSet(key, newList);
		editor.apply();

		regexRuleList.remove(position);
		notifyItemRemoved(position);
		if (listener != null)
			listener.onRegexRemove(position);
	}

	public void setOnRegexRemoveListener(OnRegexRemoveListener l) {
		listener = l;
	}

	public interface OnRegexRemoveListener {
		void onRegexRemove(int position);
	}

	public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

		protected TextView txtRule;
		protected AppCompatImageButton btnDelete;

		public ViewHolder(View itemView) {
			super(itemView);

			txtRule = (TextView) itemView.findViewById(R.id.txt_rule);
			btnDelete = (AppCompatImageButton) itemView.findViewById(R.id.btn_delete);
			btnDelete.setOnClickListener(this);
		}

		@Override
		public void onClick(View v) {
			onDelete(getAdapterPosition());
		}
	}
}


text:
package tracer

import (
	"sync"

	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
	"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/internal"
)

var _ ddtrace.SpanContext = (*spanContext)(nil)

// SpanContext represents a span state that can propagate to descendant spans
// and across process boundaries. It contains all the information needed to
// spawn a direct descendant of the span that it belongs to. It can be used
// to create distributed tracing by propagating it using the provided interfaces.
type spanContext struct {
	// the below group should propagate only locally

	trace *trace // reference to the trace that this span belongs too
	span  *span  // reference to the span that hosts this context
	drop  bool   // when true, the span will not be sent to the agent

	// the below group should propagate cross-process

	traceID uint64
	spanID  uint64

	mu          sync.RWMutex // guards below fields
	baggage     map[string]string
	priority    int
	hasPriority bool
}

// newSpanContext creates a new SpanContext to serve as context for the given
// span. If the provided parent is not nil, the context will inherit the trace,
// baggage and other values from it. This method also pushes the span into the
// new context's trace and as a result, it should not be called multiple times
// for the same span.
func newSpanContext(span *span, parent *spanContext) *spanContext {
	context := &spanContext{
		traceID: span.TraceID,
		spanID:  span.SpanID,
		span:    span,
	}
	if v, ok := span.Metrics[samplingPriorityKey]; ok {
		context.hasPriority = true
		context.priority = int(v)
	}
	if parent != nil {
		context.trace = parent.trace
		context.drop = parent.drop
		context.hasPriority = parent.hasSamplingPriority()
		context.priority = parent.samplingPriority()
		parent.ForeachBaggageItem(func(k, v string) bool {
			context.setBaggageItem(k, v)
			return true
		})
	}
	if context.trace == nil {
		context.trace = newTrace()
	}
	// put span in context's trace
	context.trace.push(span)
	return context
}

// SpanID implements ddtrace.SpanContext.
func (c *spanContext) SpanID() uint64 { return c.spanID }

// TraceID implements ddtrace.SpanContext.
func (c *spanContext) TraceID() uint64 { return c.traceID }

// ForeachBaggageItem implements ddtrace.SpanContext.
func (c *spanContext) ForeachBaggageItem(handler func(k, v string) bool) {
	c.mu.RLock()
	defer c.mu.RUnlock()
	for k, v := range c.baggage {
		if !handler(k, v) {
			break
		}
	}
}

func (c *spanContext) setSamplingPriority(p int) {
	c.mu.Lock()
	defer c.mu.Unlock()
	c.priority = p
	c.hasPriority = true
}

func (c *spanContext) samplingPriority() int {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.priority
}

func (c *spanContext) hasSamplingPriority() bool {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.hasPriority
}

func (c *spanContext) setBaggageItem(key, val string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.baggage == nil {
		c.baggage = make(map[string]string, 1)
	}
	c.baggage[key] = val
}

func (c *spanContext) baggageItem(key string) string {
	c.mu.RLock()
	defer c.mu.RUnlock()
	return c.baggage[key]
}

// finish marks this span as finished in the trace.
func (c *spanContext) finish() { c.trace.ackFinish() }

// trace holds information about a specific trace. This structure is shared
// between all spans in a trace.
type trace struct {
	mu       sync.RWMutex // guards below fields
	spans    []*span      // all the spans that are part of this trace
	finished int          // the number of finished spans
	full     bool         // signifies that the span buffer is full
}

var (
	// traceStartSize is the initial size of our trace buffer,
	// by default we allocate for a handful of spans within the trace,
	// reasonable as span is actually way bigger, and avoids re-allocating
	// over and over. Could be fine-tuned at runtime.
	traceStartSize = 10
	// traceMaxSize is the maximum number of spans we keep in memory.
	// This is to avoid memory leaks, if above that value, spans are randomly
	// dropped and ignore, resulting in corrupted tracing data, but ensuring
	// original program continues to work as expected.
	traceMaxSize = int(1e5)
)

// newTrace creates a new trace using the given callback which will be called
// upon completion of the trace.
func newTrace() *trace {
	return &trace{spans: make([]*span, 0, traceStartSize)}
}

// push pushes a new span into the trace. If the buffer is full, it returns
// a errBufferFull error.
func (t *trace) push(sp *span) {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.full {
		return
	}
	if len(t.spans) >= traceMaxSize {
		// capacity is reached, we will not be able to complete this trace.
		t.full = true
		t.spans = nil // GC
		if tr, ok := internal.GetGlobalTracer().(*tracer); ok {
			// we have a tracer we can submit errors too.
			tr.pushError(&spanBufferFullError{})
		}
		return
	}
	t.spans = append(t.spans, sp)
}

// ackFinish aknowledges that another span in the trace has finished, and checks
// if the trace is complete, in which case it calls the onFinish function.
func (t *trace) ackFinish() {
	t.mu.Lock()
	defer t.mu.Unlock()
	if t.full {
		// capacity has been reached, the buffer is no longer tracking
		// all the spans in the trace, so the below conditions will not
		// be accurate and would trigger a pre-mature flush, exposing us
		// to a race condition where spans can be modified while flushing.
		return
	}
	t.finished++
	if len(t.spans) != t.finished {
		return
	}
	if tr, ok := internal.GetGlobalTracer().(*tracer); ok {
		// we have a tracer that can receive completed traces.
		tr.pushTrace(t.spans)
	}
	t.spans = nil
	t.finished = 0 // important, because a buffer can be used for several flushes
}


text:
var exec = require('cordova/exec');

module.exports = {

    /**
     * Pings the specified url
     *
	 * @param {String} 		url       	The url to ping
     * @param {Integer} 	timeout		The number of milliseconds for the timeout
	 * @param {Function}	success		The success callback function
	 * @param {Function}	error		The error callback function
     *
     */
    ping: function(url, timeout, success, error)
	{
        /* Aligning with w3c spec */

		exec(success, error, "Ping", "ping", [url, timeout]);
    }
};


text:
Client Meetin #1
================
2016/05/10

- Required Features
    - Visualize if student is on track to graduate or missing/failed critical courses
    - Allows to change course/track in course selection season
        - Alerts for missing courses
        - Summarization at the end of the semester
    - Programming office can input/change data

- Possible/Reach Features
    - Special notifications sent to students in danger of failing
    - I/O of student databases from excel spreadsheets
    - Student client side for course selection, only see own scheule

- HOMEWORK
    - Settle on timeline

- Expected from Programming Office
    - Sample data from programming office


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mikepenz.materialdrawer">

    <uses-sdk
        android:minSdkVersion="15"
        android:targetSdkVersion="22" />
</manifest>


text:
package com.jdon.sample.test.bankaccount.processManager;

import com.jdon.annotation.Component;
import com.jdon.sample.test.bankaccount.aggregates.BankAccount;
import com.jdon.sample.test.bankaccount.command.TransferCommand;
import com.jdon.sample.test.bankaccount.infras.AccountRepositoryIF;
import com.jdon.sample.test.bankaccount.infras.BrokerProducerIF;

import java.util.*;

@Component
public class ProcessDef {
    //processDef order
    private List<TransferCommand> processDef;
    //cureent step
    private final Map<String, String> cStep =  new HashMap<>();
    private final AccountRepositoryIF accountRepository;
    private final BrokerProducerIF brokerProducer;

    public ProcessDef(AccountRepositoryIF accountRepository, BrokerProducerIF brokerProducer) {
        this.accountRepository = accountRepository;
        this.brokerProducer = brokerProducer;
    }

    public void start(List<TransferCommand> processDef){
        this.processDef = processDef;
        Iterator<TransferCommand> iterator = processDef.iterator();
        if (iterator.hasNext()){
            sendCommand(iterator.next());
        }
    }

    public void sendCommand(TransferCommand transferCommand){
        BankAccount bankAccount = accountRepository.getBankAccount(transferCommand.getAggregateId());
        brokerProducer.transfer(transferCommand.getAggregateId(), bankAccount, transferCommand);
        cStep.put(transferCommand.getTransactionId(),transferCommand.getCommandId());
    }

    public TransferCommand getNextTransferCommand(){
        Iterator<TransferCommand> iterator = processDef.iterator();
        while (iterator.hasNext()){
            TransferCommand pTransferCommand = iterator.next();
            String cTransferCommandId = cStep.get(pTransferCommand.getTransactionId());
            if (cTransferCommandId.equals(pTransferCommand.getCommandId())){
                if (iterator.hasNext())
                    return iterator.next();
                else
                    return null;
            }
        }
        return null;
    }

    public TransferCommand getPreTransferCommand(){
        Iterator<TransferCommand> iterator = processDef.listIterator();
        while (((ListIterator<TransferCommand>) iterator).hasPrevious()){
            TransferCommand pTransferCommand = ((ListIterator<TransferCommand>) iterator).previous();
            String cTransferCommandId = cStep.get(pTransferCommand.getTransactionId());
            if (cTransferCommandId.equals(pTransferCommand.getCommandId())){
                if (((ListIterator<TransferCommand>) iterator).hasPrevious())
                   return ((ListIterator<TransferCommand>) iterator).previous();
                else
                    return null;
            }
        }
        return null;
    }

    public void clear(){
        this.cStep.clear();
        this.processDef.clear();
    }

}


text:
package org.elkoserver.util.trace;

import java.io.File;

/**
 * This class knows how to construct sequenced output Files for given Files.
 *
 * This class constructs version names by appending sequence numbers to the
 * original name.
 */
class TraceVersionNamer {
    /** The file for which a version number is being created. */
    private File myFile;

    /** The 'filename' part of the given file, sans directory. */
    private String myName;

    /** A directory that contains the given file. */
    private String myDir;

    /** The part of the filename that precedes a sequence number. */
    private String myBasename;

    /**
     * Create a TraceVersionNamer from the given file.  The file object must
     * have a directory and name component.  It may be absolute or relative.
     */
    TraceVersionNamer(File file) {
        myFile = file;
        myName = myFile.getName();
        myDir = myFile.getParent();
        myBasename = myName + ".";
        Trace.trace.debugm("Finding next version of " + myFile + "(" +
                           myDir + " " + myName + " " + myBasename + ")");
    }

    /**
     * Create a version file name, given a sequence number.
     */
    private File constructVersion(int sequence) {
        return new File(myDir, myBasename + String.format("%03d", sequence));
    }

    /**
     * The backup file with sequence number 0.  Doesn't matter if it exists.
     */
    File firstVersion() {
        return constructVersion(0);
    }

    /**
     * Return a sequence number, if the given filename contains one.  If it
     * does not contain one, return -1.  Do not call this method unless
     * mightBeVersion has approved the filename.
     */
    private int getSeq(String filename) {
        String possibleSeqString = filename.substring(myBasename.length());

        try {
            return Integer.parseInt(possibleSeqString);
        } catch (NumberFormatException e) {
            Trace.trace.shred(e, filename + " has invalid sequence number");
            return -1;
        }
    }

    /**
     * True iff the filename is of a format that could be a backup version of
     * the original file.  It remains to be determined whether it truly
     * contains a sequence number.
     *
     * In the interest of platform independencee, the check is case-
     * insensitive.  This obeys Windows conventions about what "same files"
     * are, not Unix conventions.
     *
     * @param filename a filename, not including any directory part.
     */
    private boolean mightBeVersion(String filename) {
        int minlen = myBasename.length() + 1;
        return filename.length() >= minlen &&
            filename.toLowerCase().startsWith(myBasename.toLowerCase());
    }

    /**
     * Return the next file in the sequence <foo>, <foo>.0, <foo>.1, etc.
     * Subclasses will have their own name-construction rules.
     */
    File nextAvailableVersion() {
        int highestSeq = -1;
        String[] files = (new File(myDir)).list();

        if (files == null) {
            /* We were asked for a file in a nonexistent directory.  It's safe
               to assume that there are no clashing names. */
            return firstVersion();
        }

        for (String file : files) {
            if (mightBeVersion(file)) {
                int possibleSeq = getSeq(file);
                if (possibleSeq < 0) {
                    Trace.trace.verbosem(file + " has no sequence number");
                } else if (possibleSeq <= highestSeq) {
                    Trace.trace.verbosem(file + " is too low");
                } else {
                    highestSeq = possibleSeq;
                    Trace.trace.verbosem(highestSeq + " is the best so far");
                }
            } else {
                Trace.trace.verbosem(file + " is not in version file format");
            }
        }
        File result = constructVersion(highestSeq + 1);
        Trace.trace.eventi("Backup version for " + myFile + " is " + result);
        return result;
    }
}


text:
@import UIKit;
#import "NAMAppDelegate.h"

int main(int argc, char * argv[])
{
    @autoreleasepool {
        return UIApplicationMain(argc, argv, nil, NSStringFromClass([NAMAppDelegate class]));
    }
}


text:
import doctest
import os
import shutil
import tempfile
import unittest

from genshi.template.base import TemplateSyntaxError
from genshi.template.loader import TemplateLoader
from genshi.template.text import OldTextTemplate, NewTextTemplate

class OldTextTemplateTestCase(unittest.TestCase):
    """Tests for text template processing."""

    def setUp(self):
        self.dirname = tempfile.mkdtemp(suffix='markup_test')

    def tearDown(self):
        shutil.rmtree(self.dirname)

    def test_escaping(self):
        tmpl = OldTextTemplate('\\#escaped')
        self.assertEqual('#escaped', tmpl.generate().render(encoding=None))

    def test_comment(self):
        tmpl = OldTextTemplate('## a comment')
        self.assertEqual('', tmpl.generate().render(encoding=None))

    def test_comment_escaping(self):
        tmpl = OldTextTemplate('\\## escaped comment')
        self.assertEqual('## escaped comment',
                         tmpl.generate().render(encoding=None))

    def test_end_with_args(self):
        tmpl = OldTextTemplate("""
        #if foo
          bar
        #end 'if foo'""")
        self.assertEqual('\n', tmpl.generate(foo=False).render(encoding=None))

    def test_latin1_encoded(self):
        text = '$foo\xf6$bar'.encode('iso-8859-1')
        tmpl = OldTextTemplate(text, encoding='iso-8859-1')
        self.assertEqual('x\xf6y',
                         tmpl.generate(foo='x', bar='y').render(encoding=None))

    def test_unicode_input(self):
        text = '$foo\xf6$bar'
        tmpl = OldTextTemplate(text)
        self.assertEqual('x\xf6y',
                         tmpl.generate(foo='x', bar='y').render(encoding=None))

    def test_empty_lines1(self):
        tmpl = OldTextTemplate("""Your items:

        #for item in items
          * ${item}
        #end""")
        self.assertEqual("""Your items:

          * 0
          * 1
          * 2
""", tmpl.generate(items=list(range(3))).render(encoding=None))

    def test_empty_lines2(self):
        tmpl = OldTextTemplate("""Your items:

        #for item in items
          * ${item}

        #end""")
        self.assertEqual("""Your items:

          * 0

          * 1

          * 2

""", tmpl.generate(items=list(range(3))).render(encoding=None))

    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write("Included\n".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write("""----- Included data below this line -----
            #include tmpl1.txt
            ----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=OldTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
            ----- Included data above this line -----""",
                         tmpl.generate().render(encoding=None))

class NewTextTemplateTestCase(unittest.TestCase):
    """Tests for text template processing."""

    def setUp(self):
        self.dirname = tempfile.mkdtemp(suffix='markup_test')

    def tearDown(self):
        shutil.rmtree(self.dirname)

    def test_escaping(self):
        tmpl = NewTextTemplate('\\{% escaped %}')
        self.assertEqual('{% escaped %}',
                         tmpl.generate().render(encoding=None))

    def test_comment(self):
        tmpl = NewTextTemplate('{# a comment #}')
        self.assertEqual('', tmpl.generate().render(encoding=None))

    def test_comment_escaping(self):
        tmpl = NewTextTemplate('\\{# escaped comment #}')
        self.assertEqual('{# escaped comment #}',
                         tmpl.generate().render(encoding=None))

    def test_end_with_args(self):
        tmpl = NewTextTemplate("""
{% if foo %}
  bar
{% end 'if foo' %}""")
        self.assertEqual('\n', tmpl.generate(foo=False).render(encoding=None))

    def test_latin1_encoded(self):
        text = '$foo\xf6$bar'.encode('iso-8859-1')
        tmpl = NewTextTemplate(text, encoding='iso-8859-1')
        self.assertEqual('x\xf6y',
                         tmpl.generate(foo='x', bar='y').render(encoding=None))

    def test_unicode_input(self):
        text = '$foo\xf6$bar'
        tmpl = NewTextTemplate(text)
        self.assertEqual('x\xf6y',
                         tmpl.generate(foo='x', bar='y').render(encoding=None))

    def test_empty_lines1(self):
        tmpl = NewTextTemplate("""Your items:

{% for item in items %}\
  * ${item}
{% end %}""")
        self.assertEqual("""Your items:

  * 0
  * 1
  * 2
""", tmpl.generate(items=list(range(3))).render(encoding=None))

    def test_empty_lines2(self):
        tmpl = NewTextTemplate("""Your items:

{% for item in items %}\
  * ${item}

{% end %}""")
        self.assertEqual("""Your items:

  * 0

  * 1

  * 2

""", tmpl.generate(items=list(range(3))).render(encoding=None))

    def test_exec_with_trailing_space(self):
        """
        Verify that a code block with trailing space does not cause a syntax
        error (see ticket #127).
        """
        NewTextTemplate("""
          {% python
            bar = 42
          $}
        """)

    def test_exec_import(self):
        tmpl = NewTextTemplate("""{% python from datetime import timedelta %}
        ${timedelta(days=2)}
        """)
        self.assertEqual("""
        2 days, 0:00:00
        """, tmpl.generate().render(encoding=None))

    def test_exec_def(self):
        tmpl = NewTextTemplate("""{% python
        def foo():
            return 42
        %}
        ${foo()}
        """)
        self.assertEqual("""
        42
        """, tmpl.generate().render(encoding=None))

    def test_include(self):
        file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
        try:
            file1.write("Included".encode("utf-8"))
        finally:
            file1.close()

        file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
        try:
            file2.write("""----- Included data below this line -----
{% include tmpl1.txt %}
----- Included data above this line -----""".encode("utf-8"))
        finally:
            file2.close()

        loader = TemplateLoader([self.dirname])
        tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
        self.assertEqual("""----- Included data below this line -----
Included
----- Included data above this line -----""",
                         tmpl.generate().render(encoding=None))

    def test_include_expr(self):
         file1 = open(os.path.join(self.dirname, 'tmpl1.txt'), 'wb')
         try:
             file1.write("Included".encode("utf-8"))
         finally:
             file1.close()

         file2 = open(os.path.join(self.dirname, 'tmpl2.txt'), 'wb')
         try:
             file2.write("""----- Included data below this line -----
    {% include ${'%s.txt' % ('tmpl1',)} %}
    ----- Included data above this line -----""".encode("utf-8"))
         finally:
             file2.close()

         loader = TemplateLoader([self.dirname])
         tmpl = loader.load('tmpl2.txt', cls=NewTextTemplate)
         self.assertEqual("""----- Included data below this line -----
    Included
    ----- Included data above this line -----""",
                          tmpl.generate().render(encoding=None))

def suite():
    suite = unittest.TestSuite()
    suite.addTest(doctest.DocTestSuite(NewTextTemplate.__module__))
    suite.addTest(unittest.makeSuite(OldTextTemplateTestCase, 'test'))
    suite.addTest(unittest.makeSuite(NewTextTemplateTestCase, 'test'))
    return suite

if __name__ == '__main__':
    unittest.main(defaultTest='suite')


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Mycologia 63(4): 885 (1971)

#### Original name
Boletus piedmontensis Grand & A.H. Sm.

### Remarks
null


text:
package io.jafka.console;

import java.io.PrintStream;
import java.nio.ByteBuffer;
import java.util.Properties;

import io.jafka.message.Message;

/**
 * @author adyliu (imxylz@gmail.com)
 * @since 1.0
 */
public class NewlineMessageFormatter implements MessageFormatter {

    public void writeTo(Message message, PrintStream output) {
        ByteBuffer buffer = message.payload();
        output.write(buffer.array(), buffer.arrayOffset(), buffer.limit());
        output.write('\n');
    }

    public void init(Properties props) {
    }

    public void close() {
    }

}


text:
namespace {

web::WebUIIOSDataSource* CreateSyncInternalsHTMLSource() {
  web::WebUIIOSDataSource* source =
      web::WebUIIOSDataSource::Create(kChromeUISyncInternalsHost);

  source->SetJsonPath("strings.js");
  source->AddResourcePath(syncer::sync_ui_util::kSyncIndexJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_JS);
  source->AddResourcePath(syncer::sync_ui_util::kChromeSyncJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_CHROME_SYNC_JS);
  source->AddResourcePath(syncer::sync_ui_util::kTypesJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_TYPES_JS);
  source->AddResourcePath(syncer::sync_ui_util::kSyncLogJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_LOG_JS);
  source->AddResourcePath(syncer::sync_ui_util::kSyncNodeBrowserJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_NODE_BROWSER_JS);
  source->AddResourcePath(syncer::sync_ui_util::kSyncSearchJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_SYNC_SEARCH_JS);
  source->AddResourcePath(syncer::sync_ui_util::kAboutJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_ABOUT_JS);
  source->AddResourcePath(syncer::sync_ui_util::kDataJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_DATA_JS);
  source->AddResourcePath(syncer::sync_ui_util::kEventsJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_EVENTS_JS);
  source->AddResourcePath(syncer::sync_ui_util::kSearchJS,
                          IDR_SYNC_DRIVER_SYNC_INTERNALS_SEARCH_JS);
  source->SetDefaultResource(IDR_SYNC_DRIVER_SYNC_INTERNALS_INDEX_HTML);
  return source;
}

}  // namespace

SyncInternalsUI::SyncInternalsUI(web::WebUIIOS* web_ui)
    : web::WebUIIOSController(web_ui) {
  web::WebUIIOSDataSource::Add(ios::ChromeBrowserState::FromWebUIIOS(web_ui),
                               CreateSyncInternalsHTMLSource());
  web_ui->AddMessageHandler(new SyncInternalsMessageHandler);
}

SyncInternalsUI::~SyncInternalsUI() {}


text:
class CreatePlcCourses < ActiveRecord::Migration
  def change
    create_table :plc_courses do |t|
      t.string :name

      t.timestamps null: false
    end
  end
end