text:
from __future__ import print_function  # Python 2 compatibility

import sys
import keyword
from asn1ate import parser
from asn1ate.support import pygen
from asn1ate.sema import *

class Pyasn1Backend(object):
    """ Backend to generate pyasn1 declarations from semantic tree.

    Pyasn1 represents type assignments as class derivation, e.g.

        # Foo ::= INTEGER
        class Foo(univ.Integer):
            pass

    For constructed types, the component types are instantiated inline, e.g.

        # Seq ::= SEQUENCE {
        #     foo INTEGER
        # }
        class Seq(univ.Sequence):
             componentType = namedtype.NamedTypes(
                namedtype.NamedType('foo', univ.Integer())
             )

    (univ.Integer is not a base class here, but a value.)

    To cope with circular dependencies, we define types in two passes so we'll
    generate the above as:

        class Seq(univ.Sequence):
            pass

        Seq.componentType = namedtype.NamedTypes(
            namedtype.NamedType('foo', univ.Integer())
        )

    This is nice, because we separate the introduction of a name (``Seq``) from
    the details of what it contains, so we can build recursive definitions
    without getting into trouble with Python's name lookup.

    We call the empty class a *declaration*, and the population of its members
    *definition*. The instantiation of univ.Integer is called an
    *inline definition*.

    The translation from ASN.1 constructs to Pyasn1 come in different flavors,
    depending on whether they're declarations, definitions or inline
    definitions.

    Only type and value assignments generate declarations. For type assignments
    we generate a definition once all dependent declarations are created. If the
    type assignment involves a constructed type, it is filled with inline
    definitions.
    """
    def __init__(self, sema_module, out_stream):
        self.sema_module = sema_module
        self.writer = pygen.PythonWriter(out_stream)

        self.decl_generators = {
            TypeAssignment: self.decl_type_assignment,
            ValueAssignment: self.decl_value_assignment
        }

        self.defn_generators = {
            ChoiceType: self.defn_constructed_type,
            SequenceType: self.defn_constructed_type,
            SetType: self.defn_constructed_type,
            SequenceOfType: self.defn_collection_type,
            SetOfType: self.defn_collection_type,
            TaggedType: self.defn_tagged_type,
            SelectionType: self.defn_selection_type,
            SimpleType: self.defn_simple_type,
            DefinedType: self.defn_defined_type,
            ValueListType: self.defn_value_list_type,
            BitStringType: self.defn_bitstring_type,
        }

        self.inline_generators = {
            TaggedType: self.inline_tagged_type,
            SelectionType: self.inline_selection_type,
            SimpleType: self.inline_simple_type,
            DefinedType: self.inline_defined_type,
            ComponentType: self.inline_component_type,
            NamedType: self.inline_named_type,
            SequenceOfType: self.inline_sequenceof_type,
            SetOfType: self.inline_setof_type,
            ValueListType: self.inline_value_list_type,
            ChoiceType: self.inline_constructed_type,
            SequenceType: self.inline_constructed_type,
            SetType: self.inline_constructed_type,
            BitStringType: self.inline_bitstring_type,
        }

    def generate_code(self):
        self.writer.write_line('from pyasn1.type import univ, char, namedtype, namedval, tag, constraint, useful')
        self.writer.write_blanks(2)

        # Generate _OID if sema_module contains any object identifier values.
        oids = [n for n in self.sema_module.descendants() if isinstance(n, ObjectIdentifierValue)]
        if oids:
            self.writer.write_block(self.generate_OID())
            self.writer.write_blanks(2)

        assignment_components = dependency_sort(self.sema_module.assignments)
        for component in assignment_components:
            for assignment in component:
                self.writer.write_block(self.generate_decl(assignment))
                self.writer.write_blanks(2)

            for assignment in component:
                details = self.generate_definition(assignment)
                if details:
                    self.writer.write_block(details)
                    self.writer.write_blanks(2)

    def generate_definition(self, assignment):
        assert isinstance(assignment, (ValueAssignment, TypeAssignment))

        if isinstance(assignment, ValueAssignment):
            return None  # Nothing to do here.

        assigned_type, type_decl = assignment.type_name, assignment.type_decl
        assigned_type = _translate_type(assigned_type)
        return self.generate_defn(assigned_type, type_decl)

    def generate_decl(self, t):
        generator = self.decl_generators[type(t)]
        return generator(t)

    def generate_expr(self, t):
        generator = self.inline_generators[type(t)]
        return generator(t)

    def generate_defn(self, class_name, t):
        generator = self.defn_generators[type(t)]
        return generator(class_name, t)

    def decl_type_assignment(self, assignment):
        fragment = self.writer.get_fragment()

        assigned_type, type_decl = assignment.type_name, assignment.type_decl

        if isinstance(type_decl, SelectionType):
            type_decl = self.sema_module.resolve_selection_type(type_decl)

        assigned_type = _translate_type(assigned_type)
        base_type = _translate_type(type_decl.type_name)
        fragment.write_line('class %s(%s):' % (assigned_type, base_type))
        fragment.push_indent()
        fragment.write_line('pass')
        fragment.pop_indent()

        return str(fragment)

    def decl_value_assignment(self, assignment):
        assigned_value, type_decl, value = assignment.value_name, assignment.type_decl, assignment.value
        assigned_value = _sanitize_identifier(assigned_value)
        construct_expr = self.build_value_construct_expr(type_decl, value)
        return '%s = %s' % (assigned_value, construct_expr)

    def defn_simple_type(self, class_name, t):
        if t.constraint:
            return '%s.subtypeSpec = %s' % (class_name, self.build_constraint_expr(t.constraint))

        return None

    def defn_defined_type(self, class_name, t):
        return None

    def defn_constructed_type(self, class_name, t):
        fragment = self.writer.get_fragment()

        fragment.write_line('%s.componentType = namedtype.NamedTypes(' % class_name)
        fragment.push_indent()
        fragment.write_block(self.inline_component_types(t.components))
        fragment.pop_indent()
        fragment.write_line(')')

        return str(fragment)

    def defn_tagged_type(self, class_name, t):
        fragment = self.writer.get_fragment()

        implicity = self.sema_module.resolve_tag_implicity(t.implicity, t.type_decl)
        if implicity == TagImplicity.IMPLICIT:
            tag_implicity = 'tagImplicitly'
        elif implicity == TagImplicity.EXPLICIT:
            tag_implicity = 'tagExplicitly'
        else:
            assert False, "Unexpected implicity: %s" % implicity

        base_type = _translate_type(t.type_decl.type_name)

        fragment.write_line('%s.tagSet = %s.tagSet.%s(%s)' % (class_name, base_type, tag_implicity, self.build_tag_expr(t)))
        nested_dfn = self.generate_defn(class_name, t.type_decl)
        if nested_dfn:
            fragment.write_line(nested_dfn)

        return str(fragment)

    def defn_selection_type(self, class_name, t):
        return None

    def defn_value_list_type(self, class_name, t):
        fragment = self.writer.get_fragment()

        if t.named_values:
            fragment.write_line('%s.namedValues = namedval.NamedValues(' % class_name)
            fragment.push_indent()

            named_values = ['(\'%s\', %s)' % (v.identifier, v.value) for v in t.named_values if not isinstance(v, ExtensionMarker)]
            fragment.write_enumeration(named_values)

            fragment.pop_indent()
            fragment.write_line(')')

        if t.constraint:
            fragment.write_line('%s.subtypeSpec=%s' % (class_name, self.build_constraint_expr(t.constraint)))

        return str(fragment)

    def inline_bitstring_type(self, t):
        return self.inline_simple_type(t)

    def defn_bitstring_type(self, class_name, t):
        fragment = self.writer.get_fragment()

        if t.named_bits:
            fragment.write_line('%s.namedValues = namedval.NamedValues(' % class_name)
            fragment.push_indent()
            named_bits = ['(\'%s\', %s)' % (b.identifier, b.value) for b in t.named_bits]
            fragment.write_enumeration(named_bits)
            fragment.pop_indent()
            fragment.write_line(')')

        if t.constraint:
            fragment.write_line('%s.subtypeSpec=%s' % (class_name, self.build_constraint_expr(t.constraint)))

        return str(fragment)

    def defn_collection_type(self, class_name, t):
        fragment = self.writer.get_fragment()
        fragment.write_line('%s.componentType = %s' % (class_name, self.generate_expr(t.type_decl)))

        if t.size_constraint:
            fragment.write_line('%s.subtypeSpec=%s' % (class_name, self.build_constraint_expr(t.size_constraint)))

        return str(fragment)

    def inline_simple_type(self, t):
        type_expr = _translate_type(t.type_name) + '()'
        if t.constraint:
            type_expr += '.subtype(subtypeSpec=%s)' % self.build_constraint_expr(t.constraint)

        return type_expr

    def inline_defined_type(self, t):
        return _translate_type(t.type_name) + '()'

    def inline_constructed_type(self, t):
        fragment = self.writer.get_fragment()

        class_name = _translate_type(t.type_name)

        fragment.write_line('%s(componentType=namedtype.NamedTypes(' % class_name)

        fragment.push_indent()
        fragment.write_block(self.inline_component_types(t.components))
        fragment.pop_indent()

        fragment.write_line('))')

        return str(fragment)

    def inline_component_types(self, components):
        fragment = self.writer.get_fragment()

        component_exprs = []
        for c in components:
            if not isinstance(c, ExtensionMarker):
                component_exprs.append(self.generate_expr(c))

        fragment.write_enumeration(component_exprs)

        return str(fragment)

    def inline_tagged_type(self, t):
        implicity = self.sema_module.resolve_tag_implicity(t.implicity, t.type_decl)
        if implicity == TagImplicity.IMPLICIT:
            tag_implicity = 'implicitTag'
        elif implicity == TagImplicity.EXPLICIT:
            tag_implicity = 'explicitTag'
        else:
            assert False, "Unexpected implicity: %s" % implicity

        type_expr = self.generate_expr(t.type_decl)
        type_expr += '.subtype(%s=%s)' % (tag_implicity, self.build_tag_expr(t))

        return type_expr

    def inline_selection_type(self, t):
        selected_type = self.sema_module.resolve_selection_type(t)
        assert selected_type is not None, "Found no member %s in %s" % (t.identifier, t.type_decl)

        return self.generate_expr(selected_type)

    def build_tag_expr(self, tag_def):
        context = _translate_tag_class(tag_def.class_name)

        tagged_type_decl = self.sema_module.resolve_type_decl(tag_def.type_decl)
        if isinstance(tagged_type_decl, ConstructedType):
            tag_format = 'tag.tagFormatConstructed'
        else:
            tag_format = 'tag.tagFormatSimple'

        return 'tag.Tag(%s, %s, %s)' % (context, tag_format, tag_def.class_number)

    def build_constraint_expr(self, constraint):
        def unpack_size_constraint(nested):
            if isinstance(nested, SingleValueConstraint):
                return _translate_value(nested.value), _translate_value(nested.value)
            elif isinstance(nested, ValueRangeConstraint):
                return _translate_value(nested.min_value), _translate_value(nested.max_value)
            else:
                assert False, "Unrecognized nested size constraint type: %s" % type(constraint.nested).__name__

        if isinstance(constraint, SingleValueConstraint):
            return 'constraint.SingleValueConstraint(%s)' % (_translate_value(constraint.value))
        elif isinstance(constraint, SizeConstraint):
            min_value, max_value = unpack_size_constraint(constraint.nested)
            return 'constraint.ValueSizeConstraint(%s, %s)' % (_translate_value(min_value), _translate_value(max_value))
        elif isinstance (constraint, ValueRangeConstraint):
            return 'constraint.ValueRangeConstraint(%s, %s)' % (_translate_value(constraint.min_value),
                                                                _translate_value(constraint.max_value))
        else:
            assert False, "Unrecognized constraint type: %s" % type(constraint).__name__

    def build_value_construct_expr(self, type_decl, value):
        """ Build a valid construct-expression for values, depending on
        the target pyasn1 type.
        """

        def build_value_expr(type_name, value):
            """ Special treatment for bstring and hstring values,
            which use different construction depending on target type.
            """
            if isinstance(value, BinaryStringValue):
                if type_name == 'OCTET STRING':
                    return 'binValue=\'%s\'' % value.value
                else:
                    return '"\'%s\'B"' % value.value
            elif isinstance(value, HexStringValue):
                if type_name == 'OCTET STRING':
                    return 'hexValue=\'%s\'' % value.value
                else:
                    return '"\'%s\'H"' % value.value
            else:
                return _translate_value(value)

        if isinstance(value, ObjectIdentifierValue):
            return self.build_object_identifier_value(value)
        else:
            value_type = _translate_type(type_decl.type_name)
            root_type = self.sema_module.resolve_type_decl(type_decl)
            return '%s(%s)' % (value_type, build_value_expr(root_type.type_name, value))

    def inline_component_type(self, t):
        if t.components_of_type:
            # COMPONENTS OF works like a literal include, so just
            # expand all components of the referenced type.
            included_type_decl = self.sema_module.resolve_type_decl(t.components_of_type)
            included_content = self.inline_component_types(included_type_decl.components)

            # Strip trailing newline from inline_component_types
            # to make the list line up
            return included_content.strip()

        if t.optional:
            return "namedtype.OptionalNamedType('%s', %s)" % (t.identifier, self.generate_expr(t.type_decl))
        elif t.default_value is not None:
            type_expr = self.generate_expr(t.type_decl)
            type_expr += '.subtype(value=%s)' % _translate_value(t.default_value)

            return "namedtype.DefaultedNamedType('%s', %s)" % (t.identifier, type_expr)
        else:
            return "namedtype.NamedType('%s', %s)" % (t.identifier, self.generate_expr(t.type_decl))

    def inline_named_type(self, t):
        return "namedtype.NamedType('%s', %s)" % (t.identifier, self.generate_expr(t.type_decl))

    def inline_value_list_type(self, t):
        class_name = _translate_type(t.type_name)
        if t.named_values:
            named_values = ['(\'%s\', %s)' % (v.identifier, v.value) for v in t.named_values if not isinstance(v, ExtensionMarker)]
            return '%s(namedValues=namedval.NamedValues(%s))' % (class_name, ', '.join(named_values))
        else:
            return class_name + '()'

    def inline_sequenceof_type(self, t):
        return 'univ.SequenceOf(componentType=%s)' % self.generate_expr(t.type_decl)

    def inline_setof_type(self, t):
        return 'univ.SetOf(componentType=%s)' % self.generate_expr(t.type_decl)

    def build_object_identifier_value(self, t):
        objid_components = []

        for c in t.components:
            if isinstance(c, NameForm):
                if c.name in REGISTERED_OID_NAMES:
                    objid_components.append(str(REGISTERED_OID_NAMES[c.name]))
                else:
                    objid_components.append(_translate_value(c.name))
            elif isinstance(c, NumberForm):
                objid_components.append(str(c.value))
            elif isinstance(c, NameAndNumberForm):
                objid_components.append(str(c.number.value))
            else:
                assert False

        return '_OID(%s)' % ', '.join(objid_components)

    def generate_OID(self):
        fragment = self.writer.get_fragment()

        fragment.write_line('def _OID(*components):')
        fragment.push_indent()
        fragment.write_line('output = []')
        fragment.write_line('for x in tuple(components):')
        fragment.push_indent()
        fragment.write_line('if isinstance(x, univ.ObjectIdentifier):')
        fragment.push_indent()
        fragment.write_line('output.extend(list(x))')
        fragment.pop_indent()
        fragment.write_line('else:')
        fragment.push_indent()
        fragment.write_line('output.append(int(x))')
        fragment.pop_indent()
        fragment.pop_indent()
        fragment.write_blanks(1)
        fragment.write_line('return univ.ObjectIdentifier(output)')
        fragment.pop_indent()

        fragment.pop_indent()

        return str(fragment)

def generate_pyasn1(sema_module, out_stream):
    return Pyasn1Backend(sema_module, out_stream).generate_code()

# Translation tables from ASN.1 primitives to pyasn1 primitives
_ASN1_TAG_CONTEXTS = {
    'APPLICATION': 'tag.tagClassApplication',
    'PRIVATE': 'tag.tagClassPrivate',
    'UNIVERSAL': 'tag.tagClassUniversal'
}

_ASN1_BUILTIN_VALUES = {
    'FALSE': '0',
    'TRUE': '1'
}

_ASN1_BUILTIN_TYPES = {
    'ANY': 'univ.Any',
    'INTEGER': 'univ.Integer',
    'BOOLEAN': 'univ.Boolean',
    'NULL': 'univ.Null',
    'ENUMERATED': 'univ.Enumerated',
    'REAL': 'univ.Real',
    'BIT STRING': 'univ.BitString',
    'OCTET STRING': 'univ.OctetString',
    'CHOICE': 'univ.Choice',
    'SEQUENCE': 'univ.Sequence',
    'SET': 'univ.Set',
    'SEQUENCE OF': 'univ.SequenceOf',
    'SET OF': 'univ.SetOf',
    'OBJECT IDENTIFIER': 'univ.ObjectIdentifier',
    'UTF8String': 'char.UTF8String',
    'GeneralString': 'char.GeneralString',
    'NumericString': 'char.NumericString',
    'PrintableString': 'char.PrintableString',
    'IA5String': 'char.IA5String',
    'GraphicString': 'char.GraphicString',
    'GeneralizedTime': 'useful.GeneralizedTime',
    'UTCTime': 'useful.UTCTime',
    'ObjectDescriptor': 'useful.ObjectDescriptor',  # In pyasn1 r1.2
    'VisibleString': 'char.VisibleString',
}

def _translate_type(type_name):
    """ Translate ASN.1 built-in types to pyasn1 equivalents.
    Non-builtins are not translated.
    """
    assert isinstance(type_name, str), "Type name must be a string."
    type_name = _sanitize_identifier(type_name)

    return _ASN1_BUILTIN_TYPES.get(type_name, type_name)

def _translate_tag_class(tag_class):
    """ Translate ASN.1 tag class names to pyasn1 equivalents.
    Defaults to tag.tagClassContext if tag_class is not
    recognized.
    """
    return _ASN1_TAG_CONTEXTS.get(tag_class, 'tag.tagClassContext')

def _translate_value(value):
    """ Translate ASN.1 built-in values to Python equivalents.
    Unrecognized values are not translated.
    """
    if isinstance(value, ReferencedValue) or _heuristic_is_identifier(value):
        value = _sanitize_identifier(value)

    return _ASN1_BUILTIN_VALUES.get(value, value)

def _heuristic_is_identifier(value):
    """ Return True if this value is likely an identifier.
    """
    first = str(value)[0]
    return first != '-' and not first.isdigit()

def _sanitize_identifier(name):
    """ Sanitize ASN.1 type and value identifiers so that they're
    valid Python identifiers.
    """
    name = str(name)
    name = name.replace('-', '_')
    if name in keyword.kwlist:
        name += '_'

    return name

# Simplistic command-line driver
def main(args):
    with open(args[0]) as f:
        asn1def = f.read()

    parse_tree = parser.parse_asn1(asn1def)

    modules = build_semantic_model(parse_tree)
    if len(modules) > 1:
        print('WARNING: More than one module generated to the same stream.', file=sys.stderr)

    for module in modules:
        print(pygen.auto_generated_header())
        generate_pyasn1(module, sys.stdout)

    return 0

if __name__ == '__main__':
    sys.exit(main(sys.argv[1:]))


text:
class ProjectImportError (Exception):
    """Failure to import a project from a repository."""
    pass

redpajama_set_name: RedPajamaGithub


text:
package com.googlecode.yqltwitter;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

import twitter4j.Configuration;
import twitter4j.Status;

/**
 * Operations to assist YqlTwitter.
 *
 * @author Sutra Zhou
 */
/* package */class YqlTwitterUtils {
	private static final boolean DEBUG = Configuration.getDebug();
	private static final String YQL = "https://query.yahooapis.com/v1/public/yql?q=";
	private static final String enc = "UTF-8";

	/* package */static void debug(String message) {
		if (DEBUG) {
			System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
					.format(new Date())
					+ " " + message);
		}
	}

	/**
	 * Create the YQL query URL.
	 *
	 * @param q
	 *            the query string
	 * @return URL strng
	 */
	/* package */static String createYqlUrl(final String q) {
		try {
			final String url = YQL + URLEncoder.encode(q, enc);
			return url;
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
	}

	/* package */static <T> T newInstance(Class<T> clazz,
			Class<?>[] parameterTypes, Object[] initargs)
			throws InvocationTargetException {
		try {
			Constructor<T> c = clazz.getDeclaredConstructor(parameterTypes);
			c.setAccessible(true);
			return c.newInstance(initargs);
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (InstantiationException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

	@SuppressWarnings("unchecked")
	/* package */static <T, R> R invokeStaticMethod(Class<T> clazz,
			String name, Class<?>[] parameterTypes, Object[] args)
			throws InvocationTargetException {
		Method m;
		try {
			m = Status.class.getDeclaredMethod(name, parameterTypes);
			m.setAccessible(true);
			Object o = m.invoke(clazz, args);
			return (R) o;
		} catch (SecurityException e) {
			throw new RuntimeException(e);
		} catch (NoSuchMethodException e) {
			throw new RuntimeException(e);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}

}


text:
import shutil, os, re

# Create a regex that matches files with the American date format.
datePattern = re.compile(r"""^(.*?) # all text before the date
    ((0|1)?\d)-                     # one or two digits for the month
    ((0|1|2|3)?\d)-                 # one or two digits for the day
    ((19|20)\d\d)                   # for digits for the year
    (.*?)$                          # all text after the date
    """, re.VERBOSE)

# Loop over the files in the working directory.
for amerFilename in os.listdir('.'):
    mo = datePattern.search(amerFilename)

    # Skip files without a date.
    if mo == None:
        continue

    # Get the different parts of the filename.
    beforePart  = mo.group(1)
    monthPart   = mo.group(2)
    dayPart     = mo.group(4)
    yearPart    = mo.group(6)
    afterPart   = mo.group(8)

    # Form the European-style filename.
    euroFilename = beforePart + dayPart + '-' + monthPart + '-' + yearPart + afterPart

    # Get the full, absolute file paths.
    absWorkingDir = os.path.abspath('.')
    amerFilename = os.path.join(absWorkingDir, amerFilename)
    euroFilename = os.path.join(absWorkingDir, euroFilename)

    # Rename the files.
    print('Renaming "%s" to "%s"...' % (amerFilename, euroFilename))
    #shutil.move(amerFilename, euroFilename) # uncomment after testing


text:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using Modelisator.Forms.ViewModel;
using Modelisator.Model;
using Modelisator.View;

namespace Modelisator.ViewModel
{
    public class ModelisatorFrame_ViewModel
    {
        public Contexte Ctx;
        public EspaceTravail_ViewModel EspaceTravail_ViewModel;
        public Info_ViewModel Info_ViewModel;
        public MenuTop_ViewModel MenuTop_ViewModel;
        public ProduitChoix_ViewModel ProduitChoix_ViewModel;

        public event EventHandler<EventArgs> DeconnecterHandler;

        public ModelisatorFrame_ViewModel(Contexte ctx)
        {
            Ctx = ctx;
            View = new ModelisatorFram_View_UserControl();
            Model = new ModelisatorFrame_Model(ctx);
            SetupModelisatorFrame();
            ConnectView();

        }

        public ModelisatorFram_View_UserControl View { get; private set; }
        public ModelisatorFrame_Model Model { get; private set; }

        protected void PapierPeintChange(object sender, EventArgs e)
        {
            View.PapierpeintGrid.Background = MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.Model.CouleurBrush;
            Refresh();
        }

        protected void ChoixProduit_Clik_Action(object sender, EventArgs e)
        {
            EspaceTravail_ViewModel = new EspaceTravail_ViewModel(Ctx);
            View.EspaceTravail_ContentPanel.Children.Add(EspaceTravail_ViewModel.View);
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.View.btn_VueEnsemble.IsEnabled = true;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.View.btn_Export.IsEnabled = true;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.View.btn_Import.IsEnabled = true;
        }

        protected void SetupModelisatorFrame()
        {

            Info_ViewModel = new Info_ViewModel(Ctx);
            MenuTop_ViewModel = new MenuTop_ViewModel(Ctx);
            ProduitChoix_ViewModel = new ProduitChoix_ViewModel(Ctx);

            View.ProduitChoix_ContentPanel.Children.Add(ProduitChoix_ViewModel.View);
            View.Info_ContentPanel.Children.Add(Info_ViewModel.View);
            View.MenuTop_ContentPanel.Children.Add(MenuTop_ViewModel.View);
        }

        public void ConnectView()
        {
            View.PapierpeintGrid.DataContext = MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.Model.CouleurBrush;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.OKCOULEUR += PapierPeintChange;
            ProduitChoix_ViewModel.ClickBTNProduit += ChoixProduit_Clik_Action;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.VueEnsemble += VueEnsemble_Clik_Action;
        }

        public void DeconnectView()
        {
            View.PapierpeintGrid.DataContext = null;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.OKCOULEUR -= PapierPeintChange;
            ProduitChoix_ViewModel.ClickBTNProduit -= ChoixProduit_Clik_Action;
            MenuTop_ViewModel.MenuTop_CouleursForm_ViewModel.VueEnsemble += VueEnsemble_Clik_Action;
        }

        public void Refresh()
        {
            DeconnectView();
            ConnectView();
        }

        private void VueEnsemble_Clik_Action(object sender, EventArgs args)
        {
            EspaceTravail_ViewModel.RefreshVueGraph();
        }
    }
}


text:
require 'spec_helper'

describe "Promotion Adjustments" do
  stub_authorization!

  context "coupon promotions", :js => true do
    before(:each) do
      visit spree.admin_path
      click_link "Promotions"
      click_link "New Promotion"
    end

    it "should allow an admin to create a flat rate discount coupon promo" do
      fill_in "Name", :with => "Promotion"
      fill_in "Code", :with => "order"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Item total", :from => "Add rule of type"
      within('#rule_fields') { click_button "Add" }

      eventually_fill_in "promotion_promotion_rules_attributes_#{Spree::Promotion.count}_preferred_amount", :with => 30
      within('#rule_fields') { click_button "Update" }

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Flat Rate", :from => "Calculator"
      within('#actions_container') { click_button "Update" }

      within('.calculator-fields') { fill_in "Amount", :with => 5 }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.code.should == "order"

      first_rule = promotion.rules.first
      first_rule.class.should == Spree::Promotion::Rules::ItemTotal
      first_rule.preferred_amount.should == 30

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::FlatRate
      first_action_calculator.preferred_amount.should == 5
    end

    it "should allow an admin to create a single user coupon promo with flat rate discount" do
      fill_in "Name", :with => "Promotion"
      fill_in "Usage Limit", :with => "1"
      fill_in "Code", :with => "single_use"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Flat Rate", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('#action_fields') { fill_in "Amount", :with => "5" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.usage_limit.should == 1
      promotion.code.should == "single_use"

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::FlatRate
      first_action_calculator.preferred_amount.should == 5
    end

    it "should allow an admin to create an automatic promo with flat percent discount" do
      fill_in "Name", :with => "Promotion"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Item total", :from => "Add rule of type"
      within('#rule_fields') { click_button "Add" }

      eventually_fill_in "promotion_promotion_rules_attributes_1_preferred_amount", :with => 30
      within('#rule_fields') { click_button "Update" }

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Flat Percent", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('.calculator-fields') { fill_in "Flat Percent", :with => "10" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.code.should be_blank

      first_rule = promotion.rules.first
      first_rule.class.should == Spree::Promotion::Rules::ItemTotal
      first_rule.preferred_amount.should == 30

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::FlatPercentItemTotal
      first_action_calculator.preferred_flat_percent.should == 10
    end

    it "should allow an admin to create an product promo with percent per item discount" do
      create(:product, :name => "RoR Mug")

      fill_in "Name", :with => "Promotion"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Product(s)", :from => "Add rule of type"
      within("#rule_fields") { click_button "Add" }
      select2_search "RoR Mug", :from => "Choose products"
      within('#rule_fields') { click_button "Update" }

      select2 "Create per-line-item adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Percent Per Item", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('.calculator-fields') { fill_in "Percent", :with => "10" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.code.should be_blank

      first_rule = promotion.rules.first
      first_rule.class.should == Spree::Promotion::Rules::Product
      first_rule.products.map(&:name).should include("RoR Mug")

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateItemAdjustments
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::PercentOnLineItem
      first_action_calculator.preferred_percent.should == 10
    end

    xit "should allow an admin to create an automatic promotion with free shipping (no code)" do
      fill_in "Name", :with => "Promotion"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Item total", :from => "Add rule of type"
      within('#rule_fields') { click_button "Add" }
      eventually_fill_in "promotion_promotion_rules_attributes_1_preferred_amount", :with => "30"
      within('#rule_fields') { click_button "Update" }

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Free Shipping", :from => "Calculator"
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.code.should be_blank

      first_rule = promotion.rules.first
      first_rule.class.should == Spree::Promotion::Rules::ItemTotal

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::FreeShipping
    end

    it "should allow an admin to create an automatic promo requiring a landing page to be visited" do
      fill_in "Name", :with => "Promotion"
      fill_in "Path", :with => "content/cvv"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Flat Rate", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('.calculator-fields') { fill_in "Amount", :with => "4" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.path.should == "content/cvv"
      promotion.code.should be_blank
      promotion.rules.should be_blank

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action_calculator = first_action.calculator
      first_action_calculator.class.should == Spree::Calculator::FlatRate
      first_action_calculator.preferred_amount.should == 4
    end

    it "should allow an admin to create a promotion that adds a 'free' item to the cart" do
      create(:product, :name => "RoR Mug")
      fill_in "Name", :with => "Promotion"
      fill_in "Code", :with => "complex"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Create line items", :from => "Add action of type"

      within('#action_fields') { click_button "Add" }
      # Forced narcolepsy, thanks to JavaScript
      sleep(1)
      page.execute_script "$('.create_line_items .select2-choice').mousedown();"
      sleep(1)
      page.execute_script "$('.select2-input:visible').val('RoR Mug').trigger('keyup-change');"
      sleep(1)
      page.execute_script "$('.select2-highlighted').mouseup();"

      within('#actions_container') { click_button "Update" }

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#new_promotion_action_form') { click_button "Add" }
      select2 "Flat Rate", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('.calculator-fields') { fill_in "Amount", :with => "40.00" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")
      promotion.code.should == "complex"

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateLineItems
      line_item = first_action.promotion_action_line_items.should_not be_empty
    end

    it "ceasing to be eligible for a promotion with item total rule then becoming eligible again" do
      fill_in "Name", :with => "Promotion"
      click_button "Create"
      page.should have_content("Editing Promotion")

      select2 "Item total", :from => "Add rule of type"
      within('#rule_fields') { click_button "Add" }
      eventually_fill_in "promotion_promotion_rules_attributes_1_preferred_amount", :with => "50"
      within('#rule_fields') { click_button "Update" }

      select2 "Create whole-order adjustment", :from => "Add action of type"
      within('#action_fields') { click_button "Add" }
      select2 "Flat Rate", :from => "Calculator"
      within('#actions_container') { click_button "Update" }
      within('.calculator-fields') { fill_in "Amount", :with => "5" }
      within('#actions_container') { click_button "Update" }

      promotion = Spree::Promotion.find_by_name("Promotion")

      first_rule = promotion.rules.first
      first_rule.class.should == Spree::Promotion::Rules::ItemTotal
      first_rule.preferred_amount.should == 50

      first_action = promotion.actions.first
      first_action.class.should == Spree::Promotion::Actions::CreateAdjustment
      first_action.calculator.class.should == Spree::Calculator::FlatRate
      first_action.calculator.preferred_amount.should == 5
    end
  end
end


text:
Contributor L2Klbs
Contributor Pita
Contributor Dougy


text:
=pod

=head1 NAME

Locale::Codes::LangExt - standard codes for language extension identification

=head1 SYNOPSIS

   use Locale::Codes::LangExt;

   $lext = code2langext('acm');                 # $lext gets 'Mesopotamian Arabic'
   $code = langext2code('Mesopotamian Arabic'); # $code gets 'acm'

   @codes   = all_langext_codes();
   @names   = all_langext_names();

=head1 DESCRIPTION

The C<Locale::Codes::LangExt> module provides access to standard codes
used for identifying language extensions, such as those as defined in
the IANA language registry.

Most of the routines take an optional additional argument which
specifies the code set to use. If not specified, the default IANA
language registry codes will be used.

=head1 SUPPORTED CODE SETS

There are several different code sets you can use for identifying
language extensions. A code set may be specified using either a name, or a
constant that is automatically exported by this module.

For example, the two are equivalent:

   $lext = code2langext('acm','alpha');
   $lext = code2langext('acm',LOCALE_LANGEXT_ALPHA);

The codesets currently supported are:

=over 4

=item B<alpha>

This is the set of three-letter (lowercase) codes from the IANA
language registry, such as 'acm' for Mesopotamian Arabic.

This is the default code set.

=back

=head1 ROUTINES

=over 4

=item B<code2langext ( CODE [,CODESET] )>

=item B<langext2code ( NAME [,CODESET] )>

=item B<langext_code2code ( CODE ,CODESET ,CODESET2 )>

=item B<all_langext_codes ( [CODESET] )>

=item B<all_langext_names ( [CODESET] )>

=item B<Locale::Codes::LangExt::rename_langext  ( CODE ,NEW_NAME [,CODESET] )>

=item B<Locale::Codes::LangExt::add_langext  ( CODE ,NAME [,CODESET] )>

=item B<Locale::Codes::LangExt::delete_langext  ( CODE [,CODESET] )>

=item B<Locale::Codes::LangExt::add_langext_alias  ( NAME ,NEW_NAME )>

=item B<Locale::Codes::LangExt::delete_langext_alias  ( NAME )>

=item B<Locale::Codes::LangExt::rename_langext_code  ( CODE ,NEW_CODE [,CODESET] )>

=item B<Locale::Codes::LangExt::add_langext_code_alias  ( CODE ,NEW_CODE [,CODESET] )>

=item B<Locale::Codes::LangExt::delete_langext_code_alias  ( CODE [,CODESET] )>

These routines are all documented in the Locale::Codes::API man page.

=back

=head1 SEE ALSO

=over 4

=item B<Locale::Codes>

The Locale-Codes distribution.

=item B<Locale::Codes::API>

The list of functions supported by this module.

=item B<http://www.iana.org/assignments/language-subtag-registry>

The IANA language subtag registry.

=back

=head1 AUTHOR

See Locale::Codes for full author history.

Currently maintained by Sullivan Beck (sbeck@cpan.org).

=head1 COPYRIGHT

   Copyright (c) 2011-2013 Sullivan Beck

This module is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=cut


text:
import requests
from bs4 import BeautifulSoup
import processor

def parse( url ):

	r = requests.get( url )
	if r.status_code == 404:
		return processor.create_dictionary('', url, r.status_code, [u''], [u''], u'', u'', u'', u'', [u''], [u''])

	r.encoding = 'UTF-8'
	soup = BeautifulSoup( r.text, "html.parser" )

	article = soup.find( class_ = 'article-content')
	if article == None:
		return processor.create_dictionary('', url, r.status_code, [u''], [u''], u'', u'', u'', u'', [u''], [u''])

	processor.decompose_all( article.find_all( 'script' ) )
	processor.decompose( article.find( class_ = 'related-articles-container' ) )

	categories = processor.collect_categories( article.find_all( class_ = 'category' ) )

	datetime_data = article.find( class_ = 'post-meta' )
	processor.decompose( datetime_data.find( class_ = 'category' ) )
	processor.decompose( datetime_data.find( class_ = 'updated' ) )
	datetime_list = processor.collect_datetime( datetime_data )

	author = processor.collect_text( article.find( class_ = 'author--main') )
	title = processor.collect_text( article.find( class_ = 'heading--main' ) )
	images = processor.collect_images( article.find_all( 'img' ), 'src', '' )
	captions = processor.collect_image_captions( article.find_all( class_ = 'caption' ) )

	processor.decompose_all( article.find_all( class_ = 'image-wrapper' ) )
	text = processor.collect_text( article.find( class_ = 'content--main' ) )

	return processor.create_dictionary('Aamulehti', url, r.status_code, categories, datetime_list, author, title, u'', text, images, captions)

def parse_from_archive(url, content):

	article = BeautifulSoup( content, "html.parser" )

	if article == None:
		return processor.create_dictionary('Aamulehti', url, 404, [u''], [u''], u'', u'', u'', u'', [u''], [u''])

	meta = article.find( class_ = 'hakutuloslahde' )

	datetime_list = processor.collect_datetime( meta )

	category = processor.collect_text( meta ).split(',')[1].strip()
	subcat = processor.collect_text( article.find( class_ = 'jalkirivi' ) )
	subsubcat = processor.collect_text( article.find( class_ = 'esirivi' ) )

	categories = []
	for c in [category, subcat, subsubcat]:
		if c:
			categories.append(c)

	title = processor.collect_text( article.find( class_ = 'otsikko' ) )

	text_divs = article.find_all( class_ = 'artikkelip')
	text = ''
	for text_content in text_divs:
		text += processor.collect_text(text_content) + ' '
	text = processor.process( text.strip() )
	text += processor.collect_text( article.find( class_ = 'korjaus' ) )

	captions = processor.collect_image_captions( article.find_all( class_ = 'kuva') )

	return processor.create_dictionary('Aamulehti', url, 200, categories, datetime_list, u'', title, u'', text, [u''], captions)

if __name__ == '__main__':
	parse("http://www.aamulehti.fi/kotimaa/vanhemmat-uhmaavat-tamperelaisen-koulun-ohjetta-odotetaan-sita-paivaa-etta-joku-jaa-auton-alle/")


text:
namespace color
 {
  namespace trait
   {

    template< >
     struct component< ::color::category::LabCH_float >
      : public ::color::_internal::utility::component::array< float >
      {
      };

    template< >
     struct component< ::color::category::LabCH_double >
      : public ::color::_internal::utility::component::array< double >
      {
      };

    template< >
     struct component< ::color::category::LabCH_ldouble >
      : public ::color::_internal::utility::component::array< long double >
      {
      };

   }
 }

#endif


text:
package me.johnking.zsigncontroller;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.xxmicloxx.znetworklib.packet.core.GeneralRequest;
import com.xxmicloxx.znetworkplugin.ResultHandler;
import com.xxmicloxx.znetworkplugin.ZNativePlugin;
import com.xxmicloxx.znetworkplugin.ZNetworkPlugin;
import jline.console.ConsoleReader;
import me.johnking.zsigncontroller.command.CommandHandler;
import me.johnking.zsigncontroller.command.CommandLineReader;
import me.johnking.zsigncontroller.mysql.MySQL;
import me.johnking.zsigncontroller.mysql.MySQLData;

import java.io.File;
import java.io.IOException;
import java.util.logging.ConsoleHandler;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Created by Marco on 02.10.2014.
 */
public class ZSignController implements ZNativePlugin{

    private static Logger logger;

    private static ZSignController instance;
    private ConsoleReader reader;
    private ShutdownThread shutdownThread;
    private String name;
    private Gson gson;
    private CommandLineReader commandReader;
    private CommandHandler handler;
    private SignUpdater updater;

    public static void main(String[] args) {
        instance = new ZSignController();
        instance.enable();
    }

    public void start() {
        //////////////////////////////////////////////////////
        File file = new File("mysql.json");
        String input = FileHelper.stringFromFile(file);
        MySQLData data = gson.fromJson(input, MySQLData.class);
        this.updater = new SignUpdater(data);
        logger.log(Level.INFO, "Done!");
        this.updater.start();
        //////////////////////////////////////////////////////
    }

    public void stop() {
        //////////////////////////////////////////////////////
        logger.log(Level.INFO, "Disabling all signs!");
        this.updater.setEnabled(false);
        //////////////////////////////////////////////////////
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        ZSignController.getLogger().log(Level.INFO, "Disabling network-connection ... ");
        ZNetworkPlugin.getInstance().onDisable();
        ZSignController.getLogger().log(Level.INFO, "Done! Thank you and goodbye!");
    }

    public void enable() {
        new ZNetworkPlugin(this);
        ZNetworkPlugin.getInstance().onEnable();

        try {
            this.reader = new ConsoleReader(System.in, System.out);
        } catch (IOException e){
            System.out.println("Could not load console reader!");
            System.exit(2);
        }
        this.handler = new CommandHandler(this.reader);
        this.commandReader = new CommandLineReader(this.handler, this.reader);

        logger = createLogger();

        name = ZNetworkPlugin.getInstance().getConnectionName();
        if(name == null || name.equals("")){
            logger.log(Level.SEVERE, "Could not load my name!");
            System.exit(1);
        }
        gson = new GsonBuilder().setPrettyPrinting().create();
        this.shutdownThread = new ShutdownThread();
        Runtime.getRuntime().addShutdownHook(this.shutdownThread);
        start();
    }

    @Override
    public void shutdown() {
        Runtime.getRuntime().removeShutdownHook(this.shutdownThread);
        try {
            stop();
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            try {
                this.reader.getTerminal().restore();
            } catch (Exception e){
                e.printStackTrace();
            }
            System.exit(0);
        }
    }

    @Override
    public void handleRequest(GeneralRequest generalRequest, ResultHandler resultHandler) {

    }

    private static Logger createLogger(){
        Logger logger = Logger.getLogger("ZSignController");
        ConsoleHandler handler = new ConsoleHandler();
        handler.setFormatter(new LogFormatter());
        logger.addHandler(handler);
        logger.setUseParentHandlers(false);
        return logger;
    }

    public ConsoleReader getReader() {
        return reader;
    }

    public static ZSignController getInstance() {
        return instance;
    }

    public static Logger getLogger(){
        return logger;
    }

    public SignUpdater getSignUpdater() {
        return updater;
    }
}


text:
interface Animal {
    name: string;
    kind: string;
    age: number;
    location: string;
    owner: object;
}

function clonePet(pet: Animal, fullCopy?: boolean) {
    return {
        name: pet.name,
        kind: pet.kind,
        ...(fullCopy && pet),
    }
}

interface Animal2 {
    name: string;
    owner?: string;
}
function billOwner(pet: Animal2) {
    return {
        ...(pet.owner && pet),
        paid: false
    }
}

//// [spreadIdenticalTypesRemoved.js]
"use strict";
var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
function clonePet(pet, fullCopy) {
    return __assign({ name: pet.name, kind: pet.kind }, (fullCopy && pet));
}
function billOwner(pet) {
    return __assign(__assign({}, (pet.owner && pet)), { paid: false });
}


text:
layout: post
title: Lesbian sex - Katherine J and Paula B
titleinfo: pornvd
desc: Watch Lesbian sex - Katherine J and Paula B. Pornhub is the ultimate xxx porn and sex site.
---

Lesbian sex - Katherine J and Paula B

Watch Lesbian sex - Katherine J and Paula B. Pornhub is the ultimate xxx porn and sex site.


text:
import React, {Component} from 'react'
import {connect} from 'react-redux'
import Browse from './Browse'

class BrowseContainer extends Component {
  render() {
    return (
      <Browse/>
    )
  }

  componentDidMount() {
  }
}

const mapStateToProps = (rootState) => {
  return {
    payload: rootState,
  }
}
const mapDispatchToProps = () => {
  return {}
}
export default connect(mapStateToProps, mapDispatchToProps)(BrowseContainer)


text:
import json
import pytest

@pytest.mark.parametrize('_return_value , res', [
    ('test_data/process_list.json', 'test_data/process_list.md')
])
def test_entries_to_markdown(_return_value, res):
    """
    Given:
        - _return_values a process list
    When:
        - running the automation
    Then:
        - parse the _return_value string entries and return them in a markdown format
    """
    from ReadProcessesFileXDR import entries_to_markdown
    with open(_return_value, 'r') as process_list_from_xdr:
        # Reading from json file
        proces_list = json.load(process_list_from_xdr)
    entries_as_md = entries_to_markdown(proces_list)
    with open(res, 'r') as res_md:
        res_md = res_md.read()
    assert res_md == entries_as_md

@pytest.mark.parametrize('script_results , res', [
    ('test_data/filter_script_results.json', 'test_data/script_results.json'),
    ('test_data/filter_script_results_one_obj.json', 'test_data/res_filter_script_results_one_obj.json')
])
def test_find_last_process_list_script(script_results, res):
    """
    Given:
        - script_results
    When:
        - after running a script on the XDRIR integration
    Then:
        - choose the last script that is related to the process list.
        (contains the Name,CPU,Memory in the entry).
    """
    from ReadProcessesFileXDR import find_last_process_list_script
    with open('test_data/script_results.json') as f:
        script_results = json.load(f)
    script_result = find_last_process_list_script(script_results)
    with open('test_data/filter_script_results.json', 'r') as res:
        filter_res = json.load(res)
    assert filter_res == script_result

def test_entries_to_markdown_none():
    """
    Given:
        - _return_values a None process list
    When:
        - running the automation
    Then:
        - parse the _return_value string entries and return them in a markdown format
    """
    from ReadProcessesFileXDR import entries_to_markdown
    entries_as_md = entries_to_markdown(None)
    assert "" == entries_as_md

@pytest.mark.parametrize('entry, res', [('Name: System Idle Process, CPU: 50.0, Memory: 8192', True),
                                        ('Name , CPU', False),
                                        ('', False)
                                        ])
def test_detect_process_field(entry, res):
    """
    Given:
        - a _return_value record
    When:
        - calling find last process list
    Then
        - check that the first entry has all the required filds
    """
    from ReadProcessesFileXDR import detect_process_field
    assert detect_process_field(entry) == res

@pytest.mark.parametrize('script_results, res', [({'results': {
    '_return_value': ["Name: System Idle Process, CPU: 50.0, Memory: 8192"]}},
    ["Name: System Idle Process, CPU: 50.0, Memory: 8192"]),
    ([{'results': [{'_return_value': [
        "Name: System Idle Process, CPU: 50.0, Memory: 8192"]}]}],
     ["Name: System Idle Process, CPU: 50.0, Memory: 8192"]),
    ([{'results': [{'_return_value': [
        "Name: System Idle Process, CPU: 50.0, blabla: 8192"]}]}],
     None),
    (None, None),
])
def test_find_last_process_list_script_(script_results, res):
    """
    Given:
        - script_results with different structure.
    When:
        - after running a script on the XDRIR integration
    Then:
        - Check that the function knows how to parse all the cases and return the correct result
    """
    from ReadProcessesFileXDR import find_last_process_list_script
    assert find_last_process_list_script(script_results) == res


text:
package io.aeron.driver;

import io.aeron.logbuffer.LogBufferDescriptor;
import org.junit.jupiter.api.Test;
import org.mockito.InOrder;
import io.aeron.logbuffer.FrameDescriptor;
import io.aeron.logbuffer.TermRebuilder;
import io.aeron.protocol.DataHeaderFlyweight;
import io.aeron.protocol.HeaderFlyweight;
import org.agrona.concurrent.UnsafeBuffer;

import java.nio.ByteBuffer;
import java.util.concurrent.TimeUnit;

import static org.mockito.Mockito.*;
import static io.aeron.logbuffer.LogBufferDescriptor.TERM_MIN_LENGTH;
import static io.aeron.logbuffer.LogBufferDescriptor.computePosition;
import static org.agrona.BitUtil.align;

class LossDetectorTest
{
    private static final int TERM_BUFFER_LENGTH = TERM_MIN_LENGTH;
    private static final int POSITION_BITS_TO_SHIFT = LogBufferDescriptor.positionBitsToShift(TERM_BUFFER_LENGTH);
    private static final int MASK = TERM_BUFFER_LENGTH - 1;

    private static final byte[] DATA = new byte[36];

    static
    {
        for (int i = 0; i < DATA.length; i++)
        {
            DATA[i] = (byte)i;
        }
    }

    private static final int MESSAGE_LENGTH = DataHeaderFlyweight.HEADER_LENGTH + DATA.length;
    private static final int ALIGNED_FRAME_LENGTH = align(MESSAGE_LENGTH, FrameDescriptor.FRAME_ALIGNMENT);
    private static final int SESSION_ID = 0x5E55101D;
    private static final int STREAM_ID = 0xC400E;
    private static final int TERM_ID = 0xEE81D;
    private static final long ACTIVE_TERM_POSITION = computePosition(TERM_ID, 0, POSITION_BITS_TO_SHIFT, TERM_ID);

    private static final StaticDelayGenerator DELAY_GENERATOR = new StaticDelayGenerator(
        TimeUnit.MILLISECONDS.toNanos(20), false);

    private static final StaticDelayGenerator DELAY_GENERATOR_WITH_IMMEDIATE = new StaticDelayGenerator(
        TimeUnit.MILLISECONDS.toNanos(20), true);

    private final UnsafeBuffer termBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(TERM_BUFFER_LENGTH));
    private final UnsafeBuffer rcvBuffer = new UnsafeBuffer(ByteBuffer.allocateDirect(MESSAGE_LENGTH));
    private final DataHeaderFlyweight dataHeader = new DataHeaderFlyweight();

    private final LossHandler lossHandler = mock(LossHandler.class);
    private LossDetector lossDetector = new LossDetector(DELAY_GENERATOR, lossHandler);;
    private long currentTime = 0;

    {
        dataHeader.wrap(rcvBuffer);
    }

    @Test
    void shouldNotSendNakWhenBufferIsEmpty()
    {
        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION;

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(100);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verifyNoInteractions(lossHandler);
    }

    @Test
    void shouldNotNakIfNoMissingData()
    {
        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(1));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(40);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verifyNoInteractions(lossHandler);
    }

    @Test
    void shouldNakMissingData()
    {
        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(40);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler).onGapDetected(TERM_ID, offsetOfMessage(1), gapLength());
    }

    @Test
    void shouldRetransmitNakForMissingData()
    {
        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(30);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(60);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler, atLeast(2)).onGapDetected(TERM_ID, offsetOfMessage(1), gapLength());
    }

    @Test
    void shouldStopNakOnReceivingData()
    {
        long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(20);
        insertDataFrame(offsetOfMessage(1));
        rebuildPosition += (ALIGNED_FRAME_LENGTH * 3L);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(100);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verifyNoInteractions(lossHandler);
    }

    @Test
    void shouldHandleMoreThan2Gaps()
    {
        long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 7L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));
        insertDataFrame(offsetOfMessage(4));
        insertDataFrame(offsetOfMessage(6));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(40);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        insertDataFrame(offsetOfMessage(1));
        rebuildPosition += (ALIGNED_FRAME_LENGTH * 3L);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(80);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        final InOrder inOrder = inOrder(lossHandler);
        inOrder.verify(lossHandler, atLeast(1)).onGapDetected(TERM_ID, offsetOfMessage(1), gapLength());
        inOrder.verify(lossHandler, atLeast(1)).onGapDetected(TERM_ID, offsetOfMessage(3), gapLength());
        inOrder.verify(lossHandler, never()).onGapDetected(TERM_ID, offsetOfMessage(5), gapLength());
    }

    @Test
    void shouldReplaceOldNakWithNewNak()
    {
        long rebuildPosition = ACTIVE_TERM_POSITION;
        long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(20);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        insertDataFrame(offsetOfMessage(4));
        insertDataFrame(offsetOfMessage(1));
        rebuildPosition += (ALIGNED_FRAME_LENGTH * 3L);
        hwmPosition = (ALIGNED_FRAME_LENGTH * 5L);

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        currentTime = TimeUnit.MILLISECONDS.toNanos(100);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler, atLeast(1)).onGapDetected(TERM_ID, offsetOfMessage(3), gapLength());
    }

    @Test
    void shouldHandleImmediateNak()
    {
        lossDetector = getLossHandlerWithImmediate();

        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler).onGapDetected(TERM_ID, offsetOfMessage(1), gapLength());
    }

    @Test
    void shouldNotNakImmediatelyByDefault()
    {
        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verifyNoInteractions(lossHandler);
    }

    @Test
    void shouldOnlySendNaksOnceOnMultipleScans()
    {
        lossDetector = getLossHandlerWithImmediate();

        final long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);

        insertDataFrame(offsetOfMessage(0));
        insertDataFrame(offsetOfMessage(2));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);
        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler).onGapDetected(TERM_ID, offsetOfMessage(1), gapLength());
    }

    @Test
    void shouldHandleHwmGreaterThanCompletedBuffer()
    {
        lossDetector = getLossHandlerWithImmediate();

        long rebuildPosition = ACTIVE_TERM_POSITION;
        final long hwmPosition = ACTIVE_TERM_POSITION + TERM_BUFFER_LENGTH + ALIGNED_FRAME_LENGTH;

        insertDataFrame(offsetOfMessage(0));
        rebuildPosition += ALIGNED_FRAME_LENGTH;

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler).onGapDetected(TERM_ID, offsetOfMessage(1), TERM_BUFFER_LENGTH - (int)rebuildPosition);
    }

    @Test
    void shouldHandleNonZeroInitialTermOffset()
    {
        lossDetector = getLossHandlerWithImmediate();

        final long rebuildPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 3L);
        final long hwmPosition = ACTIVE_TERM_POSITION + (ALIGNED_FRAME_LENGTH * 5L);

        insertDataFrame(offsetOfMessage(2));
        insertDataFrame(offsetOfMessage(4));

        lossDetector.scan(termBuffer, rebuildPosition, hwmPosition, currentTime, MASK, POSITION_BITS_TO_SHIFT, TERM_ID);

        verify(lossHandler).onGapDetected(TERM_ID, offsetOfMessage(3), gapLength());
        verifyNoMoreInteractions(lossHandler);
    }

    private LossDetector getLossHandlerWithImmediate()
    {
        return new LossDetector(DELAY_GENERATOR_WITH_IMMEDIATE, lossHandler);
    }

    private void insertDataFrame(final int offset)
    {
        insertDataFrame(offset, DATA);
    }

    private void insertDataFrame(final int offset, final byte[] payload)
    {
        dataHeader
            .termId(TERM_ID)
            .streamId(STREAM_ID)
            .sessionId(SESSION_ID)
            .termOffset(offset)
            .frameLength(payload.length + DataHeaderFlyweight.HEADER_LENGTH)
            .headerType(HeaderFlyweight.HDR_TYPE_DATA)
            .flags(DataHeaderFlyweight.BEGIN_AND_END_FLAGS)
            .version(HeaderFlyweight.CURRENT_VERSION);

        rcvBuffer.putBytes(dataHeader.dataOffset(), payload);

        TermRebuilder.insert(termBuffer, offset, rcvBuffer, payload.length + DataHeaderFlyweight.HEADER_LENGTH);
    }

    private int offsetOfMessage(final int index)
    {
        return index * ALIGNED_FRAME_LENGTH;
    }

    private int gapLength()
    {
        return ALIGNED_FRAME_LENGTH;
    }
}


text:
<?php
namespace Tuurbo\Spreedly;

return [
    'service_manager' => [
        'factories' => [
            'spreedly.client' => 'Tuurbo\Spreedly\Factory\ClientFactory',
        ],
    ],
    'spreedly' => [
      'key'     => '', // Environment key
      'secret'  => '', // Signing Secret
      'gateway' => '', // Default gateway
    ]
];


text:
if [ "x$1" = "x-b" ]; then
	# This is highly x86-centric and will be used directly below.
	bootable="-o bootimage=i386;$4/boot/cdboot -o no-emul-boot"
	shift
else
	bootable=""
fi

if [ $# -lt 3 ]; then
	echo Usage: $0 '[-b] image-label image-name base-bits-dir [extra-bits-dir]'
	exit 1
fi

LABEL=`echo $1 | tr '[:lower:]' '[:upper:]'`; shift
NAME=$1; shift

publisher="The FreeBSD Project.  http://www.FreeBSD.org/"
echo "/dev/iso9660/$LABEL / cd9660 ro 0 0" > $1/etc/fstab
makefs -t cd9660 $bootable -o rockridge -o label=$LABEL -o publisher="$publisher" $NAME $*
rm $1/etc/fstab


text:
/* $NetBSD: t_msgget.c,v 1.1 2011/11/05 07:45:41 jruoho Exp $ */

/*-
 * Copyright (c) 2011 The NetBSD Foundation, Inc.
 * All rights reserved.
 *
 * This code is derived from software contributed to The NetBSD Foundation
 * by Jukka Ruohonen.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
#include <sys/cdefs.h>
__RCSID("$NetBSD: t_msgget.c,v 1.1 2011/11/05 07:45:41 jruoho Exp $");

#include <sys/msg.h>
#include <sys/stat.h>
#include <sys/sysctl.h>
#include <sys/wait.h>

#include <atf-c.h>
#include <errno.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sysexits.h>
#include <time.h>
#include <unistd.h>

#define MSG_KEY		12345689

static void		clean(void);

static void
clean(void)
{
	int id;

	if ((id = msgget(MSG_KEY, 0)) != -1)
		(void)msgctl(id, IPC_RMID, 0);
}

ATF_TC_WITH_CLEANUP(msgget_excl);
ATF_TC_HEAD(msgget_excl, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test msgget(2) with IPC_EXCL");
}

ATF_TC_BODY(msgget_excl, tc)
{
	int id;

	/*
	 * Create a message queue and re-open it with
	 * O_CREAT and IPC_EXCL set. This should fail.
	 */
	id = msgget(MSG_KEY, IPC_CREAT | 0600);

	if (id < 0)
		atf_tc_fail("failed to create message queue");

	errno = 0;

	if (msgget(MSG_KEY, IPC_CREAT | IPC_EXCL | 0600) != -1)
		atf_tc_fail("msgget(2) failed for IPC_EXCL");

	ATF_REQUIRE(errno == EEXIST);

	/*
	 * However, the same call should succeed
	 * when IPC_EXCL is not set in the flags.
	 */
	id = msgget(MSG_KEY, IPC_CREAT | 0600);

	if (id < 0)
		atf_tc_fail("msgget(2) failed to re-open");

	ATF_REQUIRE(msgctl(id, IPC_RMID, 0) == 0);
}

ATF_TC_CLEANUP(msgget_excl, tc)
{
	clean();
}

ATF_TC_WITH_CLEANUP(msgget_exit);
ATF_TC_HEAD(msgget_exit, tc)
{
	atf_tc_set_md_var(tc, "descr",
	    "Test that XSI message queues are "
	    "not removed when the process exits");
}

ATF_TC_BODY(msgget_exit, tc)
{
	int id, sta;
	pid_t pid;

	pid = fork();
	ATF_REQUIRE(pid >= 0);

	if (pid == 0) {

		if (msgget(MSG_KEY, IPC_CREAT | IPC_EXCL | 0600) == -1)
			_exit(EXIT_FAILURE);

		_exit(EXIT_SUCCESS);
	}

	(void)wait(&sta);

	if (WIFEXITED(sta) == 0 || WEXITSTATUS(sta) != EXIT_SUCCESS)
		atf_tc_fail("failed to create message queue");

	id = msgget(MSG_KEY, 0);

	if (id == -1)
		atf_tc_fail("message queue was removed on process exit");

	ATF_REQUIRE(msgctl(id, IPC_RMID, 0) == 0);
}

ATF_TC_CLEANUP(msgget_exit, tc)
{
	clean();
}

ATF_TC_WITH_CLEANUP(msgget_init);
ATF_TC_HEAD(msgget_init, tc)
{
	atf_tc_set_md_var(tc, "descr",
	    "Test that msgget(2) initializes data structures properly");
}

ATF_TC_BODY(msgget_init, tc)
{
	const uid_t uid = geteuid();
	const gid_t gid = getegid();
	struct msqid_ds msgds;
	time_t t;
	int id;

	(void)memset(&msgds, 0x9, sizeof(struct msqid_ds));

	t = time(NULL);
	id = msgget(MSG_KEY, IPC_CREAT | 0600);

	ATF_REQUIRE(id !=-1);
	ATF_REQUIRE(msgctl(id, IPC_STAT, &msgds) == 0);

	ATF_CHECK(msgds.msg_qnum == 0);
	ATF_CHECK(msgds.msg_lspid == 0);
	ATF_CHECK(msgds.msg_lrpid == 0);
	ATF_CHECK(msgds.msg_rtime == 0);
	ATF_CHECK(msgds.msg_stime == 0);
	ATF_CHECK(msgds.msg_perm.uid == uid);
	ATF_CHECK(msgds.msg_perm.gid == gid);
	ATF_CHECK(msgds.msg_perm.cuid == uid);
	ATF_CHECK(msgds.msg_perm.cgid == gid);
	ATF_CHECK(msgds.msg_perm.mode == 0600);

	if (abs(t - msgds.msg_ctime) > 5)
		atf_tc_fail("msgget(2) initialized current time incorrectly");

	ATF_REQUIRE(msgctl(id, IPC_RMID, 0) == 0);
}

ATF_TC_CLEANUP(msgget_init, tc)
{
	clean();
}

ATF_TC(msgget_limit);
ATF_TC_HEAD(msgget_limit, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test msgget(2) against system limits");
}

ATF_TC_BODY(msgget_limit, tc)
{
	size_t len = sizeof(int);
	bool fail = false;
	int i, lim = 0;
	int *buf;

	if (sysctlbyname("kern.ipc.msgmni", &lim, &len, NULL, 0) != 0)
		atf_tc_skip("failed to read kern.ipc.msgmni sysctl");

	buf = calloc(lim + 1, sizeof(*buf));
	ATF_REQUIRE(buf != NULL);

	for (i = 0; i < lim; i++) {

		buf[i] = msgget(MSG_KEY + i, IPC_CREAT | IPC_EXCL | 0600);

		(void)fprintf(stderr, "key[%d] = %d\n", i, buf[i]);

		/*
		 * This test only works when there are zero existing
		 * message queues. Thus, bypass the unit test when
		 * this precondition is not met, for reason or another.
		 */
		if (buf[i] == -1)
			goto out;
	}

	i++;
	errno = 0;

	buf[i] = msgget(MSG_KEY + i, IPC_CREAT | IPC_EXCL | 0600);

	if (buf[i] != -1 || errno != ENOSPC)
		fail = true;

out:	/* Remember to clean-up. */
	for (i = 0; i < lim; i++)
		(void)msgctl(buf[i], IPC_RMID, 0);

	free(buf);

	if (fail != false)
		atf_tc_fail("msgget(2) opened more than %d queues", lim);
}

ATF_TC_WITH_CLEANUP(msgget_mode);
ATF_TC_HEAD(msgget_mode, tc)
{
	atf_tc_set_md_var(tc, "descr", "Test different modes with msgget(2)");
	atf_tc_set_md_var(tc, "require.user", "root");
}

ATF_TC_BODY(msgget_mode, tc)
{
	static const mode_t mode[] = {
		S_IRWXU, S_IRUSR, S_IWUSR, S_IXUSR, S_IRWXG, S_IRGRP,
		S_IWGRP, S_IXGRP, S_IRWXO, S_IROTH, S_IWOTH, S_IXOTH
	};

	struct msqid_ds msgds;
	size_t i;
	int id;

	for (i = 0; i < __arraycount(mode); i++) {

		(void)fprintf(stderr, "testing mode %d\n", mode[i]);
		(void)memset(&msgds, 0, sizeof(struct msqid_ds));

		id = msgget(MSG_KEY, IPC_CREAT | IPC_EXCL | (int)mode[i]);

		ATF_REQUIRE(id != -1);
		ATF_REQUIRE(msgctl(id, IPC_STAT, &msgds) == 0);
		ATF_REQUIRE(msgds.msg_perm.mode == mode[i]);
		ATF_REQUIRE(msgctl(id, IPC_RMID, 0) == 0);
	}
}

ATF_TC_CLEANUP(msgget_mode, tc)
{
	clean();
}

ATF_TP_ADD_TCS(tp)
{

	ATF_TP_ADD_TC(tp, msgget_excl);
	ATF_TP_ADD_TC(tp, msgget_exit);
	ATF_TP_ADD_TC(tp, msgget_init);
	ATF_TP_ADD_TC(tp, msgget_limit);
	ATF_TP_ADD_TC(tp, msgget_mode);

	return atf_no_error();
}


text:
namespace NCrontab
{
    using System;

    /// <summary>
    /// Represents the method that will generate an <see cref="Exception"/> object.
    /// </summary>

    public delegate Exception ExceptionProvider();
}


text:
package com.google.cloud.workflows.v1beta.samples;

// [START workflows_v1beta_generated_Workflows_UpdateWorkflow_LRO_async]
import com.google.api.gax.longrunning.OperationFuture;
import com.google.cloud.workflows.v1beta.OperationMetadata;
import com.google.cloud.workflows.v1beta.UpdateWorkflowRequest;
import com.google.cloud.workflows.v1beta.Workflow;
import com.google.cloud.workflows.v1beta.WorkflowsClient;
import com.google.protobuf.FieldMask;

public class AsyncUpdateWorkflowLRO {

  public static void main(String[] args) throws Exception {
    asyncUpdateWorkflowLRO();
  }

  public static void asyncUpdateWorkflowLRO() throws Exception {
    // This snippet has been automatically generated and should be regarded as a code template only.
    // It will require modifications to work:
    // - It may require correct/in-range values for request initialization.
    // - It may require specifying regional endpoints when creating the service client as shown in
    // https://cloud.google.com/java/docs/setup#configure_endpoints_for_the_client_library
    try (WorkflowsClient workflowsClient = WorkflowsClient.create()) {
      UpdateWorkflowRequest request =
          UpdateWorkflowRequest.newBuilder()
              .setWorkflow(Workflow.newBuilder().build())
              .setUpdateMask(FieldMask.newBuilder().build())
              .build();
      OperationFuture<Workflow, OperationMetadata> future =
          workflowsClient.updateWorkflowOperationCallable().futureCall(request);
      // Do something.
      Workflow response = future.get();
    }
  }
}
// [END workflows_v1beta_generated_Workflows_UpdateWorkflow_LRO_async]


text:
"""Support for interface with an Samsung TV."""
from __future__ import annotations

import asyncio
from collections.abc import Coroutine, Sequence
from datetime import datetime, timedelta
from typing import Any

from async_upnp_client.aiohttp import AiohttpNotifyServer, AiohttpSessionRequester
from async_upnp_client.client import UpnpDevice, UpnpService, UpnpStateVariable
from async_upnp_client.client_factory import UpnpFactory
from async_upnp_client.exceptions import (
    UpnpActionResponseError,
    UpnpCommunicationError,
    UpnpConnectionError,
    UpnpError,
    UpnpResponseError,
    UpnpXmlContentError,
)
from async_upnp_client.profiles.dlna import DmrDevice
from async_upnp_client.utils import async_get_local_ip
import voluptuous as vol
from wakeonlan import send_magic_packet

from homeassistant.components.media_player import (
    MediaPlayerDeviceClass,
    MediaPlayerEntity,
    MediaPlayerEntityFeature,
)
from homeassistant.components.media_player.const import (
    MEDIA_TYPE_APP,
    MEDIA_TYPE_CHANNEL,
)
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntry
from homeassistant.const import (
    CONF_HOST,
    CONF_MAC,
    CONF_MODEL,
    CONF_NAME,
    STATE_OFF,
    STATE_ON,
)
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import entity_component
from homeassistant.helpers.aiohttp_client import async_get_clientsession
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.device_registry import CONNECTION_NETWORK_MAC
from homeassistant.helpers.entity import DeviceInfo
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.script import Script
from homeassistant.util import dt as dt_util

from .bridge import SamsungTVBridge, SamsungTVWSBridge
from .const import (
    CONF_MANUFACTURER,
    CONF_ON_ACTION,
    CONF_SSDP_RENDERING_CONTROL_LOCATION,
    DEFAULT_NAME,
    DOMAIN,
    LOGGER,
)

SOURCES = {"TV": "KEY_TV", "HDMI": "KEY_HDMI"}

SUPPORT_SAMSUNGTV = (
    MediaPlayerEntityFeature.PAUSE
    | MediaPlayerEntityFeature.VOLUME_STEP
    | MediaPlayerEntityFeature.VOLUME_MUTE
    | MediaPlayerEntityFeature.PREVIOUS_TRACK
    | MediaPlayerEntityFeature.SELECT_SOURCE
    | MediaPlayerEntityFeature.NEXT_TRACK
    | MediaPlayerEntityFeature.TURN_OFF
    | MediaPlayerEntityFeature.PLAY
    | MediaPlayerEntityFeature.PLAY_MEDIA
)

# Since the TV will take a few seconds to go to sleep
# and actually be seen as off, we need to wait just a bit
# more than the next scan interval
SCAN_INTERVAL_PLUS_OFF_TIME = entity_component.DEFAULT_SCAN_INTERVAL + timedelta(
    seconds=5
)

# Max delay waiting for app_list to return, as some TVs simply ignore the request
APP_LIST_DELAY = 3

async def async_setup_entry(
    hass: HomeAssistant, entry: ConfigEntry, async_add_entities: AddEntitiesCallback
) -> None:
    """Set up the Samsung TV from a config entry."""
    bridge = hass.data[DOMAIN][entry.entry_id]

    host = entry.data[CONF_HOST]
    on_script = None
    data = hass.data[DOMAIN]
    if turn_on_action := data.get(host, {}).get(CONF_ON_ACTION):
        on_script = Script(
            hass, turn_on_action, entry.data.get(CONF_NAME, DEFAULT_NAME), DOMAIN
        )

    async_add_entities([SamsungTVDevice(bridge, entry, on_script)], True)

class SamsungTVDevice(MediaPlayerEntity):
    """Representation of a Samsung TV."""

    _attr_source_list: list[str]

    def __init__(
        self,
        bridge: SamsungTVBridge,
        config_entry: ConfigEntry,
        on_script: Script | None,
    ) -> None:
        """Initialize the Samsung device."""
        self._config_entry = config_entry
        self._host: str | None = config_entry.data[CONF_HOST]
        self._mac: str | None = config_entry.data.get(CONF_MAC)
        self._ssdp_rendering_control_location: str | None = config_entry.data.get(
            CONF_SSDP_RENDERING_CONTROL_LOCATION
        )
        self._on_script = on_script
        # Assume that the TV is in Play mode
        self._playing: bool = True

        self._attr_name: str | None = config_entry.data.get(CONF_NAME)
        self._attr_state: str | None = None
        self._attr_unique_id = config_entry.unique_id
        self._attr_is_volume_muted: bool = False
        self._attr_device_class = MediaPlayerDeviceClass.TV
        self._attr_source_list = list(SOURCES)
        self._app_list: dict[str, str] | None = None
        self._app_list_event: asyncio.Event = asyncio.Event()

        self._attr_supported_features = SUPPORT_SAMSUNGTV
        if self._on_script or self._mac:
            # Add turn-on if on_script or mac is available
            self._attr_supported_features |= MediaPlayerEntityFeature.TURN_ON
        if self._ssdp_rendering_control_location:
            self._attr_supported_features |= MediaPlayerEntityFeature.VOLUME_SET

        self._attr_device_info = DeviceInfo(
            name=self.name,
            manufacturer=config_entry.data.get(CONF_MANUFACTURER),
            model=config_entry.data.get(CONF_MODEL),
        )
        if self.unique_id:
            self._attr_device_info["identifiers"] = {(DOMAIN, self.unique_id)}
        if self._mac:
            self._attr_device_info["connections"] = {
                (CONNECTION_NETWORK_MAC, self._mac)
            }

        # Mark the end of a shutdown command (need to wait 15 seconds before
        # sending the next command to avoid turning the TV back ON).
        self._end_of_power_off: datetime | None = None
        self._bridge = bridge
        self._auth_failed = False
        self._bridge.register_reauth_callback(self.access_denied)
        self._bridge.register_app_list_callback(self._app_list_callback)

        self._dmr_device: DmrDevice | None = None
        self._upnp_server: AiohttpNotifyServer | None = None

    def _update_sources(self) -> None:
        self._attr_source_list = list(SOURCES)
        if app_list := self._app_list:
            self._attr_source_list.extend(app_list)

    def _app_list_callback(self, app_list: dict[str, str]) -> None:
        """App list callback."""
        self._app_list = app_list
        self._update_sources()
        self._app_list_event.set()

    def access_denied(self) -> None:
        """Access denied callback."""
        LOGGER.debug("Access denied in getting remote object")
        self._auth_failed = True
        self.hass.create_task(
            self.hass.config_entries.flow.async_init(
                DOMAIN,
                context={
                    "source": SOURCE_REAUTH,
                    "entry_id": self._config_entry.entry_id,
                },
                data=self._config_entry.data,
            )
        )

    async def async_will_remove_from_hass(self) -> None:
        """Handle removal."""
        await self._async_shutdown_dmr()

    async def async_update(self) -> None:
        """Update state of device."""
        if self._auth_failed or self.hass.is_stopping:
            return
        old_state = self._attr_state
        if self._power_off_in_progress():
            self._attr_state = STATE_OFF
        else:
            self._attr_state = (
                STATE_ON if await self._bridge.async_is_on() else STATE_OFF
            )
        if self._attr_state != old_state:
            LOGGER.debug("TV %s state updated to %s", self._host, self._attr_state)

        if self._attr_state != STATE_ON:
            if self._dmr_device and self._dmr_device.is_subscribed:
                await self._dmr_device.async_unsubscribe_services()
            return

        startup_tasks: list[Coroutine[Any, Any, Any]] = []

        if not self._app_list_event.is_set():
            startup_tasks.append(self._async_startup_app_list())

        if self._dmr_device and not self._dmr_device.is_subscribed:
            startup_tasks.append(self._async_resubscribe_dmr())
        if not self._dmr_device and self._ssdp_rendering_control_location:
            startup_tasks.append(self._async_startup_dmr())

        if startup_tasks:
            await asyncio.gather(*startup_tasks)

        self._update_from_upnp()

    @callback
    def _update_from_upnp(self) -> bool:
        # Upnp events can affect other attributes that we currently do not track
        # We want to avoid checking every attribute in 'async_write_ha_state' as we
        # currently only care about two attributes
        if (dmr_device := self._dmr_device) is None:
            return False

        has_updates = False

        if (
            volume_level := dmr_device.volume_level
        ) is not None and self._attr_volume_level != volume_level:
            self._attr_volume_level = volume_level
            has_updates = True

        if (
            is_muted := dmr_device.is_volume_muted
        ) is not None and self._attr_is_volume_muted != is_muted:
            self._attr_is_volume_muted = is_muted
            has_updates = True

        return has_updates

    async def _async_startup_app_list(self) -> None:
        await self._bridge.async_request_app_list()
        if self._app_list_event.is_set():
            # The try+wait_for is a bit expensive so we should try not to
            # enter it unless we have to (Python 3.11 will have zero cost try)
            return
        try:
            await asyncio.wait_for(self._app_list_event.wait(), APP_LIST_DELAY)
        except asyncio.TimeoutError as err:
            # No need to try again
            self._app_list_event.set()
            LOGGER.debug("Failed to load app list from %s: %r", self._host, err)

    async def _async_startup_dmr(self) -> None:
        assert self._ssdp_rendering_control_location is not None
        if self._dmr_device is None:
            session = async_get_clientsession(self.hass)
            upnp_requester = AiohttpSessionRequester(session)
            # Set non_strict to avoid invalid data sent by Samsung TV:
            # Got invalid value for <UpnpStateVariable(PlaybackStorageMedium, string)>:
            # NETWORK,NONE
            upnp_factory = UpnpFactory(upnp_requester, non_strict=True)
            upnp_device: UpnpDevice | None = None
            try:
                upnp_device = await upnp_factory.async_create_device(
                    self._ssdp_rendering_control_location
                )
            except (UpnpConnectionError, UpnpResponseError, UpnpXmlContentError) as err:
                LOGGER.debug("Unable to create Upnp DMR device: %r", err, exc_info=True)
                return
            _, event_ip = await async_get_local_ip(
                self._ssdp_rendering_control_location, self.hass.loop
            )
            source = (event_ip or "0.0.0.0", 0)
            self._upnp_server = AiohttpNotifyServer(
                requester=upnp_requester,
                source=source,
                callback_url=None,
                loop=self.hass.loop,
            )
            await self._upnp_server.async_start_server()
            self._dmr_device = DmrDevice(upnp_device, self._upnp_server.event_handler)

            try:
                self._dmr_device.on_event = self._on_upnp_event
                await self._dmr_device.async_subscribe_services(auto_resubscribe=True)
            except UpnpResponseError as err:
                # Device rejected subscription request. This is OK, variables
                # will be polled instead.
                LOGGER.debug("Device rejected subscription: %r", err)
            except UpnpError as err:
                # Don't leave the device half-constructed
                self._dmr_device.on_event = None
                self._dmr_device = None
                await self._upnp_server.async_stop_server()
                self._upnp_server = None
                LOGGER.debug("Error while subscribing during device connect: %r", err)
                raise

    async def _async_resubscribe_dmr(self) -> None:
        assert self._dmr_device
        try:
            await self._dmr_device.async_subscribe_services(auto_resubscribe=True)
        except UpnpCommunicationError as err:
            LOGGER.debug("Device rejected re-subscription: %r", err, exc_info=True)

    async def _async_shutdown_dmr(self) -> None:
        """Handle removal."""
        if (dmr_device := self._dmr_device) is not None:
            self._dmr_device = None
            dmr_device.on_event = None
            await dmr_device.async_unsubscribe_services()

        if (upnp_server := self._upnp_server) is not None:
            self._upnp_server = None
            await upnp_server.async_stop_server()

    def _on_upnp_event(
        self, service: UpnpService, state_variables: Sequence[UpnpStateVariable]
    ) -> None:
        """State variable(s) changed, let home-assistant know."""
        # Ensure the entity has been added to hass to avoid race condition
        if self._update_from_upnp() and self.entity_id:
            self.async_write_ha_state()

    async def _async_launch_app(self, app_id: str) -> None:
        """Send launch_app to the tv."""
        if self._power_off_in_progress():
            LOGGER.info("TV is powering off, not sending launch_app command")
            return
        assert isinstance(self._bridge, SamsungTVWSBridge)
        await self._bridge.async_launch_app(app_id)

    async def _async_send_keys(self, keys: list[str]) -> None:
        """Send a key to the tv and handles exceptions."""
        assert keys
        if self._power_off_in_progress() and keys[0] != "KEY_POWEROFF":
            LOGGER.info("TV is powering off, not sending keys: %s", keys)
            return
        await self._bridge.async_send_keys(keys)

    def _power_off_in_progress(self) -> bool:
        return (
            self._end_of_power_off is not None
            and self._end_of_power_off > dt_util.utcnow()
        )

    @property
    def available(self) -> bool:
        """Return the availability of the device."""
        if self._auth_failed:
            return False
        return (
            self._attr_state == STATE_ON
            or self._on_script is not None
            or self._mac is not None
            or self._power_off_in_progress()
        )

    async def async_turn_off(self) -> None:
        """Turn off media player."""
        self._end_of_power_off = dt_util.utcnow() + SCAN_INTERVAL_PLUS_OFF_TIME
        await self._bridge.async_power_off()

    async def async_set_volume_level(self, volume: float) -> None:
        """Set volume level on the media player."""
        if (dmr_device := self._dmr_device) is None:
            LOGGER.info("Upnp services are not available on %s", self._host)
            return
        try:
            await dmr_device.async_set_volume_level(volume)
        except UpnpActionResponseError as err:
            LOGGER.warning("Unable to set volume level on %s: %r", self._host, err)

    async def async_volume_up(self) -> None:
        """Volume up the media player."""
        await self._async_send_keys(["KEY_VOLUP"])

    async def async_volume_down(self) -> None:
        """Volume down media player."""
        await self._async_send_keys(["KEY_VOLDOWN"])

    async def async_mute_volume(self, mute: bool) -> None:
        """Send mute command."""
        await self._async_send_keys(["KEY_MUTE"])

    async def async_media_play_pause(self) -> None:
        """Simulate play pause media player."""
        if self._playing:
            await self.async_media_pause()
        else:
            await self.async_media_play()

    async def async_media_play(self) -> None:
        """Send play command."""
        self._playing = True
        await self._async_send_keys(["KEY_PLAY"])

    async def async_media_pause(self) -> None:
        """Send media pause command to media player."""
        self._playing = False
        await self._async_send_keys(["KEY_PAUSE"])

    async def async_media_next_track(self) -> None:
        """Send next track command."""
        await self._async_send_keys(["KEY_CHUP"])

    async def async_media_previous_track(self) -> None:
        """Send the previous track command."""
        await self._async_send_keys(["KEY_CHDOWN"])

    async def async_play_media(
        self, media_type: str, media_id: str, **kwargs: Any
    ) -> None:
        """Support changing a channel."""
        if media_type == MEDIA_TYPE_APP:
            await self._async_launch_app(media_id)
            return

        if media_type != MEDIA_TYPE_CHANNEL:
            LOGGER.error("Unsupported media type")
            return

        # media_id should only be a channel number
        try:
            cv.positive_int(media_id)
        except vol.Invalid:
            LOGGER.error("Media ID must be positive integer")
            return

        await self._async_send_keys(
            keys=[f"KEY_{digit}" for digit in media_id] + ["KEY_ENTER"]
        )

    def _wake_on_lan(self) -> None:
        """Wake the device via wake on lan."""
        send_magic_packet(self._mac, ip_address=self._host)
        # If the ip address changed since we last saw the device
        # broadcast a packet as well
        send_magic_packet(self._mac)

    async def async_turn_on(self) -> None:
        """Turn the media player on."""
        if self._on_script:
            await self._on_script.async_run(context=self._context)
        elif self._mac:
            await self.hass.async_add_executor_job(self._wake_on_lan)

    async def async_select_source(self, source: str) -> None:
        """Select input source."""
        if self._app_list and source in self._app_list:
            await self._async_launch_app(self._app_list[source])
            return

        if source in SOURCES:
            await self._async_send_keys([SOURCES[source]])
            return

        LOGGER.error("Unsupported source")