text:
import os

import py

from pyshark.packet.fields import LayerField
from pyshark.packet.fields import LayerFieldsContainer
from pyshark.packet.layers.base import BaseLayer

class JsonLayer(BaseLayer):
    __slots__ = [
        "duplicate_layers",
        "_showname_fields_converted_to_regular",
        "_full_name",
        "_is_intermediate",
        "_wrapped_fields",
        "value",
        "_all_fields"
    ] + BaseLayer.__slots__

    def __init__(self, layer_name, layer_dict, full_name=None, is_intermediate=False):
        """Creates a JsonLayer. All sublayers and fields are created lazily later."""
        super().__init__(layer_name)
        self.duplicate_layers = []
        self._showname_fields_converted_to_regular = False
        if not full_name:
            self._full_name = self._layer_name
        else:
            self._full_name = full_name
        self._is_intermediate = is_intermediate
        self._wrapped_fields = {}
        if isinstance(layer_dict, list):
            self.duplicate_layers = [JsonLayer(layer_name, duplicate_dict,
                                               full_name=full_name, is_intermediate=is_intermediate)
                                     for duplicate_dict in layer_dict[1:]]
            layer_dict = layer_dict[0]
        if not isinstance(layer_dict, dict):
            self.value = layer_dict
            self._all_fields = {}
            return

        self._all_fields = layer_dict

    def get_field(self, name):
        """Gets a field by its full or partial name."""
        # We only make the wrappers here (lazily) to avoid creating a ton of objects needlessly.
        self._convert_showname_field_names_to_field_names()
        field = self._wrapped_fields.get(name)
        if field is None:
            is_fake = False
            field = self._get_internal_field_by_name(name)
            if field is None:
                # Might be a "fake" field in JSON
                is_fake = self._is_fake_field(name)
                if not is_fake:
                    raise AttributeError("No such field %s" % name)
            field = self._make_wrapped_field(name, field, is_fake=is_fake)
            self._wrapped_fields[name] = field
        return field

    @property
    def field_names(self):
        self._convert_showname_field_names_to_field_names()
        return list(set([self._sanitize_field_name(name) for name in self._all_fields
                         if name.startswith(self._full_name)] +
                        [name.rsplit('.', 1)[1] for name in self._all_fields if '.' in name]))

    def has_field(self, dotted_name) -> bool:
        """Checks whether the layer has the given field name.

        Can get a dotted name, i.e. layer.sublayer.subsublayer.field
        """
        parts = dotted_name.split('.')
        cur_layer = self
        for part in parts:
            if part in cur_layer.field_names:
                cur_layer = cur_layer.get_field(part)
            else:
                return False
        return True

    def _pretty_print_layer_fields(self, terminal_writer: py.io.TerminalWriter):
        for field_line in self._get_all_field_lines():
            if ':' in field_line:
                field_name, field_line = field_line.split(':', 1)
                terminal_writer.write(field_name + ':', green=True, bold=True)
            terminal_writer.write(field_line, bold=True)

    def _get_all_field_lines(self):
        """Returns all lines that represent the fields of the layer (both their names and values)."""
        for field in self._get_all_fields_with_alternates():
            yield from self._get_field_or_layer_repr(field)

    def _get_field_or_layer_repr(self, field):
        if isinstance(field, JsonLayer):
            yield "\t" + field.layer_name + ":" + os.linesep
            for line in field._get_all_field_lines():
                yield "\t" + line
        elif isinstance(field, list):
            for subfield_or_layer in field:
                yield from self._get_field_or_layer_repr(subfield_or_layer)
        else:
            yield f"\t{self._sanitize_field_name(field.name)}: {field.raw_value}{os.linesep}"

    def _sanitize_field_name(self, field_name):
        return field_name.replace(self._full_name + '.', '')

    def _field_name_from_showname(self, field_name):
        """Converts a 'showname'-like field key to a regular field name

        Sometimes in the JSON, there are "text" type fields which might look like this:
        "my_layer":
            {
                "my_layer.some_field": 1,
                "Something Special: it's special": {
                    "my_layer.special_field": "it's special"
                }
            }

        We convert the showname key into the field name. The internals will turn into a fake layer.
        In this case the field will be accessible by pkt.my_layer.something_special.special_field
        """
        showname_key = field_name.split(":", 1)[0]
        return self._full_name + "." + showname_key.lower().replace(" ", "_")

    def _get_all_fields_with_alternates(self):
        return [self.get_field(name) for name in self.field_names]

    def _convert_showname_field_names_to_field_names(self):
        """Converts all fields that don't have a proper name (they have a showname name) to a regular name

        See self._field_name_from_showname docs for more.
        """
        if self._showname_fields_converted_to_regular:
            return
        for field_name in list(self._all_fields):
            if ":" in field_name:
                field_value = self._all_fields.pop(field_name)
                if isinstance(field_value, dict):
                    # Save the showname
                    field_value["showname"] = field_name
                # Convert the old name to the new name.
                self._all_fields[
                    self._field_name_from_showname(field_name)] = field_value

        self._showname_fields_converted_to_regular = True

    def _get_internal_field_by_name(self, name):
        """Gets the field by name, or None if not found."""
        field = self._all_fields.get(name, self._all_fields.get('%s.%s' % (self._full_name, name)))
        if field is not None:
            return field
        for field_name in self._all_fields:
            # Specific name
            if field_name.endswith('.%s' % name):
                return self._all_fields[field_name]

    def _is_fake_field(self, name):
        # Some fields include parts that are not reflected in the JSON dictionary
        # i.e. a possible json is:
        # {
        #   foo: {
        #           foo.bar.baz: {
        #                   foo.baz: 3
        #               }
        # }
        # So in this case we must create a fake layer for "bar".
        field_full_name = '%s.%s.' % (self._full_name, name)
        for name, field in self._all_fields.items():
            if name.startswith(field_full_name):
                return True
        return False

    def _make_wrapped_field(self, name, field, is_fake=False, full_name=None):
        """Creates the field lazily.

        If it's a simple field, wraps it in a container that adds extra features.
        If it's a nested layer, creates a layer for it.
        If it's an intermediate layer, copies over the relevant fields and creates a new layer for
        it.
        """
        if not full_name:
            full_name = '%s.%s' % (self._full_name, name)

        if is_fake:
            # Populate with all fields that are supposed to be inside of it
            field = {key: value for key, value in self._all_fields.items()
                     if key.startswith(full_name)}
        if isinstance(field, dict):
            if name.endswith('_tree'):
                name = name.replace('_tree', '')
                full_name = '%s.%s' % (self._full_name, name)
            return JsonLayer(name, field, full_name=full_name, is_intermediate=is_fake)
        elif isinstance(field, list):
            # For whatever reason in list-type object it goes back to using the original parent name
            return [self._make_wrapped_field(name, field_part,
                                             full_name=self._full_name.split('.')[0])
                    for field_part in field]

        return LayerFieldsContainer(LayerField(name=name, value=field))


text:
use std::mem;
use std::f32;
use enum_set::{EnumSet, CLike};

use linalg::{self, Vector};
use film::Colorf;
use mc;

pub use self::bsdf::BSDF;
pub use self::lambertian::Lambertian;
pub use self::oren_nayar::OrenNayar;
pub use self::specular_reflection::SpecularReflection;
pub use self::specular_transmission::SpecularTransmission;
pub use self::merl::Merl;
pub use self::torrance_sparrow::TorranceSparrow;

pub mod bsdf;
pub mod lambertian;
pub mod oren_nayar;
pub mod fresnel;
pub mod specular_reflection;
pub mod specular_transmission;
pub mod merl;
pub mod microfacet;
pub mod torrance_sparrow;

/// Various types of BxDFs that can be selected to specify which
/// types of surface functions should be evaluated
#[repr(u32)]
#[derive(Clone, Copy, Debug)]
pub enum BxDFType {
    Reflection, Transmission, Diffuse, Glossy, Specular,
}

impl BxDFType {
    /// Get an EnumSet containing all flags for the different types of
    /// BxDFs: Diffuse, Glossy, Specular
    pub fn all_types() -> EnumSet<BxDFType> {
        let mut e = EnumSet::new();
        e.insert(BxDFType::Diffuse);
        e.insert(BxDFType::Glossy);
        e.insert(BxDFType::Specular);
        e
    }
    /// Get an EnumSet containing all flags for reflective BxDFs (eg. BRDFs)
    pub fn all_brdf() -> EnumSet<BxDFType> {
        let mut e = BxDFType::all_types();
        e.insert(BxDFType::Reflection);
        e
    }
    /// Get an EnumSet containing all flags for transmissive BxDFs (eg. BTDFs)
    pub fn all_btdf() -> EnumSet<BxDFType> {
        let mut e = BxDFType::all_types();
        e.insert(BxDFType::Transmission);
        e
    }
    /// Get an EnumSet containing all flags for all BxDFs. This would be all
    /// types of BRDFs and BTDFs
    pub fn all() -> EnumSet<BxDFType> { BxDFType::all_brdf().union(BxDFType::all_btdf()) }
    /// Get an EnumSet containing flags for all types of specular BxDFs
    pub fn specular() -> EnumSet<BxDFType> {
        let mut e = EnumSet::new();
        e.insert(BxDFType::Specular);
        e.insert(BxDFType::Reflection);
        e.insert(BxDFType::Transmission);
        e
    }
    /// Get an EnumSet containing flags for all non-specular BxDFs
    pub fn non_specular() -> EnumSet<BxDFType> {
        let mut e = EnumSet::new();
        e.insert(BxDFType::Diffuse);
        e.insert(BxDFType::Glossy);
        e.insert(BxDFType::Reflection);
        e.insert(BxDFType::Transmission);
        e
    }
}

impl CLike for BxDFType {
    fn to_u32(&self) -> u32 { *self as u32 }
    unsafe fn from_u32(v: u32) -> BxDFType { mem::transmute(v) }
}

/// Trait implemented by BRDF/BTDFs in tray_rust. Provides methods for
/// evaluating and sampling the function
pub trait BxDF {
    /// Get the type of this BxDF
    fn bxdf_type(&self) -> EnumSet<BxDFType>;
    /// Evaluate the BxDF for the pair of incident and outgoing light directions,
    /// `w_i` and `w_o`.
    fn eval(&self, w_o: &Vector, w_i: &Vector) -> Colorf;
    /// Sample an incident light direction for an outgoing light direction `w_o`.
    /// `samples` will be used to randomly sample a direction for the outgoing light
    /// Returns the color of the material for the pair of directions, the incident
    /// light direction and pdf
    fn sample(&self, w_o: &Vector, samples: &(f32, f32)) -> (Colorf, Vector, f32) {
        let mut w_i = mc::cos_sample_hemisphere(samples);
        // We may need to flip the sampled direction to be on the same hemisphere as w_o
        if w_o.z < 0.0 {
            w_i.z *= -1.0;
        }
        (self.eval(w_o, &w_i), w_i, self.pdf(w_o, &w_i))
    }
    /// Check if this BxDF matches the type flags passed
    fn matches(&self, flags: EnumSet<BxDFType>) -> bool {
        self.bxdf_type().is_subset(&flags)
    }
    /// Compute the pdf of sampling the pair of directions passed for this BxDF
    fn pdf(&self, w_o: &Vector, w_i: &Vector) -> f32 {
        if same_hemisphere(w_o, w_i) {
            f32::abs(cos_theta(w_i)) * f32::consts::FRAC_1_PI
        } else {
            0.0
        }
    }
}

/// Compute the value of cosine theta for a vector in shading space
pub fn cos_theta(v: &Vector) -> f32 { v.z }
/// Compute the value of (sine theta)^2  for a vector in shading space
pub fn sin_theta_sqr(v: &Vector) -> f32 { f32::max(0.0, 1.0 - v.z * v.z) }
/// Compute the value of sine theta for a vector in shading space
pub fn sin_theta(v: &Vector) -> f32 { f32::sqrt(sin_theta_sqr(v)) }
/// Compute the value of cosine phi for a vector in shading space
pub fn cos_phi(v: &Vector) -> f32 {
    let sin_theta = sin_theta(v);
    if sin_theta == 0.0 {
        1.0
    } else {
        linalg::clamp(v.x / sin_theta, -1.0, 1.0)
    }
}
/// Compute the value of sine phi for a vector in shading space
pub fn sin_phi(v: &Vector) -> f32 {
    let sin_theta = sin_theta(v);
    if sin_theta == 0.0 {
        0.0
    } else {
        linalg::clamp(v.y / sin_theta, -1.0, 1.0)
    }
}
/// Check if two vectors are in the same hemisphere in shading space
pub fn same_hemisphere(a: &Vector, b: &Vector) -> bool { a.z * b.z > 0.0 }

redpajama_set_name: RedPajamaGithub


text: GLOBAL.app = require('../../server');


text:
var Immutable = require('immutable');
var Cursor = require('immutable/contrib/cursor');
var AnsiParser = require('node-ansiparser');

var BATCH_SIZE = 300;

function LogsModel() {
  this.lines = Immutable.fromJS([[[]]]);
  this.batchCursor = Cursor.from(this.lines, function(newLines) {
    this.lines = newLines;
  }.bind(this));
  this.linesCursor = this.batchCursor.last();
  this.seqsSinceCR = 0;

  this.state = {}

  this.inst_p = function(s) {
    var textLen = s.length;
    var seqsSinceCR = this.seqsSinceCR;

    var cursor = this.cursor.update(function(line) {
      return line.slice(seqsSinceCR);
    });

    this.cursor = this.cursor.update(function(line) {
      return line.slice(0, seqsSinceCR);
    });

    this.pushSequence({
      text: s,
      foreground: this.state.foreground,
      background: this.state.background,
      bold: this.state.bold,
      italic: this.state.italic,
      underline: this.state.underline
    });

    this.seqsSinceCR++;

    cursor.forEach(function(e, i) {
      if(e.text.length >= textLen) {
        e.text = e.text.substr(textLen);
        textLen -= e.text.length;
        this.pushSequence(e);
        return false;
      }
    }, this);

    this.refreshLineCursor();
    this.changed = true;
  }

  this.inst_x = function(flag) {
    switch(flag.charCodeAt(0)) {
    case 10: // LN
      this.pushLine(Immutable.List.of({text: "\n", linebreak: true}))
      this.refreshCursor();
      this.changed = true;
      this.seqsSinceCR = 0;
      break;
    case 13: // CR
      this.seqsSinceCR = 0;
      break;
    default:
      this.inst_p(flag);
      break;
    }
  }

  this.inst_c = function(collected, params, flag) {
    for (var p in params) {
      var ansiCode = params[p];

      if (foregroundColors[ansiCode]) {
        this.state.foreground = foregroundColors[ansiCode];
      } else if (brightForegroundColors[ansiCode]) {
        this.state.foreground = brightForegroundColors[ansiCode];
      } else if (backgroundColors[ansiCode]) {
        this.state.background = backgroundColors[ansiCode];
      } else if (ansiCode == 39) {
        delete this.state.foreground;
      } else if (ansiCode == 49) {
        delete this.state.background;
      } else if (styles[ansiCode]) {
        this.state[styles[ansiCode]] = true;
      } else if (ansiCode == 22) {
        this.state.bold = false;
      } else if (ansiCode == 23) {
        this.state.italic = false;
      } else if (ansiCode == 24) {
        this.state.underline = false;
      } else if (ansiCode == 0) {
        this.state = {};
      }
    }
  }

  var ansiParser = new AnsiParser(this);

  this.addLog = function(line) {
    ansiParser.parse(line);
  };

  this.addError = function(message) {
    this.pushLine(Immutable.List())
    this.refreshCursor();
    this.pushSequence({
      text: message,
      error: true,
    });
    this.refreshLineCursor();
    this.changed = true;
  };

  this.refreshLineCursor = function() {
    this.linesCursor = this.linesCursor.set(this.linesCursor.count() - 1, this.cursor);
  };

  this.refreshCursor = function() {
    this.cursor = this.linesCursor.last();
  };

  this.pushLine = function(line) {
    if (this.linesCursor.count() >= BATCH_SIZE) {
      this.batchCursor = this.batchCursor.set(this.batchCursor.count() - 1, this.linesCursor);
      this.batchCursor = this.batchCursor.update(function(batches) {
        return batches.push(Immutable.List.of(line));
      });
      this.linesCursor = this.batchCursor.last();
    } else {
      this.linesCursor = this.linesCursor.update(function(lines) {
        return lines.push(line);
      });
    }
  };

  this.pushSequence = function(sequence) {
    this.cursor = this.cursor.update(function(line) {
      return line.push(sequence);
    });
  };

  this.refreshCursor();
  this.changed = false;
}

var foregroundColors = {
  30: 'black',
  31: 'red',
  32: 'green',
  33: 'yellow',
  34: 'blue',
  35: 'magenta',
  36: 'cyan',
  37: 'white',
};

var brightForegroundColors = {
  90: 'bright-black',
  91: 'bright-red',
  92: 'bright-green',
  93: 'bright-yellow',
  94: 'bright-blue',
  95: 'bright-magenta',
  96: 'bright-cyan',
  97: 'bright-white',
};

var backgroundColors = {
  40: 'black',
  41: 'red',
  42: 'green',
  43: 'yellow',
  44: 'blue',
  45: 'magenta',
  46: 'cyan',
  47: 'white'
};

var styles = {
  1: 'bold',
  3: 'italic',
  4: 'underline'
};

module.exports = LogsModel;


text:
<?php

namespace Fuel\Tasks;

/**
 * Sessions DB Table Task
 *
 * @PullRequest https://github.com/fuel/core/pull/786
 *
 * Run this task to set add/remove/clear the db sessions table
 * Table name will be generated from your config file.
 * for your app. This could be expanded in app/tasks for application specific stuff.
 *
 * @package Fuel
 * @version 1.1
 * @author Daniel Berry
 * @license MIT License
 *
 *          Usage:
 *          php oil r session = will prompt with menu
 *          php oil r session:create = create the db table.
 *          php oil r session:remove = remove the sessions table
 *          php oil r session:clear = clear the sessions table
 */
class Session {

	// default function if no command is selected. Provided user with menu
	public static function run() {
		// Prompt the user with menu options
		$option = \Cli::prompt ( 'What would you like to do?', array (
				'create',
				'remove',
				'clear',
				'help'
		) );

		switch ($option) {
			case "create" :
				return static::create ();
				break;
			case "remove" :
				return static::remove ();
				break;
			case "clear" :
				return static::clear ();
				break;
			default :
				return static::help ();
				break;
		}
	}

	/**
	 * create the sessions table
	 * php oil r session:create
	 */
	public static function create() {
		// load session config
		\Config::load ( 'session', true );

		if (\Config::get ( 'session.driver' ) != 'db') {
			// prompt the user to confirm they want to remove the table.
			$continue = \Cli::prompt ( \Cli::color ( 'Your current driver type is not set db. Would you like to continue and add the sessions table anyway?', 'yellow' ), array (
					'y',
					'n'
			) );

			if ($continue === 'n') {
				return \Cli::color ( 'Database sessions table was not created.', 'red' );
			}
		}

		if (\DBUtil::table_exists ( \Config::get ( 'session.db.table' ) )) {
			return \Cli::write ( 'Session table already exists.' );
		}

		// create the session table using the table name from the config file
		\DBUtil::create_table ( \Config::get ( 'session.db.table' ), array (
				'session_id' => array (
						'constraint' => 40,
						'type' => 'varchar'
				),
				'previous_id' => array (
						'constraint' => 40,
						'type' => 'varchar'
				),
				'user_agent' => array (
						'type' => 'text',
						'null' => false
				),
				'ip_hash' => array (
						'constraint' => 32,
						'type' => 'char'
				),
				'created' => array (
						'constraint' => 10,
						'type' => 'int',
						'unsigned' => true
				),
				'updated' => array (
						'constraint' => 10,
						'type' => 'int',
						'unsigned' => true
				),
				'payload' => array (
						'type' => 'longtext'
				)
		), array (
				'session_id'
		), false, 'InnoDB', \Config::get ( 'db.default.charset' ) );

		// make previous_id a unique_key. speeds up query and prevents duplicate id's
		\DBUtil::create_index ( \Config::get ( 'session.db.table' ), 'previous_id', 'previous_id', 'unique' );

		if (\Config::get ( 'session.driver' ) === 'db') {
			// return success message.
			return \Cli::color ( 'Success! Your session table has been created!', 'green' );
		} else {
			// return success message notifying that the driver is not db.
			return \Cli::color ( 'Success! Your session table has been created! Your current session driver type is set to ' . \Config::get ( 'session.driver' ) . '. In order to use the table you just created to manage your sessions, you will need to set your driver type to "db" in your session config file.', 'green' );
		}
	}

	/**
	 * remove the sessions table
	 * php oil r session:remove
	 */
	public static function remove() {
		// load session config
		\Config::load ( 'session', true );

		// prompt the user to confirm they want to remove the table.
		$iamsure = \Cli::prompt ( 'Are you sure you want to delete the sessions table?', array (
				'y',
				'n'
		) );

		// if they are sure, then let's drop it
		if ($iamsure === 'y') {
			\DBUtil::drop_table ( \Config::get ( 'session.db.table' ) );
			return \Cli::color ( 'Session database table deleted.', 'green' );
		}

		// if we made it to here, than that means the user said no.
		return \Cli::color ( 'Session database table was not deleted.', 'red' );
	}

	/**
	 * clear the sessions table
	 * php oil r session:clear
	 */
	public static function clear() {
		// load session config
		\Config::load ( 'session', true );

		// prompt the user to confirm they want to clear the table.
		$iamsure = \Cli::prompt ( 'Are you sure you want to clear the sessions table?', array (
				'y',
				'n'
		) );

		// if they are sure, then let's drop it
		if ($iamsure === 'y') {
			\DBUtil::truncate_table ( \Config::get ( 'session.db.table' ) );
			return \Cli::color ( 'Session database table successfully truncated.', 'green' );
		}

		// if we made it to here, than that means the user said no.
		return \Cli::color ( 'Session database table was not cleared.', 'red' );
	}

	/**
	 * Shows basic help instructions for using migrate in oil
	 */
	public static function help() {
		echo <<<HELP
            Usage:
                php oil refine session

            Description:
                The session task will create the necessary db tables.

            Examples:
                php oil r session:create
                php oil r session:remove
                php oil r session:clear
                php oil r session:help

HELP;
	}
}

/* End of file tasks/session.php */


text:
<?xml version="1.0" encoding="UTF-8"?>
<document xmlns="http://commonmark.org/xml/1.0">
    <table_of_contents type="bullet" tight="false">
        <item>
            <link destination="#content-a-level-2-heading-to-start" title="">
                <text>A level 2 heading to start</text>
            </link>
        </item>
        <item>
            <link destination="#content-followed-by-a-level-4" title="">
                <text>Followed by a level 4</text>
            </link>
        </item>
        <item>
            <link destination="#content-then-a-level-1" title="">
                <text>Then a level 1</text>
            </link>
        </item>
        <item>
            <link destination="#content-and-another-level-2" title="">
                <text>And another level 2</text>
            </link>
        </item>
        <item>
            <link destination="#content-then-a-level-5" title="">
                <text>Then a level 5</text>
            </link>
        </item>
        <item>
            <link destination="#content-and-then-a-level-3" title="">
                <text>And then a level 3</text>
            </link>
        </item>
        <item>
            <link destination="#content-followed-by-a-level-6" title="">
                <text>Followed by a level 6</text>
            </link>
        </item>
        <item>
            <link destination="#content-then-another-level-3" title="">
                <text>Then another level 3</text>
            </link>
        </item>
        <item>
            <link destination="#content-then-level-4" title="">
                <text>Then level 4</text>
            </link>
        </item>
        <item>
            <link destination="#content-level-3" title="">
                <text>Level 3</text>
            </link>
        </item>
        <item>
            <link destination="#content-level-2" title="">
                <text>Level 2</text>
            </link>
        </item>
        <item>
            <link destination="#content-level-4" title="">
                <text>Level 4</text>
            </link>
        </item>
        <item>
            <link destination="#content-level-1" title="">
                <text>Level 1</text>
            </link>
        </item>
    </table_of_contents>
    <paragraph>
        <text>Here's a sample Markdown document with weird headings</text>
    </paragraph>
    <heading level="2">
        <heading_permalink slug="a-level-2-heading-to-start" />
        <text>A level 2 heading to start</text>
    </heading>
    <heading level="4">
        <heading_permalink slug="followed-by-a-level-4" />
        <text>Followed by a level 4</text>
    </heading>
    <heading level="1">
        <heading_permalink slug="then-a-level-1" />
        <text>Then a level 1</text>
    </heading>
    <heading level="2">
        <heading_permalink slug="and-another-level-2" />
        <text>And another level 2</text>
    </heading>
    <heading level="5">
        <heading_permalink slug="then-a-level-5" />
        <text>Then a level 5</text>
    </heading>
    <heading level="3">
        <heading_permalink slug="and-then-a-level-3" />
        <text>And then a level 3</text>
    </heading>
    <heading level="6">
        <heading_permalink slug="followed-by-a-level-6" />
        <text>Followed by a level 6</text>
    </heading>
    <heading level="3">
        <heading_permalink slug="then-another-level-3" />
        <text>Then another level 3</text>
    </heading>
    <heading level="4">
        <heading_permalink slug="then-level-4" />
        <text>Then level 4</text>
    </heading>
    <heading level="3">
        <heading_permalink slug="level-3" />
        <text>Level 3</text>
    </heading>
    <heading level="2">
        <heading_permalink slug="level-2" />
        <text>Level 2</text>
    </heading>
    <heading level="4">
        <heading_permalink slug="level-4" />
        <text>Level 4</text>
    </heading>
    <heading level="1">
        <heading_permalink slug="level-1" />
        <text>Level 1</text>
    </heading>
</document>


text:
#ifndef _EASYSPRPACKER_PACK_SHAPE_SPR_H_
#define _EASYSPRPACKER_PACK_SHAPE_SPR_H_

#include "PackNode.h"

#include <memory>

namespace eshape { class Sprite; }

namespace esprpacker
{

class PackShapeSpr : public PackNode
{
public:
	PackShapeSpr(const std::shared_ptr<eshape::Sprite>& spr);
	virtual ~PackShapeSpr();

	/**
	 *  @interface
	 *    lua
	 */
	virtual void PackToLuaString(ebuilder::CodeGenerator& gen,
		const ee::TexturePacker& tp) const override;

	/**
	 *  @interface
	 *    bin
	 */
	virtual int SizeOfUnpackFromBin() const override;
	virtual int SizeOfPackToBin() const override;
	virtual void PackToBin(uint8_t** ptr, const ee::TexturePacker& tp) const override;

	bool Equal(const std::shared_ptr<eshape::Sprite>& spr) const { return true; }

private:
	const PackNode* m_sym;

}; // PackShapeSpr

}

#endif // _EASYSPRPACKER_PACK_SHAPE_SPR_H_


text:
@interface PodsDummy_Pods_InkChatTests : NSObject
@end
@implementation PodsDummy_Pods_InkChatTests
@end


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.

package com.azure.storage.file.datalake;

import com.azure.core.annotation.ServiceClient;
import com.azure.core.credential.TokenCredential;
import com.azure.core.http.HttpPipeline;
import com.azure.core.http.rest.PagedFlux;
import com.azure.core.http.rest.Response;
import com.azure.core.http.rest.SimpleResponse;
import com.azure.core.util.CoreUtils;
import com.azure.core.util.FluxUtil;
import com.azure.core.util.logging.ClientLogger;
import com.azure.storage.blob.BlobServiceAsyncClient;
import com.azure.storage.common.StorageSharedKeyCredential;
import com.azure.storage.common.Utility;
import com.azure.storage.common.implementation.StorageImplUtils;
import com.azure.storage.common.sas.AccountSasSignatureValues;
import com.azure.storage.file.datalake.implementation.DataLakeStorageClientBuilder;
import com.azure.storage.file.datalake.implementation.DataLakeStorageClientImpl;
import com.azure.storage.file.datalake.implementation.util.DataLakeImplUtils;
import com.azure.storage.file.datalake.models.DataLakeRequestConditions;
import com.azure.storage.file.datalake.models.FileSystemItem;
import com.azure.storage.file.datalake.models.ListFileSystemsOptions;
import com.azure.storage.file.datalake.models.PublicAccessType;
import com.azure.storage.file.datalake.models.UserDelegationKey;
import reactor.core.publisher.Mono;

import java.time.OffsetDateTime;
import java.util.Map;

import static com.azure.core.util.FluxUtil.monoError;
import static com.azure.core.util.FluxUtil.pagedFluxError;

/**
 * Client to a storage account. It may only be instantiated through a {@link DataLakeServiceClientBuilder}. This class
 * does not hold any state about a particular storage account but is instead a convenient way of sending off appropriate
 * requests to the resource on the service. It may also be used to construct URLs to file systems, files and
 * directories.
 *
 *

 * This client contains operations on the main data lake service account. Operations on a file system are available on
 * {@link DataLakeFileSystemAsyncClient} through {@link #getFileSystemAsyncClient(String)}, and operations on a file or
 * directory are available on {@link DataLakeFileAsyncClient} or {@link DataLakeDirectoryAsyncClient}.
 *
 *

 * Note this client is an async client that returns reactive responses from Spring Reactor Core project
 * (https://projectreactor.io/). Calling the methods in this client will NOT start the actual network
 * operation, until {@code .subscribe()} is called on the reactive response. You can simply convert one of these
 * responses to a {@link java.util.concurrent.CompletableFuture} object through {@link Mono#toFuture()}.
 */
@ServiceClient(builder = DataLakeServiceClientBuilder.class, isAsync = true)
public class DataLakeServiceAsyncClient {
    private final ClientLogger logger = new ClientLogger(DataLakeServiceAsyncClient.class);

    private final DataLakeStorageClientImpl azureDataLakeStorage;

    private final String accountName;
    private final DataLakeServiceVersion serviceVersion;

    private final BlobServiceAsyncClient blobServiceAsyncClient;

    /**
     * Package-private constructor for use by {@link DataLakeServiceClientBuilder}.
     *
     * @param pipeline The pipeline used to send and receive service requests.
     * @param url The endpoint where to send service requests.
     * @param serviceVersion The version of the service to receive requests.
     * @param accountName The storage account name.
     * @param blobServiceAsyncClient The underlying {@link BlobServiceAsyncClient}
     */
    DataLakeServiceAsyncClient(HttpPipeline pipeline, String url, DataLakeServiceVersion serviceVersion,
        String accountName, BlobServiceAsyncClient blobServiceAsyncClient) {
        this.azureDataLakeStorage = new DataLakeStorageClientBuilder()
            .pipeline(pipeline)
            .url(url)
            .version(serviceVersion.getVersion())
            .build();
        this.serviceVersion = serviceVersion;

        this.accountName = accountName;

        this.blobServiceAsyncClient = blobServiceAsyncClient;
    }

    /**
     * Initializes a {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system. This method
     * does not create a file system. It simply constructs the URL to the file system and offers access to methods
     * relevant to file systems.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getFileSystemAsyncClient#String}
     *
     * @param fileSystemName The name of the file system to point to. A value of null or empty string will be
     * interpreted as pointing to the root file system and will be replaced by "$root".
     * @return A {@link DataLakeFileSystemAsyncClient} object pointing to the specified file system
     */
    public DataLakeFileSystemAsyncClient getFileSystemAsyncClient(String fileSystemName) {
        if (CoreUtils.isNullOrEmpty(fileSystemName)) {
            fileSystemName = DataLakeFileSystemAsyncClient.ROOT_FILESYSTEM_NAME;
        }
        return new DataLakeFileSystemAsyncClient(getHttpPipeline(),
            StorageImplUtils.appendToUrlPath(getAccountUrl(), Utility.urlEncode(Utility.urlDecode(fileSystemName)))
                .toString(), getServiceVersion(), getAccountName(), fileSystemName,
            blobServiceAsyncClient.getBlobContainerAsyncClient(fileSystemName)
        );
    }

    /**
     * Gets the {@link HttpPipeline} powering this client.
     *
     * @return The pipeline.
     */
    public HttpPipeline getHttpPipeline() {
        return azureDataLakeStorage.getHttpPipeline();
    }

    /**
     * Gets the service version the client is using.
     *
     * @return the service version the client is using.
     */
    public DataLakeServiceVersion getServiceVersion() {
        return serviceVersion;
    }

    /**
     * Creates a new file system within a storage account. If a file system with the same name already exists, the
     * operation fails. For more information, see the
     * Azure Docs.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystem#String}
     *
     * @param fileSystemName Name of the file system to create
     * @return A {@link Mono} containing a {@link DataLakeFileSystemAsyncClient} used to interact with the file system
     * created.
     */
    public Mono<DataLakeFileSystemAsyncClient> createFileSystem(String fileSystemName) {
        try {
            return createFileSystemWithResponse(fileSystemName, null, null).flatMap(FluxUtil::toMono);
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Creates a new file system within a storage account. If a file system with the same name already exists, the
     * operation fails. For more information, see the
     * Azure Docs.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.createFileSystemWithResponse#String-Map-PublicAccessType}
     *
     * @param fileSystemName Name of the file system to create
     * @param metadata Metadata to associate with the file system
     * @param accessType Specifies how the data in this file system is available to the public. See the
     * x-ms-blob-public-access header in the Azure Docs for more information. Pass null for no public access.
     * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} contains a {@link
     * DataLakeFileSystemAsyncClient} used to interact with the file system created.
     */
    public Mono<Response<DataLakeFileSystemAsyncClient>> createFileSystemWithResponse(String fileSystemName,
        Map<String, String> metadata, PublicAccessType accessType) {
        try {
            DataLakeFileSystemAsyncClient dataLakeFileSystemAsyncClient = getFileSystemAsyncClient(fileSystemName);

            return dataLakeFileSystemAsyncClient.createWithResponse(metadata, accessType).
                map(response -> new SimpleResponse<>(response, dataLakeFileSystemAsyncClient));
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
     * For more information see the Azure
     * Docs.
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystem#String}
     *
     * @param fileSystemName Name of the file system to delete
     * @return A reactive response signalling completion.
     */
    public Mono<Void> deleteFileSystem(String fileSystemName) {
        try {
            return deleteFileSystemWithResponse(fileSystemName, null).flatMap(FluxUtil::toMono);
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Deletes the specified file system in the storage account. If the file system doesn't exist the operation fails.
     * For more information see the Azure
     * Docs.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.deleteFileSystemWithResponse#String-DataLakeRequestConditions}
     *
     * @param fileSystemName Name of the file system to delete
     * @param requestConditions {@link DataLakeRequestConditions}
     * @return A {@link Mono} containing containing status code and HTTP headers
     */
    public Mono<Response<Void>> deleteFileSystemWithResponse(String fileSystemName,
        DataLakeRequestConditions requestConditions) {
        try {
            return getFileSystemAsyncClient(fileSystemName).deleteWithResponse(requestConditions);
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Gets the URL of the storage account represented by this client.
     *
     * @return the URL.
     */
    public String getAccountUrl() {
        return azureDataLakeStorage.getUrl();
    }

    /**
     * Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
     * information, see the Azure Docs.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems}
     *
     * @return A reactive response emitting the list of file systems.
     */
    public PagedFlux<FileSystemItem> listFileSystems() {
        try {
            return this.listFileSystems(new ListFileSystemsOptions());
        } catch (RuntimeException ex) {
            return pagedFluxError(logger, ex);
        }
    }

    /**
     * Returns a reactive Publisher emitting all the file systems in this account lazily as needed. For more
     * information, see the Azure Docs.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.listFileSystems#ListFileSystemsOptions}
     *
     * @param options A {@link ListFileSystemsOptions} which specifies what data should be returned by the service.
     * @return A reactive response emitting the list of file systems.
     */
    public PagedFlux<FileSystemItem> listFileSystems(ListFileSystemsOptions options) {
        try {
            return blobServiceAsyncClient.listBlobContainers(Transforms.toListBlobContainersOptions(options))
//                .onErrorMap(ex -> DataLakeImplUtils.transformBlobStorageException((BlobStorageException) ex))
                .mapPage(Transforms::toFileSystemItem);
        } catch (RuntimeException ex) {
            return pagedFluxError(logger, ex);
        }
    }

    /**
     * Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
     * when using {@link TokenCredential} in this object's {@link HttpPipeline}.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKey#OffsetDateTime-OffsetDateTime}
     *
     * @param start Start time for the key's validity. Null indicates immediate start.
     * @param expiry Expiration of the key's validity.
     * @return A {@link Mono} containing the user delegation key.
     * @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
     * @throws NullPointerException If {@code expiry} is null.
     */
    public Mono<UserDelegationKey> getUserDelegationKey(OffsetDateTime start, OffsetDateTime expiry) {
        try {
            return this.getUserDelegationKeyWithResponse(start, expiry).flatMap(FluxUtil::toMono);
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Gets a user delegation key for use with this account's data lake storage. Note: This method call is only valid
     * when using {@link TokenCredential} in this object's {@link HttpPipeline}.
     *
     *
Code Samples

     *
     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.getUserDelegationKeyWithResponse#OffsetDateTime-OffsetDateTime}
     *
     * @param start Start time for the key's validity. Null indicates immediate start.
     * @param expiry Expiration of the key's validity.
     * @return A {@link Mono} containing a {@link Response} whose {@link Response#getValue() value} containing the user
     * delegation key.
     * @throws IllegalArgumentException If {@code start} isn't null and is after {@code expiry}.
     * @throws NullPointerException If {@code expiry} is null.
     */
    public Mono<Response<UserDelegationKey>> getUserDelegationKeyWithResponse(OffsetDateTime start,
        OffsetDateTime expiry) {
        try {
            return blobServiceAsyncClient.getUserDelegationKeyWithResponse(start, expiry)
                .onErrorMap(DataLakeImplUtils::transformBlobStorageException)
                .map(response ->
                new SimpleResponse<>(response, Transforms.toDataLakeUserDelegationKey(response.getValue())));
        } catch (RuntimeException ex) {
            return monoError(logger, ex);
        }
    }

    /**
     * Get associated account name.
     *
     * @return account name associated with this storage resource.
     */
    public String getAccountName() {
        return this.accountName;
    }

    /**
     * Generates an account SAS for the Azure Storage account using the specified {@link AccountSasSignatureValues}.
     * Note : The client must be authenticated via {@link StorageSharedKeyCredential}
     *
See {@link AccountSasSignatureValues} for more information on how to construct an account SAS.

     *
     *
The snippet below generates a SAS that lasts for two days and gives the user read and list access to file
     * systems and file shares.

     * {@codesnippet com.azure.storage.file.datalake.DataLakeServiceAsyncClient.generateAccountSas#AccountSasSignatureValues}
     *
     * @param accountSasSignatureValues {@link AccountSasSignatureValues}
     *
     * @return A {@code String} representing all SAS query parameters.
     */
    public String generateAccountSas(AccountSasSignatureValues accountSasSignatureValues) {
        return blobServiceAsyncClient.generateAccountSas(accountSasSignatureValues);
    }

}


text:
//
//  DevicesViewController.m
//  CustomKMLPlayer
//
//  Created by Petro Ladkin on 15.05.15.
//  Copyright (c) 2015 PeLa. All rights reserved.
//

#import "SourcesViewController.h"
#import "FileSystemViewController.h"

#import "KWMLDeviceTableViewCell.h"
#import "LocalStorageTableViewCell.h"

#import "KWMLDeviceManager.h"
#import "LocalStorageManager.h"

#import "WebDavFileSystem.h"
#import "LocalFileSystem.h"

//#import "InMemmoryCoreDataManager.h"

@interface SourcesViewController () <UITableViewDataSource, UITableViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (strong, nonatomic) UIActivityIndicatorView* busyIndicator;
@property (strong, nonatomic) UIRefreshControl* tableRefreshControl;

@property (weak, nonatomic) KWMLDeviceInfo* kwmlDevice;
@property (weak, nonatomic) LocalStorageInfo* localStorage;

@end

@implementation SourcesViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.tableRefreshControl = [[UIRefreshControl alloc] init];
    [self.tableView addSubview:self.tableRefreshControl];
    [self.tableRefreshControl addTarget:self action:@selector(refreshTable) forControlEvents:UIControlEventValueChanged];

    self.busyIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    self.busyIndicator.hidesWhenStopped = YES;
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:self.busyIndicator];

    self.kwmlDevice = nil;
    self.localStorage = nil;

    NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
    [nc addObserver:self selector:@selector(deviceManagerWillUpdateDeviceList:) name:DeviceManagerWillUpdateDeviceList object:nil];
    [nc addObserver:self selector:@selector(deviceManagerDidUpdateDeviceList:) name:DeviceManagerDidUpdateDeviceList object:nil];
    [nc addObserver:self selector:@selector(deviceManagerFailUpdateDeviceList:) name:DeviceManagerFailUpdateDeviceList object:nil];
    [nc addObserver:self selector:@selector(deviceManagerTimeoutUpdateDeviceList:) name:DeviceManagerTimeoutUpdateDeviceList object:nil];
    [nc addObserver:self selector:@selector(deviceManagerDidUpdateDeviceInfo:) name:DeviceManagerDidUpdateDeviceInfo object:nil];

//    [[KWMLDeviceManager sharedManager] updateDevice];
}

#pragma mark - notifications

- (void)deviceManagerWillUpdateDeviceList:(NSNotification*)notification {
//    if (!self.tableRefreshControl.refreshing) {
//        [self.busyIndicator startAnimating];
//    }
}

- (void)deviceManagerDidUpdateDeviceList:(NSNotification*)notification {
    [self.busyIndicator stopAnimating];
    [self.tableRefreshControl endRefreshing];

    self.kwmlDevice = [KWMLDeviceManager sharedManager].device;

    [self.tableView reloadData];
}

- (void)deviceManagerFailUpdateDeviceList:(NSNotification*)notification {
    [self.busyIndicator stopAnimating];
    [self.tableRefreshControl endRefreshing];

    self.kwmlDevice = nil;

    [self.tableView reloadData];
}

- (void)deviceManagerTimeoutUpdateDeviceList:(NSNotification*)notification {
    [self.busyIndicator stopAnimating];
    [self.tableRefreshControl endRefreshing];

    self.kwmlDevice = nil;

    [self.tableView reloadData];
}

- (void)deviceManagerDidUpdateDeviceInfo:(NSNotification*)notification {
    self.kwmlDevice = [KWMLDeviceManager sharedManager].device;
    [self.tableView reloadData];
}

#pragma mark - events

- (void)refreshTable {
    [[KWMLDeviceManager sharedManager] updateDevice];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1 /*devices*/ + 1 /*local storage*/;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.kwmlDevice != nil ? 1 : 0;
    } else if (section == 1) {
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString* cellDevice = @"cellKWMLDevice";
    static NSString* cellLocalStorage = @"cellLocalStorage";

    UITableViewCell* cell = nil;
    if (indexPath.section == 0) {
        KWMLDeviceTableViewCell* dcell = [self.tableView dequeueReusableCellWithIdentifier:cellDevice];

        [dcell update:self.kwmlDevice];
        cell = dcell;
    } else if (indexPath.section == 1) {
        LocalStorageTableViewCell* lscell = [self.tableView dequeueReusableCellWithIdentifier:cellLocalStorage];

        cell = lscell;
    } else {

    }

    return cell;
}

#pragma mark - UITableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];

    FileSystemViewController* fsvc = [self.storyboard instantiateViewControllerWithIdentifier:@"FileSystemViewController"];
    if (indexPath.section == 0) {
        [fsvc setRootPath:@"/" ofFileSystem:[WebDavFileSystem fileSystemWithUrl:self.kwmlDevice.url userName:@"" andPassword:@""]];
    } else if (indexPath.section == 1) {
        NSURL* rootPath = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];

        [fsvc setRootPath:@"/" ofFileSystem:[LocalFileSystem fileSystemWithRootPath:rootPath.path]];
    } else {
    }
    [self.navigationController pushViewController:fsvc animated:YES];
}

@end


text:
package org.apache.ignite.internal.metric;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.Spliterators;
import java.util.concurrent.CountDownLatch;
import java.util.stream.StreamSupport;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.apache.ignite.internal.IgniteInternalFuture;
import org.apache.ignite.internal.processors.metric.MetricRegistry;
import org.apache.ignite.internal.processors.metric.impl.AtomicLongMetric;
import org.apache.ignite.internal.processors.metric.impl.BooleanMetricImpl;
import org.apache.ignite.internal.processors.metric.impl.DoubleMetricImpl;
import org.apache.ignite.internal.processors.metric.impl.HistogramMetricImpl;
import org.apache.ignite.internal.processors.metric.impl.HitRateMetric;
import org.apache.ignite.internal.processors.metric.impl.IntMetricImpl;
import org.apache.ignite.internal.processors.metric.impl.LongAdderMetric;
import org.apache.ignite.internal.util.typedef.T2;
import org.apache.ignite.internal.util.typedef.internal.U;
import org.apache.ignite.spi.IgniteSpiException;
import org.apache.ignite.spi.metric.BooleanMetric;
import org.apache.ignite.spi.metric.DoubleMetric;
import org.apache.ignite.spi.metric.IntMetric;
import org.apache.ignite.spi.metric.LongMetric;
import org.apache.ignite.spi.metric.Metric;
import org.apache.ignite.spi.metric.MetricExporterSpi;
import org.apache.ignite.spi.metric.ObjectMetric;
import org.apache.ignite.spi.metric.ReadOnlyMetricManager;
import org.apache.ignite.spi.metric.noop.NoopMetricExporterSpi;
import org.apache.ignite.testframework.GridTestUtils;
import org.apache.ignite.testframework.junits.GridTestKernalContext;
import org.apache.ignite.testframework.junits.common.GridCommonAbstractTest;
import org.jetbrains.annotations.Nullable;
import org.junit.Before;
import org.junit.Test;

import static java.util.Arrays.asList;
import static java.util.stream.Collectors.toSet;
import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.fromFullName;
import static org.apache.ignite.internal.processors.metric.impl.MetricUtils.histogramBucketNames;
import static org.apache.ignite.testframework.GridTestUtils.runAsync;
import static org.junit.Assert.assertArrayEquals;

/** */
public class MetricsSelfTest extends GridCommonAbstractTest {
    /** */
    private MetricRegistry mreg;

    /** */
    @Before
    public void setUp() throws Exception {
        mreg = new MetricRegistry("group", name -> null, name -> null, null);
    }

    /** */
    @Test
    public void testLongCounter() throws Exception {
        AtomicLongMetric l = mreg.longMetric("ltest", "test");

        run(l::increment, 100);

        assertEquals(100 * 100, l.value());

        l.reset();

        assertEquals(0, l.value());
    }

    /** */
    @Test
    public void testLongAdderCounter() throws Exception {
        LongAdderMetric l = mreg.longAdderMetric("latest", "test");

        run(l::increment, 100);

        assertEquals(100 * 100, l.value());

        l.reset();

        assertEquals(0, l.value());
    }

    /** */
    @Test
    public void testDoubleCounter() throws Exception {
        DoubleMetricImpl l = mreg.doubleMetric("dtest", "test");

        run(() -> l.add(1), 100);

        assertEquals(100 * 100f, l.value(), .000001);

        l.reset();

        assertEquals(0, l.value(), .000001);
    }

    /** */
    @Test
    public void testIntCounter() throws Exception {
        IntMetricImpl l = mreg.intMetric("itest", "test");

        run(() -> l.add(1), 100);

        assertEquals(100 * 100, l.value());

        l.reset();

        assertEquals(0, l.value());
    }

    /** */
    @Test
    public void testRegister() throws Exception {
        AtomicLongMetric l = new AtomicLongMetric("rtest", "test");

        mreg.register(l);

        assertEquals(l, mreg.findMetric("rtest"));

        l.reset();

        assertEquals(0, l.value());
    }

    /** */
    @Test
    public void testBooleanMetric() throws Exception {
        final boolean[] v = new boolean[1];

        mreg.register("bmtest", () -> v[0], "test");

        BooleanMetric m = mreg.findMetric("bmtest");

        assertEquals(v[0], m.value());

        v[0] = true;

        assertEquals(v[0], m.value());
    }

    /** */
    @Test
    public void testDoubleMetric() throws Exception {
        final double[] v = new double[] {42};

        mreg.register("dmtest", () -> v[0], "test");

        DoubleMetric m = mreg.findMetric("dmtest");

        assertEquals(v[0], m.value(), 0);

        v[0] = 1;

        assertEquals(v[0], m.value(), 0);
    }

    /** */
    @Test
    public void testIntMetric() throws Exception {
        final int[] v = new int[] {42};

        mreg.register("imtest", () -> v[0], "test");

        IntMetric m = mreg.findMetric("imtest");

        assertEquals(v[0], m.value());

        v[0] = 1;

        assertEquals(v[0], m.value());
    }

    /** */
    @Test
    public void testLongMetric() throws Exception {
        final long[] v = new long[] {42};

        mreg.register("lmtest", () -> v[0], "test");

        LongMetric m = mreg.findMetric("lmtest");

        assertEquals(v[0], m.value());

        v[0] = 1;

        assertEquals(v[0], m.value());
    }

    /** */
    @Test
    public void testObjectMetric() throws Exception {
        final String[] v = new String[] {"42"};

        mreg.register("omtest", () -> v[0], String.class, "test");

        ObjectMetric<String> m = mreg.findMetric("omtest");

        assertEquals(v[0], m.value());

        v[0] = "1";

        assertEquals(v[0], m.value());
    }

    /** */
    @Test
    public void testBooleanGauges() throws Exception {
        BooleanMetricImpl bg = mreg.booleanMetric("bg", "test");

        bg.value(true);

        assertTrue(bg.value());

        bg.reset();

        assertFalse(bg.value());
    }

    /** */
    @Test
    public void testHistogram() throws Exception {
        HistogramMetricImpl h = mreg.histogram("hmtest", new long[] {10, 100, 500}, "test");

        List<IgniteInternalFuture> futs = new ArrayList<>();

        int cnt = 10;

        futs.add(runAsync(() -> {
            for (int i = 0; i < cnt; i++)
                h.value(9);
        }));

        futs.add(runAsync(() -> {
            for (int i = 0; i < cnt * 2; i++)
                h.value(99);
        }));

        futs.add(runAsync(() -> {
            for (int i = 0; i < cnt * 3; i++)
                h.value(500);
        }));

        futs.add(runAsync(() -> {
            for (int i = 0; i < cnt * 4; i++)
                h.value(501);
        }));

        for (IgniteInternalFuture fut : futs)
            fut.get();

        long[] res = h.value();

        assertEquals(cnt, res[0]);
        assertEquals(cnt * 2, res[1]);
        assertEquals(cnt * 3, res[2]);
        assertEquals(cnt * 4, res[3]);
    }

    /** */
    @Test
    public void testGetMetrics() throws Exception {
        MetricRegistry mreg = new MetricRegistry("group", name -> null, name -> null, null);

        mreg.longMetric("test1", "");
        mreg.longMetric("test2", "");
        mreg.longMetric("test3", "");
        mreg.longMetric("test4", "");
        mreg.longMetric("test5", "");

        Set<String> names = new HashSet<>(asList("group.test1", "group.test2", "group.test3", "group.test4",
            "group.test5"));

        Set<String> res = StreamSupport.stream(Spliterators.spliteratorUnknownSize(mreg.iterator(), 0), false)
            .map(Metric::name)
            .collect(toSet());

        assertEquals(names, res);
    }

    /** */
    @Test
    public void testRemove() throws Exception {
        MetricRegistry mreg = new MetricRegistry("group", name -> null, name -> null, null);

        AtomicLongMetric cntr = mreg.longMetric("my.name", null);
        AtomicLongMetric cntr2 = mreg.longMetric("my.name.x", null);

        assertNotNull(cntr);
        assertNotNull(cntr2);

        assertNotNull(mreg.findMetric("my.name"));
        assertNotNull(mreg.findMetric("my.name.x"));

        mreg.remove("my.name");

        assertNull(mreg.findMetric("my.name"));
        assertNotNull(mreg.findMetric("my.name.x"));

        cntr = mreg.longMetric("my.name", null);

        assertNotNull(mreg.findMetric("my.name"));
    }

    /** */
    @Test
    public void testHitRateMetric() throws Exception {
        long rateTimeInterval = 500;

        HitRateMetric metric = mreg.hitRateMetric("testHitRate", null, rateTimeInterval, 10);

        assertEquals(0, metric.value());

        long startTs = U.currentTimeMillis();

        GridTestUtils.runMultiThreaded(metric::increment, 10, "test-thread");

        assertTrue(metric.value() > 0 || U.currentTimeMillis() - startTs > rateTimeInterval);

        U.sleep(rateTimeInterval * 2);

        assertEquals(0, metric.value());

        assertEquals(rateTimeInterval, metric.rateTimeInterval());

        metric.reset(rateTimeInterval * 2, 10);

        assertEquals(rateTimeInterval * 2, metric.rateTimeInterval());
    }

    /** */
    @Test
    public void testHistogramNames() throws Exception {
        HistogramMetricImpl h = new HistogramMetricImpl("test", null, new long[]{10, 50, 500});

        String[] names = histogramBucketNames(h);

        assertArrayEquals(new String[] {
            "test_0_10",
            "test_10_50",
            "test_50_500",
            "test_500_inf"
        }, names);
    }

    /** */
    @Test
    public void testFromFullName() {
        assertEquals(new T2<>("org.apache", "ignite"), fromFullName("org.apache.ignite"));

        assertEquals(new T2<>("org", "apache"), fromFullName("org.apache"));
    }

    /** */
    @Test
    public void testAddBeforeRemoveCompletes() throws Exception {
        MetricExporterSpi checkSpi = new NoopMetricExporterSpi() {
            private ReadOnlyMetricManager registry;

            private Set<String> names = new HashSet<>();

            @Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
                registry.addMetricRegistryCreationListener(mreg -> {
                    assertFalse(mreg.name() + " should be unique", names.contains(mreg.name()));

                    names.add(mreg.name());
                });

                registry.addMetricRegistryRemoveListener(mreg -> names.remove(mreg.name()));
            }

            @Override public void setMetricRegistry(ReadOnlyMetricManager registry) {
                this.registry = registry;
            }
        };

        CountDownLatch rmvStarted = new CountDownLatch(1);
        CountDownLatch rmvCompleted = new CountDownLatch(1);

        MetricExporterSpi blockingSpi = new NoopMetricExporterSpi() {
            private ReadOnlyMetricManager registry;

            @Override public void spiStart(@Nullable String igniteInstanceName) throws IgniteSpiException {
                registry.addMetricRegistryRemoveListener(mreg -> {
                    rmvStarted.countDown();
                    try {
                        rmvCompleted.await();
                    }
                    catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                });
            }

            @Override public void setMetricRegistry(ReadOnlyMetricManager registry) {
                this.registry = registry;
            }
        };

        IgniteConfiguration cfg = new IgniteConfiguration().setMetricExporterSpi(blockingSpi, checkSpi);

        GridTestKernalContext ctx = new GridTestKernalContext(log(), cfg);

        ctx.start();

        // Add metric registry.
        ctx.metric().registry("test");

        // Removes it async, blockingSpi will block remove procedure.
        IgniteInternalFuture rmvFut = runAsync(() -> ctx.metric().remove("test"));

        rmvStarted.await();

        CountDownLatch addStarted = new CountDownLatch(1);

        IgniteInternalFuture addFut = runAsync(() -> {
            addStarted.countDown();

            ctx.metric().registry("test");
        });

        // Waiting for creation to start.
        addStarted.await();

        Thread.sleep(100);

        // Complete removal.
        rmvCompleted.countDown();

        rmvFut.get(getTestTimeout());

        addFut.get(getTestTimeout());
    }

    /** */
    private void run(Runnable r, int cnt) throws org.apache.ignite.IgniteCheckedException {
        List<IgniteInternalFuture> futs = new ArrayList<>();

        for (int i = 0; i < cnt; i++) {
            futs.add(runAsync(() -> {
                for (int j = 0; j < cnt; j++)
                    r.run();
            }));
        }

        for (IgniteInternalFuture fut : futs)
            fut.get();
    }
}


text:
 Work Experience

Place of Work: Rootstack SA

Role:  Drupal 7 Developer

Time Worked:   December 2016 - August 2017

Key Functions:

Theming and styling drupal twigs and template files to match design provided by the design department.

Testing responsiveness of modules, features and new pages in Drupal 7.

Custom module creation, administration, maintenance and general development process.

Feature creation for easier maintenance and deployment


text:
import json, os
from flask_assets import Filter, register_filter

class AngularTemplateCacheFilter(Filter):
    """ A Flask-Assets filter for compressing AngularJS templates and storing
        them in the $templateCache to improve application performance.
    """

    angular_module = 'flask-assets-templates'
    name = 'angulartemplatecache'

    template_start = "angular.module('%s', []).run(['$templateCache', function($templateCache) {\n"
    template_file  = "  $templateCache.put('{rel_path}', {escaped_html});\n"
    template_end   = "}]);\n"

    def input(self, _in, out, source_path=None, **kwargs):
        """ prepare each file before concatenating """
        #base_path = os.path.dirname(source_path)
        rel_path = source_path[source_path.index('/static/partials'):]
        html_template = _in.read()
        out.write(self.template_file.format(rel_path=rel_path, escaped_html=json.dumps(html_template)))

    def output(self, _in, out, output_path=None, **kwargs):
        """ after concatenating, just throw it back out """
        out.write(self.template_start  % (self.angular_module)) #js brace breaks .format
        out.write(_in.read())
        out.write(self.template_end)

register_filter(AngularTemplateCacheFilter)


text:
module Facts
  module Macosx
    module SystemProfiler
      class Processors
        FACT_NAME = 'system_profiler.processors'
        ALIASES = 'sp_packages'

        def call_the_resolver
          fact_value = Facter::Resolvers::Macosx::SystemProfiler.resolve(:number_of_processors)
          [Facter::ResolvedFact.new(FACT_NAME, fact_value), Facter::ResolvedFact.new(ALIASES, fact_value, :legacy)]
        end
      end
    end
  end
end


text:
__author__ = 'lobocv'
__version__ = '1.13'

from distutils.core import setup

setup(
    name='crashreporter',
    packages=['crashreporter'],  # this must be the same as the name above
    package_dir={'crashreporter': 'crashreporter'},
    package_data={'crashreporter': ['*.html']},
    version=__version__,
    description='Track and send crash reports by email or FTP',
    author='Calvin Lobo',
    author_email='calvinvlobo@gmail.com',
    license='MIT',
    url='https://github.com/lobocv/crashreporter',
    download_url='https://github.com/lobocv/crashreporter/tarball/%s' % __version__,
    keywords=['crash', 'reporting', 'testing', 'debugging', 'bugs'],
    classifiers=[],
    install_requires=["Jinja2==2.8",
                      "requests==2.8.1"]
)


text:
package com.google.common.cache;

import static com.google.common.truth.Truth.assertThat;

import java.util.concurrent.TimeUnit;
import java.util.function.IntConsumer;
import java.util.stream.IntStream;
import junit.framework.TestCase;

/** Test Java8 map.compute in concurrent cache context. */
public class LocalCacheMapComputeTest extends TestCase {
  final int count = 10000;
  final String delimiter = "-";
  final String key = "key";
  Cache<String, String> cache;

  // helper
  private static void doParallelCacheOp(int count, IntConsumer consumer) {
    IntStream.range(0, count).parallel().forEach(consumer);
  }

  @Override
  public void setUp() throws Exception {
    super.setUp();
    this.cache =
        CacheBuilder.newBuilder()
            .expireAfterAccess(500000, TimeUnit.MILLISECONDS)
            .maximumSize(count)
            .build();
  }

  public void testComputeIfAbsent() {
    // simultaneous insertion for same key, expect 1 winner
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().computeIfAbsent(key, k -> "value" + n);
        });
    assertEquals(1, cache.size());
  }

  public void testComputeIfAbsentEviction() {
    // b/80241237

    Cache<String, String> c = CacheBuilder.newBuilder().maximumSize(1).build();

    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.asMap().computeIfAbsent("hash-1", k -> "")).isEqualTo("");
    assertThat(c.size()).isEqualTo(1);
    assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
  }

  public void testComputeEviction() {
    // b/80241237

    Cache<String, String> c = CacheBuilder.newBuilder().maximumSize(1).build();

    assertThat(c.asMap().compute("hash-1", (k, v) -> "a")).isEqualTo("a");
    assertThat(c.asMap().compute("hash-1", (k, v) -> "b")).isEqualTo("b");
    assertThat(c.asMap().compute("hash-1", (k, v) -> "c")).isEqualTo("c");
    assertThat(c.size()).isEqualTo(1);
    assertThat(c.asMap().computeIfAbsent("hash-2", k -> "")).isEqualTo("");
  }

  public void testComputeIfPresent() {
    cache.put(key, "1");
    // simultaneous update for same key, expect count successful updates
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().computeIfPresent(key, (k, v) -> v + delimiter + n);
        });
    assertEquals(1, cache.size());
    assertThat(cache.getIfPresent(key).split(delimiter)).hasLength(count + 1);
  }

  public void testUpdates() {
    cache.put(key, "1");
    // simultaneous update for same key, some null, some non-null
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().compute(key, (k, v) -> n % 2 == 0 ? v + delimiter + n : null);
        });
    assertTrue(1 >= cache.size());
  }

  public void testCompute() {
    cache.put(key, "1");
    // simultaneous deletion
    doParallelCacheOp(
        count,
        n -> {
          cache.asMap().compute(key, (k, v) -> null);
        });
    assertEquals(0, cache.size());
  }

  public void testComputeExceptionally() {
    try {
      doParallelCacheOp(
          count,
          n -> {
            cache
                .asMap()
                .compute(
                    key,
                    (k, v) -> {
                      throw new RuntimeException();
                    });
          });
      fail("Should not get here");
    } catch (RuntimeException ex) {
    }
  }
}


text:
//Copyright 2006-2009 Jeroen van Menen
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

#endregion Copyright

using WatiN.Core.Native;

namespace WatiN.Core
{
	/// <summary>
	/// This class provides specialized functionality for a HTML div element.
	/// </summary>
    [ElementTag("div")]
    public class Div : ElementContainer<Div>
	{
		/// <summary>
		/// Initializes a new instance of the <see cref="Div"/> class.
		/// Mainly used by WatiN internally.
		/// </summary>
		/// <param name="domContainer">The DOM container.</param>
		/// <param name="htmlDivElement">The HTML div element.</param>
		public Div(DomContainer domContainer, INativeElement htmlDivElement) : base(domContainer, htmlDivElement) {}

		/// <summary>
		/// Initializes a new instance of the <see cref="Div"/> class.
		/// Mainly used by WatiN internally.
		/// </summary>
		/// <param name="domContainer">The DOM container.</param>
		/// <param name="finder">The HTML div element.</param>
        public Div(DomContainer domContainer, ElementFinder finder) : base(domContainer, finder) { }
	}
}


text:
package com.amazonaws.services.migrationhuborchestrator.model.transform;

import java.math.*;

import javax.annotation.Generated;

import com.amazonaws.services.migrationhuborchestrator.model.*;
import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*;
import com.amazonaws.transform.*;

import com.fasterxml.jackson.core.JsonToken;
import static com.fasterxml.jackson.core.JsonToken.*;

/**
 * UpdateWorkflowResult JSON Unmarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public class UpdateWorkflowResultJsonUnmarshaller implements Unmarshaller<UpdateWorkflowResult, JsonUnmarshallerContext> {

    public UpdateWorkflowResult unmarshall(JsonUnmarshallerContext context) throws Exception {
        UpdateWorkflowResult updateWorkflowResult = new UpdateWorkflowResult();

        int originalDepth = context.getCurrentDepth();
        String currentParentElement = context.getCurrentParentElement();
        int targetDepth = originalDepth + 1;

        JsonToken token = context.getCurrentToken();
        if (token == null)
            token = context.nextToken();
        if (token == VALUE_NULL) {
            return updateWorkflowResult;
        }

        while (true) {
            if (token == null)
                break;

            if (token == FIELD_NAME || token == START_OBJECT) {
                if (context.testExpression("id", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("arn", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setArn(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("name", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setName(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("description", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setDescription(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("templateId", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setTemplateId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("adsApplicationConfigurationId", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setAdsApplicationConfigurationId(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("workflowInputs", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setWorkflowInputs(new MapUnmarshaller<String, StepInput>(context.getUnmarshaller(String.class),
                            StepInputJsonUnmarshaller.getInstance()).unmarshall(context));
                }
                if (context.testExpression("stepTargets", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setStepTargets(new ListUnmarshaller<String>(context.getUnmarshaller(String.class))

                    .unmarshall(context));
                }
                if (context.testExpression("status", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setStatus(context.getUnmarshaller(String.class).unmarshall(context));
                }
                if (context.testExpression("creationTime", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setCreationTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("lastModifiedTime", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setLastModifiedTime(DateJsonUnmarshallerFactory.getInstance("unixTimestamp").unmarshall(context));
                }
                if (context.testExpression("tags", targetDepth)) {
                    context.nextToken();
                    updateWorkflowResult.setTags(new MapUnmarshaller<String, String>(context.getUnmarshaller(String.class), context
                            .getUnmarshaller(String.class)).unmarshall(context));
                }
            } else if (token == END_ARRAY || token == END_OBJECT) {
                if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals(currentParentElement)) {
                    if (context.getCurrentDepth() <= originalDepth)
                        break;
                }
            }
            token = context.nextToken();
        }

        return updateWorkflowResult;
    }

    private static UpdateWorkflowResultJsonUnmarshaller instance;

    public static UpdateWorkflowResultJsonUnmarshaller getInstance() {
        if (instance == null)
            instance = new UpdateWorkflowResultJsonUnmarshaller();
        return instance;
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="horizontal"
    android:padding="10dip" >

    <View
        android:id="@+id/channel_line"
        android:layout_width="3dp"
        android:layout_height="15dp"
        android:layout_marginLeft="5dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:background="#79BEF7" />

    <TextView
        android:id="@+id/channel_group_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_gravity="center"
        android:layout_marginLeft="5dp"
        android:layout_toRightOf="@id/channel_line"
        android:text="体育"
        android:textColor="#8e8e8e"
        android:textSize="18sp" />

    <ImageView
        android:id="@+id/channel_imageview_orientation"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="5dp"
        android:src="@drawable/channel_expandablelistview_bottom_icon" />

</RelativeLayout>


text:
namespace send_tab_to_self {
class SendTabToSelfEntry;
class SendTabToSelfSyncService;
}  // namespace send_tab_to_self

namespace send_tab_to_self_helper {

// Class that allows waiting until a particular |url| is exposed by the
// SendTabToSelfModel in |service|.
class SendTabToSelfUrlChecker
    : public StatusChangeChecker,
      public send_tab_to_self::SendTabToSelfModelObserver {
 public:
  // The caller must ensure that |service| is not null and will outlive this
  // object.
  SendTabToSelfUrlChecker(send_tab_to_self::SendTabToSelfSyncService* service,
                          const GURL& url);

  SendTabToSelfUrlChecker(const SendTabToSelfUrlChecker&) = delete;
  SendTabToSelfUrlChecker& operator=(const SendTabToSelfUrlChecker&) = delete;

  ~SendTabToSelfUrlChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // SendTabToSelfModelObserver implementation.
  void SendTabToSelfModelLoaded() override;
  void EntriesAddedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          new_entries) override;
  void EntriesRemovedRemotely(
      const std::vector<std::string>& guids_removed) override;

 private:
  const GURL url_;
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service_;
};

// Class that allows waiting until a particular |url| is marked opened by the
// SendTabToSelfModel in |service|.
class SendTabToSelfUrlOpenedChecker
    : public StatusChangeChecker,
      public send_tab_to_self::SendTabToSelfModelObserver {
 public:
  // The caller must ensure that |service| is not null and will outlive this
  // object.
  SendTabToSelfUrlOpenedChecker(
      send_tab_to_self::SendTabToSelfSyncService* service,
      const GURL& url);

  SendTabToSelfUrlOpenedChecker(const SendTabToSelfUrlOpenedChecker&) = delete;
  SendTabToSelfUrlOpenedChecker& operator=(
      const SendTabToSelfUrlOpenedChecker&) = delete;

  ~SendTabToSelfUrlOpenedChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // SendTabToSelfModelObserver implementation.
  void SendTabToSelfModelLoaded() override;
  void EntriesAddedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          new_entries) override;
  void EntriesRemovedRemotely(
      const std::vector<std::string>& guids_removed) override;
  void EntriesOpenedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          opened_entries) override;

 private:
  const GURL url_;
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service_;
};

// Class that allows waiting the number of entries in until |service0|
// matches the number of entries in |service1|.
class SendTabToSelfModelEqualityChecker
    : public StatusChangeChecker,
      public send_tab_to_self::SendTabToSelfModelObserver {
 public:
  // The caller must ensure that |service0| and |service1| are not null and
  // will outlive this object.
  SendTabToSelfModelEqualityChecker(
      send_tab_to_self::SendTabToSelfSyncService* service0,
      send_tab_to_self::SendTabToSelfSyncService* service1);

  SendTabToSelfModelEqualityChecker(const SendTabToSelfModelEqualityChecker&) =
      delete;
  SendTabToSelfModelEqualityChecker& operator=(
      const SendTabToSelfModelEqualityChecker&) = delete;

  ~SendTabToSelfModelEqualityChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // SendTabToSelfModelObserver implementation.
  void SendTabToSelfModelLoaded() override;
  void EntriesAddedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          new_entries) override;
  void EntriesRemovedRemotely(
      const std::vector<std::string>& guids_removed) override;

 private:
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service0_;
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service1_;
};

// Class that allows waiting until the bridge is ready.
class SendTabToSelfActiveChecker
    : public StatusChangeChecker,
      public send_tab_to_self::SendTabToSelfModelObserver {
 public:
  // The caller must ensure that |service| is not null and will outlive this
  // object.
  explicit SendTabToSelfActiveChecker(
      send_tab_to_self::SendTabToSelfSyncService* service);

  SendTabToSelfActiveChecker(const SendTabToSelfActiveChecker&) = delete;
  SendTabToSelfActiveChecker& operator=(const SendTabToSelfActiveChecker&) =
      delete;

  ~SendTabToSelfActiveChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // SendTabToSelfModelObserver implementation.
  void SendTabToSelfModelLoaded() override;
  void EntriesAddedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          new_entries) override;
  void EntriesRemovedRemotely(
      const std::vector<std::string>& guids_removed) override;

 private:
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service_;
};

// Class that allows waiting until two devices are ready.
class SendTabToSelfMultiDeviceActiveChecker
    : public StatusChangeChecker,
      public syncer::DeviceInfoTracker::Observer {
 public:
  explicit SendTabToSelfMultiDeviceActiveChecker(
      syncer::DeviceInfoTracker* tracker);

  SendTabToSelfMultiDeviceActiveChecker(
      const SendTabToSelfMultiDeviceActiveChecker&) = delete;
  SendTabToSelfMultiDeviceActiveChecker& operator=(
      const SendTabToSelfMultiDeviceActiveChecker&) = delete;

  ~SendTabToSelfMultiDeviceActiveChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // DeviceInfoTracker::Observer implementation.
  void OnDeviceInfoChange() override;

 private:
  const raw_ptr<syncer::DeviceInfoTracker> tracker_;
};

// Class that allows waiting until device has send_tab_to_self disabled.
class SendTabToSelfDeviceDisabledChecker
    : public StatusChangeChecker,
      public syncer::DeviceInfoTracker::Observer {
 public:
  SendTabToSelfDeviceDisabledChecker(syncer::DeviceInfoTracker* tracker,
                                     const std::string& device_guid);
  ~SendTabToSelfDeviceDisabledChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // DeviceInfoTracker::Observer implementation.
  void OnDeviceInfoChange() override;

 private:
  const raw_ptr<syncer::DeviceInfoTracker> tracker_;
  std::string device_guid_;
};

class SendTabToSelfUrlDeletedChecker
    : public StatusChangeChecker,
      public send_tab_to_self::SendTabToSelfModelObserver {
 public:
  // The caller must ensure that |service| is not null and will outlive this
  // object.
  SendTabToSelfUrlDeletedChecker(
      send_tab_to_self::SendTabToSelfSyncService* service,
      const GURL& url);

  SendTabToSelfUrlDeletedChecker(const SendTabToSelfUrlDeletedChecker&) =
      delete;
  SendTabToSelfUrlDeletedChecker& operator=(
      const SendTabToSelfUrlDeletedChecker&) = delete;

  ~SendTabToSelfUrlDeletedChecker() override;

  // StatusChangeChecker implementation.
  bool IsExitConditionSatisfied(std::ostream* os) override;

  // SendTabToSelfModelObserver implementation.
  void SendTabToSelfModelLoaded() override;
  void EntriesAddedRemotely(
      const std::vector<const send_tab_to_self::SendTabToSelfEntry*>&
          new_entries) override;
  void EntriesRemovedRemotely(
      const std::vector<std::string>& guids_removed) override;

 private:
  const GURL url_;
  const raw_ptr<send_tab_to_self::SendTabToSelfSyncService> service_;
};

}  // namespace send_tab_to_self_helper

#endif  // CHROME_BROWSER_SYNC_TEST_INTEGRATION_SEND_TAB_TO_SELF_HELPER_H_


text:
package com.tle.core.item.standard.filter;

import com.google.common.collect.Multimap;
import com.google.inject.assistedinject.Assisted;
import com.google.inject.assistedinject.AssistedInject;
import com.tle.beans.item.ItemIdKey;
import com.tle.beans.item.ItemStatus;
import com.tle.core.item.operations.WorkflowOperation;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;

/** @author jmaginnis */
@SuppressWarnings("nls")
public class NewItemFilter extends AbstractStandardOperationFilter {
  private final Multimap<String, String> collectionMap;

  @AssistedInject
  protected NewItemFilter(@Assisted Multimap<String, String> collectionMap) {
    this.collectionMap = collectionMap;
  }

  @Override
  public WorkflowOperation[] createOperations() {
    return new WorkflowOperation[] {
      operationFactory.createOperation(collectionMap), operationFactory.reIndexIfRequired()
    };
  }

  @Override
  public FilterResults getItemIds() {
    if (collectionMap.keySet().isEmpty()) {
      Iterator<ItemIdKey> empty = Collections.emptyIterator();
      return new FilterResults(0, empty);
    }
    return super.getItemIds();
  }

  @Override
  public void queryValues(Map<String, Object> values) {
    Calendar calendar = Calendar.getInstance();
    calendar.add(Calendar.DAY_OF_YEAR, -1);
    values.put("date", calendar.getTime());
    values.put("status", ItemStatus.LIVE.name());
    values.put("itemdefs", collectionMap.keySet());
  }

  @Override
  public String getWhereClause() {
    return "status = :status and moderation.liveApprovalDate > :date and itemDefinition.uuid in (:itemdefs)";
  }

  @Override
  public boolean isReadOnly() {
    return true;
  }
}


text:
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0
// Changes may cause incorrect behavior and will be lost if the code is regenerated.

using Newtonsoft.Json.Linq;

namespace BuildIt.Bot.Client.DirectLinkApi.Models
{
    /// <summary>
    ///
    /// </summary>
    public partial class Attachment
    {
        /// <summary>
        /// Optional. Content type for this attachment
        /// </summary>
        public string ContentType { get; set; }

        /// <summary>
        /// Optional. URL for this attachment
        /// </summary>
        public string Url { get; set; }

        /// <summary>
        /// Initializes a new instance of the Attachment class.
        /// </summary>
        public Attachment()
        {
        }

        /// <summary>
        /// Deserialize the object
        /// </summary>
        public virtual void DeserializeJson(JToken inputObject)
        {
            if (inputObject != null && inputObject.Type != JTokenType.Null)
            {
                JToken contentTypeValue = inputObject["contentType"];
                if (contentTypeValue != null && contentTypeValue.Type != JTokenType.Null)
                {
                    this.ContentType = ((string)contentTypeValue);
                }
                JToken urlValue = inputObject["url"];
                if (urlValue != null && urlValue.Type != JTokenType.Null)
                {
                    this.Url = ((string)urlValue);
                }
            }
        }

        /// <summary>
        /// Serialize the object
        /// </summary>
        /// <returns>
        /// Returns the json model for the type Attachment
        /// </returns>
        public virtual JToken SerializeJson(JToken outputObject)
        {
            if (outputObject == null)
            {
                outputObject = new JObject();
            }
            if (this.ContentType != null)
            {
                outputObject["contentType"] = this.ContentType;
            }
            if (this.Url != null)
            {
                outputObject["url"] = this.Url;
            }
            return outputObject;
        }
    }
}


text:
/*

 */
package servlets;

import dao.EmployeeDAO;
import domain.Employee;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author cameron
 */
public class EditEmployee extends HttpServlet {

    /**
     * Handles the HTTP POST method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        EmployeeDAO.updateEmployee(request.getParameter("id"),
                request.getParameter("ename"),
                request.getParameter("email"),
                Double.parseDouble(request.getParameter("minHours")),
                Double.parseDouble(request.getParameter("maxHours")));

        response.sendRedirect("/amendEmployee.jsp");

    }
}


text:
#include <TinySTL/stddef.h>

#include "AssertLog.h"
#include "Log.h"
#include "PlatformDefines.h"
#include "SoundSystem.h"

#ifdef WIN32
#pragma warning(disable: 4099)
#pragma comment(lib, "hss.lib")

#ifdef _DEBUG
#pragma comment(linker, "/NODEFAULTLIB:msvcrt.lib")
#endif
#endif

NAMESPACE(SPlay)

SoundSystem::SoundSystem()
#if !defined __ANDROID__ && !defined MARMALADE
	:
	m_pSpeaker(NULL)
#endif
{
}

SoundSystem::~SoundSystem()
{
	close();
}

SoundSystem* SoundSystem::create()
{
	SoundSystem*	pSoundSystem	= new SoundSystem();

	if (false == pSoundSystem->initialize())
	{
		delete	pSoundSystem;

		pSoundSystem	= NULL;
	}

	return	pSoundSystem;
}

bool SoundSystem::initialize()
{
#if !defined __ANDROID__ && !defined MARMALADE
	m_pSpeaker	= hss::createSpeaker();

	if (NULL == m_pSpeaker)
	{
		Log::instance()->logError("Unable to create speaker.");

		return	false;
	}

	int	iRetVal	= m_pSpeaker->open(gsc_iSoundFrequency, 16, true);

	if (iRetVal != hss::kOk)
	{
		Log::instance()->logError("Unable to setup audio %d.", iRetVal);

		return        false;
	}
#endif

	return	true;
}

void SoundSystem::close()
{
	releaseSounds();
	releaseMusic();

#if !defined __ANDROID__ && !defined MARMALADE
	if (m_pSpeaker != NULL)
	{
		m_pSpeaker->close();
		m_pSpeaker->release();

		m_pSpeaker	= NULL;
	}
#endif
}

void SoundSystem::pause()
{
#if !defined __ANDROID__ && !defined MARMALADE
	ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

	m_pSpeaker->pauseSounds();
#endif
}

void SoundSystem::unpause()
{
#if !defined __ANDROID__ && !defined MARMALADE
	ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

	m_pSpeaker->unpauseSounds();
#endif
}

void SoundSystem::setVolume(int _iVolume)
{
#if !defined __ANDROID__ && !defined MARMALADE
	ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

	hss::ChannelGroup*	pGroup	= m_pSpeaker->getMasterChannelGroup();

	if (pGroup != NULL)
	{
		pGroup->setVolume(static_cast<float>(_iVolume) / 100.0f);
	}
#endif
}

bool SoundSystem::addSoundEvent(const tinystl::string& _strSoundName, int _iEventID)
{
	if (true == soundExists(_iEventID))
	{
		return	false;
	}

#if !defined __ANDROID__ && !defined MARMALADE
	ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

	hss::Sound*	pSound	= m_pSpeaker->createSound(_strSoundName.c_str());

	if (NULL == pSound)
	{
		Log::instance()->logError("Unable to create sound %s", _strSoundName.c_str());

		return	false;
	}

	m_mapSoundEvents[_iEventID]	= pSound;
#endif

	return	true;
}

void SoundSystem::triggerSoundEvent(int _iEventID)
{
	if (true == soundExists(_iEventID))
	{
#if !defined __ANDROID__ && !defined MARMALADE
		ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

		m_pSpeaker->playSound(m_mapSoundEvents[_iEventID]);
#endif
	}
}

void SoundSystem::stopSoundEvent(int _iEventID)
{
	if (true == soundExists(_iEventID))
	{
#if !defined __ANDROID__ && !defined MARMALADE
		ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

		m_pSpeaker->stopSoundInstances(m_mapSoundEvents[_iEventID]);
#endif
	}
}

bool SoundSystem::addMusicEvent(const tinystl::string& _strMusicName, int _iEventID)
{
	if (true == musicExists(_iEventID))
	{
		return	false;
	}

#if !defined __ANDROID__ && !defined MARMALADE
	ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

	hss::Sound*	pSound	= m_pSpeaker->createSound(_strMusicName.c_str());

	if (NULL == pSound)
	{
		Log::instance()->logError("Unable to create music %s", _strMusicName.c_str());

		return	false;
	}

	m_mapMusicEvents[_iEventID]	= pSound;
#endif

	return	true;
}

void SoundSystem::triggerMusicEvent(int _iEventID)
{
	if (true == musicExists(_iEventID))
	{
#if !defined __ANDROID__ && !defined MARMALADE
		ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

		m_pSpeaker->playSound(m_mapMusicEvents[_iEventID]);
#endif
	}
}

void SoundSystem::stopMusicEvent(int _iEventID)
{
	if (true == musicExists(_iEventID))
	{
#if !defined __ANDROID__ && !defined MARMALADE
		ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

		m_pSpeaker->stopSoundInstances(m_mapMusicEvents[_iEventID]);
#endif
	}
}

void SoundSystem::releaseSounds()
{
#if !defined __ANDROID__ && !defined MARMALADE
	for (SoundEventIterator iterator = m_mapSoundEvents.begin(); iterator != m_mapSoundEvents.end(); ++iterator)
	{
		if (iterator->second != NULL)
		{
			ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

			m_pSpeaker->releaseSound(iterator->second);
		}
	}

	m_mapSoundEvents.clear();
#endif
}

bool SoundSystem::soundExists(int _iEventID)
{
#if !defined __ANDROID__ && !defined MARMALADE
	if (m_mapSoundEvents.find(_iEventID) == m_mapSoundEvents.end())
	{
		return	false;
	}
#endif

	return	true;
}

void SoundSystem::releaseMusic()
{
#if !defined __ANDROID__ && !defined MARMALADE
	for (MusicEventIterator iterator = m_mapMusicEvents.begin(); iterator != m_mapMusicEvents.end(); ++iterator)
	{
		if (iterator->second != NULL)
		{
			ASSERT_LOG(m_pSpeaker != NULL, "Sound system not initialized");

			m_pSpeaker->releaseSound(iterator->second);
		}
	}

	m_mapMusicEvents.clear();
#endif
}

bool SoundSystem::musicExists(int _iEventID)
{
#if !defined __ANDROID__ && !defined MARMALADE
	if (m_mapMusicEvents.find(_iEventID) == m_mapMusicEvents.end())
	{
		return	false;
	}
#endif

	return	true;
}

ENDNAMESPACE