text:
package io.spine.testing.logging.mute;

import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.logging.Logger;

import static com.google.common.truth.Truth.assertThat;
import static io.spine.testing.TestValues.randomString;

@DisplayName("`MutingLoggerTap` should")
class MutingLoggerTapTest extends SystemOutputTest {

    private MutingLoggerTap tap;

    @BeforeEach
    void createTap() {
        tap = new MutingLoggerTap(name());
    }

    @Nested
    @DisplayName("when not installed, NOT intercept")
    class NonInterception {

        @Test
        @DisplayName("regular logging")
        void regularLog() {
            var expected = "Test non interception.";
            logger().info(expected);

            assertThat(loggingOutput()).contains(expected);
        }

        @Test
        @DisplayName("error logging")
        void errorLog() {
            var expectedError = "Testing error non interception.";
            logger().severe(expectedError);

            assertThat(loggingOutput()).contains(expectedError);
        }
    }

    @Nested
    @DisplayName("intercept")
    class Interception {

        @BeforeEach
        void install() {
            tap.install();
        }

        @AfterEach
        void remove() {
            tap.remove();
        }

        @Test
        @DisplayName("regular logging")
        void regularLog() {
            var expected = "Test interception.";
            logger().info(expected);

            assertThat(loggingOutput()).doesNotContain(expected);
        }

        @Test
        @DisplayName("error logging")
        void errorLog() {
            var expectedError = "Testing error interception.";
            logger().severe(expectedError);

            assertThat(loggingOutput()).doesNotContain(expectedError);
        }

        @Test
        @DisplayName("redirecting to `MemoizingStream`")
        void redirection() {
            assertThat(tap.streamSize())
                    .isEqualTo(0);
            var msg = randomString();
            var logger = logger();

            logger.info(msg);

            assertThat(tap.streamSize() > 0)
                    .isTrue();
        }

        @Nested
        @DisplayName("flush to `OutputStream`")
        class Flushing {

            private ByteArrayOutputStream stream;
            private String logMessage;
            private String errorMessage;

            @BeforeEach
            void flush() throws IOException {
                stream = new ByteArrayOutputStream();
                logMessage = "Testing log flushing. Random suffix: " + randomString();
                logger().info(logMessage);
                errorMessage = "Testing error flushing. Random suffix: " + randomString();
                logger().severe(errorMessage);
                tap.flushTo(stream);
            }

            @Test
            @DisplayName("accumulated output")
            void ofRegularLogs() {
                var fo = flushedOutput();
                assertThat(fo).contains(logMessage);
            }

            @Test
            @DisplayName("accumulated error output")
            void ofErrorLogs() {
                var fo = flushedOutput();
                assertThat(fo).contains(errorMessage);
            }
            String flushedOutput() {
                return stream.toString(Charset.defaultCharset());
            }
        }
    }

    private String name() {
        return getClass().getName();
    }

    private Logger logger() {
        return Logger.getLogger(name());
    }
}


text:
u<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>Wardrobe Helper</title>

    <link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">

        Wardrobe Helper
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarResponsive" aria-controls="navbarResponsive" aria-expanded="false" aria-label="Toggle navigation">

        </button>

Input Link To Clothing

          <form>
          WebLink:

          <input id="weblink" type="text" value="">

          <input type="button" id="buttonID" value="submit" onclick="getLink()"/>
        </form>

redpajama_set_name: RedPajamaGithub


text:
"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = _default;

var _lodash = _interopRequireDefault(require("lodash"));

var _nameClass = _interopRequireDefault(require("../util/nameClass"));

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _default() {
  return function ({
    addUtilities,
    theme,
    variants
  }) {
    const utilities = _lodash.default.fromPairs(_lodash.default.map(theme('backgroundImage'), (value, modifier) => {
      return [(0, _nameClass.default)('bg', modifier), {
        'background-image': value
      }];
    }));

    addUtilities(utilities, variants('backgroundImage'));
  };
}


text:
module Kuroko2
  module Workflow
    class Node
      PATH_REGEXP = %r(\A(?:/|(?:/\d+-[a-z0-9_]+)+)\z)
      TASK_REGISTRY = {
        root:                  Task::Sequence,
        noop:                  Task::Noop,
        sequence:              Task::Sequence,
        auto_skip_error:       Task::AutoSkipError,
        fork:                  Task::Fork,
        parallel_fork:         Task::ParallelFork,
        env:                   Task::Env,
        execute:               Task::Execute,
        queue:                 Task::Queue,
        sub_process:           Task::SubProcess,
        subprocess:            Task::SubProcess,
        timeout:               Task::Timeout,
        expected_time:         Task::ExpectedTime,
        wait:                  Task::Wait,
        sleep:                 Task::Sleep,
        rails_env:             Task::RailsEnv,
        kuroko_runner:         Task::KurokoRunner,
        echo:                  Task::Echo,
        retry:                 Task::Retry,
      }

      attr_reader :type, :option, :children
      attr_accessor :parent

      def self.register(key: nil, klass:)
        key ||= klass.to_s.demodulize.underscore.to_sym

        unless TASK_REGISTRY.has_key?(key)
          TASK_REGISTRY.store(key, klass)
        else
          Kuroko2.logger.warn("Unable to add '#{klass}' to task registry. '#{TASK_REGISTRY[key]}' is already registered.")
        end
      end

      def self.deregister(key)
        TASK_REGISTRY.delete(key)
      end

      def initialize(type, option = nil)
        @type       = type.to_sym
        @task_klass = TASK_REGISTRY.fetch(@type, nil)
        @option     = option.try(:strip)
        @parent     = nil
        @children   = []

        raise AssertionError, "`#{@type}` is not registered in task repository." unless @task_klass
      end

      def append_child(child)
        child.parent = self
        @children << child
      end

      def execute(token)
        Kuroko2.logger.debug { "(token #{token.uuid}) Execute #{@type} with option '#{@option}'." }
        @task_klass.new(self, token).execute.tap do |result|
          Kuroko2.logger.debug("(token #{token.uuid}) Result is '#{result}'.")
        end
      end

      def find(path)
        raise AssertionError, "path query('#{path}') is invalid." unless PATH_REGEXP === path

        query = path.split('/')
        query.shift # drop first empty string.

        traverse(query)
      end

      def next(index = 0)
        if (child = children[index])
          child
        else
          next_sibling
        end
      end

      def next_sibling
        if parent
          parent.next(current_index + 1)
        else
          nil
        end
      end

      def path
        if parent
          parent.path + "/#{current_index}-#{type}"
        else
          ''
        end
      end

      def to_script(indent = 0)
        "#{'  ' * indent}#{type}: #{option}\n" + children.map { |child| child.to_script(indent + 1) }.join
      end

      def validate_all
        @task_klass.new(self, nil).validate
        @children.each do |child|
          child.validate_all
        end
      end

      protected

      def current_index
        @_current_index = parent.children.index(self)
      end

      def traverse(query)
        return self if query.empty?

        first    = query.shift
        index, _ = first.split('-')

        @children[index.to_i].traverse(query)
      end

    end
  end
end


text:
package org.discotools.gwt.leaflet.client.controls.attribution;

import org.discotools.gwt.leaflet.client.controls.Control;
import org.discotools.gwt.leaflet.client.controls.Position;

/**
 * <bAdds attribution to maps.
 *

 * The attribution control allows you to display attribution data in a small text box on a map.
 * It is put on the map by default unless you set its attributionControl option to false, and it
 * fetches attribution texts from layers with getAttribution method automatically.
  *

 * Options
 * <nl>
 *
{@link #POSITION}

 *
{@link #PREFIX}

 * </nl>
 *

 * @author kennethg
 * @author Lionel Leiva-Marcon
 *
 * @see L.Control.Attribution (Leaflet API)
 *
 */
public class Attribution extends Control {

	/**
	 * The initial position of the control (one of the map corners).
	 *

	 * Default: {@link Position#BOTTOM_RIGHT}.
	 */
	public static final String POSITION = "position";

	/**
	 * The HTML text shown before the attributions. Pass false to disable.
	 *

	 * DEFAULT: 'Powered by Leaflet'
	 */
	public static final String PREFIX = "prefix";

	public Attribution(AttributionOptions options) {
		this("",options);
	}

	public Attribution(String text, AttributionOptions options) {
		super(AttributionImpl.create(text, options.getJSObject()));
	}

	/**
	 * Get the string before the attributions ("Powered by Leaflet" by default).
	 */
	public String getPrefix() {
		return AttributionImpl.getPrefix(getJSObject());
	}

	/**
	 * Sets the string before the attributions ("Powered by Leaflet" by default).
	 * @param text - {@link Attribution} prefix.
	 */
	public Attribution setPrefix(String text) {
		AttributionImpl.setPrefix(getJSObject(), text);
		return this;
	}

	/**
	 * Adds an attribution text (e.g. "Vector data © CloudMade").
	 * @param text - {@link Attribution} text.
	 */
	public Attribution addAttribution(String text) {
		AttributionImpl.addAttribution(getJSObject(), text);
		return this;
	}

	/**
	 * Removes an attribution text.
	 * @param text - {@link Attribution} text.
	 */
	public Attribution removeAttribution(String text) {
		AttributionImpl.removeAttribution(getJSObject(), text);
		return this;
	}

}


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

using Gtk;
using Gdk;

using Mono.Unix;

using FSpot;
using FSpot.Core;
using FSpot.UI.Dialog;

using Hyena;

public class TagCommands {

	public enum TagType {
		Tag,
		Category
	}

	public class Create : BuilderDialog {
		TagStore tag_store;

		[GtkBeans.Builder.Object] Button create_button;
		[GtkBeans.Builder.Object] Entry tag_name_entry;
		[GtkBeans.Builder.Object] Label prompt_label;
		[GtkBeans.Builder.Object] Label already_in_use_label;
		[GtkBeans.Builder.Object] ComboBox category_option_menu;
		[GtkBeans.Builder.Object] CheckButton auto_icon_checkbutton;

		private List<Tag> categories;

		private void PopulateCategories (List<Tag> categories, Category parent)
		{
			foreach (Tag tag in parent.Children) {
				if (tag is Category) {
					categories.Add (tag);
					PopulateCategories (categories, tag as Category);
				}
			}
		}

		private string Indentation (Category category)
		{
			int indentations = 0;
			for (Category parent = category.Category;
			     parent != null && parent.Category != null;
			     parent = parent.Category)
				indentations++;
			return new string (' ', indentations*2);
		}

		private void PopulateCategoryOptionMenu ()
		{
			categories = new List<Tag> ();
			categories.Add (tag_store.RootCategory);
			PopulateCategories (categories, tag_store.RootCategory);

			ListStore category_store = new ListStore (typeof(Pixbuf), typeof(string));

			foreach (Category category in categories) {
				category_store.AppendValues (category.SizedIcon, Indentation (category) + category.Name);
			}

			category_option_menu.Sensitive = true;

			category_option_menu.Model = category_store;
			var icon_renderer = new CellRendererPixbuf ();
			icon_renderer.Width = (int)Tag.TagIconSize;
			category_option_menu.PackStart (icon_renderer, true);

			var text_renderer = new CellRendererText ();
			text_renderer.Alignment = Pango.Alignment.Left;
			text_renderer.Width = 150;
			category_option_menu.PackStart (text_renderer, true);

			category_option_menu.AddAttribute (icon_renderer, "pixbuf", 0);
			category_option_menu.AddAttribute (text_renderer, "text", 1);
			category_option_menu.ShowAll ();
		}

		private bool TagNameExistsInCategory (string name, Category category)
		{
			foreach (Tag tag in category.Children) {
				if (String.Compare(tag.Name, name, true) == 0)
					return true;

				if (tag is Category && TagNameExistsInCategory (name, tag as Category))
					return true;
			}

			return false;
		}

		private void Update ()
		{
			if (tag_name_entry.Text == String.Empty) {
				create_button.Sensitive = false;
				already_in_use_label.Markup = String.Empty;
			} else if (TagNameExistsInCategory (tag_name_entry.Text, tag_store.RootCategory)) {
				create_button.Sensitive = false;
				already_in_use_label.Markup = "<small>" + Catalog.GetString ("This name is already in use") + "</small>";
			} else {
				create_button.Sensitive = true;
				already_in_use_label.Markup = String.Empty;
			}
		}

        // XXX: never called
        private void HandleTagNameEntryChanged(object sender, EventArgs args)
		{
			Update ();
		}

		private Category Category {
			get
			{
			    if (categories.Count == 0)
					return tag_store.RootCategory;
			    return categories [category_option_menu.Active] as Category;
			}
		    set {
				if ((value != null) && (categories.Count > 0)) {
					//System.Console.WriteLine("TagCreateCommand.set_Category(" + value.Name + ")");
					for (int i = 0; i < categories.Count; i++) {
						Category category = (Category)categories[i];
						// should there be an equals type method?
						if (value.Id == category.Id) {
							category_option_menu.Active = i;
							return;
						}
					}
				} else {
					category_option_menu.Active = 0;
				}
			}
		}

		public Tag Execute (TagType type, Tag [] selection)
		{
			Category default_category = null;
			if (selection.Length > 0) {
				if (selection [0] is Category)
					default_category = (Category) selection [0];
				else
					default_category = selection [0].Category;
			} else {
				default_category = tag_store.RootCategory;
			}

			this.DefaultResponse = ResponseType.Ok;

			this.Title = Catalog.GetString ("Create New Tag");
			prompt_label.Text = Catalog.GetString ("Name of New Tag:");
			this.auto_icon_checkbutton.Active = Preferences.Get<bool> (Preferences.TAG_ICON_AUTOMATIC);

			PopulateCategoryOptionMenu ();
			this.Category = default_category;
			Update ();
			tag_name_entry.GrabFocus ();

			ResponseType response = (ResponseType) this.Run ();

			Tag new_tag = null;
			if (response == ResponseType.Ok) {
				bool autoicon = this.auto_icon_checkbutton.Active;
				Preferences.Set (Preferences.TAG_ICON_AUTOMATIC, autoicon);
				try {
					Category parent_category = Category;

					if (type == TagType.Category)
						new_tag = tag_store.CreateCategory (parent_category, tag_name_entry.Text, autoicon);
					else
						new_tag = tag_store.CreateTag (parent_category, tag_name_entry.Text, autoicon);
				} catch (Exception ex) {
					// FIXME error dialog.
					Log.Exception (ex);
				}
			}

			this.Destroy ();
			return new_tag;
		}

		public Create (TagStore tag_store) : base ("CreateTagDialog.ui", "create_tag_dialog")
		{
			this.tag_store = tag_store;
		}
	}
}


text:
{{extend 'layout.html'}}

Event created

Your location is created.

What to do next

Next step is to create events for your locations.  Events and locations may both be either real physical places and meetings or virtual if you just want to use as containers for questions and actions.

   <INPUT TYPE=BUTTON  class="btn btn-primary btn-sm btn-group-sm" onclick="parent.location='{{=URL('event','new_event')}}'" VALUE="New Event">
<INPUT TYPE=BUTTON  class="btn btn-primary btn-sm btn-group-sm" onclick="parent.location='{{=URL('location','new_location')}}'" VALUE="New Event">

{{block right_sidebar}}

{{include 'sidebar.html'}}


text:
<?php
namespace C4\View\Template;

class SmartyExtensions {

	public function get_template($tpl_name, &$tpl_source, $smarty) {
		if (file_exists(ROOT_PATH . "/templates/$tpl_name.html")) {
			$tpl_source = file_get_contents(ROOT_PATH . "/templates/$tpl_name.html");
			return true;
		}

    	return false;
	}

	public function get_timestamp($tpl_name, &$tpl_timestamp, $smarty) {

		if (file_exists(ROOT_PATH . "/templates/$tpl_name.html")) {
			$tpl_timestamp = filemtime(ROOT_PATH . "/templates/$tpl_name.html");
			return true;
		}
		else {
			//critical_error("Template Error", "Cannot load template <em>$tpl_name</em>", true);
		}

	    return false;
	}

	public function get_secure($tpl_name, &$smarty) {
    	return true;
	}

	public function get_trusted($tpl_name, &$smarty) {

	}

}


text:
"""
Testris is the test runner for Learntris. Learntris is
the part *you* write, in whatever language you prefer.

If you're seeing this message when you tried to run
testris.py, it means testris can't find your code!

Your first step is to write a *console-mode* program
(one that does absolutely nothing!) and tell testris
where to find it:

    ./testris.py [/path/to/learntris] [arguments]

The path should refer to a physical file on disk, so if
you need command line arguments, create a wrapper program.
The default path is "./learntris".

You can pass extra arguments that will be passed to the
guest learntris program.

Once testris is able to launch your program, this message
will be replaced with instructions for implementing your
first feature.
"""
from __future__ import print_function # let's keep it 3.x compatible
import sys, os, subprocess, difflib, pprint, time, traceback
import extract

if sys.version_info.major < 3:
    class FileNotFoundError(IOError):
        pass

class Test(object):
    def __init__(self):
        self.desc = ""
        self.seq = [] # sequence of commands

    def __repr__(self):
        return "<Test: %s, %d commands>" %  (self.desc, len(self.seq))

class TestFailure(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

class TimeoutFailure(TestFailure):
    pass

def parse_test(lines):
    while lines and lines[-1].strip() == "":
        lines.pop()
    opcodes = {
        'title': None,
        'doc': [],
        'in': [],
        'out': [],
    }
    for line in lines:
        if line.startswith('#'): continue
        if '#' in line:                # strip trailing comments
            line = line[:line.find('#')]
        sline = line.strip()
        if sline.startswith('='):      # test title
            opcodes['title'] = sline[2:]
        elif sline.startswith(':'):    # test description
            opcodes['doc'].append(sline)
        elif sline.startswith('>'):    # input to send
            opcodes['in'].append(sline[1:].lstrip())
        else:                          # expected output
            opcodes['out'].append(sline)
    return opcodes

def spawn(program_args, use_shell):
    return subprocess.Popen(program_args,
                            shell=use_shell,
                            stdin=subprocess.PIPE,
                            stdout=subprocess.PIPE)

def await_results(program, timeout_seconds=2):
    """
    This polls the child program until it finishes
    executing. If it takes more than =timeout_seconds=,
    kill the program and raise a TimeoutFailure.
    """
    countdown = timeout_seconds * 10
    while program.poll() is None and countdown > 0:
        time.sleep(0.1) # seep for 1/10 of a second
        countdown -= 1
    if countdown == 0:
        program.kill()
        raise TimeoutFailure("<program timed out>")

def run_test(program, opcodes):
    # send all the input lines:
    print(opcodes['title'])
    print("---- sending commands ----")
    for cmd in opcodes['in']:
        print(cmd)
        program.stdin.write((cmd + "\n").encode('utf-8'))
        # in python3, subprocess opens stdin in binary mode: http://hg.python.org/cpython/file/c9cb931b20f4/Lib/subprocess.py#l828
        # with a default bufsize, which for binary mode is io.DEFAULT_BUFFER_SIZE (4096): https://docs.python.org/3.3/library/functions.html#open
        # we can't use line buffering because, even though the subprocess docs don't say so
        # and no error is thrown when you try, line buffering is only for text mode
        # so, instead, we flush
        program.stdin.flush()

    # let the program do its thing:
    print("---- awaiting results ----")
    await_results(program)

    # read all the actual output lines and compare to expected:
    actual = [line.strip() for line in
              program.stdout.read().decode('utf-8').split("\n")]
    while actual and actual[-1] == "":
        actual.pop()
    if actual != opcodes['out']:
        print('\n'.join(opcodes['doc']))
        print("---- expected results ----")
        print('\n'.join(opcodes['out']))
        diff = '\n'.join(list(difflib.Differ().compare(actual, opcodes['out'])))
        raise TestFailure('output mismatch:\n' + diff)

def run_tests(program_args, use_shell):
    for i, test in enumerate(extract.tests()):
        program = spawn(program_args, use_shell)
        opcodes = parse_test(test.lines)
        print("Running test %d: %s" % (i+1, test.name))
        try:
            run_test(program, opcodes)
            print("Test %d passed" % (i+1))
        except (TimeoutFailure, TestFailure) as e:
            print("Test %d failed: %s" % (i+1, e))
            break
        print("\n") # add 2 blank lines between tests

def find_learntris():
    default = "./learntris"
    program_args = sys.argv[1:] if len(sys.argv) >= 2 else [default]
    if "--shell" in program_args: # --shell option
        program_args.remove("--shell")
        return (program_args, True)
    elif os.path.exists(program_args[0]):
        return (program_args, False)
    elif program_args[0] == default:
        print(__doc__)
        raise FileNotFoundError(default)
    else:
        raise FileNotFoundError("%s" % program_args[0])

def main():
    try: cmdline, use_shell = find_learntris()
    except FileNotFoundError as e:
        print('File not found:', e)
    else:
        cmd = cmdline[0]
        try: run_tests(cmdline, use_shell)
        except PermissionError as e:
            print(); print(e)
            print("Couldn't run %r due to a permission error." % cmd)
            print("Make sure your program is marked as an executable.")
        except BrokenPipeError as e:
            print(); print(e)
            print("%r quit before reading any input." % cmd)
            print("Make sure you are reading commands from standard input,")
            print("not trying to take arguments from the command line.")
        except Exception as e:
            print('-'*50)
            traceback.print_exc()
            print('-'*50)
            print("Oh no! Testris encountered an unexpected problem while")
            print("attempting to run your program. Please report the above")
            print("traceback in the issue tracker, so that we can help you")
            print("with the problem and provide a better error message in")
            print("the future.")
            print()
            print("  https://github.com/LearnProgramming/learntris/issues")
            print()

if __name__ == '__main__':
    main()

# vim: set expandtab:


text:
/**
 * @file
 * @brief libmemcached Queue Storage Declarations
 */

#ifndef __GEARMAN_QUEUE_LIBMEMCACHED_H__
#define __GEARMAN_QUEUE_LIBMEMCACHED_H__

#ifdef __cplusplus
extern "C" {
#endif

/**
 * @addtogroup gearman_queue_libmemcached libmemcached Queue Storage Functions
 * @ingroup gearman_queue
 * @{
 */

/**
 * Get module configuration options.
 */
GEARMAN_API
gearman_return_t gearman_queue_libmemcached_conf(gearman_conf_st *conf);

/**
 * Initialize the queue.
 */
GEARMAN_API
gearman_return_t gearman_queue_libmemcached_init(gearman_st *gearman,
                                                 gearman_conf_st *conf);

/**
 * De-initialize the queue.
 */
GEARMAN_API
gearman_return_t gearman_queue_libmemcached_deinit(gearman_st *gearman);

/**
 * Initialize the queue for a gearmand object.
 */
GEARMAN_API
gearman_return_t gearmand_queue_libmemcached_init(gearmand_st *gearmand,
                                                  gearman_conf_st *conf);

/**
 * De-initialize the queue for a gearmand object.
 */
GEARMAN_API
gearman_return_t gearmand_queue_libmemcached_deinit(gearmand_st *gearmand);

/** @} */

#ifdef __cplusplus
}
#endif

#endif /* __GEARMAN_QUEUE_LIBMEMCACHED_H__ */


text:
- Open issue to make sure the work is valid.

- Branch off of develop, name branch descriptively.

- Commit referencing the issue #, example: Issue #14 in commit message.

- Update contributors.

- Open PR.


text:
import {
	FileLoader,
	Loader,
	CanvasTexture,
	NearestFilter
} from "../../../build/three.module.js";

var LottieLoader = function ( manager ) {

	Loader.call( this, manager );

};

LottieLoader.prototype = Object.assign( Object.create( Loader.prototype ), {

	constructor: LottieLoader,

	setQuality: function ( value ) {

		this._quality = value;

	},

	load: function ( url, onLoad, onProgress, onError ) {

		const quality = this._quality || 1;

		const texture = new CanvasTexture();
		texture.minFilter = NearestFilter;

		const loader = new FileLoader( this.manager );
		loader.setPath( this.path );
		loader.setWithCredentials( this.withCredentials );

		loader.load( url, function ( text ) {

			const data = JSON.parse( text );

			// bodymoving uses container.offetWidth and offsetHeight
			// to define width/height

			const container = document.createElement( 'div' );
			container.style.width = data.w + 'px';
			container.style.height = data.h + 'px';
			document.body.appendChild( container );

			const animation = bodymovin.loadAnimation( {
				container: container,
				animType: 'canvas',
				loop: true,
				autoplay: true,
				animationData: data,
				rendererSettings: { dpr: quality }
			} );

			texture.animation = animation;
			texture.image = animation.container;

			animation.addEventListener( 'enterFrame', function () {

				texture.needsUpdate = true;

			} );

			container.style.display = 'none';

			if ( onLoad !== undefined ) {

				onLoad( texture );

			}

		}, onProgress, onError );

		return texture;

	}

} );

export { LottieLoader };


text:
import os

import sys

from twisted.internet import reactor
from twisted.internet.defer import Deferred, inlineCallbacks, returnValue

from common.utils.asleep import asleep
from common.utils.consulhelpers import get_endpoint_from_consul
from structlog import get_logger
import grpc
from grpc import StatusCode
from grpc._channel import _Rendezvous
from ofagent.protos import third_party
from protos import voltha_pb2
from protos.voltha_pb2 import OfAgentSubscriber
from grpc_client import GrpcClient

from agent import Agent
from common.utils.dockerhelpers import get_my_containers_name

# _ = third_party

class ConnectionManager(object):
    def __init__(self, consul_endpoint, vcore_endpoint, vcore_grpc_timeout,
                 controller_endpoints, instance_id,
                 enable_tls=False, key_file=None, cert_file=None,
                 vcore_retry_interval=0.5, devices_refresh_interval=5,
                 subscription_refresh_interval=5):

        self.log = get_logger()
        self.log.info('init-connection-manager')
        self.log.info('list-of-controllers',
                      controller_endpoints=controller_endpoints)

        self.controller_endpoints = controller_endpoints
        self.consul_endpoint = consul_endpoint
        self.vcore_endpoint = vcore_endpoint
        self.grpc_timeout = vcore_grpc_timeout
        self.instance_id = instance_id
        self.enable_tls = enable_tls
        self.key_file = key_file
        self.cert_file = cert_file

        self.channel = None
        self.grpc_client = None  # single, shared gRPC client to vcore

        self.agent_map = {}  # (datapath_id, controller_endpoint) -> Agent()
        self.device_id_to_datapath_id_map = {}

        self.vcore_retry_interval = vcore_retry_interval
        self.devices_refresh_interval = devices_refresh_interval
        self.subscription_refresh_interval = subscription_refresh_interval
        self.subscription = None

        self.running = False

    def start(self):

        if self.running:
            return

        self.log.debug('starting')

        self.running = True

        # Start monitoring the vcore grpc channel
        reactor.callInThread(self.monitor_vcore_grpc_channel)

        # Start monitoring logical devices and manage agents accordingly
        reactor.callLater(0, self.monitor_logical_devices)

        self.log.info('started')

        return self

    def stop(self):
        self.log.debug('stopping')
        # clean up all controller connections
        for agent in self.agent_map.itervalues():
            agent.stop()
        self.running = False

        self._reset_grpc_attributes()

        self.log.info('stopped')

    def resolve_endpoint(self, endpoint):
        ip_port_endpoint = endpoint
        if endpoint.startswith('@'):
            try:
                ip_port_endpoint = get_endpoint_from_consul(
                    self.consul_endpoint, endpoint[1:])
                self.log.info(
                    '{}-service-endpoint-found'.format(endpoint), address=ip_port_endpoint)
            except Exception as e:
                self.log.error('{}-service-endpoint-not-found'.format(endpoint), exception=repr(e))
                self.log.error('committing-suicide')
                # Committing suicide in order to let docker restart ofagent
                os.system("kill -15 {}".format(os.getpid()))
        if ip_port_endpoint:
            host, port = ip_port_endpoint.split(':', 2)
            return host, int(port)

    def _reset_grpc_attributes(self):
        self.log.debug('start-reset-grpc-attributes')

        if self.grpc_client is not None:
            self.grpc_client.stop()

        if self.channel is not None:
            del self.channel

        self.is_alive = False
        self.channel = None
        self.subscription = None
        self.grpc_client = None

        self.log.debug('stop-reset-grpc-attributes')

    def _assign_grpc_attributes(self):
        self.log.debug('start-assign-grpc-attributes')

        host, port = self.resolve_endpoint(self.vcore_endpoint)
        self.log.info('revolved-vcore-endpoint', endpoint=self.vcore_endpoint, host=host, port=port)

        assert host is not None
        assert port is not None

        # Establish a connection to the vcore GRPC server
        self.channel = grpc.insecure_channel('{}:{}'.format(host, port))
        self.is_alive = True

        self.log.debug('stop-assign-grpc-attributes')

    @inlineCallbacks
    def monitor_vcore_grpc_channel(self):
        self.log.debug('start-monitor-vcore-grpc-channel')

        while self.running:
            try:
                # If a subscription is not yet assigned then establish new GRPC connection
                # ... otherwise keep using existing connection details
                if self.subscription is None:
                    self._assign_grpc_attributes()

                # Send subscription request to register the current ofagent instance
                container_name = self.instance_id
                if self.grpc_client is None:
                    self.grpc_client = GrpcClient(self, self.channel, self.grpc_timeout)
                subscription = yield self.grpc_client.subscribe(
                    OfAgentSubscriber(ofagent_id=container_name))

                # If the subscriber id matches the current instance
                # ... then the subscription has succeeded
                if subscription is not None and subscription.ofagent_id == container_name:
                    if self.subscription is None:
                        # Keep details on the current GRPC session and subscription
                        self.log.debug('subscription-with-vcore-successful', subscription=subscription)
                        self.subscription = subscription
                        self.grpc_client.start()

                    # Sleep a bit in between each subscribe
                    yield asleep(self.subscription_refresh_interval)

                    # Move on to next subscribe request
                    continue

                # The subscription did not succeed, reset and move on
                else:
                    self.log.info('subscription-with-vcore-unavailable', subscription=subscription)

            except _Rendezvous, e:
                self.log.error('subscription-with-vcore-terminated',exception=e, status=e.code())

            except Exception as e:
                self.log.exception('unexpected-subscription-termination-with-vcore', e=e)

            # Reset grpc details
            # The vcore instance is either not available for subscription
            # or a failure occurred with the existing communication.
            self._reset_grpc_attributes()

            # Sleep for a short period and retry
            yield asleep(self.vcore_retry_interval)

        self.log.debug('stop-monitor-vcore-grpc-channel')

    @inlineCallbacks
    def get_list_of_reachable_logical_devices_from_voltha(self):

        while self.running:
            self.log.debug('retrieve-logical-device-list')
            try:
                devices = yield \
                    self.grpc_client.list_reachable_logical_devices()

                for device in devices:
                    self.log.debug("reachable-logical-device-entry", id=device.id,
                                   datapath_id=device.datapath_id)

                returnValue(devices)

            except _Rendezvous, e:
                status = e.code()
                self.log.error('vcore-communication-failure', exception=e, status=status)
                if status == StatusCode.UNAVAILABLE or status == StatusCode.DEADLINE_EXCEEDED:
                    os.system("kill -15 {}".format(os.getpid()))

            except Exception as e:
                self.log.exception('logical-devices-retrieval-failure', exception=e)

            self.log.info('reconnect', after_delay=self.vcore_retry_interval)
            yield asleep(self.vcore_retry_interval)

    def refresh_agent_connections(self, devices):
        """
        Based on the new device list, update the following state in the class:
        * agent_map
        * datapath_map
        * device_id_map
        :param devices: full device list freshly received from Voltha
        :return: None
        """

        # Use datapath ids for deciding what's new and what's obsolete
        desired_datapath_ids = set(d.datapath_id for d in devices)
        current_datapath_ids = set(datapath_ids[0] for datapath_ids in self.agent_map.iterkeys())

        # if identical, nothing to do
        if desired_datapath_ids == current_datapath_ids:
            return

        # ... otherwise calculate differences
        to_add = desired_datapath_ids.difference(current_datapath_ids)
        to_del = current_datapath_ids.difference(desired_datapath_ids)

        # remove what we don't need
        for datapath_id in to_del:
            self.delete_agent(datapath_id)

        # start new agents as needed
        for device in devices:
            if device.datapath_id in to_add:
                self.create_agent(device)

        self.log.debug('updated-agent-list', count=len(self.agent_map))
        self.log.debug('updated-device-id-to-datapath-id-map',
                  map=str(self.device_id_to_datapath_id_map))

    def create_agent(self, device):
        datapath_id = device.datapath_id
        device_id = device.id
        for controller_endpoint in self.controller_endpoints:
            agent = Agent(controller_endpoint, datapath_id,
                          device_id, self.grpc_client, self.enable_tls,
                          self.key_file, self.cert_file)
            agent.start()
            self.agent_map[(datapath_id,controller_endpoint)] = agent
            self.device_id_to_datapath_id_map[device_id] = datapath_id

    def delete_agent(self, datapath_id):
        for controller_endpoint in self.controller_endpoints:
            agent = self.agent_map[(datapath_id,controller_endpoint)]
            device_id = agent.get_device_id()
            agent.stop()
            del self.agent_map[(datapath_id,controller_endpoint)]
            del self.device_id_to_datapath_id_map[device_id]

    @inlineCallbacks
    def monitor_logical_devices(self):
        self.log.debug('start-monitor-logical-devices')

        while self.running:
            self.log.debug('monitoring-logical-devices')

            # should change to a gRPC streaming call
            # see https://jira.opencord.org/browse/CORD-821

            try:
                if self.channel is not None and self.grpc_client is not None and \
                                self.subscription is not None:
                    # get current list from Voltha
                    reachable_devices = yield \
                        self.get_list_of_reachable_logical_devices_from_voltha()

                    # update agent list and mapping tables as needed
                    self.refresh_agent_connections(reachable_devices)
                else:
                    self.log.warning('vcore-communication-unavailable')

                # wait before next poll
                yield asleep(self.devices_refresh_interval)

            except _Rendezvous, e:
                self.log.error('vcore-communication-failure', exception=repr(e), status=e.code())

            except Exception as e:
                self.log.exception('unexpected-vcore-communication-failure', exception=repr(e))

        self.log.debug('stop-monitor-logical-devices')

    def forward_packet_in(self, device_id, ofp_packet_in):
        datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
        if datapath_id:
            for controller_endpoint in self.controller_endpoints:
                agent = self.agent_map[(datapath_id, controller_endpoint)]
                agent.forward_packet_in(ofp_packet_in)

    def forward_change_event(self, device_id, event):
        datapath_id = self.device_id_to_datapath_id_map.get(device_id, None)
        if datapath_id:
            for controller_endpoint in self.controller_endpoints:
                agent = self.agent_map[(datapath_id, controller_endpoint)]
                agent.forward_change_event(event)


text:
package com.cultome.bizlang.language.function;

import java.io.ByteArrayInputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.events.Characters;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;

import com.cultome.bizlang.dataaccess.WSReader;
import com.cultome.bizlang.dataaccess.object.HttpMethod;
import com.cultome.bizlang.dataaccess.object.WsResponse;
import com.cultome.bizlang.language.BizlangException;
import com.cultome.bizlang.language.BizlangExpression;
import com.cultome.bizlang.language.util.Utils;
import com.cultomebizlang.language.interpreter.Bindings;

public class GetFromWsFunction implements JavaFunction {

	public static final String ACCESSOR = "accessor";
	public static final String ENDPOINT_PROPERTY = "endpoint";
	public static final String HTTP_METHOD_PROPERTY = "httpMethod";
	public static final String CONTENT_PROPERTY = "content";
	public static final String HEADERS_PROPERTY = "headers";
	private static final String APPLICATION_XML_MIME_TYPE = "application/xml";
	private static final String TEXT_XML_MIME_TYPE = "text/xml";

	private XMLInputFactory inputFactory;

	public GetFromWsFunction() {
		inputFactory = XMLInputFactory.newInstance();
	}

	@SuppressWarnings("unchecked")
	@Override
	public Object execute(Bindings bindings, BizlangExpression... params) throws BizlangException {
		try {
			if(params.length < 1){
				throw new RuntimeException("getFromWs function requires at least one parameter: web service alias.");
			}

			String wsAlias = (String) params[0].execute(bindings);

			// extraemos los objetos necesarios
			WSReader accessor = bindings.getConfig(Bindings.CNFG_NS_WEBSERVICES, ACCESSOR, WSReader.class);
			Map<String, Object> config = bindings.getConfig(Bindings.CNFG_NS_WEBSERVICES, wsAlias, Map.class);
			// sacamos las configuracion de la peticion
			String endpoint = (String) config.get(ENDPOINT_PROPERTY);
			HttpMethod method = HttpMethod.valueOf(((String) config.get(HTTP_METHOD_PROPERTY)).toUpperCase());
			String content = (String) config.get(CONTENT_PROPERTY);
			Map<String, String> headers = (Map<String, String>) config.get(HEADERS_PROPERTY);
			// hacemos el remplazo de datos para la peticion
			endpoint = Utils.replacePlaceholders(endpoint, bindings);
			content = Utils.replacePlaceholders(content, bindings);
			Set<String> keySet = headers.keySet();
			for(String key : keySet){
				headers.put(key, Utils.replacePlaceholders(headers.get(key), bindings));
			}

			WsResponse response = accessor.call(endpoint, method, content, headers);

			Map<String, Object> flatResponse = flattenResponse(response);

			return flatResponse;
		} catch (Exception e) {
			e.printStackTrace();
			throw new BizlangException(e);
		}
	}

	protected Map<String, Object> flattenResponse(WsResponse response) {
		if(APPLICATION_XML_MIME_TYPE.equals(response.getContentType()) || TEXT_XML_MIME_TYPE.equals(response.getContentType())){
			return parseXml(response.getContentBody());
		}
		return null;
	}

	protected Map<String, Object> parseXml(String contentBody) {
		Map<String, String> detectCollections = detectCollections(contentBody);
		Map<String, Object> filledMap = fillMap(detectCollections, contentBody);
		return filledMap;
	}

	protected Map<String, Object> fillMap(final Map<String, String> routes, String contentBody) {
		final Map<String, Object> returnValue = new HashMap<String, Object>();

		searchForDataNodes(contentBody, new DataNodeListener() {
			protected Map<String, Integer> idxs = new HashMap<String, Integer>();

			@SuppressWarnings({ "unchecked", "rawtypes" })
			@Override public void onData(String route, String data) {
				String actualRoute = routes.get(route);
				if(actualRoute.contains("[]")){
					String subTreeRoute = actualRoute.substring(0, actualRoute.indexOf("["));
					String leafRoute = actualRoute.substring(actualRoute.indexOf("[") + 3);
					Object subTree = Utils.getSubTree(returnValue, subTreeRoute);
					Map lastMapInserted = null;
					if(subTree instanceof Map){
						lastMapInserted = (Map) subTree;
					} else if(subTree instanceof List){
						List l = ((List) subTree);
						lastMapInserted = (Map) l.get(l.size() - 1);
					}
					// agregamos a un mapa existente o es un nuevo nodo?
					if(lastMapInserted != null && Utils.getSubTree(lastMapInserted, leafRoute) == null){
						if(leafRoute.contains("[]")){
							if(idxs.get(leafRoute) == null){
								idxs.put(leafRoute, 0);
							}

							String actualLeafRoute = setIndexes(leafRoute);
							Utils.addToTree(lastMapInserted, actualLeafRoute, data);
						} else {
							Utils.addToTree(lastMapInserted, leafRoute, data);
						}
					} else {
						if(idxs.get(subTreeRoute) == null){
							idxs.put(subTreeRoute, 0);
						}

						actualRoute = actualRoute.replaceFirst("\\[\\]", "[" + idxs.get(subTreeRoute) + "]");
						int newIdx = idxs.get(subTreeRoute) + 1;
						// reseteamos los indices
						for(String key : idxs.keySet()){
							idxs.put(key, 0);
						}
						// restauramos el indice principal
						idxs.put(subTreeRoute, newIdx);

						Utils.addToTree(returnValue, actualRoute, data);
					}
				} else {
					Utils.addToTree(returnValue, actualRoute, data);
				}
			}

			private String setIndexes(String route) {
				int lastIdx = route.lastIndexOf("[");
				String replaced = route.substring(0, lastIdx) + "[" + idxs.get(route) + "]" + route.substring(lastIdx + 2);
				idxs.put(route, idxs.get(route) + 1);
				return replaced;
			}
		});

		return returnValue;
	}

	/**
	 * Trata de adivinar la estructura del archivo XML para generar una estructura anidada dadas rutas planas.
	 * Esto implica que las siguientes rutas:
	 * 	uno.dos.tres.cuatro
	 * 	uno.dos.tres.cinco
	 * 	uno.dos.cuatro.cinco
	 * 	uno.dos.cuatro.cinco
	 * Se conviertan en las siguientes rutas:
	 * 	uno.dos.tres[].cuatro
	 * 	uno.dos.tres[].cinco
	 * 	uno.dos.cuatro.cinco[]
	 *
	 * @param contentBody
	 * @return
	 */
	protected Map<String, String> detectCollections(String contentBody) {
		final Map<String, String> routes = new HashMap<String, String>();

		searchForDataNodes(contentBody, new DataNodeListener() {
			boolean isParsingFirstNode = true;
			boolean isFirstDataNode = true;
			String firstElementRoute = "";

			@Override
			public void onData(String route, String data) {
				if (isFirstDataNode) {
					firstElementRoute = route;
					isFirstDataNode = false;
				} else {
					if (isParsingFirstNode && route.equals(firstElementRoute)) {
						isParsingFirstNode = false;
					}
				}

				if (isParsingFirstNode) {
					if (routes.get(route) == null) {
						routes.put(route, route);
					} else {
						routes.put(route, insertNestedLevel(route, countLevels(route) - 1));
					}

				} else {
					String detectedRoute = routes.get(route);
					if (detectedRoute == null) {
						throw new RuntimeException("Invalid format in response document.");
					}

					int lvl = countLevels(detectedRoute) - 1;
					String parentLvlName = getLevelName(detectedRoute, lvl);
					if (!parentLvlName.endsWith("[]")) {
						for (String key : routes.keySet()) {
							String routeValue = routes.get(key);
							int routeValueLvl = countLevels(routeValue) - 1;
							if (routeValueLvl >= lvl) {
								// uno.dos.tres   uno.dos
								String refParentLvlName = getLevelName(detectedRoute, lvl);
								String existingParentLvlName = getLevelName(routeValue, lvl);
								if (refParentLvlName.equals(existingParentLvlName)) {
									int idxBeforeChange = routeValue.indexOf("[");
									String newNestedLevel = insertNestedLevel(routeValue, lvl);
									int idxAfterChange = newNestedLevel.indexOf("[");

									if ((idxBeforeChange < 0 && idxAfterChange > 0) || (idxBeforeChange > 0 && idxAfterChange > 0 && idxBeforeChange != idxAfterChange)) {
										routes.put(key, newNestedLevel);
									}
								}

							}
						}
					}
				}
			}
		});

		return routes;
	}

	protected String insertNestedLevel(String route, int level) {
		StringBuilder b = new StringBuilder();
		String[] split = route.split("\\.");
		boolean first = true;
		for(int i = 0; i < split.length; i++){
			// ponemos el punto?
			if(first){
				first = false;
			} else {
				b.append(".");
			}
			// el pedazo de ruta
			b.append(split[i]);

			// la indicacion de anidado
			if(i == level){
				b.append("[]");
			}
		}
		return b.toString();
	}

	// uno.dos.cuatro
	protected String getLevelName(String route, int level) {
		String[] split = route.split("\\.");
		if(level >= split.length){
			return null;
		}
		return split[level];
	}

	protected int countLevels(String value) {
		int idx = 0;
		int count = 0;
		while((idx = value.indexOf(".", idx+1)) > 0){
			count++;
		}
		return count;
	}

	private String getTreeRoute(Stack<String> paramTree) {
		StringBuilder b = new StringBuilder();
		boolean first = true;
		for (Iterator<String> it = paramTree.iterator(); it.hasNext();) {
			if (first) {
				b.append(it.next());
				first = false;
			} else {
				b.append("." + it.next());
			}
		}
		return b.toString();
	}

	private void searchForDataNodes(String contentBody, DataNodeListener listener){
		Stack<String> paramTree = new Stack<String>();

		try {
			XMLEventReader eventReader = inputFactory.createXMLEventReader(new ByteArrayInputStream(contentBody.getBytes()));
			while (eventReader.hasNext()) {
				XMLEvent event = eventReader.nextEvent();

				if (event.isStartElement()) {
					StartElement startElement = event.asStartElement();
					paramTree.push(startElement.getName().getLocalPart());
				} else if (event.isCharacters()) {
					Characters chars = event.asCharacters();
					String data = chars.getData();
					if(!data.matches("^[\\s]+$")){
						String route = getTreeRoute(paramTree);
						listener.onData(route, data);
					}
				} else if (event.isEndElement()) {
					if(!paramTree.isEmpty()){
						paramTree.pop();
					}
				}
			}
		} catch(Exception e){
			e.printStackTrace();
		}
	}

	interface DataNodeListener {
		void onData(String route, String data);
	}

}


text:
<component name="libraryTable">
  <library name="play-services-ads-8.1.0">
    <CLASSES>
      <root url="jar://$PROJECT_DIR$/ParseStarterProject/build/intermediates/exploded-aar/com.google.android.gms/play-services-ads/8.1.0/jars/classes.jar!/" />
      <root url="file://$PROJECT_DIR$/ParseStarterProject/build/intermediates/exploded-aar/com.google.android.gms/play-services-ads/8.1.0/res" />
    </CLASSES>
    <JAVADOC />
    <SOURCES />
  </library>
</component>


text:
virtualenv -p python3 env
. ./env/bin/activate
pip install --upgrade pip
pip install -r requirements.txt


text:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="co.todai">

    <application
        android:allowBackup="true"/>

</manifest>


text:
<?php

declare(strict_types=1);

namespace Sylius\Bundle\ProductBundle\Form\Type;

use Sylius\Bundle\AttributeBundle\Form\Type\AttributeChoiceType;

/**
 * @author Kamil Kokot <kamil@kokot.me>
 */
final class ProductAttributeChoiceType extends AttributeChoiceType
{
    /**
     * {@inheritdoc}
     */
    public function getBlockPrefix()
    {
        return 'sylius_product_attribute_choice';
    }
}


text:
package syslog

import (
	"crypto/tls"
	"fmt"
	"io"
	"net"
	"net/url"
	"os"
	"strings"
	"sync"
	"time"
	"unicode"

	"github.com/influxdata/go-syslog/rfc5424"
	"github.com/influxdata/go-syslog/rfc5425"
	"github.com/influxdata/telegraf"
	"github.com/influxdata/telegraf/internal"
	tlsConfig "github.com/influxdata/telegraf/internal/tls"
	"github.com/influxdata/telegraf/plugins/inputs"
)

const defaultReadTimeout = time.Second * 5
const ipMaxPacketSize = 64 * 1024

// Syslog is a syslog plugin
type Syslog struct {
	tlsConfig.ServerConfig
	Address         string `toml:"server"`
	KeepAlivePeriod *internal.Duration
	ReadTimeout     *internal.Duration
	MaxConnections  int
	BestEffort      bool
	Separator       string `toml:"sdparam_separator"`

	now      func() time.Time
	lastTime time.Time

	mu sync.Mutex
	wg sync.WaitGroup
	io.Closer

	isStream      bool
	tcpListener   net.Listener
	tlsConfig     *tls.Config
	connections   map[string]net.Conn
	connectionsMu sync.Mutex

	udpListener net.PacketConn
}

var sampleConfig = `
  ## Specify an ip or hostname with port - eg., tcp://localhost:6514, tcp://10.0.0.1:6514
  ## Protocol, address and port to host the syslog receiver.
  ## If no host is specified, then localhost is used.
  ## If no port is specified, 6514 is used (RFC5425#section-4.1).
  server = "tcp://:6514"

  ## TLS Config
  # tls_allowed_cacerts = ["/etc/telegraf/ca.pem"]
  # tls_cert = "/etc/telegraf/cert.pem"
  # tls_key = "/etc/telegraf/key.pem"

  ## Period between keep alive probes.
  ## 0 disables keep alive probes.
  ## Defaults to the OS configuration.
  ## Only applies to stream sockets (e.g. TCP).
  # keep_alive_period = "5m"

  ## Maximum number of concurrent connections (default = 0).
  ## 0 means unlimited.
  ## Only applies to stream sockets (e.g. TCP).
  # max_connections = 1024

  ## Read timeout is the maximum time allowed for reading a single message (default = 5s).
  ## 0 means unlimited.
  # read_timeout = "5s"

  ## Whether to parse in best effort mode or not (default = false).
  ## By default best effort parsing is off.
  # best_effort = false

  ## Character to prepend to SD-PARAMs (default = "_").
  ## A syslog message can contain multiple parameters and multiple identifiers within structured data section.
  ## Eg., [id1 name1="val1" name2="val2"][id2 name1="val1" nameA="valA"]
  ## For each combination a field is created.
  ## Its name is created concatenating identifier, sdparam_separator, and parameter name.
  # sdparam_separator = "_"
`

// SampleConfig returns sample configuration message
func (s *Syslog) SampleConfig() string {
	return sampleConfig
}

// Description returns the plugin description
func (s *Syslog) Description() string {
	return "Accepts syslog messages per RFC5425"
}

// Gather ...
func (s *Syslog) Gather(_ telegraf.Accumulator) error {
	return nil
}

// Start starts the service.
func (s *Syslog) Start(acc telegraf.Accumulator) error {
	s.mu.Lock()
	defer s.mu.Unlock()

	scheme, host, err := getAddressParts(s.Address)
	if err != nil {
		return err
	}
	s.Address = host

	switch scheme {
	case "tcp", "tcp4", "tcp6", "unix", "unixpacket":
		s.isStream = true
	case "udp", "udp4", "udp6", "ip", "ip4", "ip6", "unixgram":
		s.isStream = false
	default:
		return fmt.Errorf("unknown protocol '%s' in '%s'", scheme, s.Address)
	}

	if scheme == "unix" || scheme == "unixpacket" || scheme == "unixgram" {
		os.Remove(s.Address)
	}

	if s.isStream {
		l, err := net.Listen(scheme, s.Address)
		if err != nil {
			return err
		}
		s.Closer = l
		s.tcpListener = l
		s.tlsConfig, err = s.TLSConfig()
		if err != nil {
			return err
		}

		s.wg.Add(1)
		go s.listenStream(acc)
	} else {
		l, err := net.ListenPacket(scheme, s.Address)
		if err != nil {
			return err
		}
		s.Closer = l
		s.udpListener = l

		s.wg.Add(1)
		go s.listenPacket(acc)
	}

	if scheme == "unix" || scheme == "unixpacket" || scheme == "unixgram" {
		s.Closer = unixCloser{path: s.Address, closer: s.Closer}
	}

	return nil
}

// Stop cleans up all resources
func (s *Syslog) Stop() {
	s.mu.Lock()
	defer s.mu.Unlock()

	if s.Closer != nil {
		s.Close()
	}
	s.wg.Wait()
}

// getAddressParts returns the address scheme and host
// it also sets defaults for them when missing
// when the input address does not specify the protocol it returns an error
func getAddressParts(a string) (string, string, error) {
	parts := strings.SplitN(a, "://", 2)
	if len(parts) != 2 {
		return "", "", fmt.Errorf("missing protocol within address '%s'", a)
	}

	u, _ := url.Parse(a)
	switch u.Scheme {
	case "unix", "unixpacket", "unixgram":
		return parts[0], parts[1], nil
	}

	var host string
	if u.Hostname() != "" {
		host = u.Hostname()
	}
	host += ":"
	if u.Port() == "" {
		host += "6514"
	} else {
		host += u.Port()
	}

	return u.Scheme, host, nil
}

func (s *Syslog) listenPacket(acc telegraf.Accumulator) {
	defer s.wg.Done()
	b := make([]byte, ipMaxPacketSize)
	p := rfc5424.NewParser()
	for {
		n, _, err := s.udpListener.ReadFrom(b)
		if err != nil {
			if !strings.HasSuffix(err.Error(), ": use of closed network connection") {
				acc.AddError(err)
			}
			break
		}

		message, err := p.Parse(b[:n], &s.BestEffort)
		if message != nil {
			acc.AddFields("syslog", fields(*message, s), tags(*message), s.time())
		}
		if err != nil {
			acc.AddError(err)
		}
	}
}

func (s *Syslog) listenStream(acc telegraf.Accumulator) {
	defer s.wg.Done()

	s.connections = map[string]net.Conn{}

	for {
		conn, err := s.tcpListener.Accept()
		if err != nil {
			if !strings.HasSuffix(err.Error(), ": use of closed network connection") {
				acc.AddError(err)
			}
			break
		}
		var tcpConn, _ = conn.(*net.TCPConn)
		if s.tlsConfig != nil {
			conn = tls.Server(conn, s.tlsConfig)
		}

		s.connectionsMu.Lock()
		if s.MaxConnections > 0 && len(s.connections) >= s.MaxConnections {
			s.connectionsMu.Unlock()
			conn.Close()
			continue
		}
		s.connections[conn.RemoteAddr().String()] = conn
		s.connectionsMu.Unlock()

		if err := s.setKeepAlive(tcpConn); err != nil {
			acc.AddError(fmt.Errorf("unable to configure keep alive (%s): %s", s.Address, err))
		}

		go s.handle(conn, acc)
	}

	s.connectionsMu.Lock()
	for _, c := range s.connections {
		c.Close()
	}
	s.connectionsMu.Unlock()
}

func (s *Syslog) removeConnection(c net.Conn) {
	s.connectionsMu.Lock()
	delete(s.connections, c.RemoteAddr().String())
	s.connectionsMu.Unlock()
}

func (s *Syslog) handle(conn net.Conn, acc telegraf.Accumulator) {
	defer func() {
		s.removeConnection(conn)
		conn.Close()
	}()

	var p *rfc5425.Parser

	if s.BestEffort {
		p = rfc5425.NewParser(conn, rfc5425.WithBestEffort())
	} else {
		p = rfc5425.NewParser(conn)
	}

	if s.ReadTimeout != nil && s.ReadTimeout.Duration > 0 {
		conn.SetReadDeadline(time.Now().Add(s.ReadTimeout.Duration))
	}

	p.ParseExecuting(func(r *rfc5425.Result) {
		s.store(*r, acc)
		if s.ReadTimeout != nil && s.ReadTimeout.Duration > 0 {
			conn.SetReadDeadline(time.Now().Add(s.ReadTimeout.Duration))
		}
	})
}

func (s *Syslog) setKeepAlive(c *net.TCPConn) error {
	if s.KeepAlivePeriod == nil {
		return nil
	}

	if s.KeepAlivePeriod.Duration == 0 {
		return c.SetKeepAlive(false)
	}
	if err := c.SetKeepAlive(true); err != nil {
		return err
	}
	return c.SetKeepAlivePeriod(s.KeepAlivePeriod.Duration)
}

func (s *Syslog) store(res rfc5425.Result, acc telegraf.Accumulator) {
	if res.Error != nil {
		acc.AddError(res.Error)
	}
	if res.MessageError != nil {
		acc.AddError(res.MessageError)
	}
	if res.Message != nil {
		msg := *res.Message
		acc.AddFields("syslog", fields(msg, s), tags(msg), s.time())
	}
}

func tags(msg rfc5424.SyslogMessage) map[string]string {
	ts := map[string]string{}

	// Not checking assuming a minimally valid message
	ts["severity"] = *msg.SeverityShortLevel()
	ts["facility"] = *msg.FacilityLevel()

	if msg.Hostname() != nil {
		ts["hostname"] = *msg.Hostname()
	}

	if msg.Appname() != nil {
		ts["appname"] = *msg.Appname()
	}

	return ts
}

func fields(msg rfc5424.SyslogMessage, s *Syslog) map[string]interface{} {
	// Not checking assuming a minimally valid message
	flds := map[string]interface{}{
		"version": msg.Version(),
	}
	flds["severity_code"] = int(*msg.Severity())
	flds["facility_code"] = int(*msg.Facility())

	if msg.Timestamp() != nil {
		flds["timestamp"] = (*msg.Timestamp()).UnixNano()
	}

	if msg.ProcID() != nil {
		flds["procid"] = *msg.ProcID()
	}

	if msg.MsgID() != nil {
		flds["msgid"] = *msg.MsgID()
	}

	if msg.Message() != nil {
		flds["message"] = strings.TrimRightFunc(*msg.Message(), func(r rune) bool {
			return unicode.IsSpace(r)
		})
	}

	if msg.StructuredData() != nil {
		for sdid, sdparams := range *msg.StructuredData() {
			if len(sdparams) == 0 {
				// When SD-ID does not have params we indicate its presence with a bool
				flds[sdid] = true
				continue
			}
			for name, value := range sdparams {
				// Using whitespace as separator since it is not allowed by the grammar within SDID
				flds[sdid+s.Separator+name] = value
			}
		}
	}

	return flds
}

type unixCloser struct {
	path   string
	closer io.Closer
}

func (uc unixCloser) Close() error {
	err := uc.closer.Close()
	os.Remove(uc.path) // ignore error
	return err
}

func (s *Syslog) time() time.Time {
	t := s.now()
	if t == s.lastTime {
		t = t.Add(time.Nanosecond)
	}
	s.lastTime = t
	return t
}

func getNanoNow() time.Time {
	return time.Unix(0, time.Now().UnixNano())
}

func init() {
	receiver := &Syslog{
		Address: ":6514",
		now:     getNanoNow,
		ReadTimeout: &internal.Duration{
			Duration: defaultReadTimeout,
		},
		Separator: "_",
	}

	inputs.Add("syslog", func() telegraf.Input { return receiver })
}


text: default["apache"]["greetings"] = "World"


text:
Usage
======

This document is meant to give a tutorial-like overview of all common tasks
while using Valuehorizon Forex.

The purpose of this app is to provide tools for working with Foreign Exchange Data.
It allows you to calculate and convert one currency to another, compute the mid point
between bid and ask prices, generates dataframe consisting of the currency prices plus more!


text:
(function(){

  'use strict';

  window.console || (window.console = {});
  window.console.log || (window.console.log = function() {});

  var w = 300,
      h = 300,
      r = Math.min(w, h) / 2;

  var color =
    d3
      .scale
      .ordinal()
      .range([
        '#ff7f7f',
        '#7fbfff',
        '#7fffff',
        '#7fffbf',
        '#ffff7f',
        '#ffbf7f'
      ]);

  var arc =
    d3
      .svg
      .arc()
      .outerRadius(r - 10)
      .innerRadius(0);

  var pie =
    d3
      .layout
      .pie()
      .sort(null)
      .value(function(d) {
        return d.radius;
      });

  var svg =
    d3
      .select('body')
      .append('svg')
      .attr('width', w)
      .attr('height', h)
      .attr('class', 'roulette')
      .append('g')
      .attr('transform', 'translate(' + w / 2 + ',' + h / 2 + ')');

  var g =
    svg
      .selectAll('.arc')
      .data(pie([
        { radius: 45, index: 0 },
        { radius: 45, index: 1 },
        { radius: 45, index: 2 },
        { radius: 45, index: 3 },
        { radius: 45, index: 4 },
        { radius: 45, index: 5 }
      ]))
      .enter()
      .append('g')
      .attr('class', 'pocket js-pocket')
      .attr('style', 'opacity: 0.5;')
      .attr('data-arc-index', function(d) {
        return d.data.index;
      })
      .append('path')
      .attr('d', arc)
      .style('fill', function(d) {
        return color(d.data.index);
      });

  //----------------------------------------------------------------------------

  function Pocket(props) {
    this.element = props.element;
  }

  Pocket.prototype.animate = function(props) {
    var delay, duration, loop;

    props || (props = {});

    delay = props.delay || 0;
    duration = props.duration || 0;
    loop = props.loop || 0;

    return Velocity(this.element, {
      opacity: 1
    }, {
      delay: delay,
      duration: duration,
      easing: 'ease-in-out',
      loop: loop
    });
  };

  Pocket.prototype.reset = function(props) {
    var duration;

    props || (props = {});

    duration = props.duration || 0;

    return Velocity(this.element, {
      opacity: 0.5
    }, {
      duration: duration,
      queue: false
    });
  };

  //----------------------------------------------------------------------------

  function Roulette(props) {
    var onReady = props.onReady,
        onStart = props.onStart,
        onPlaying = props.onPlaying,
        onStop = props.onStop;

    this.pockets = props.pockets;

    this.stopIndex = props.stopIndex;
    this.stepDuration = props.stepDuration;
    this.stopThreshold = props.stopThreshold;

    this.index = props.index;
    this.delay = props.delay;
    this.duration = props.duration;
    this.loop = props.loop;

    this.onReady = (typeof onReady === 'function') ? onReady : function() {};
    this.onStart = (typeof onStart === 'function') ? onStart : function() {};
    this.onPlaying = (typeof onPlaying === 'function') ? onPlaying : function() {};
    this.onStop = (typeof onStop  === 'function') ? onStop : function() {};
  }

  Roulette.prototype.states = {
    READY: 0,
    START: 1,
    PLAYING: 2,
    STOP: 3
  };

  Roulette.prototype.ready = function(props) {
    var i, len;

    for (i = 0, len = this.pockets.length; i < len; ++i) {
      this.pockets[i].reset();
    }

    props || (props = {});

    this.index = props.index;
    this.delay = props.delay;
    this.duration = props.duration;
    this.loop = props.loop;

    if (typeof props.onReady === 'function') {
      this.onReady = props.onReady;
    }

    this.state = this.states.READY;
    this.onReady();
  };

  Roulette.prototype.start = function(props) {
    this.state = this.states.START;
    this.onStart();

    props || (props = {});

    this.index || (this.index = props.index);
    this.delay || (this.delay = props.delay);
    this.duration || (this.duration = props.duration);
    this.loop || (this.loop = props.loop);

    if (typeof props.onStart === 'function') {
      this.onStart = props.onStart;
    }

    this.state = this.states.PLAYING;
    this._main();
  };

  Roulette.prototype.stop = function(props) {
    props || (props = {});

    this.stopIndex || (this.stopIndex = props.stopIndex);
    this.stepDuration || (this.stepDuration = props.stepDuration);
    this.stopThreshold || (this.stopThreshold = props.stopThreshold);

    if (typeof props.onStop === 'function') {
      this.onStop = props.onStop;
    }

    this.state = this.states.STOP;
  };

  Roulette.prototype._main = function() {
    var pockets, index, pocket, options, that;

    pockets = this.pockets;
    index = this.index;

    pocket = pockets[index % pockets.length];
    this.index = index = index + 1;

    if (index > pockets.length - 1) {
      this.index = index = 0;
    }

    //--------------------------------------------------------------------------

    if (this.state === this.states.STOP) {
      this.duration += this.stepDuration;
    }

    //--------------------------------------------------------------------------

    options = {
      delay: this.delay,
      duration: this.duration,
      loop: this.loop
    };

    this.onPlaying();

    that = this;

    pocket
      .animate(options)
      .then(function() {
        Velocity(pocket.element, {
          opacity: 0.5
        }, {
          duration: 300
        });

        return Promise.resolve();
      })
      .then(function() {
        if (that.state === that.states.STOP &&
            that.index === that.stopIndex &&
            that.duration > that.stopThreshold) {
              return that.onStop();
        }

        setTimeout(function() {
          that._main();
          that = null;
        }, 0);
      });
  };

  //----------------------------------------------------------------------------

  var pockets = (function(){
    var pocketElements = document.querySelectorAll('.js-pocket');

    var result = [],
        i, len;

    for (i = 0, len = pocketElements.length; i < len; ++i) {
      result.push(new Pocket({
        element: pocketElements[i]
      }));
    }

    return result;
  }());

  //----------------------------------------------------------------------------

  var startButton = document.getElementById('js-start-button'),
      stopButton = document.getElementById('js-stop-button');

  var roulette = new Roulette({
    pockets: pockets,
    onReady: function() {
      console.log('ready');
    },
    onStart: function() {
      console.log('start');
    },
    onPlaying: function() {
      console.log('playing');
    },
    onStop: function() {
      var pocket, options;

      console.log('stop');

      pocket = pockets[roulette.stopIndex];
      options = {
        duration: 100,
        loop: 5
      };

      pocket.animate(options).then(function() {
        Velocity(pocket.element, 'reverse', { duration: 0 });

        startButton.disabled = false;
      });
    }
  });

  startButton.addEventListener('click', function() {
    var options = {
      index: 0,
      delay: 0,
      duration: 75,
      loop: 0
    };

    startButton.disabled = true;
    stopButton.disabled = false;

    roulette.ready(options);
    roulette.start(options);
  }, false);

  stopButton.addEventListener('click', function() {
    stopButton.disabled = true;

    roulette.stop({
      stopIndex: 4,
      stepDuration: 10,
      stopThreshold: 300
    });
  }, false);

}());


text:
<!doctype html>

        <meta charset="utf-8">
        <meta http-equiv="x-ua-compatible" content="ie=edge">
        <title></title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="apple-touch-icon" href="apple-touch-icon.png">

        <link rel="stylesheet" href="css/normalize.css">
        <link rel="stylesheet" href="css/main.css">

        <link href='http://fonts.googleapis.com/css?family=Lora:700' rel='stylesheet' type='text/css'>
        <link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,300' rel='stylesheet' type='text/css'>

I am a Responsive Designer & Developer who thrives on visual storytelling and the best user experience. When I'm not working, pursuing side projects or getting lost in the rabbit hole of blogs and books, I can be found traveling, hiking and searching for new stories.


text:
if node['platform'] == 'ubuntu'
  include_recipe 'desktop::backports'

  if Gem::Version.new(node[:lsb][:release]) < Gem::Version.new('16.04')
    apt_preference 'ubuntu-xenial' do
      glob '*'
      pin 'release n=xenial'
      pin_priority '100'
    end

    apt_preference 'ubuntu-xenial-git' do
      glob 'git'
      pin 'release n=xenial'
      pin_priority '710'
    end

    apt_repository 'xenial' do
      uri node[:ubuntu][:archive_url]
      distribution 'xenial'
      components ['main']
    end
  else
    # Delete the preferences, if present, on 16.04 and above.
    apt_preference 'ubuntu-xenial' do
      action :remove
    end

    apt_preference 'ubuntu-xenial-git' do
      action :remove
    end
  end
end

if node[:lsb][:id] == 'Debian'
  if Gem::Version.new(node[:lsb][:release]) < Gem::Version.new('9.0')
    include_recipe 'desktop::stretch'

    apt_preference 'debian-stretch-git' do
      glob 'git'
      pin 'release n=stretch'
      pin_priority '710'
    end
  else
    apt_preference 'debian-stretch-git' do
      action :remove
    end
  end
end

package 'git' do
  action :upgrade
end


text:
/*
 * ElementaryStream.h
 *
 *  Created on: Jul 18, 2014
 *      Author: satram
 */

#ifndef ELEMENTARYSTREAM_H_
#define ELEMENTARYSTREAM_H_

#include "mt_common.h"

class ElementaryStream {
public:
//	ElementaryStream();
//	virtual ~ElementaryStream();

	virtual void start_recording(int streamtype, int pid);
	virtual void insert_pkt(TsPacket *pkt);
	virtual bool validate_pid(int pid);
	virtual void print_stats();

};

inline void ElementaryStream::start_recording(int streamtype, int pid)
{
}

inline void ElementaryStream::insert_pkt(TsPacket *pkt)
{
}

inline bool ElementaryStream::validate_pid(int pid)
{
	return false;
}

inline void ElementaryStream::print_stats()
{

}

#endif /* ELEMENTARYSTREAM_H_ */


text:
import {Sgfs} from '../../lib/collections';
import {Meteor} from 'meteor/meteor';
import {check} from 'meteor/check';

export default function () {
  Meteor.publish('sgfs.list', function () {
    const selector = {};
    const options = {
      fields: {_id: 1, title: 1},
      sort: {createdAt: -1},
      limit: 1000
    };

    return Sgfs.find(selector, options);
  });

  Meteor.publish('sgfs.single', function (sgfId) {
    check(sgfId, String);
    const selector = {_id: sgfId};
    return Sgfs.find(selector);
  });

}


text:
import { useEnvironment } from "app/store/GlobalStore"
import { useEffect } from "react"
// @ts-expect-error no typings
import stripe from "tipsi-stripe"

export function useStripeConfig() {
  const publishableKey = useEnvironment().stripePublishableKey
  useEffect(() => {
    stripe.setOptions({ publishableKey })
  }, [publishableKey])
}