text:
"""Utilities for pyActiveResource."""

__author__ = 'Mark Roach (mrroach@google.com)'

import base64
import calendar
import decimal
from . import element_containers
import re
import time
import datetime
import urllib.request, urllib.parse, urllib.error
try:
    import yaml
except ImportError:
    yaml = None

try:
    from dateutil.parser import parse as date_parse
except ImportError:
    try:
        from xml.utils import iso8601
        def date_parse(time_string):
            """Return a datetime object for the given ISO8601 string.

            Args:
                time_string: An ISO8601 timestamp.
            Returns:
                A datetime.datetime object.
            """
            return datetime.datetime.utcfromtimestamp(
                    iso8601.parse(time_string))
    except ImportError:
        date_parse = None

try:
    from xml.etree import cElementTree as ET
except ImportError:
    try:
        import cElementTree as ET
    except ImportError:
        from xml.etree import ElementTree as ET

XML_HEADER = b'<?xml version="1.0" encoding="UTF-8"?>'

# Patterns blatently stolen from Rails' Inflector
PLURALIZE_PATTERNS = [
    (r'(quiz)$', r'\1zes'),
    (r'^(ox)$', r'\1en'),
    (r'([m|l])ouse$', r'\1ice'),
    (r'(matr|vert|ind)(?:ix|ex)$', r'\1ices'),
    (r'(x|ch|ss|sh)$', r'\1es'),
    (r'([^aeiouy]|qu)y$', r'\1ies'),
    (r'(hive)$', r'1s'),
    (r'(?:([^f])fe|([lr])f)$', r'\1\2ves'),
    (r'sis$', r'ses'),
    (r'([ti])um$', r'\1a'),
    (r'(buffal|tomat)o$', r'\1oes'),
    (r'(bu)s$', r'\1ses'),
    (r'(alias|status)$', r'\1es'),
    (r'(octop|vir)us$', r'\1i'),
    (r'(ax|test)is$', r'\1es'),
    (r's$', 's'),
    (r'$', 's')
]

SINGULARIZE_PATTERNS = [
    (r'(quiz)zes$', r'\1'),
    (r'(matr)ices$', r'\1ix'),
    (r'(vert|ind)ices$', r'\1ex'),
    (r'^(ox)en', r'\1'),
    (r'(alias|status)es$', r'\1'),
    (r'(octop|vir)i$', r'\1us'),
    (r'(cris|ax|test)es$', r'\1is'),
    (r'(shoe)s$', r'\1'),
    (r'(o)es$', r'\1'),
    (r'(bus)es$', r'\1'),
    (r'([m|l])ice$', r'\1ouse'),
    (r'(x|ch|ss|sh)es$', r'\1'),
    (r'(m)ovies$', r'\1ovie'),
    (r'(s)eries$', r'\1eries'),
    (r'([^aeiouy]|qu)ies$', r'\1y'),
    (r'([lr])ves$', r'\1f'),
    (r'(tive)s$', r'\1'),
    (r'(hive)s$', r'\1'),
    (r'([^f])ves$', r'\1fe'),
    (r'(^analy)ses$', r'\1sis'),
    (r'((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)ses$',
     r'\1\2sis'),
    (r'([ti])a$', r'\1um'),
    (r'(n)ews$', r'\1ews'),
    (r's$', r'')
]

IRREGULAR = [
    ('person', 'people'),
    ('man', 'men'),
    ('child', 'children'),
    ('sex', 'sexes'),
    ('move', 'moves'),
    #('cow', 'kine') WTF?
]

UNCOUNTABLES = ['equipment', 'information', 'rice', 'money', 'species',
                'series', 'fish', 'sheep']

# An array of type-specific serializer methods which will be passed the value
# and should return the element type and modified value.
SERIALIZERS = [
    {'type': bool,
     'method': lambda value: ('boolean', str(value).lower())},
    {'type': int,
     'method': lambda value: ('integer', str(value))},
    {'type': int,
     'method': lambda value: ('integer', str(value))},
    {'type': str,
     'method': lambda value: (None, str(value))}]

DEFAULT_SERIALIZER = {
    'type': object,
    'method': lambda value: (None, str(value))}

class Error(Exception):
    """Base exception class for this module."""

class FileObject(object):
    """Represent a 'file' xml entity."""

    def __init__(self, data, name='untitled',
                 content_type='application/octet-stream'):
        self.data = data
        self.name = name
        self.content_type = content_type

def pluralize(singular):
    """Convert singular word to its plural form.

    Args:
        singular: A word in its singular form.

    Returns:
        The word in its plural form.
    """
    if singular in UNCOUNTABLES:
        return singular
    for i in IRREGULAR:
        if i[0] == singular:
            return i[1]
    for i in PLURALIZE_PATTERNS:
        if re.search(i[0], singular):
            return re.sub(i[0], i[1], singular)

def singularize(plural):
    """Convert plural word to its singular form.

    Args:
        plural: A word in its plural form.
    Returns:
        The word in its singular form.
    """
    if plural in UNCOUNTABLES:
        return plural
    for i in IRREGULAR:
        if i[1] == plural:
            return i[0]
    for i in SINGULARIZE_PATTERNS:
        if re.search(i[0], plural):
            return re.sub(i[0], i[1], plural)
    return plural

def camelize(word):
    """Convert a word from lower_with_underscores to CamelCase.

    Args:
        word: The string to convert.
    Returns:
        The modified string.
    """
    return ''.join(w[0].upper() + w[1:]
                   for w in re.sub('[^A-Z^a-z^0-9^:]+', ' ', word).split(' '))

def underscore(word):
    """Convert a word from CamelCase to lower_with_underscores.

    Args:
        word: The string to convert.
    Returns:
        The modified string.
    """
    return re.sub(r'\B((?<=[a-z])[A-Z]|[A-Z](?=[a-z]))',
                  r'_\1', word).lower()

def to_query(query_params):
    """Convert a dictionary to url query parameters.

    Args:
        query_params: A dictionary of arguments.
    Returns:
        A string of query parameters.
    """
    def annotate_params(params):
        annotated = {}
        for key, value in params.items():
            if isinstance(value, list):
                key = '%s[]' % key
            elif isinstance(value, dict):
                dict_options = {}
                for dk, dv in value.items():
                    dict_options['%s[%s]' % (key, dk)] = dv
                annotated.update(annotate_params(dict_options))
                continue
            elif isinstance(value, str):
                value = value.encode('utf-8')
            else:
                value = str(value)
            annotated[key] = value
        return annotated
    annotated = annotate_params(query_params)
    return urllib.parse.urlencode(annotated, True)

def xml_pretty_format(element, level=0):
    """Add PrettyPrint formatting to an ElementTree element.

    Args:
        element: An ElementTree element which is modified in-place.
    Returns:
        None
    """
    indent = '\n%s' % ('  ' * level)
    if len(element):
        if not element.text or not element.text.strip():
            element.text = indent + '  '
        for i, child in enumerate(element):
            xml_pretty_format(child, level + 1)
            if not child.tail or not child.tail.strip():
                if i + 1 < len(element):
                    child.tail = indent + "  "
                else:
                    child.tail = indent
    else:
        if level and (not element.tail or not element.tail.strip()):
            element.tail = indent

def serialize(value, element):
    """Write a serialized value to an xml element.

    Args:
        value: The value to serialize.
        element: An xml element to write to.
    Returns:
        None
    """
    if value is None:
      element.set('nil', 'true')
      return

    for serializer in SERIALIZERS + [DEFAULT_SERIALIZER]:
        if isinstance(value, serializer['type']):
            element_type, element.text = serializer['method'](value)
            if element_type:
                element.set('type', element_type)
            break

def to_xml(obj, root='object', pretty=False, header=True, dasherize=True):
    """Convert a dictionary or list to an XML string.

    Args:
        obj: The dictionary/list object to convert.
        root: The name of the root xml element.
        pretty: Whether to pretty-format the xml (default False).
        header: Whether to include an xml header (default True).
        dasherize: Whether to convert underscores to dashes in
                   attribute names (default True).
    Returns:
        An xml string.
    """
    root = dasherize and root.replace('_', '-') or root
    root_element = ET.Element(root)
    if isinstance(obj, list):
        root_element.set('type', 'array')
        for i in obj:
            element = ET.fromstring(
                    to_xml(i, root=singularize(root), header=False,
                           pretty=pretty, dasherize=dasherize))
            root_element.append(element)
    # stupid redmine hack again, see other occurence...
    elif isinstance(obj, str):
        return "<value>" + obj + "</value>"
    else:
        for key, value in obj.items():
            key = dasherize and key.replace('_', '-') or key
            if isinstance(value, dict) or isinstance(value, list):
                element = ET.fromstring(
                    to_xml(value, root=key, header=False,
                           pretty=pretty, dasherize=dasherize))
                root_element.append(element)
            else:
                element = ET.SubElement(root_element, key)
                serialize(value, element)
    if pretty:
        xml_pretty_format(root_element)
    xml_data = ET.tostring(root_element)
    if header:
        return XML_HEADER + b'\n' + xml_data
    return xml_data

def xml_to_dict(xmlobj, saveroot=True):
    """Parse the xml into a dictionary of attributes.

    Args:
        xmlobj: An ElementTree element or an xml string.
        saveroot: Keep the xml element names (ugly format)
    Returns:
        An ElementDict object or ElementList for multiple objects
    """
    if isinstance(xmlobj, bytes):
        xmlobj = xmlobj.decode()

    if isinstance(xmlobj, str):
        # Allow for blank (usually HEAD) result on success
        if xmlobj.isspace():
            return {}
        try:
            element = ET.fromstring(xmlobj)
        except Exception as err:
            raise Error('Unable to parse xml data: %s' % err)
    else:
        element = xmlobj

    element_type = element.get('type', '').lower()
    if element_type == 'array':
        element_list_type = element.tag.replace('-', '_')
        return_list = element_containers.ElementList(element_list_type)
        for child in element.getchildren():
            child_element = xml_to_dict(child, saveroot)
            if saveroot and isinstance(child_element, dict):
                  return_list.append(iter(child_element.values())[0])
            else:
                  return_list.append(child_element)
        if saveroot:
            return element_containers.ElementDict(element_list_type,
                                                  {element_list_type:
                                                   return_list})
        else:
            return return_list
    elif element.get('nil') == 'true':
        return None
    elif element_type in ('integer', 'datetime', 'date',
                          'decimal', 'double', 'float') and not element.text:
        return None
    elif element_type == 'integer':
        return int(element.text)
    elif element_type == 'datetime':
        if date_parse:
            return date_parse(element.text)
        else:
            try:
                timestamp = calendar.timegm(
                        time.strptime(element.text, '%Y-%m-%dT%H:%M:%S+0000'))

                return datetime.datetime.utcfromtimestamp(timestamp)
            except ValueError as err:
                raise Error('Unable to parse timestamp. Install dateutil'
                            ' (http://labix.org/python-dateutil) or'
                            ' pyxml (http://pyxml.sf.net/topics/)'
                            ' for ISO8601 support.')
    elif element_type == 'date':
        time_tuple = time.strptime(element.text, '%Y-%m-%d')
        return datetime.date(*time_tuple[:3])
    elif element_type == 'decimal':
        return decimal.Decimal(element.text)
    elif element_type in ('float', 'double'):
        return float(element.text)
    elif element_type == 'boolean':
        if not element.text:
            return False
        return element.text.strip() in ('true', '1')
    elif element_type == 'yaml':
        if not yaml:
            raise ImportError('PyYaml is not installed: http://pyyaml.org/')
        return yaml.safe_load(element.text)
    elif element_type == 'base64binary':
        return base64.decodestring(element.text).decode()
    elif element_type == 'file':
        content_type = element.get('content_type',
                                   'application/octet-stream')
        filename = element.get('name', 'untitled')
        return FileObject(element.text, filename, content_type)
    elif element_type in ('symbol', 'string'):
        if not element.text:
            return ''
        return element.text
    elif element.getchildren():
        # This is an element with children. The children might be simple
        # values, or nested hashes.
        if element_type:
            attributes = element_containers.ElementDict(
                underscore(element.get('type', '')), list(element.items()))
        else:
            attributes = element_containers.ElementDict(singularize(
                element.tag.replace('-', '_')), list(element.items()))
        for child in element.getchildren():
            attribute = xml_to_dict(child, saveroot)
            child_tag = child.tag.replace('-', '_')
            if saveroot:
                # If this is a nested hash, it will come back as
                # {child_tag: {key: value}}, we only want the inner hash
                if isinstance(attribute, dict):
                    if len(attribute) == 1 and child_tag in attribute:
                        attribute = attribute[child_tag]
            # Handle multiple elements with the same tag name
            if child_tag in attributes:
                if isinstance(attributes[child_tag], list):
                    attributes[child_tag].append(attribute)
                else:
                    attributes[child_tag] = [attributes[child_tag],
                                             attribute]
            else:
                attributes[child_tag] = attribute
        if saveroot:
            return {element.tag.replace('-', '_'): attributes}
        else:
            return attributes
    elif list(element.items()):
        return element_containers.ElementDict(element.tag.replace('-', '_'),
                                              list(element.items()))
    else:
        return element.text

def main():
    pass

if __name__ == '__main__':
    main()


text:
package com.laticobsa.modelo;
// Generated 31-jul-2017 17:40:44 by Hibernate Tools 4.3.1

import java.util.Date;
import java.util.HashSet;
import java.util.Set;

/**
 * LcTipoGestion generated by hbm2java
 */
public class LcTipoGestion  implements java.io.Serializable {

     private int idTipoGestion;
     private String nombreTipoGestion;
     private Integer idCliente;
     private String observacion;
     private Date fechaRegistro;
     private String estado;
     private Set lcGestioneses = new HashSet(0);

    public LcTipoGestion() {
    }

    public LcTipoGestion(int idTipoGestion) {
        this.idTipoGestion = idTipoGestion;
    }
    public LcTipoGestion(int idTipoGestion, String nombreTipoGestion, Integer idCliente, String observacion, Date fechaRegistro, String estado, Set lcGestioneses) {
       this.idTipoGestion = idTipoGestion;
       this.nombreTipoGestion = nombreTipoGestion;
       this.idCliente = idCliente;
       this.observacion = observacion;
       this.fechaRegistro = fechaRegistro;
       this.estado = estado;
       this.lcGestioneses = lcGestioneses;
    }

    public int getIdTipoGestion() {
        return this.idTipoGestion;
    }

    public void setIdTipoGestion(int idTipoGestion) {
        this.idTipoGestion = idTipoGestion;
    }
    public String getNombreTipoGestion() {
        return this.nombreTipoGestion;
    }

    public void setNombreTipoGestion(String nombreTipoGestion) {
        this.nombreTipoGestion = nombreTipoGestion;
    }
    public Integer getIdCliente() {
        return this.idCliente;
    }

    public void setIdCliente(Integer idCliente) {
        this.idCliente = idCliente;
    }
    public String getObservacion() {
        return this.observacion;
    }

    public void setObservacion(String observacion) {
        this.observacion = observacion;
    }
    public Date getFechaRegistro() {
        return this.fechaRegistro;
    }

    public void setFechaRegistro(Date fechaRegistro) {
        this.fechaRegistro = fechaRegistro;
    }
    public String getEstado() {
        return this.estado;
    }

    public void setEstado(String estado) {
        this.estado = estado;
    }
    public Set getLcGestioneses() {
        return this.lcGestioneses;
    }

    public void setLcGestioneses(Set lcGestioneses) {
        this.lcGestioneses = lcGestioneses;
    }

}

redpajama_set_name: RedPajamaGithub


text:
"""System tests for Jupyter/IPython connector."""

import re

import pytest
import psutil

IPython = pytest.importorskip("IPython")
io = pytest.importorskip("IPython.utils.io")
pandas = pytest.importorskip("pandas")
tools = pytest.importorskip("IPython.testing.tools")
interactiveshell = pytest.importorskip("IPython.terminal.interactiveshell")

@pytest.fixture(scope="session")
def ipython():
    config = tools.default_config()
    config.TerminalInteractiveShell.simple_prompt = True
    shell = interactiveshell.TerminalInteractiveShell.instance(config=config)
    return shell

@pytest.fixture()
def ipython_interactive(ipython):
    """Activate IPython's builtin hooks

    for the duration of the test scope.
    """
    with ipython.builtin_trap:
        yield ipython

def test_bigquery_magic(ipython_interactive):
    ip = IPython.get_ipython()
    current_process = psutil.Process()
    conn_count_start = len(current_process.connections())

    ip.extension_manager.load_extension("google.cloud.bigquery")
    sql = """
        SELECT
            CONCAT(
            'https://stackoverflow.com/questions/',
            CAST(id as STRING)) as url,
            view_count
        FROM `bigquery-public-data.stackoverflow.posts_questions`
        WHERE tags like '%google-bigquery%'
        ORDER BY view_count DESC
        LIMIT 10
    """
    with io.capture_output() as captured:
        result = ip.run_cell_magic("bigquery", "--use_rest_api", sql)

    conn_count_end = len(current_process.connections())

    lines = re.split("\n|\r", captured.stdout)
    # Removes blanks & terminal code (result of display clearing)
    updates = list(filter(lambda x: bool(x) and x != "\x1b[2K", lines))
    assert re.match("Executing query with job ID: .*", updates[0])
    assert (re.match("Query executing: .*s", line) for line in updates[1:-1])
    assert isinstance(result, pandas.DataFrame)
    assert len(result) == 10  # verify row count
    assert list(result) == ["url", "view_count"]  # verify column names

    # NOTE: For some reason, the number of open sockets is sometimes one *less*
    # than expected when running system tests on Kokoro, thus using the <= assertion.
    # That's still fine, however, since the sockets are apparently not leaked.
    assert conn_count_end <= conn_count_start  # system resources are released


text:
[back](../README.md)

# Query::update() Examples
Here we're going to update the firstname and lastname of a user compared by the users ID
```php
Query::update( 'Users', [ 'firstname', 'lastname' ], [ 'ID' ] );
```
Output:
```sql
UPDATE `Users` SET `Users`.`firstname` = :FIRSTNAME, `Users`.`lastname` = :LASTNAME WHERE `ID` = :ID LIMIT 1;
```


text:
Here are some useful slide decks about The Apache Way.  These have
been presented by some amazing Apache committers and Members at
ApacheCon and a variety of other open source conferences in the past
15 years.  This is a curated selection of publicly posted slide decks.

Note that in the past, these talks were often an overview of history
and how the ASF is organized, along with touching on the behavioral
and community aspects of the Apache Way.  For a time, they were a common
main track presentation at the start of ApacheCon.

The Apache Way slot at ApacheCon morphed over time into the "State of the Feather",
which is now given by an officer of the ASF.  It is more of a snapshot about
the health of the ASF as an organization - not just it's component projects,
but the corporation and operations that keep the servers running and
the press releases and tweets and events coming too.

So, too, morphs the Apache Way talk of today, focusing much more on the
behaviors and practices that are core to running a successful and
diverse community-led project.

For more learning about The Apache Way:

http://theapacheway.org/
https://www.apache.org/foundation/how-it-works.html

# Inner Source And The Apache WAy
## JimJag - InnerSource Commons 2017
https://www.slideshare.net/jimjag/innersource-101-and-the-apache-way

This is an advanced talk using the aspects of the Apache Way to lead
corporate developers and managers how to use InnerSource - taking
open source / open development concepts for use inside the firewall and
inside corporate development teams.

### Top Aspects Covered

- Meritocracy
- Peer-based
- Consensus decision making
- Collaborative development
- Responsible oversight
- Individual participation

### Quotable Bits

- Focus on community
- Focus on the un-aligned volunteer contributor

- Since we are all volunteers, people's time and interests change
- A healthy community is "warm and inviting" and encourages a continued influx of developers
- Poisonous people/communities turn people off, and the project will die

- Open and asynchronous
- Doesn't disenfranchise anyone
- Maintains history and allows ebb/flow of participants

- Transparency: You can only reuse what you can **see**

- Communities can create durable assets, processes and culture

- Merit: Technical decisions made by technical experts, with **earned** authority in that community

- A Community is not the same as a team:
  - Self organizing
  - Self identifying
  - Working in own time frames

# The Apache Way - Amalgamation
## Daniel Ruggeri - 2015 UMiss
http://people.apache.org/~druggeri/presentations/TheApacheWay.odp

This is a new Apache Member's amalgamation of many past Apache Way
slide decks, covering all the points in a detailed yet condensed way.

### Quotable Bits

- Clear steps through all other common themes of past slide decks
- "The board runs the foundation, not the projects"
- "The code is owned by the foundation" (but: really just licensed)
- "Community agrees on direction - (but) Individuals then make it happen"
- "Pragmatic and permissive - Maximum freedom for users"

### Final slide

The Apache way is.....
Meritocracy – those who do, decide
Participation – by individuals with peer review
Oversight – responsible and independent
Decisions – made by consensus
Collaboration – public and asynchronous

# The Apache Way
## Nick Burch - ApacheCon North America 2015
http://home.apache.org/~nick/Talks/ApacheConNA15/TheApacheWay15.pdf

This is a modern version of the early classic Apache Way talks, that
emphasizes all the past people who helped create the content.

### Top Aspects Covered

- History lesson
- Apache by the numbers & graphs
- Structure/governance of the ASF and projects
- Example: Jakarta & Umbrellas -> flattened, each project reports on community health; can't measure if not same community
- Merit and different kinds of contributions
- Decision making
- Link to poisonous people video https://www.youtube.com/watch?v=-F-3E8pyjFo
- Brief list of ways corporations to contribute (different than as individuals)

"Foundation has some common support (eg infra, press, trademarks), to help projects focus on their code and on their communities"

Problem areas: Umbrella projects: who is responsible / who can evaluate the work or new contributors?

"Merit does not buy you authority (community must still agree)"
"Merit gets you privileges: commit access, voting on committers"

# Training Our Team The Apache Way
## Alan Gates - ApacheCon Europe Keynote 2016
http://www.slideshare.net/alanfgates/keynote-apache-bdeunov2016

Short but powerfully presented deck about Hortonworks' internal employee
training on the Apache Way.  Internal one-hour training session; started
with developers & project management, but rolling out throughout company.

"Apache has ways to train new community members and new communities - e.g. the Incubator"

Key points: Apache Way; permissive license; why their company chose to work this way;
how to be an employee & committer both; trademarks and proper use.

Great distillation of Apache Way messages in context of employee teams.

- Act as individuals "The fact that you're a manager or an architect or a founder [at our company] doesn't mean anything in Apache [communities]"

# The Apache Way
## Nick Burch - ApacheCon Europe 2014
https://www.slideshare.net/gagravarr/the-apache-way-41759378

Earlier version of the 2015 talk.

# Open Source At Scale
## Bertrand Delacretaz - ApacheCon 2013
https://www.slideshare.net/bdelacretaz/open-source-at-scale-the-apache-software-foundation

Graphics-heavy version presented in Bertrand's inimitable style (and hats).

# Writing And Distributing Software The Apache Way
## Justin Erenkrantz - OSBC 2010
http://www.erenkrantz.com/apachecon/OSBC%20-%20No%20Jerks%20Allowed.pdf

- Historical perspective
- PMCS are each separate merit structures
- Voting, communication and consensus techniques
- Define many terms (it was still the early days of explaining the Apache Way)
- "No jerks allowed" - a key early message
  - FOSS communities value group contributors, not lone wolves
  - Diverse communities that can attract new contributors over time


text:
<?php

namespace DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIROrganization;

use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAddress;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRContactPoint;
use DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRHumanName;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRConstants;
use DCarbone\PHPFHIRGenerated\R4\PHPFHIRTypeInterface;

/**
 * A formally or informally recognized grouping of people or organizations formed
 * for the purpose of achieving some form of collective action. Includes companies,
 * institutions, corporations, departments, community groups, healthcare practice
 * groups, payer/insurer, etc.
 *
 * Class FHIROrganizationContact
 * @package \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIROrganization
 */
class FHIROrganizationContact extends FHIRBackboneElement
{
    // name of FHIR type this class describes
    const FHIR_TYPE_NAME = PHPFHIRConstants::TYPE_NAME_ORGANIZATION_DOT_CONTACT;
    const FIELD_ADDRESS = 'address';
    const FIELD_NAME = 'name';
    const FIELD_PURPOSE = 'purpose';
    const FIELD_TELECOM = 'telecom';

    /** @var string */
    private $_xmlns = 'http://hl7.org/fhir';

    /**
     * An address expressed using postal conventions (as opposed to GPS or other
     * location definition formats). This data type may be used to convey addresses for
     * use in delivering mail as well as for visiting locations which might not be
     * valid for mail delivery. There are a variety of postal address formats defined
     * around the world.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Visiting or postal addresses for the contact.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAddress
     */
    protected $address = null;

    /**
     * A human's name with the ability to identify parts and usage.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A name associated with the contact.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRHumanName
     */
    protected $name = null;

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Indicates a purpose for which the contact can be reached.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
     */
    protected $purpose = null;

    /**
     * Details for all kinds of technology mediated contact points for a person or
     * organization, including telephone, email, etc.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A contact detail (e.g. a telephone number or an email address) by which the
     * party may be contacted.
     *
     * @var null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRContactPoint[]
     */
    protected $telecom = [];

    /**
     * Validation map for fields in type Organization.Contact
     * @var array
     */
    private static $_validationRules = [    ];

    /**
     * FHIROrganizationContact Constructor
     * @param null|array $data
     */
    public function __construct($data = null)
    {
        if (null === $data || [] === $data) {
            return;
        }
        if (!is_array($data)) {
            throw new \InvalidArgumentException(sprintf(
                'FHIROrganizationContact::_construct - $data expected to be null or array, %s seen',
                gettype($data)
            ));
        }
        parent::__construct($data);
        if (isset($data[self::FIELD_ADDRESS])) {
            if ($data[self::FIELD_ADDRESS] instanceof FHIRAddress) {
                $this->setAddress($data[self::FIELD_ADDRESS]);
            } else {
                $this->setAddress(new FHIRAddress($data[self::FIELD_ADDRESS]));
            }
        }
        if (isset($data[self::FIELD_NAME])) {
            if ($data[self::FIELD_NAME] instanceof FHIRHumanName) {
                $this->setName($data[self::FIELD_NAME]);
            } else {
                $this->setName(new FHIRHumanName($data[self::FIELD_NAME]));
            }
        }
        if (isset($data[self::FIELD_PURPOSE])) {
            if ($data[self::FIELD_PURPOSE] instanceof FHIRCodeableConcept) {
                $this->setPurpose($data[self::FIELD_PURPOSE]);
            } else {
                $this->setPurpose(new FHIRCodeableConcept($data[self::FIELD_PURPOSE]));
            }
        }
        if (isset($data[self::FIELD_TELECOM])) {
            if (is_array($data[self::FIELD_TELECOM])) {
                foreach($data[self::FIELD_TELECOM] as $v) {
                    if (null === $v) {
                        continue;
                    }
                    if ($v instanceof FHIRContactPoint) {
                        $this->addTelecom($v);
                    } else {
                        $this->addTelecom(new FHIRContactPoint($v));
                    }
                }
            } else if ($data[self::FIELD_TELECOM] instanceof FHIRContactPoint) {
                $this->addTelecom($data[self::FIELD_TELECOM]);
            } else {
                $this->addTelecom(new FHIRContactPoint($data[self::FIELD_TELECOM]));
            }
        }
    }

    /**
     * @return string
     */
    public function _getFHIRTypeName()
    {
        return self::FHIR_TYPE_NAME;
    }

    /**
     * @return string
     */
    public function _getFHIRXMLElementDefinition()
    {
        $xmlns = $this->_getFHIRXMLNamespace();
        if (null !== $xmlns) {
            $xmlns = " xmlns=\"{$xmlns}\"";
        }
        return "<OrganizationContact{$xmlns}></OrganizationContact>";
    }

    /**
     * An address expressed using postal conventions (as opposed to GPS or other
     * location definition formats). This data type may be used to convey addresses for
     * use in delivering mail as well as for visiting locations which might not be
     * valid for mail delivery. There are a variety of postal address formats defined
     * around the world.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Visiting or postal addresses for the contact.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAddress
     */
    public function getAddress()
    {
        return $this->address;
    }

    /**
     * An address expressed using postal conventions (as opposed to GPS or other
     * location definition formats). This data type may be used to convey addresses for
     * use in delivering mail as well as for visiting locations which might not be
     * valid for mail delivery. There are a variety of postal address formats defined
     * around the world.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Visiting or postal addresses for the contact.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRAddress $address
     * @return static
     */
    public function setAddress(FHIRAddress $address = null)
    {
        $this->address = $address;
        return $this;
    }

    /**
     * A human's name with the ability to identify parts and usage.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A name associated with the contact.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRHumanName
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * A human's name with the ability to identify parts and usage.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A name associated with the contact.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRHumanName $name
     * @return static
     */
    public function setName(FHIRHumanName $name = null)
    {
        $this->name = $name;
        return $this;
    }

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Indicates a purpose for which the contact can be reached.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept
     */
    public function getPurpose()
    {
        return $this->purpose;
    }

    /**
     * A concept that may be defined by a formal reference to a terminology or ontology
     * or may be provided by text.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * Indicates a purpose for which the contact can be reached.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRCodeableConcept $purpose
     * @return static
     */
    public function setPurpose(FHIRCodeableConcept $purpose = null)
    {
        $this->purpose = $purpose;
        return $this;
    }

    /**
     * Details for all kinds of technology mediated contact points for a person or
     * organization, including telephone, email, etc.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A contact detail (e.g. a telephone number or an email address) by which the
     * party may be contacted.
     *
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRContactPoint[]
     */
    public function getTelecom()
    {
        return $this->telecom;
    }

    /**
     * Details for all kinds of technology mediated contact points for a person or
     * organization, including telephone, email, etc.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A contact detail (e.g. a telephone number or an email address) by which the
     * party may be contacted.
     *
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRContactPoint $telecom
     * @return static
     */
    public function addTelecom(FHIRContactPoint $telecom = null)
    {
        $this->telecom[] = $telecom;
        return $this;
    }

    /**
     * Details for all kinds of technology mediated contact points for a person or
     * organization, including telephone, email, etc.
     * If the element is present, it must have a value for at least one of the defined
     * elements, an \@id referenced from the Narrative, or extensions
     *
     * A contact detail (e.g. a telephone number or an email address) by which the
     * party may be contacted.
     *
     * @param \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRContactPoint[] $telecom
     * @return static
     */
    public function setTelecom(array $telecom = [])
    {
        $this->telecom = [];
        if ([] === $telecom) {
            return $this;
        }
        foreach($telecom as $v) {
            if ($v instanceof FHIRContactPoint) {
                $this->addTelecom($v);
            } else {
                $this->addTelecom(new FHIRContactPoint($v));
            }
        }
        return $this;
    }

    /**
     * Returns the validation rules that this type's fields must comply with to be considered "valid"
     * The returned array is in ["fieldname[.offset]" => ["rule" => {constraint}]]
     *
     * @return array
     */
    public function _getValidationRules()
    {
        return self::$_validationRules;
    }

    /**
     * Validates that this type conforms to the specifications set forth for it by FHIR.  An empty array must be seen as
     * passing.
     *
     * @return array
     */
    public function _getValidationErrors()
    {
        $errs = parent::_getValidationErrors();
        $validationRules = $this->_getValidationRules();
        if (null !== ($v = $this->getAddress())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_ADDRESS] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getName())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_NAME] = $fieldErrs;
            }
        }
        if (null !== ($v = $this->getPurpose())) {
            if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                $errs[self::FIELD_PURPOSE] = $fieldErrs;
            }
        }
        if ([] !== ($vs = $this->getTelecom())) {
            foreach($vs as $i => $v) {
                if ([] !== ($fieldErrs = $v->_getValidationErrors())) {
                    $errs[sprintf('%s.%d', self::FIELD_TELECOM, $i)] = $fieldErrs;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ADDRESS])) {
            $v = $this->getAddress();
            foreach($validationRules[self::FIELD_ADDRESS] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ORGANIZATION_DOT_CONTACT, self::FIELD_ADDRESS, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ADDRESS])) {
                        $errs[self::FIELD_ADDRESS] = [];
                    }
                    $errs[self::FIELD_ADDRESS][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_NAME])) {
            $v = $this->getName();
            foreach($validationRules[self::FIELD_NAME] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ORGANIZATION_DOT_CONTACT, self::FIELD_NAME, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_NAME])) {
                        $errs[self::FIELD_NAME] = [];
                    }
                    $errs[self::FIELD_NAME][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_PURPOSE])) {
            $v = $this->getPurpose();
            foreach($validationRules[self::FIELD_PURPOSE] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ORGANIZATION_DOT_CONTACT, self::FIELD_PURPOSE, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_PURPOSE])) {
                        $errs[self::FIELD_PURPOSE] = [];
                    }
                    $errs[self::FIELD_PURPOSE][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_TELECOM])) {
            $v = $this->getTelecom();
            foreach($validationRules[self::FIELD_TELECOM] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ORGANIZATION_DOT_CONTACT, self::FIELD_TELECOM, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_TELECOM])) {
                        $errs[self::FIELD_TELECOM] = [];
                    }
                    $errs[self::FIELD_TELECOM][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_MODIFIER_EXTENSION])) {
            $v = $this->getModifierExtension();
            foreach($validationRules[self::FIELD_MODIFIER_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_BACKBONE_ELEMENT, self::FIELD_MODIFIER_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_MODIFIER_EXTENSION])) {
                        $errs[self::FIELD_MODIFIER_EXTENSION] = [];
                    }
                    $errs[self::FIELD_MODIFIER_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_EXTENSION])) {
            $v = $this->getExtension();
            foreach($validationRules[self::FIELD_EXTENSION] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_EXTENSION, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_EXTENSION])) {
                        $errs[self::FIELD_EXTENSION] = [];
                    }
                    $errs[self::FIELD_EXTENSION][$rule] = $err;
                }
            }
        }
        if (isset($validationRules[self::FIELD_ID])) {
            $v = $this->getId();
            foreach($validationRules[self::FIELD_ID] as $rule => $constraint) {
                $err = $this->_performValidation(PHPFHIRConstants::TYPE_NAME_ELEMENT, self::FIELD_ID, $rule, $constraint, $v);
                if (null !== $err) {
                    if (!isset($errs[self::FIELD_ID])) {
                        $errs[self::FIELD_ID] = [];
                    }
                    $errs[self::FIELD_ID][$rule] = $err;
                }
            }
        }
        return $errs;
    }

    /**
     * @param \SimpleXMLElement|string|null $sxe
     * @param null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIROrganization\FHIROrganizationContact $type
     * @param null|int $libxmlOpts
     * @return null|\DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIROrganization\FHIROrganizationContact
     */
    public static function xmlUnserialize($sxe = null, PHPFHIRTypeInterface $type = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            return null;
        }
        if (is_string($sxe)) {
            libxml_use_internal_errors(true);
            $sxe = new \SimpleXMLElement($sxe, $libxmlOpts, false);
            if ($sxe === false) {
                throw new \DomainException(sprintf('FHIROrganizationContact::xmlUnserialize - String provided is not parseable as XML: %s', implode(', ', array_map(function(\libXMLError $err) { return $err->message; }, libxml_get_errors()))));
            }
            libxml_use_internal_errors(false);
        }
        if (!($sxe instanceof \SimpleXMLElement)) {
            throw new \InvalidArgumentException(sprintf('FHIROrganizationContact::xmlUnserialize - $sxe value must be null, \\SimpleXMLElement, or valid XML string, %s seen', gettype($sxe)));
        }
        if (null === $type) {
            $type = new FHIROrganizationContact;
        } elseif (!is_object($type) || !($type instanceof FHIROrganizationContact)) {
            throw new \RuntimeException(sprintf(
                'FHIROrganizationContact::xmlUnserialize - $type must be instance of \DCarbone\PHPFHIRGenerated\R4\FHIRElement\FHIRBackboneElement\FHIROrganization\FHIROrganizationContact or null, %s seen.',
                is_object($type) ? get_class($type) : gettype($type)
            ));
        }
        FHIRBackboneElement::xmlUnserialize($sxe, $type);
        $xmlNamespaces = $sxe->getDocNamespaces(false, false);
        if ([] !== $xmlNamespaces) {
            $ns = reset($xmlNamespaces);
            if (false !== $ns && '' !== $ns) {
                $type->_xmlns = $ns;
            }
        }
        $attributes = $sxe->attributes();
        $children = $sxe->children();
        if (isset($children->address)) {
            $type->setAddress(FHIRAddress::xmlUnserialize($children->address));
        }
        if (isset($children->name)) {
            $type->setName(FHIRHumanName::xmlUnserialize($children->name));
        }
        if (isset($children->purpose)) {
            $type->setPurpose(FHIRCodeableConcept::xmlUnserialize($children->purpose));
        }
        if (isset($children->telecom)) {
            foreach($children->telecom as $child) {
                $type->addTelecom(FHIRContactPoint::xmlUnserialize($child));
            }
        }
        return $type;
    }

    /**
     * @param null|\SimpleXMLElement $sxe
     * @param null|int $libxmlOpts
     * @return \SimpleXMLElement
     */
    public function xmlSerialize(\SimpleXMLElement $sxe = null, $libxmlOpts = 591872)
    {
        if (null === $sxe) {
            $sxe = new \SimpleXMLElement($this->_getFHIRXMLElementDefinition(), $libxmlOpts, false);
        }
        parent::xmlSerialize($sxe);
        if (null !== ($v = $this->getAddress())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_ADDRESS, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getName())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_NAME, null, $v->_getFHIRXMLNamespace()));
        }
        if (null !== ($v = $this->getPurpose())) {
            $v->xmlSerialize($sxe->addChild(self::FIELD_PURPOSE, null, $v->_getFHIRXMLNamespace()));
        }
        if ([] !== ($vs = $this->getTelecom())) {
            foreach($vs as $v) {
                if (null === $v) {
                    continue;
                }
                $v->xmlSerialize($sxe->addChild(self::FIELD_TELECOM, null, $v->_getFHIRXMLNamespace()));
            }
        }
        return $sxe;
    }

    /**
     * @return array
     */
    public function jsonSerialize()
    {
        $a = parent::jsonSerialize();
        if (null !== ($v = $this->getAddress())) {
            $a[self::FIELD_ADDRESS] = $v;
        }
        if (null !== ($v = $this->getName())) {
            $a[self::FIELD_NAME] = $v;
        }
        if (null !== ($v = $this->getPurpose())) {
            $a[self::FIELD_PURPOSE] = $v;
        }
        if ([] !== ($vs = $this->getTelecom())) {
            $a[self::FIELD_TELECOM] = [];
            foreach($vs as $v) {
                if (null === $v) {
                    continue;
                }
                $a[self::FIELD_TELECOM][] = $v;
            }
        }
        if ([] !== ($vs = $this->_getFHIRComments())) {
            $a[PHPFHIRConstants::JSON_FIELD_FHIR_COMMENTS] = $vs;
        }
        return $a;
    }

    /**
     * @return string
     */
    public function __toString()
    {
        return self::FHIR_TYPE_NAME;
    }
}


text:
const repl = require('repl');
const connection = require('../db/connection');

const replServer = repl.start({
  prompt: 'pika > ',
});
require('repl.history')(replServer, `${process.env.HOME}/.node_history`);

replServer.context.connection = connection;


text:
'use strict';

const RelayFeatureFlags = require('../../util/RelayFeatureFlags');
const RelayInMemoryRecordSource = require('../RelayInMemoryRecordSource');
const RelayModernEnvironment = require('../RelayModernEnvironment');
const RelayModernOperationDescriptor = require('../RelayModernOperationDescriptor');
const RelayModernStore = require('../RelayModernStore');
const RelayNetwork = require('../../network/RelayNetwork');
const RelayObservable = require('../../network/RelayObservable');

const nullthrows = require('nullthrows');

const {getSingularSelector} = require('../RelayModernSelector');
const {generateAndCompile, matchers} = require('relay-test-utils-internal');

function createOperationDescriptor(...args) {
  const operation = RelayModernOperationDescriptor.createOperationDescriptor(
    ...args,
  );
  // For convenience of the test output, override toJSON to print
  // a more succint description of the operation.
  // $FlowFixMe
  operation.toJSON = () => {
    return {
      name: operation.fragment.node.name,
      variables: operation.variables,
    };
  };
  return operation;
}

describe('execute() a query with @match', () => {
  let callbacks;
  let complete;
  let dataSource;
  let environment;
  let error;
  let fetch;
  let markdownRendererFragment;
  let markdownRendererNormalizationFragment;
  let MarkupHandler;
  let next;
  let operation;
  let operationCallback;
  let operationLoader;
  let query;
  let resolveFragment;
  let source;
  let store;
  let variables;

  beforeEach(() => {
    jest.resetModules();

    expect.extend(matchers);
    ({
      UserQuery: query,
      MarkdownUserNameRenderer_name: markdownRendererFragment,
      MarkdownUserNameRenderer_name$normalization: markdownRendererNormalizationFragment,
    } = generateAndCompile(`
        query UserQuery($id: ID!) {
          node(id: $id) {
            ... on User {
              nameRenderer @match {
                ...PlainUserNameRenderer_name
                  @module(name: "PlainUserNameRenderer.react")
                ...MarkdownUserNameRenderer_name
                  @module(name: "MarkdownUserNameRenderer.react")
              }
            }
          }
        }

        fragment PlainUserNameRenderer_name on PlainUserNameRenderer {
          plaintext
          data {
            text
          }
        }

        fragment MarkdownUserNameRenderer_name on MarkdownUserNameRenderer {
          __typename
          markdown
          data {
            markup @__clientField(handle: "markup_handler")
          }
        }
      `));
    variables = {id: '1'};
    operation = createOperationDescriptor(query, variables);
    MarkupHandler = {
      update(storeProxy, payload) {
        const record = storeProxy.get(payload.dataID);
        if (record != null) {
          const markup = record.getValue(payload.fieldKey);
          record.setValue(
            typeof markup === 'string' ? markup.toUpperCase() : null,
            payload.handleKey,
          );
        }
      },
    };

    complete = jest.fn();
    error = jest.fn();
    next = jest.fn();
    callbacks = {complete, error, next};
    fetch = (_query, _variables, _cacheConfig) => {
      return RelayObservable.create(sink => {
        dataSource = sink;
      });
    };
    operationLoader = {
      load: jest.fn(moduleName => {
        return new Promise(resolve => {
          resolveFragment = resolve;
        });
      }),
      get: jest.fn(),
    };
    source = new RelayInMemoryRecordSource();
    store = new RelayModernStore(source);
    environment = new RelayModernEnvironment({
      network: RelayNetwork.create(fetch),
      store,
      operationLoader,
      handlerProvider: name => {
        switch (name) {
          case 'markup_handler':
            return MarkupHandler;
        }
      },
    });

    const operationSnapshot = environment.lookup(operation.fragment, operation);
    operationCallback = jest.fn();
    environment.subscribe(operationSnapshot, operationCallback);
  });

  it('calls next() and publishes the initial payload to the store', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    jest.runAllTimers();

    expect(operationLoader.load).toBeCalledTimes(1);
    expect(operationLoader.load.mock.calls[0][0]).toEqual(
      'MarkdownUserNameRenderer_name$normalization.graphql',
    );

    expect(next.mock.calls.length).toBe(1);
    expect(complete).not.toBeCalled();
    expect(error).not.toBeCalled();
    expect(operationCallback).toBeCalledTimes(1);
    const operationSnapshot = operationCallback.mock.calls[0][0];
    expect(operationSnapshot.isMissingData).toBe(false);
    expect(operationSnapshot.data).toEqual({
      node: {
        nameRenderer: {
          __id:
            'client:1:nameRenderer(supported:["PlainUserNameRenderer","MarkdownUserNameRenderer"])',
          __fragmentPropName: 'name',
          __fragments: {
            MarkdownUserNameRenderer_name: {},
          },
          __fragmentOwner: operation,
          __module_component: 'MarkdownUserNameRenderer.react',
        },
      },
    });

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );
    const matchSnapshot = environment.lookup(matchSelector.selector, operation);
    // ref exists but match field data hasn't been processed yet
    expect(matchSnapshot.isMissingData).toBe(true);
    expect(matchSnapshot.data).toEqual({
      __typename: 'MarkdownUserNameRenderer',
      data: undefined,
      markdown: undefined,
    });
  });

  it('loads the @match fragment and normalizes/publishes the field payload', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              // NOTE: should be uppercased when normalized (by MarkupHandler)
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    jest.runAllTimers();
    next.mockClear();
    expect(operationCallback).toBeCalledTimes(1); // initial results tested above
    const operationSnapshot = operationCallback.mock.calls[0][0];
    operationCallback.mockClear();

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );
    // initial results tested above
    const initialMatchSnapshot = environment.lookup(
      matchSelector.selector,
      operation,
    );
    expect(initialMatchSnapshot.isMissingData).toBe(true);
    const matchCallback = jest.fn();
    environment.subscribe(initialMatchSnapshot, matchCallback);

    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    // next() should not be called when @match resolves, no new GraphQLResponse
    // was received for this case
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
    expect(matchCallback).toBeCalledTimes(1);

    const matchSnapshot = matchCallback.mock.calls[0][0];
    expect(matchSnapshot.isMissingData).toBe(false);
    expect(matchSnapshot.data).toEqual({
      __typename: 'MarkdownUserNameRenderer',
      data: {
        // NOTE: should be uppercased by the MarkupHandler
        markup: '<MARKUP/>',
      },
      markdown: 'markdown payload',
    });
  });

  it('synchronously normalizes/publishes the field payload if @match fragment is available synchronously', () => {
    environment.execute({operation}).subscribe(callbacks);
    jest
      .spyOn(operationLoader, 'get')
      .mockImplementationOnce(() => markdownRendererNormalizationFragment);

    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              // NOTE: should be uppercased when normalized (by MarkupHandler)
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    expect(next).toBeCalledTimes(1);
    next.mockClear();

    expect(operationCallback).toBeCalledTimes(1); // initial results tested above
    const operationSnapshot = operationCallback.mock.calls[0][0];
    operationCallback.mockClear();

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );

    // At this point the matchSnapshot should contain all the data,
    // since it should've been normalized synchronously
    const matchSnapshot = environment.lookup(matchSelector.selector, operation);
    expect(matchSnapshot.isMissingData).toBe(false);
    expect(matchSnapshot.data).toEqual({
      __typename: 'MarkdownUserNameRenderer',
      data: {
        // NOTE: should be uppercased by the MarkupHandler
        markup: '<MARKUP/>',
      },
      markdown: 'markdown payload',
    });
  });

  it('loads the @match fragment and normalizes/publishes the field payload with scheduling', () => {
    let taskID = 0;
    const tasks = new Map();
    const scheduler = {
      cancel: id => {
        tasks.delete(id);
      },
      schedule: task => {
        const id = String(taskID++);
        tasks.set(id, task);
        return id;
      },
    };
    const runTask = () => {
      for (const [id, task] of tasks) {
        tasks.delete(id);
        task();
        break;
      }
    };
    environment = new RelayModernEnvironment({
      network: environment.getNetwork(),
      store: environment.getStore(),
      operationLoader,
      scheduler,
      handlerProvider: name => {
        switch (name) {
          case 'markup_handler':
            return MarkupHandler;
        }
      },
    });
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              // NOTE: should be uppercased when normalized (by MarkupHandler)
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0);
    expect(tasks.size).toBe(1);
    runTask();
    jest.runAllTimers();
    next.mockClear();
    expect(operationCallback).toBeCalledTimes(1); // initial results tested above
    const operationSnapshot = operationCallback.mock.calls[0][0];
    operationCallback.mockClear();

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );
    // initial results tested above
    const initialMatchSnapshot = environment.lookup(
      matchSelector.selector,
      operation,
    );
    expect(initialMatchSnapshot.isMissingData).toBe(true);
    const matchCallback = jest.fn();
    environment.subscribe(initialMatchSnapshot, matchCallback);

    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    expect(matchCallback).toBeCalledTimes(0);
    expect(tasks.size).toBe(1);
    runTask();
    // next() should not be called when @match resolves, no new GraphQLResponse
    // was received for this case
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
    expect(matchCallback).toBeCalledTimes(1);

    const matchSnapshot = matchCallback.mock.calls[0][0];
    expect(matchSnapshot.isMissingData).toBe(false);
    expect(matchSnapshot.data).toEqual({
      __typename: 'MarkdownUserNameRenderer',
      data: {
        // NOTE: should be uppercased by the MarkupHandler
        markup: '<MARKUP/>',
      },
      markdown: 'markdown payload',
    });
  });

  it('cancels processing of @match fragments with scheduling', () => {
    let taskID = 0;
    const tasks = new Map();
    const scheduler = {
      cancel: id => {
        tasks.delete(id);
      },
      schedule: task => {
        const id = String(taskID++);
        tasks.set(id, task);
        return id;
      },
    };
    const runTask = () => {
      for (const [id, task] of tasks) {
        tasks.delete(id);
        task();
        break;
      }
    };
    environment = new RelayModernEnvironment({
      network: environment.getNetwork(),
      store: environment.getStore(),
      operationLoader,
      scheduler,
      handlerProvider: name => {
        switch (name) {
          case 'markup_handler':
            return MarkupHandler;
        }
      },
    });
    const subscription = environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              // NOTE: should be uppercased when normalized (by MarkupHandler)
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0);
    expect(tasks.size).toBe(1);
    runTask();
    jest.runAllTimers();
    next.mockClear();
    expect(operationCallback).toBeCalledTimes(1); // initial results tested above
    const operationSnapshot = operationCallback.mock.calls[0][0];
    operationCallback.mockClear();

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );
    // initial results tested above
    const initialMatchSnapshot = environment.lookup(
      matchSelector.selector,
      operation,
    );
    expect(initialMatchSnapshot.isMissingData).toBe(true);
    const matchCallback = jest.fn();
    environment.subscribe(initialMatchSnapshot, matchCallback);

    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    expect(matchCallback).toBeCalledTimes(0);
    expect(tasks.size).toBe(1);

    subscription.unsubscribe();
    expect(tasks.size).toBe(0);
    expect(matchCallback).toBeCalledTimes(0);
    expect(complete).toBeCalledTimes(0);
    expect(error).toBeCalledTimes(0);
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
  });

  it('calls complete() if the network completes before processing the match', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    jest.runAllTimers();
    dataSource.complete();
    expect(callbacks.complete).toBeCalledTimes(0);
    expect(callbacks.error).toBeCalledTimes(0);
    expect(callbacks.next).toBeCalledTimes(1);

    expect(operationLoader.load).toBeCalledTimes(1);
    expect(operationLoader.load.mock.calls[0][0]).toBe(
      'MarkdownUserNameRenderer_name$normalization.graphql',
    );
    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    expect(callbacks.complete).toBeCalledTimes(1);
    expect(callbacks.error).toBeCalledTimes(0);
    expect(callbacks.next).toBeCalledTimes(1);
  });

  it('calls complete() if the network completes after processing the match', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    jest.runAllTimers();

    expect(operationLoader.load).toBeCalledTimes(1);
    expect(operationLoader.load.mock.calls[0][0]).toBe(
      'MarkdownUserNameRenderer_name$normalization.graphql',
    );
    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    expect(callbacks.complete).toBeCalledTimes(0);
    expect(callbacks.error).toBeCalledTimes(0);
    expect(callbacks.next).toBeCalledTimes(1);

    dataSource.complete();
    expect(callbacks.complete).toBeCalledTimes(1);
    expect(callbacks.error).toBeCalledTimes(0);
    expect(callbacks.next).toBeCalledTimes(1);
  });

  it('calls error() if the operationLoader function throws synchronously', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    const loaderError = new Error();
    operationLoader.load = jest.fn(() => {
      throw loaderError;
    });
    dataSource.next(payload);
    jest.runAllTimers();

    expect(callbacks.error).toBeCalledTimes(1);
    expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
  });

  it('calls error() if operationLoader.get function throws synchronously', () => {
    environment.execute({operation}).subscribe(callbacks);
    const loaderError = new Error();
    jest.spyOn(operationLoader, 'get').mockImplementationOnce(() => {
      throw loaderError;
    });

    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);

    expect(callbacks.error).toBeCalledTimes(1);
    expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
  });

  it('calls error() if the operationLoader promise fails', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    const loaderError = new Error();
    operationLoader.load = jest.fn(() => {
      return Promise.reject(loaderError);
    });
    dataSource.next(payload);
    jest.runAllTimers();

    expect(callbacks.error).toBeCalledTimes(1);
    expect(callbacks.error.mock.calls[0][0]).toBe(loaderError);
  });

  it('calls error() if processing a match payload throws', () => {
    environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              markup: '<markup/>',
            },
          },
        },
      },
    };
    operationLoader.load = jest.fn(() => {
      // Invalid fragment node, no 'selections' field
      // This is to make sure that users implementing operationLoader
      // incorrectly still get reasonable error handling
      return Promise.resolve(({}: any));
    });
    dataSource.next(payload);
    jest.runAllTimers();

    expect(callbacks.error).toBeCalledTimes(1);
    expect(callbacks.error.mock.calls[0][0].message).toBe(
      "Cannot read property 'length' of undefined",
    );
  });

  it('cancels @match processing if unsubscribed before match payload is processed', () => {
    const subscription = environment.execute({operation}).subscribe(callbacks);
    const payload = {
      data: {
        node: {
          id: '1',
          __typename: 'User',
          nameRenderer: {
            __typename: 'MarkdownUserNameRenderer',
            __module_component_UserQuery: 'MarkdownUserNameRenderer.react',
            __module_operation_UserQuery:
              'MarkdownUserNameRenderer_name$normalization.graphql',
            markdown: 'markdown payload',
            data: {
              // NOTE: should be uppercased when normalized (by MarkupHandler)
              markup: '<markup/>',
            },
          },
        },
      },
    };
    dataSource.next(payload);
    jest.runAllTimers();
    next.mockClear();
    expect(operationCallback).toBeCalledTimes(1); // initial results tested above
    const operationSnapshot = operationCallback.mock.calls[0][0];
    operationCallback.mockClear();

    const matchSelector = nullthrows(
      getSingularSelector(
        variables,
        markdownRendererFragment,
        (operationSnapshot.data?.node: any)?.nameRenderer,
      ),
    );
    // initial results tested above
    const initialMatchSnapshot = environment.lookup(
      matchSelector.selector,
      operation,
    );
    expect(initialMatchSnapshot.isMissingData).toBe(true);
    const matchCallback = jest.fn();
    environment.subscribe(initialMatchSnapshot, matchCallback);

    subscription.unsubscribe();
    resolveFragment(markdownRendererNormalizationFragment);
    jest.runAllTimers();
    // next() should not be called when @match resolves, no new GraphQLResponse
    // was received for this case
    expect(next).toBeCalledTimes(0);
    expect(operationCallback).toBeCalledTimes(0); // operation result shouldn't change
    expect(matchCallback).toBeCalledTimes(0); // match result shouldn't change
  });
});


text:
<?php

namespace tests\Dudulina\CodeGeneration\CommandHandlersMapCodeGeneratorWithInvalidHandlersData;

use Dudulina\Command;

class Command2 implements Command
{

    public function getAggregateId()
    {
    }
}


text:
package com.novoda.downloadmanager;

import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import static com.google.common.truth.Truth.assertThat;
import static org.mockito.BDDMockito.willAnswer;
import static org.mockito.Mockito.*;

public class FixedRateTimerActionSchedulerTest {

    private static final long FREQUENCY = 100;

    private final Timer timer = mock(Timer.class);
    private final Map<ActionScheduler.Action, TimerTask> actionTimerTasks = new HashMap<>();
    private final ActionScheduler.Action anyAction = mock(ActionScheduler.Action.class);
    private TimerTask timerTask;

    private FixedRateTimerActionScheduler scheduler;

    @Before
    public void setUp() {
        scheduler = new FixedRateTimerActionScheduler(timer, FREQUENCY, actionTimerTasks);

        final ArgumentCaptor<TimerTask> argumentCaptor = ArgumentCaptor.forClass(TimerTask.class);
        willAnswer(new Answer<Void>() {
            @Override
            public Void answer(InvocationOnMock invocation) throws Throwable {
                timerTask = argumentCaptor.getValue();
                return null;
            }
        }).given(timer).scheduleAtFixedRate(argumentCaptor.capture(), eq(0L), eq(FREQUENCY));
    }

    @Test
    public void executesAction_whenSchedulingAction() {
        scheduler.schedule(anyAction);

        timerTask.run();

        verify(anyAction).perform();
    }

    @Test
    public void recordsAction_whenSchedulingAction() {
        scheduler.schedule(anyAction);

        assertThat(actionTimerTasks).containsEntry(anyAction, timerTask);
    }

    @Test
    public void doesNothing_whenActionAlreadyScheduled() {
        givenScheduledAction();

        scheduler.schedule(anyAction);

        verifyZeroInteractions(timer);
    }

    @Test
    public void cancelTimerTask_whenCancellingSpecificAction() {
        TimerTask timerTask = mock(TimerTask.class);
        actionTimerTasks.put(anyAction, timerTask);

        scheduler.cancel(anyAction);

        verify(timerTask).cancel();
    }

    @Test
    public void removeTimerTask_whenCancellingSpecificAction() {
        TimerTask timerTask = mock(TimerTask.class);
        actionTimerTasks.put(anyAction, timerTask);

        ActionScheduler.Action additionalAction = mock(ActionScheduler.Action.class);
        TimerTask additionalTimerTask = mock(TimerTask.class);
        actionTimerTasks.put(anyAction, timerTask);
        actionTimerTasks.put(additionalAction, additionalTimerTask);

        scheduler.cancel(anyAction);

        assertThat(actionTimerTasks).doesNotContainEntry(anyAction, timerTask);
        assertThat(actionTimerTasks).containsEntry(additionalAction, additionalTimerTask);
    }

    @Test
    public void clearsTimerTasks_whenCancellingAll() {
        givenScheduledAction();

        scheduler.cancelAll();

        for (Map.Entry<ActionScheduler.Action, TimerTask> actionTimerTaskEntry : actionTimerTasks.entrySet()) {
            verify(actionTimerTaskEntry.getValue()).cancel();
        }
    }

    @Test
    public void clearsAllActions_whenCancellingAll() {
        givenScheduledAction();

        scheduler.cancelAll();

        assertThat(actionTimerTasks).isEmpty();
    }

    @Test
    public void returnsTrue_whenActionIsScheduled() {
        givenScheduledAction();

        boolean scheduled = scheduler.isScheduled(anyAction);

        assertThat(scheduled).isTrue();
    }

    @Test
    public void returnsFalse_whenActionIsNotScheduled() {
        boolean scheduled = scheduler.isScheduled(anyAction);

        assertThat(scheduled).isFalse();
    }

    private void givenScheduledAction() {
        scheduler.schedule(anyAction);
        reset(timer);
    }

}


text:
// // Copyright (c) Microsoft. All rights reserved.
// // Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows;

namespace WPFHostingWin32Control
{
    /// <summary>
    ///     Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        internal const int
            LbnSelchange = 0x00000001,
            WmCommand = 0x00000111,
            LbGetcursel = 0x00000188,
            LbGettextlen = 0x0000018A,
            LbAddstring = 0x00000180,
            LbGettext = 0x00000189,
            LbDeletestring = 0x00000182,
            LbGetcount = 0x0000018B;

        private Application _app;
        private IntPtr _hwndListBox;
        private int _itemCount;
        private ControlHost _listControl;
        private Window _myWindow;
        private int _selectedItem;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void On_UIReady(object sender, EventArgs e)
        {
            _app = Application.Current;
            _myWindow = _app.MainWindow;
            _myWindow.SizeToContent = SizeToContent.WidthAndHeight;
            _listControl = new ControlHost(ControlHostElement.ActualHeight, ControlHostElement.ActualWidth);
            ControlHostElement.Child = _listControl;
            _listControl.MessageHook += ControlMsgFilter;
            _hwndListBox = _listControl.HwndListBox;
            for (var i = 0; i < 15; i++) //populate listbox
            {
                var itemText = "Item" + i;
                SendMessage(_hwndListBox, LbAddstring, IntPtr.Zero, itemText);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private void AppendText(object sender, EventArgs args)
        {
            if (txtAppend.Text != string.Empty)
            {
                SendMessage(_hwndListBox, LbAddstring, IntPtr.Zero, txtAppend.Text);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private void DeleteText(object sender, EventArgs args)
        {
            _selectedItem = SendMessage(_listControl.HwndListBox, LbGetcursel, IntPtr.Zero, IntPtr.Zero);
            if (_selectedItem != -1) //check for selected item
            {
                SendMessage(_hwndListBox, LbDeletestring, (IntPtr) _selectedItem, IntPtr.Zero);
            }
            _itemCount = SendMessage(_hwndListBox, LbGetcount, IntPtr.Zero, IntPtr.Zero);
            numItems.Text = "" + _itemCount;
        }

        private IntPtr ControlMsgFilter(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            int textLength;

            handled = false;
            if (msg == WmCommand)
            {
                switch ((uint) wParam.ToInt32() >> 16 & 0xFFFF) //extract the HIWORD
                {
                    case LbnSelchange: //Get the item text and display it
                        _selectedItem = SendMessage(_listControl.HwndListBox, LbGetcursel, IntPtr.Zero, IntPtr.Zero);
                        textLength = SendMessage(_listControl.HwndListBox, LbGettextlen, IntPtr.Zero, IntPtr.Zero);
                        var itemText = new StringBuilder();
                        SendMessage(_hwndListBox, LbGettext, _selectedItem, itemText);
                        selectedText.Text = itemText.ToString();
                        handled = true;
                        break;
                }
            }
            return IntPtr.Zero;
        }

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern int SendMessage(IntPtr hwnd,
            int msg,
            IntPtr wParam,
            IntPtr lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern int SendMessage(IntPtr hwnd,
            int msg,
            int wParam,
            [MarshalAs(UnmanagedType.LPWStr)] StringBuilder lParam);

        [DllImport("user32.dll", EntryPoint = "SendMessage", CharSet = CharSet.Unicode)]
        internal static extern IntPtr SendMessage(IntPtr hwnd,
            int msg,
            IntPtr wParam,
            string lParam);
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<title>Position Relative</title>

	<link rel="stylesheet" href="relative.css">

Position Relative

O position relative posiciona o elemento em relação a si mesmo. O ponto zero é o canto superior esquerdo, e ele começara a posicionar a partir dali.


text:
package ihr

import (
	"log"
	"regexp"
)

var (
	botInstance *Bot
)

type Bot struct {
	connector        Connector
	name             string
	connectErrorChan chan bool
	eventHandler     *EventHandler
}

func BotInstance() *Bot {
	return botInstance
}

func NewBot(connector Connector, name string, ignoreUsers []string) *Bot {
	if botInstance != nil {
		return botInstance
	}

	bot := &Bot{
		connector:        connector,
		name:             name,
		connectErrorChan: make(chan bool),
		eventHandler:     NewEventHandler(ignoreUsers),
	}
	botInstance = bot

	bot.Connect()
	return bot
}

func (self *Bot) Connect() {
	self.connector.Connect()

	go func() {
		res := self.connector.Listen()
		if res != nil {
			self.connectErrorChan <- true
		}
	}()
}

func (self *Bot) Start() {
	for {
		select {
		case event := <-self.connector.ReceivedEvent():
			event.Bot = self
			if self.connector.Async() == true {
				go self.eventHandler.Handle(*event)
			} else {
				self.eventHandler.Handle(*event)
				self.connector.Idle() <- true
			}
		case <-self.connectErrorChan:
			log.Print("reconnect")
			self.Connect()
		}
	}
}

func (self *Bot) Send(event *Event, text string) {
	self.connector.Send(event, self.name, text)
}

func (self *Bot) Hear(pattern string, callback func(Event)) {
	self.eventHandler.AddCommand(regexp.MustCompile(pattern), "", callback, false)
}

func (self *Bot) Command(pattern string, description string, callback func(Event)) {
	self.eventHandler.AddCommand(regexp.MustCompile("\\A"+self.name+"\\s+"+pattern+"\\z"), pattern+" - "+description, callback, false)
}

func (self *Bot) CommandWithArgv(pattern string, description string, callback func(Event)) {
	self.eventHandler.AddCommand(regexp.MustCompile("\\A"+self.name+"\\s+"+pattern+"(?:\\s+(.+))*\\z"), pattern+" - "+description, callback, true)
}

func (self *Bot) Appearance(user string, callback func(Event)) {
	self.eventHandler.Appearance(user, callback)
}

func (self *Bot) ShowHelp() string {
	return self.eventHandler.RenderHelp()
}

func (self *Event) Say(text string) {
	self.Bot.Send(self, text)
}