text:
import { fireEvent, screen } from "@testing-library/react-native"
import { ArtworkDetails_artwork_TestQuery } from "__generated__/ArtworkDetails_artwork_TestQuery.graphql"
import { navigate } from "app/navigation/navigate"
import { flushPromiseQueue } from "app/tests/flushPromiseQueue"
import { renderWithHookWrappersTL } from "app/tests/renderWithWrappers"
import { resolveMostRecentRelayOperation } from "app/tests/resolveMostRecentRelayOperation"
import { graphql, useLazyLoadQuery } from "react-relay"
import { createMockEnvironment } from "relay-test-utils"
import { ArtworkDetails } from "./ArtworkDetails"

jest.unmock("react-relay")

describe("ArtworkDetails", () => {
  let mockEnvironment: ReturnType<typeof createMockEnvironment>

  beforeEach(() => {
    mockEnvironment = createMockEnvironment()
  })
  const TestRenderer = () => {
    const data = useLazyLoadQuery<ArtworkDetails_artwork_TestQuery>(
      graphql`
        query ArtworkDetails_artwork_TestQuery @relay_test_operation {
          artwork(id: "four-pence-coins-david-lynch") {
            ...ArtworkDetails_artwork
          }
        }
      `,
      {}
    )

    return <ArtworkDetails artwork={data.artwork!} />
  }

  it("renders all data correctly", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {})
    await flushPromiseQueue()

    expect(screen.queryByText("Medium")).toBeTruthy()
    expect(screen.queryByText("Materials")).toBeTruthy()
    expect(screen.queryByText("Size")).toBeTruthy()
    expect(screen.queryByText("Rarity")).toBeTruthy()
    expect(screen.queryByText("Edition")).toBeTruthy()
    expect(screen.queryByText("Certificate of Authenticity")).toBeTruthy()
    expect(screen.queryByText("Condition")).toBeTruthy()
    expect(screen.queryByText("Frame")).toBeTruthy()
    expect(screen.queryByText("Signature")).toBeTruthy()
    expect(screen.queryByText("Series")).toBeTruthy()
    expect(screen.queryByText("Publisher")).toBeTruthy()
    expect(screen.queryByText("Manufacturer")).toBeTruthy()
    expect(screen.queryByText("Image rights")).toBeTruthy()
  })

  it("doesn't render fields that are null or empty string", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {
      Artwork: () => ({
        framed: {
          details: "",
        },
        publisher: null,
        manufacturer: null,
      }),
    })
    await flushPromiseQueue()

    expect(screen.queryByText("Medium")).toBeTruthy()
    expect(screen.queryByText("Materials")).toBeTruthy()
    expect(screen.queryByText("Size")).toBeTruthy()
    expect(screen.queryByText("Rarity")).toBeTruthy()
    expect(screen.queryByText("Edition")).toBeTruthy()
    expect(screen.queryByText("Certificate of Authenticity")).toBeTruthy()
    expect(screen.queryByText("Condition")).toBeTruthy()

    expect(screen.queryByText("Signature")).toBeTruthy()
    expect(screen.queryByText("Series")).toBeTruthy()

    expect(screen.queryByText("Image rights")).toBeTruthy()

    expect(screen.queryByText("Frame")).toBeNull()
    expect(screen.queryByText("Publisher")).toBeNull()
    expect(screen.queryByText("Manufacturer")).toBeNull()
  })

  describe("Edition", () => {
    it("should be rendered edition sets 0/1", async () => {
      renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

      resolveMostRecentRelayOperation(mockEnvironment, {
        Artwork: () => ({
          editionOf: "Edition Set",
          editionSets: [
            {
              internalID: "edition-set",
              editionOf: "Edition Set",
              saleMessage: "$1000",
            },
          ],
        }),
      })
      await flushPromiseQueue()

      expect(screen.queryByText("Edition Set")).toBeTruthy()
    })

    it("should NOT be rendered edition sets 2 or more", async () => {
      renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

      resolveMostRecentRelayOperation(mockEnvironment, {
        Artwork: () => ({
          editionOf: null,
          editionSets: [
            {
              internalID: "edition-set-one",
              editionOf: "Edition Set One",
              saleMessage: "$1000",
            },
            {
              internalID: "edition-set-two",
              editionOf: "Edition Set Two",
              saleMessage: "$2000",
            },
          ],
        }),
      })
      await flushPromiseQueue()

      expect(screen.queryByText("Edition")).toBeNull()
      expect(screen.queryByText("Edition Set One")).toBeNull()
      expect(screen.queryByText("Edition Set Two")).toBeNull()
    })
  })

  it("navigates to medium info modal when tapped", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {})
    await flushPromiseQueue()

    fireEvent.press(screen.getByText("name-1"))

    expect(navigate).toHaveBeenCalledWith("/artwork/slug-1/medium", { modal: true })
  })

  it("navigates to artwork classifications modal when tapped", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {})
    await flushPromiseQueue()

    fireEvent.press(screen.getByText("attributionClass.name-1"))

    expect(navigate).toHaveBeenCalledWith("/artwork-classifications", { modal: true })
  })

  it("navigates to artwork certificate of authenticity modal when tapped", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {})
    await flushPromiseQueue()

    fireEvent.press(screen.getByText("details-1"))

    expect(navigate).toHaveBeenCalledWith("/artwork-certificate-of-authenticity", { modal: true })
  })

  it("should not render condition report button when canRequestLotConditionsReport false", async () => {
    renderWithHookWrappersTL(<TestRenderer />, mockEnvironment)

    resolveMostRecentRelayOperation(mockEnvironment, {
      Artwork: () => ({
        canRequestLotConditionsReport: false,
      }),
    })

    await flushPromiseQueue()

    expect(screen.queryByText("conditionDescription.details-1")).toBeTruthy()
  })
})


text:
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)

_sym_db = _symbol_database.Default()

DESCRIPTOR = _descriptor.FileDescriptor(
  name='wireprotocol.proto',
  package='',
  serialized_pb=_b('\n\x12wireprotocol.proto\"p\n\x07Message\x12\r\n\x05magic\x18\x01 \x02(\x0c\x12\x11\n\tmessageID\x18\x02 \x02(\x0c\x12\x15\n\x06sender\x18\x03 \x02(\x0b\x32\x05.Node\x12\x19\n\x07\x63ommand\x18\x04 \x02(\x0e\x32\x08.Command\x12\x11\n\targuments\x18\x05 \x03(\t\"3\n\x04Node\x12\x0e\n\x06nodeID\x18\x03 \x02(\t\x12\x1b\n\x08services\x18\x04 \x03(\x0e\x32\t.Services*U\n\x07\x43ommand\x12\x08\n\x04PING\x10\x01\x12\t\n\x05STORE\x10\x02\x12\x07\n\x03RTC\x10\x03\x12\r\n\tFIND_NODE\x10\x04\x12\x0e\n\nFIND_VALUE\x10\x05\x12\r\n\tGET_NODES\x10\x06**\n\x08Services\x12\r\n\tNODE_LITE\x10\x01\x12\x0f\n\x0bNODE_SERVER\x10\x02')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)

_COMMAND = _descriptor.EnumDescriptor(
  name='Command',
  full_name='Command',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='PING', index=0, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='STORE', index=1, number=2,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='RTC', index=2, number=3,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='FIND_NODE', index=3, number=4,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='FIND_VALUE', index=4, number=5,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='GET_NODES', index=5, number=6,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=189,
  serialized_end=274,
)
_sym_db.RegisterEnumDescriptor(_COMMAND)

Command = enum_type_wrapper.EnumTypeWrapper(_COMMAND)
_SERVICES = _descriptor.EnumDescriptor(
  name='Services',
  full_name='Services',
  filename=None,
  file=DESCRIPTOR,
  values=[
    _descriptor.EnumValueDescriptor(
      name='NODE_LITE', index=0, number=1,
      options=None,
      type=None),
    _descriptor.EnumValueDescriptor(
      name='NODE_SERVER', index=1, number=2,
      options=None,
      type=None),
  ],
  containing_type=None,
  options=None,
  serialized_start=276,
  serialized_end=318,
)
_sym_db.RegisterEnumDescriptor(_SERVICES)

Services = enum_type_wrapper.EnumTypeWrapper(_SERVICES)
PING = 1
STORE = 2
RTC = 3
FIND_NODE = 4
FIND_VALUE = 5
GET_NODES = 6
NODE_LITE = 1
NODE_SERVER = 2

_MESSAGE = _descriptor.Descriptor(
  name='Message',
  full_name='Message',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='magic', full_name='Message.magic', index=0,
      number=1, type=12, cpp_type=9, label=2,
      has_default_value=False, default_value=_b(""),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='messageID', full_name='Message.messageID', index=1,
      number=2, type=12, cpp_type=9, label=2,
      has_default_value=False, default_value=_b(""),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='sender', full_name='Message.sender', index=2,
      number=3, type=11, cpp_type=10, label=2,
      has_default_value=False, default_value=None,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='command', full_name='Message.command', index=3,
      number=4, type=14, cpp_type=8, label=2,
      has_default_value=False, default_value=1,
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='arguments', full_name='Message.arguments', index=4,
      number=5, type=9, cpp_type=9, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=22,
  serialized_end=134,
)

_NODE = _descriptor.Descriptor(
  name='Node',
  full_name='Node',
  filename=None,
  file=DESCRIPTOR,
  containing_type=None,
  fields=[
    _descriptor.FieldDescriptor(
      name='nodeID', full_name='Node.nodeID', index=0,
      number=3, type=9, cpp_type=9, label=2,
      has_default_value=False, default_value=_b("").decode('utf-8'),
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
    _descriptor.FieldDescriptor(
      name='services', full_name='Node.services', index=1,
      number=4, type=14, cpp_type=8, label=3,
      has_default_value=False, default_value=[],
      message_type=None, enum_type=None, containing_type=None,
      is_extension=False, extension_scope=None,
      options=None),
  ],
  extensions=[
  ],
  nested_types=[],
  enum_types=[
  ],
  options=None,
  is_extendable=False,
  extension_ranges=[],
  oneofs=[
  ],
  serialized_start=136,
  serialized_end=187,
)

_MESSAGE.fields_by_name['sender'].message_type = _NODE
_MESSAGE.fields_by_name['command'].enum_type = _COMMAND
_NODE.fields_by_name['services'].enum_type = _SERVICES
DESCRIPTOR.message_types_by_name['Message'] = _MESSAGE
DESCRIPTOR.message_types_by_name['Node'] = _NODE
DESCRIPTOR.enum_types_by_name['Command'] = _COMMAND
DESCRIPTOR.enum_types_by_name['Services'] = _SERVICES

Message = _reflection.GeneratedProtocolMessageType('Message', (_message.Message,), dict(
  DESCRIPTOR = _MESSAGE,
  __module__ = 'wireprotocol_pb2'
  # @@protoc_insertion_point(class_scope:Message)
  ))
_sym_db.RegisterMessage(Message)

Node = _reflection.GeneratedProtocolMessageType('Node', (_message.Message,), dict(
  DESCRIPTOR = _NODE,
  __module__ = 'wireprotocol_pb2'
  # @@protoc_insertion_point(class_scope:Node)
  ))
_sym_db.RegisterMessage(Node)

# @@protoc_insertion_point(module_scope)

redpajama_set_name: RedPajamaGithub


text:
namespace ChainUtils.BouncyCastle.Math.EC
{
    public interface ECPointMap
    {
        ECPoint Map(ECPoint p);
    }
}


text:
declare namespace WebdriverIOAsync {
  interface Browser {
    setHitsPerPage(label: string): Promise<void>;
  }
}

browser.addCommand('setHitsPerPage', async (label: string) => {
  const oldUrl = await browser.getUrl();
  const hitsPerPage = await browser.$('.ais-HitsPerPage-select');

  await hitsPerPage.selectByVisibleText(label);

  // Changing the URL will also change the page element IDs in Internet Explorer
  // Not waiting for the URL to be properly updated before continuing can make the next tests fail
  await browser.waitUntil(
    async () => (await browser.getUrl()) !== oldUrl,
    undefined,
    `URL was not updated after setting hits per page to "${label}"`
  );
});


text:
import { GoogleMapContainerProps } from "../components/GoogleMapContainer";
import { UrlHelper } from "./UrlHelper";

export interface Location {
    address?: string;
    latitude?: number;
    longitude?: number;
    url?: string;
}

export interface StaticLocation {
    address: string;
    latitude: string;
    longitude: string;
    icon: string;
}

export const getStaticMarkerUrl = (enumImage: string, defaultMakerIcon: string): string => {
    if (enumImage) {
        return UrlHelper.getStaticResourceUrl(enumImage);
    } else if (defaultMakerIcon) {
        return UrlHelper.getStaticResourceUrl(defaultMakerIcon);
    } else {
        return "";
    }
};

// Mendix does not support negative and decimal number as static inputs, so they are strings.
export const parseStaticLocations = (props: GoogleMapContainerProps): Location[] => {
    return props.staticLocations.map(location => ({
        address: location.address,
        latitude: location.latitude.trim() !== "" ? Number(location.latitude) : undefined,
        longitude: location.longitude.trim() !== "" ? Number(location.longitude) : undefined,
        url: getStaticMarkerUrl(location.icon, props.defaultMakerIcon)
    }));
};

export const parseStyle = (style = ""): {[key: string]: string} => { // Doesn't support a few stuff.
    try {
        return style.split(";").reduce<{[key: string]: string}>((styleObject, line) => {
            const pair = line.split(":");
            if (pair.length === 2) {
                const name = pair[0].trim().replace(/(-.)/g, match => match[1].toUpperCase());
                styleObject[name] = pair[1].trim();
            }
            return styleObject;
        }, {});
    } catch (error) {
        // tslint:disable-next-line no-console
        window.console.log("Failed to parse style", style, error);
    }

    return {};
};


text:
class Question(object):
    template = "<Question>%(items)s</Question>"

    def __init__(self, identifier, content, answer_spec,
                 is_required=False, display_name=None):
        # copy all of the parameters into object attributes
        self.__dict__.update(vars())
        del self.self

    def get_as_params(self, label='Question'):
        return { label : self.get_as_xml() }

    def get_as_xml(self):
        items = [
            SimpleField('QuestionIdentifier', self.identifier),
            SimpleField('IsRequired', str(self.is_required).lower()),
            self.content,
            self.answer_spec,
        ]
        if self.display_name is not None:
            items.insert(1, SimpleField('DisplayName', self.display_name))
        items = ''.join(item.get_as_xml() for item in items)
        return self.template % vars()

try:
	from lxml import etree
	class ValidatingXML(object):
		def validate(self):
			import urllib2
			schema_src_file = urllib2.urlopen(self.schema_url)
			schema_doc = etree.parse(schema_src_file)
			schema = etree.XMLSchema(schema_doc)
			doc = etree.fromstring(self.get_as_xml())
			schema.assertValid(doc)
except ImportError:
	class ValidatingXML(object):
		def validate(self): pass

class ExternalQuestion(ValidatingXML):
    """
    An object for constructing an External Question.
    """
    schema_url = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/ExternalQuestion.xsd"
    template = '<ExternalQuestion xmlns="%(schema_url)s"><ExternalURL>%%(external_url)s</ExternalURL><FrameHeight>%%(frame_height)s</FrameHeight></ExternalQuestion>' % vars()

    def __init__(self, external_url, frame_height):
        self.external_url = external_url
        self.frame_height = frame_height

    def get_as_params(self, label='ExternalQuestion'):
        return { label : self.get_as_xml() }

    def get_as_xml(self):
        return self.template % vars(self)

class XMLTemplate:
    def get_as_xml(self):
        return self.template % vars(self)

class SimpleField(object, XMLTemplate):
    """
    A Simple name/value pair that can be easily rendered as XML.

    >>> SimpleField('Text', 'A text string').get_as_xml()
    '<Text>A text string</Text>'
    """
    template = '<%(field)s>%(value)s</%(field)s>'

    def __init__(self, field, value):
        self.field = field
        self.value = value

class Binary(object, XMLTemplate):
    template = """<Binary><MimeType><Type>%(type)s</Type><SubType>%(subtype)s</SubType></MimeType><DataURL>%(url)s</DataURL><AltText>%(alt_text)s</AltText></Binary>"""
    def __init__(self, type, subtype, url, alt_text):
        self.__dict__.update(vars())
        del self.self

class List(list):
    """A bulleted list suitable for OrderedContent or Overview content"""
    def get_as_xml(self):
        items = ''.join('<ListItem>%s</ListItem>' % item for item in self)
        return '<List>%s</List>' % items

class Application(object):
    template = "<Application><%(class_)s>%(content)s</%(class_)s></Application>"
    parameter_template = "<Name>%(name)s</Name><Value>%(value)s</Value>"

    def __init__(self, width, height, **parameters):
        self.width = width
        self.height = height
        self.parameters = parameters

    def get_inner_content(self, content):
        content.append_field('Width', self.width)
        content.append_field('Height', self.height)
        for name, value in self.parameters.items():
            value = self.parameter_template % vars()
            content.append_field('ApplicationParameter', value)

    def get_as_xml(self):
        content = OrderedContent()
        self.get_inner_content(content)
        content = content.get_as_xml()
        class_ = self.__class__.__name__
        return self.template % vars()

class JavaApplet(Application):
    def __init__(self, path, filename, *args, **kwargs):
        self.path = path
        self.filename = filename
        super(JavaApplet, self).__init__(*args, **kwargs)

    def get_inner_content(self, content):
        content = OrderedContent()
        content.append_field('AppletPath', self.path)
        content.append_field('AppletFilename', self.filename)
        super(JavaApplet, self).get_inner_content(content)

class Flash(Application):
    def __init__(self, url, *args, **kwargs):
        self.url = url
        super(Flash, self).__init__(*args, **kwargs)

    def get_inner_content(self, content):
        content = OrderedContent()
        content.append_field('FlashMovieURL', self.url)
        super(Flash, self).get_inner_content(content)

class FormattedContent(object, XMLTemplate):
    schema_url = 'http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2006-07-14/FormattedContentXHTMLSubset.xsd'
    template = '<FormattedContent><![CDATA[%(content)s]]></FormattedContent>'
    def __init__(self, content):
        self.content = content

class OrderedContent(list):

    def append_field(self, field, value):
        self.append(SimpleField(field, value))

    def get_as_xml(self):
        return ''.join(item.get_as_xml() for item in self)

class Overview(OrderedContent):
    template = '<Overview>%(content)s</Overview>'

    def get_as_params(self, label='Overview'):
        return { label : self.get_as_xml() }

    def get_as_xml(self):
        content = super(Overview, self).get_as_xml()
        return self.template % vars()

class QuestionForm(ValidatingXML, list):
    """
    From the AMT API docs:

    The top-most element of the QuestionForm data structure is a
    QuestionForm element. This element contains optional Overview
    elements and one or more Question elements. There can be any
    number of these two element types listed in any order. The
    following example structure has an Overview element and a
    Question element followed by a second Overview element and
    Question element--all within the same QuestionForm.

    ::

        <QuestionForm xmlns="[the QuestionForm schema URL]">
            <Overview>
                [...]
            </Overview>
            <Question>
                [...]
            </Question>
            <Overview>
                [...]
            </Overview>
            <Question>
                [...]
            </Question>
            [...]
        </QuestionForm>

    QuestionForm is implemented as a list, so to construct a
    QuestionForm, simply append Questions and Overviews (with at least
    one Question).
    """
    schema_url = "http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd"
    xml_template = """<QuestionForm xmlns="%(schema_url)s">%%(items)s</QuestionForm>""" % vars()

    def is_valid(self):
        return (
            any(isinstance(item, Question) for item in self)
            and
            all(isinstance(item, (Question, Overview)) for item in self)
            )

    def get_as_xml(self):
        assert self.is_valid(), "QuestionForm contains invalid elements"
        items = ''.join(item.get_as_xml() for item in self)
        return self.xml_template % vars()

class QuestionContent(OrderedContent):
    template = '<QuestionContent>%(content)s</QuestionContent>'

    def get_as_xml(self):
        content = super(QuestionContent, self).get_as_xml()
        return self.template % vars()

class AnswerSpecification(object):
    template = '<AnswerSpecification>%(spec)s</AnswerSpecification>'

    def __init__(self, spec):
        self.spec = spec

    def get_as_xml(self):
        spec = self.spec.get_as_xml()
        return self.template % vars()

class Constraints(OrderedContent):
    template = '<Constraints>%(content)s</Constraints>'

    def get_as_xml(self):
        content = super(Constraints, self).get_as_xml()
        return self.template % vars()

class Constraint(object):
    def get_attributes(self):
        pairs = zip(self.attribute_names, self.attribute_values)
        attrs = ' '.join(
            '%s="%d"' % (name,value)
            for (name,value) in pairs
            if value is not None
            )
        return attrs

    def get_as_xml(self):
        attrs = self.get_attributes()
        return self.template % vars()

class NumericConstraint(Constraint):
    attribute_names = 'minValue', 'maxValue'
    template = '<IsNumeric %(attrs)s />'

    def __init__(self, min_value=None, max_value=None):
        self.attribute_values = min_value, max_value

class LengthConstraint(Constraint):
    attribute_names = 'minLength', 'maxLength'
    template = '<Length %(attrs)s />'

    def __init__(self, min_length=None, max_length=None):
        self.attribute_values = min_length, max_length

class RegExConstraint(Constraint):
    attribute_names = 'regex', 'errorText', 'flags'
    template = '<AnswerFormatRegex %(attrs)s />'

    def __init__(self, pattern, error_text=None, flags=None):
        self.attribute_values = pattern, error_text, flags

class NumberOfLinesSuggestion(object):
    template = '<NumberOfLinesSuggestion>%(num_lines)s</NumberOfLinesSuggestion>'

    def __init__(self, num_lines=1):
        self.num_lines = num_lines

    def get_as_xml(self):
        num_lines = self.num_lines
        return self.template % vars()

class FreeTextAnswer(object):
    template = '<FreeTextAnswer>%(items)s</FreeTextAnswer>'

    def __init__(self, default=None, constraints=None, num_lines=None):
        self.default = default
        if constraints is None:
            self.constraints = Constraints()
        else:
            self.constraints = Constraints(constraints)
        self.num_lines = num_lines

    def get_as_xml(self):
        items = [self.constraints]
        if self.default:
            items.append(SimpleField('DefaultText', self.default))
        if self.num_lines:
            items.append(NumberOfLinesSuggestion(self.num_lines))
        items = ''.join(item.get_as_xml() for item in items)
        return self.template % vars()

class FileUploadAnswer(object):
    template = """<FileUploadAnswer><MinFileSizeInBytes>%(min_bytes)d</MinFileSizeInBytes><MaxFileSizeInBytes>%(max_bytes)d</MaxFileSizeInBytes></FileUploadAnswer>"""

    def __init__(self, min_bytes, max_bytes):
        assert 0 <= min_bytes <= max_bytes <= 2*10**9
        self.min_bytes = min_bytes
        self.max_bytes = max_bytes

    def get_as_xml(self):
        return self.template % vars(self)

class SelectionAnswer(object):
    """
    A class to generate SelectionAnswer XML data structures.
    Does not yet implement Binary selection options.
    """
    SELECTIONANSWER_XML_TEMPLATE = """<SelectionAnswer>%s%s<Selections>%s</Selections></SelectionAnswer>""" # % (count_xml, style_xml, selections_xml)
    SELECTION_XML_TEMPLATE = """<Selection><SelectionIdentifier>%s</SelectionIdentifier>%s</Selection>""" # (identifier, value_xml)
    SELECTION_VALUE_XML_TEMPLATE = """<%s>%s</%s>""" # (type, value, type)
    STYLE_XML_TEMPLATE = """<StyleSuggestion>%s</StyleSuggestion>""" # (style)
    MIN_SELECTION_COUNT_XML_TEMPLATE = """<MinSelectionCount>%s</MinSelectionCount>""" # count
    MAX_SELECTION_COUNT_XML_TEMPLATE = """<MaxSelectionCount>%s</MaxSelectionCount>""" # count
    ACCEPTED_STYLES = ['radiobutton', 'dropdown', 'checkbox', 'list', 'combobox', 'multichooser']
    OTHER_SELECTION_ELEMENT_NAME = 'OtherSelection'

    def __init__(self, min=1, max=1, style=None, selections=None, type='text', other=False):

        if style is not None:
            if style in SelectionAnswer.ACCEPTED_STYLES:
                self.style_suggestion = style
            else:
                raise ValueError("style '%s' not recognized; should be one of %s" % (style, ', '.join(SelectionAnswer.ACCEPTED_STYLES)))
        else:
            self.style_suggestion = None

        if selections is None:
            raise ValueError("SelectionAnswer.__init__(): selections must be a non-empty list of (content, identifier) tuples")
        else:
            self.selections = selections

        self.min_selections = min
        self.max_selections = max

        assert len(selections) >= self.min_selections, "# of selections is less than minimum of %d" % self.min_selections
        #assert len(selections) <= self.max_selections, "# of selections exceeds maximum of %d" % self.max_selections

        self.type = type

        self.other = other

    def get_as_xml(self):
        if self.type == 'text':
            TYPE_TAG = "Text"
        elif self.type == 'binary':
            TYPE_TAG = "Binary"
        else:
            raise ValueError("illegal type: %s; must be either 'text' or 'binary'" % str(self.type))

        # build list of <Selection> elements
        selections_xml = ""
        for tpl in self.selections:
            value_xml = SelectionAnswer.SELECTION_VALUE_XML_TEMPLATE % (TYPE_TAG, tpl[0], TYPE_TAG)
            selection_xml = SelectionAnswer.SELECTION_XML_TEMPLATE % (tpl[1], value_xml)
            selections_xml += selection_xml

        if self.other:
            # add OtherSelection element as xml if available
            if hasattr(self.other, 'get_as_xml'):
                assert type(self.other) == FreeTextAnswer, 'OtherSelection can only be a FreeTextAnswer'
                selections_xml += self.other.get_as_xml().replace('FreeTextAnswer', 'OtherSelection')
            else:
                selections_xml += "<OtherSelection />"

        if self.style_suggestion is not None:
            style_xml = SelectionAnswer.STYLE_XML_TEMPLATE % self.style_suggestion
        else:
            style_xml = ""

        if self.style_suggestion != 'radiobutton':
            count_xml = SelectionAnswer.MIN_SELECTION_COUNT_XML_TEMPLATE %self.min_selections
            count_xml += SelectionAnswer.MAX_SELECTION_COUNT_XML_TEMPLATE %self.max_selections
        else:
            count_xml = ""

        ret = SelectionAnswer.SELECTIONANSWER_XML_TEMPLATE % (count_xml, style_xml, selections_xml)

        # return XML
        return ret


text:
using System;
using System.Runtime.InteropServices;

[StructLayout(LayoutKind.Sequential)]
public struct Tri {
	public const int SideCount = 3;

	public int Index0 { get; }
	public int Index1 { get; }
	public int Index2 { get; }

	public Tri(int index0, int index1, int index2) {
		this.Index0 = index0;
		this.Index1 = index1;
		this.Index2 = index2;
	}

	public int GetCorner(int idx) {
		idx %= SideCount;
		if (idx < 0) {
			idx += SideCount;
		}
		switch (idx % SideCount) {
			case 0: return Index0;
			case 1: return Index1;
			default: return Index2;
		}
	}

	public Tri Flip() {
		return new Tri(Index2, Index1, Index0);
	}

	public bool Contains(int vertexIdx) {
		return Index0 == vertexIdx || Index1 == vertexIdx || Index2 == vertexIdx;
	}

	public Tri Map(Func<int, int> func) {
		return new Tri(
			func(Index0),
			func(Index1),
			func(Index2)
		);
	}

	public override string ToString() {
		return string.Format("Quad[{0}, {1}, {2}, {3}]", Index0, Index1, Index2);
	}

	public Tri Reindex(int offset) {
		return new Tri(Index0 + offset, Index1 + offset, Index2 + offset);
	}
}


text:
<?php
namespace Google\Service;

/**
 * This class defines attributes, valid values, and usage which is generated from
 * a given json schema. http://tools.ietf.org/html/draft-zyp-json-schema-03#section-5
 *
 * @author Chirag Shah <chirags@google.com>
 *
 */
class Model {
  public function __construct( /* polymorphic */ ) {
    if (func_num_args() ==  1 && is_array(func_get_arg(0))) {
      // Initialize the model with the array's contents.
      $array = func_get_arg(0);
      $this->mapTypes($array);
    }
  }

  /**
   * Initialize this object's properties from an array.
   *
   * @param array $array Used to seed this object's properties.
   * @return void
   */
  protected function mapTypes($array) {
    foreach ($array as $key => $val) {
      $this->$key = $val;

      $keyTypeName = "__$key" . 'Type';
      $keyDataType = "__$key" . 'DataType';
      if ($this->useObjects() && property_exists($this, $keyTypeName)) {
        if ($this->isAssociativeArray($val)) {
          if (isset($this->$keyDataType) && 'map' == $this->$keyDataType) {
            foreach($val as $arrayKey => $arrayItem) {
              $val[$arrayKey] = $this->createObjectFromName($keyTypeName, $arrayItem);
            }
            $this->$key = $val;
          } else {
            $this->$key = $this->createObjectFromName($keyTypeName, $val);
          }
        } else if (is_array($val)) {
          $arrayObject = array();
          foreach ($val as $arrayIndex => $arrayItem) {
            $arrayObject[$arrayIndex] = $this->createObjectFromName($keyTypeName, $arrayItem);
          }
          $this->$key = $arrayObject;
        }
      }
    }
  }

  /**
   * Returns true only if the array is associative.
   * @param array $array
   * @return bool True if the array is associative.
   */
  protected function isAssociativeArray($array) {
    if (!is_array($array)) {
      return false;
    }
    $keys = array_keys($array);
    foreach($keys as $key) {
      if (is_string($key)) {
        return true;
      }
    }
    return false;
  }

  /**
   * Given a variable name, discover its type.
   *
   * @param $name
   * @param $item
   * @return object The object from the item.
   */
  private function createObjectFromName($name, $item) {
    $type = $this->$name;
    return new $type($item);
  }

  protected function useObjects() {
    global $apiConfig;
    return (isset($apiConfig['use_objects']) && $apiConfig['use_objects']);
  }

  /**
   * Verify if $obj is an array.
   * @throws Exception Thrown if $obj isn't an array.
   * @param array $obj Items that should be validated.
   * @param string $type Array items should be of this type.
   * @param string $method Method expecting an array as an argument.
   */
  public function assertIsArray($obj, $type, $method) {
    if ($obj && !is_array($obj)) {
      throw new \Exception("Incorrect parameter type passed to $method(), expected an"
          . " array containing items of type $type.");
    }
  }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import 'index.scss';
import App from 'app/App';
import OwnerView from 'app/OwnerView';
import * as serviceWorker from 'serviceWorker';

ReactDOM.render(
	<App>
		<OwnerView />
	</App>,
	document.getElementById('main-container')
);

// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();


text:
package manon.model.user.form;

import nl.jqno.equalsverifier.EqualsVerifier;
import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;

class UserPasswordUpdateFormTest {

    @Test
    void shouldVerifyToString() {
        assertThat(UserPasswordUpdateForm.builder().build().toString()).contains(
            "oldPassword", "newPassword");
    }

    @Test
    void shouldVerifyEqualsContract() {
        EqualsVerifier.simple().forClass(UserPasswordUpdateForm.class)
            .verify();
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context="com.example.luan.checkgasosa.MainActivity">

        <ImageView
            android:id="@+id/imageView2"
            android:layout_width="314dp"
            android:layout_height="145dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:background="@drawable/logo_full"
            app:layout_constraintBottom_toBottomOf="parent"
            android:layout_marginBottom="8dp"
            android:layout_marginRight="8dp"
            app:layout_constraintRight_toRightOf="parent"
            android:layout_marginLeft="8dp"
            app:layout_constraintLeft_toLeftOf="parent"
            android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/tvAutonomia" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginLeft="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:onClick="visualizar"
            android:text="Visualizar"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <Button
            android:id="@+id/button3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginTop="8dp"
            android:onClick="cadastrar"
            android:text="Cadastrar"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="63dp"
            android:text="Autonomia atual"
            android:textAlignment="center"
            android:textColor="@color/bgBlack"
            android:textSize="30dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/tvAutonomia"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginLeft="8dp"
            android:layout_marginRight="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:textAlignment="center"
            android:textColor="@color/bgBlack"
            android:textSize="25dp"
            app:layout_constraintHorizontal_bias="0.0"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/textView5" />

    </android.support.constraint.ConstraintLayout>

    <ImageView
        android:id="@+id/imageView4"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="66dp"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:background="@drawable/logo_full"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent" />

    <Button
        android:id="@+id/button6"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:onClick="visualizar"
        android:text="Visualizar"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <Button
        android:id="@+id/button7"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginTop="8dp"
        android:onClick="cadastrar"
        android:text="Cadastrar"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView17"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="96dp"
        android:text="Autonomia atual"
        android:textAlignment="center"
        android:textColor="@color/bgBlack"
        android:textSize="40dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <TextView
        android:id="@+id/textView18"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginEnd="8dp"
        android:layout_marginLeft="8dp"
        android:layout_marginRight="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:textAlignment="center"
        android:textColor="@color/bgBlack"
        android:textSize="35dp"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/textView5" />
</LinearLayout>


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Puccinia inclusa var. inclusa

### Remarks
null


text:
define([
    "dojo/_base/declare",
    "dojo/_base/lang",
    "dojo/_base/array",
    "dojo/dom-construct",
    "dojo/dom-style",
    "dojo/dom-class",
    "dojo/dom-geometry",
    "dojo/on",
    "dojo/query",
    "dojo/sniff",
    "dojo/topic",
    "dojo/NodeList-dom",
    "dojox/mobile/Switch", // pre-loaded as required by Dojo

    "application/lib/SvgHelper",

    "dijit/_WidgetBase",
    "dijit/_TemplatedMixin",
    "dijit/_WidgetsInTemplateMixin",
    "dojo/Evented",
    "dojo/text!./ItemListView.html"
], function (declare, lang, array, domConstruct, domStyle, domClass, domGeom, on, query, has, topic, nld, Switch,
    SvgHelper,
    _WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented,
    template) {

    return declare([_WidgetBase, _TemplatedMixin, _WidgetsInTemplateMixin, Evented], {
        templateString: template,

        /**
         * Constructor for class.
         * @param {object} appConfig App configuration object; see subclass for required parameter(s)
         * @memberOf social#
         * @constructor
         */
        constructor: function () {
            this.votesField = null;
        },

        /**
         * Widget postCreate, called automatically in widget creation
         * life cycle, after constructor. Sets class variables.
         */
        postCreate: function () {
            this.inherited(arguments);
            this.i18n = this.appConfig.i18n.item_list;
            this.hide();

            // Adjust the toggle for linking the item list to the map extents
            this.linkToggleLabel.innerHTML = this.i18n.linkToMapViewOptionLabel;
            this.linkToMapViewIsTemporarilyOff = this.appConfig.showAllFeatures;
            this.linkToMapView = !this.appConfig.showAllFeatures;
            this.linkToggleBtn.set("leftLabel", "");
            this.linkToggleBtn.set("rightLabel", "");
            this.linkToggleBtn.set("value", this.linkToMapView ?
                "on" :
                "off");
            this.linkToggleBtn.set("title", this.i18n.linkToMapViewOptionTooltip);

            this.inherited(arguments);
        },

        /**
         * Widget startup, called automatically in widget creation
         * life cycle, after postCreate. Prepares for resizing now
         * that widget has been added to DOM.
         */
        startup: function () {
            this.inherited(arguments);
            this.linkToggleBtn.resize();

            this.own(on(window, "resize", lang.hitch(this, function () {
                this.fitFilterLabelToContainer();
            })));

            this.linkToggleBtn.on("stateChanged", lang.hitch(this, function (newState) {
                this.linkToMapView = newState === "on";
                topic.publish("linkToMapViewChanged", this.linkToMapView);
            }));

            array.forEach(query(".mblSwitchBgLeft", this.itemListActionBar), function (item) {
                domClass.add(item, "themeHeaderInverted");
            });
            domStyle.set(this.itemListActionBar, "border-bottom-color", this.appConfig.theme.header.text);
        },

        /**
         * Adjusts the width of the filter-to-map label based on the size of its container.
         */
        fitFilterLabelToContainer: function () {
            var actionBarBounds, switchBounds, newWidth;

            actionBarBounds = domGeom.getMarginBox(this.itemListActionBar);
            switchBounds = domGeom.getMarginBox(this.linkToggleBtn.domNode);

            newWidth = actionBarBounds.w - switchBounds.w - 12 /*margins*/ - 8; /*padding*/
            if (newWidth > 0) {
                domStyle.set(this.linkToggleLabel, "width", newWidth + "px");

                // If the screen is wide enough to show map and list, restore the linkage of
                // map to list if it was on the last time that we could see the action bar
                if (!this.linkToMapViewIsTemporarilyOff) {
                    this.linkToMapViewIsTemporarilyOff = true;
                    if (this.linkToMapView) {
                        topic.publish("linkToMapViewChanged", true);
                    }
                }
                // If the screen is narrow enough that we're not showing the action bar,
                // turn off linking the list to the map
            }
            else if (this.linkToMapViewIsTemporarilyOff) {
                this.linkToMapViewIsTemporarilyOff = false;
                topic.publish("linkToMapViewChanged", false);
            }
        },

        /**
         * Shows the widget.
         */
        show: function () {
            domStyle.set(this.domNode, "display", "block");
            this.fitFilterLabelToContainer();

            if (has("ff")) {
                // Scroll to the top of the list; needed for Firefox
                this.scrollIntoView(this.list);
            }
        },

        /**
         * Hides the widget.
         */
        hide: function () {
            domStyle.set(this.domNode, "display", "none");
        },

        /**
         * Sets the fields that are needed to display feature information in this list (number of votes).
         * Needs to be called before first setItems to tell the widget which fields to look for.
         * @param {string} votesField Name of votes property
         */
        setFields: function (votesField) {
            this.votesField = votesField;
        },

        /**
         * Sets the items to be displayed in the items list, and then builds the list.
         * @param {array} items feature collection or array
         * @param {function} [compareFunction] Function to compare two items (a, b) for the desired sort order; returns
         * <0 value if a < b, 0 if a = b, >0 if a > b
         */
        setItems: function (items, compareFunction) {
            this.items = items;
            this.clearList();
            this.buildList(compareFunction);
        },

        /**
         * Sets the OID of the item to be considered the current selection.
         * @param {OID} itemOID
         */
        setSelection: function (itemOID) {
            this.selectedItemOID = itemOID;
        },

        /**
         * Clears the items list
         */
        clearList: function () {
            domConstruct.empty(this.list);
        },

        /**
         * Builds the items list
         * @param {function} [compareFunction] Function to compare two items (a, b) for the desired sort order; returns
         * <0 value if a < b, 0 if a = b, >0 if a > b
         */
        buildList: function (compareFunction) {
            if (compareFunction) {
                this.items.sort(compareFunction);
            }
            array.forEach(this.items, lang.hitch(this, this.buildItemSummary));
            this.emit("itemListLoaded");
        },

        /**
         * Builds an individual item summary given an item.
         * @param  {feature} item to display in the list
         */
        buildItemSummary: function (item) {
            var itemTitle, itemVotes, itemSummaryDiv, itemTitleDiv, favDiv, iconDiv, votesIconSurface;

            itemTitle = this.getItemTitle(item) || " ";

            itemVotes = this.getItemVotes(item);

            itemSummaryDiv = domConstruct.create("div", {
                "class": "itemSummary themeItemList",
                "click": lang.partial(this.summaryClick, this, item)
            }, this.list);
            domStyle.set(itemSummaryDiv, "border-bottom-color", this.appConfig.theme.body.text);

            itemTitleDiv = domConstruct.create("div", {
                "class": "itemTitle",
                "title": itemTitle,
                "innerHTML": itemTitle
            }, itemSummaryDiv);

            // If we're displaying votes, create the count and icon displays
            if (itemVotes) {
                if (itemVotes.needSpace) {
                    domClass.add(itemTitleDiv, "itemListTitleOverride");
                }

                favDiv = domConstruct.create("div", {
                    "class": "itemFav",
                    "title": this.i18n.likesForThisItemTooltip
                }, itemSummaryDiv);

                domConstruct.create("div", {
                    "class": "itemVotes themeItemListVotes",
                    "innerHTML": itemVotes.label
                }, favDiv);

                iconDiv = domConstruct.create("div", {
                    "class": "fav"
                }, favDiv);

                votesIconSurface = SvgHelper.createSVGItem(this.appConfig.likeIcon, iconDiv, 12, 12);
                SvgHelper.changeColor(votesIconSurface, this.appConfig.theme.accents.bodyTextAlt);
            }

            // If this item's OID matches the current selection, apply the theme to highlight it
            // only if showRelatedFeatures is false or showRelatedFeatures and highlightSelectedFeature
            // is set to true
            if (this.selectedItemOID === item.attributes[item._layer.objectIdField] &&
                (!this.appConfig.showRelatedFeatures ||
                    (this.appConfig.showRelatedFeatures && this.appConfig.highlightSelectedFeature))) {
                domClass.add(itemSummaryDiv, "themeItemListSelected");
            }
        },

        /**
         * Scrolls a container node to make a specified node visible.
         * @param {object} nodeToMakeVisible Node that's to be brought into view
         */
        scrollIntoView: function (nodeToMakeVisible) {
            // Firefox defaults to former scroll position if we're returning to a previously-scrolled node (which could
            // be a different item's details--they go into the same scrollable div). The scrollIntoView can't change this
            // unless it occurs a little later than the default behavior, hence the setTimeout.
            setTimeout(function () {
                nodeToMakeVisible.scrollIntoView({ behavior: "smooth", block: "nearest"});
            }, 500);
        },

        /**
         * Gets title of feature for list display
         * @param  {feature} item The feature for which to get the title
         * @return {string} The title of the feature
         */
        getItemTitle: function (item) {
            return item.getTitle ? this.stripTags(item.getTitle()) : "";
        },

        /**
         * Removes HTML tags from a string
         * @param {string} str String possibly containing HTML tags
         * @return {string} Cleaned string; if str is undefined or null, an empty string is returned
         * @see http://dojo-toolkit.33424.n3.nabble.com/Stripping-HTML-tags-from-a-string-tp3999505p3999576.html
         */
        stripTags: function (str) {
            if (str) {
                return domConstruct.create("div", {
                    innerHTML: str
                }).textContent;
            }
            return "";
        },

        /**
         * Gets the number of votes for an item
         * @param  {feature} item The feature for which to get the vote count
         * @return {null|object} Object containing "label" with vote count for the item in a shortened form
         * (num if <1000, floor(count/1000)+"k" if <1M, floor(count/1000000)+"M" otherwise) and "needSpace"
         * that's indicates if an extra digit of room is needed to handle numbers between 99K and 1M, exclusive;
         * returns null if the feature layer's votes field is unknown
         */
        getItemVotes: function (item) {
            var needSpace = false,
                votes;

            if (this.votesField) {
                votes = item.attributes[this.votesField] || 0;

                if (votes > 999) {
                    if (votes > 99999) {
                        needSpace = true;
                    }
                    // Using SI prefixes from http://physics.nist.gov/cuu/pdf/sp811.pdf
                    if (votes > 999999999999999) {
                        votes = Math.floor(votes / 1000000000000000) + "P";
                    }
                    else if (votes > 999999999999) {
                        votes = Math.floor(votes / 1000000000000) + "T";
                    }
                    else if (votes > 999999999) {
                        votes = Math.floor(votes / 1000000000) + "G";
                    }
                    else if (votes > 999999) {
                        votes = Math.floor(votes / 1000000) + "M";
                    }
                    else {
                        votes = Math.floor(votes / 1000) + "k";
                    }
                }
                return {
                    "label": votes,
                    "needSpace": needSpace
                };
            }
            return null;
        },

        /**
         * Called on an item summary click
         * @param  {context} self The widget itself, since 'this' is the row that was clicked
         * @param  {feature} feat The feature that corresponds to the row that was clicked
         * @param  {mouse event} evt  The click event on the row that was clicked
         */
        summaryClick: function (self, feat, evt) {
            // 'this' = row click
            topic.publish("itemSelected", feat);
        }

    });
});


text:
var searchData=
[
  ['l1_20cache_20functions',['L1 Cache Functions',['../group__L1__cache__functions.html',1,'']]],
  ['l2c_2d310_20cache_20controller_20functions',['L2C-310 Cache Controller Functions',['../group__L2__cache__functions.html',1,'']]]
];


text:
'use strict';

var React = require('react/addons');

var Header = React.createClass({

  render: function() {
    return (

Lance-REST Browser

    );
  }
});

module.exports = Header;


text:
require File.expand_path(File.dirname(__FILE__) + "/../../test_helper")

class Admin::BlogPosts5IntegrationTest < ActionController::IntegrationTest
  def setup
    User.destroy_all
    @soren = User.create! :username => 'soren'
    @jean = User.create! :username => 'jean'
  end

  def test_create_with_title_alt
    post(
      "/admin/blog_posts5",
      :blog_post => {
        :user_id => @soren.id, :title => '', :title_alt => 'alternate field'
      }
    )
    assert_response :redirect

    # should use the value of title alt for the title
    bp = BlogPost.last
    assert_equal('alternate field', bp.title)
  end

  def test_index
    BlogPost.create!(
      :published_at => Time.utc(2009, 9, 1, 12, 30, 0), :user => @soren,
      :title => 'whatever'
    )
    BlogPost.create!(
      :published_at => Time.utc(2009, 9, 1, 12, 30, 0), :user => @soren,
      :title => 'just do it'
    )
    get "/admin/blog_posts5"
    assert_response :success

    # should render the filter.html.erb partial
    assert_select('ul.aa_filter')
    assert_select('ul.aa_filter li a', :text => "soren")
    assert_select('td', :text => "whatever")
    assert_select('td', :text => "just do it")
  end

  def test_index_filter
    BlogPost.create!(
      :published_at => Time.utc(2009, 9, 1, 12, 30, 0), :user => @soren,
      :title => 'whatever'
    )
    BlogPost.create!(
      :published_at => Time.utc(2009, 9, 1, 12, 30, 0), :user => @soren,
      :title => 'whatever'
    )

    get "/admin/blog_posts5?filter=#{@soren.id}"
    assert_response :success

    # should filter blog posts by user id
    assert_select('td', :text => "whatever")
    assert_no_match(%r|<td[^>]*>just do it</td>|, response.body)
  end

  def test_search_retains_filter
    user1 = User.find_or_create_by_username 'friedrich'
    user2 = User.find_or_create_by_username 'rene'

    BlogPost.create! :title => "God is dead", :user => user1
    blog_post2 = BlogPost.create! :title => "I think therefore I am", :user => user2

    visit "/admin/blog_posts5"
    click_link "friedrich"
    fill_in "search", :with => 'I think therefore I am'
    click_button 'Search'

    assert_select 'a[href=?]', "/admin/blog_posts5/edit/#{blog_post2.id}", false
  end
end


text:
<?php

namespace ForkCMS\Core\Domain\Kernel\Event;

use Symfony\Contracts\EventDispatcher\Event;

final class ClearCacheEvent extends Event
{
}


text:
require 'spec_helper'

RSpec.describe 'Dashboard action', type: :request do
  subject { page }

  it 'shows statistics by default' do
    allow(RailsAdmin.config(Player).abstract_model).to receive(:count).and_return(0)
    expect(RailsAdmin.config(Player).abstract_model).to receive(:count)
    visit dashboard_path
  end

  it 'does not show statistics if turned off' do
    RailsAdmin.config do |c|
      c.included_models = [Player]
      c.actions do
        dashboard do
          statistics false
        end
        index # mandatory
      end
    end

    expect(RailsAdmin.config(Player).abstract_model).not_to receive(:count)
    visit dashboard_path
  end

  it 'counts are different for same-named models in different modules' do
    allow(RailsAdmin.config(User::Confirmed).abstract_model).to receive(:count).and_return(10)
    allow(RailsAdmin.config(Comment::Confirmed).abstract_model).to receive(:count).and_return(0)

    visit dashboard_path
    expect(find('tr.user_confirmed_links .progress').text).to eq '10'
    expect(find('tr.comment_confirmed_links .progress').text).to eq '0'
  end

  it 'most recent change dates are different for same-named models in different modules' do
    user_create = 10.days.ago
    comment_create = 20.days.ago
    FactoryBot.create(:user_confirmed, created_at: user_create)
    FactoryBot.create(:comment_confirmed, created_at: comment_create)

    visit dashboard_path
    expect(find('tr.user_confirmed_links')).to have_content '10 days ago'
    expect(find('tr.comment_confirmed_links')).to have_content '20 days ago'
  end

  describe 'I18n' do
    around do |example|
      I18n.config.available_locales = I18n.config.available_locales + [:xx]
      I18n.backend.class.send(:include, I18n::Backend::Pluralization)
      I18n.backend.store_translations :xx,
                                      admin: {
                                        misc: {
                                          ago: 'back',
                                        },
                                      },
                                      datetime: {
                                        distance_in_words: {
                                          x_days: {
                                            one: '1 day',
                                          },
                                        },
                                      }

      I18n.locale = :xx

      example.run

      I18n.locale = :en
      I18n.config.available_locales = I18n.config.available_locales - [:xx]
    end

    it "fallbacks to 'ago' when 'time_ago' is not available" do
      FactoryBot.create(:player, created_at: 1.day.ago)

      visit dashboard_path
      expect(page).to have_content '1 day back'
    end
  end
end


text:
<!DOCTYPE html>
<html>
<head>
    {% load static %}
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">
    <meta name="robots" content="noindex">
    <title>{{ SITE_NAME }} | {{ SITE_DESCRIPTION }}</title>
    <link href="{% static 'account/css/account.css' %}" rel="stylesheet">
    {% load compress %}
    {% compress css %}
        <!-- Bootstrap core CSS -->
        <link href="{% static 'assets/css/bootstrap.min.css' %}" rel="stylesheet">
        <link href="{% static 'blog/css/oauth_style.css' %}" rel="stylesheet">
        <!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->
        <link href="{% static 'assets/css/ie10-viewport-bug-workaround.css' %}" rel="stylesheet">
        <!-- TODC Bootstrap core CSS -->
        <link href="{% static 'assets/css/todc-bootstrap.min.css' %}" rel="stylesheet">
        <!-- Custom styles for this template -->
        <link href="{% static 'assets/css/signin.css' %}" rel="stylesheet">
    {% endcompress %}
    {% compress js %}
        <script src="{% static 'assets/js/ie10-viewport-bug-workaround.js' %}"></script>
        <script src="{% static 'assets/js/ie-emulation-modes-warning.js' %}"></script>
    {% endcompress %}
    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>

<body>
{% block content %}
{% endblock %}

<!-- IE10 viewport hack for Surface/desktop Windows 8 bug -->

</body>
    <script type="text/javascript" src="{% static 'blog/js/jquery-3.6.0.min.js' %}"></script>
    <script src="{% static 'account/js/account.js' %}" type="text/javascript"></script>
</html>


text:
#
#include <stdexcept>
#include "fisx_material.h"
#include <iostream>

namespace fisx
{

Material::Material()
{
    this->initialized = false;
    this->name = "Unset name";
    this->comment = "";
    this->defaultDensity = 1.0;
    this->defaultThickness = 1.0;
}

Material::Material(const std::string & materialName, const double & density,\
                    const double & thickness, const std::string & comment)
{
    this->initialize(materialName, density, thickness, comment);
}

void Material::setName(const std::string & name)
{
    std::string msg;

    if (this->initialized)
    {
        msg = "Material::setName. Material is already initialized with name " + this->name;
        throw std::invalid_argument(msg);
    }
    this->initialize(name, this->defaultDensity, this->defaultThickness, this->comment);
}

void Material::initialize(const std::string & materialName, const double & density, \
                          const double & thickness, const std::string & comment)
{
    std::string msg;

/*
    if (this->initialized)
    {
        msg = "Material::initialize. Material is already initialized with name " + this->name;
        throw std::invalid_argument(msg);
    }
*/
    if(materialName.size() < 1)
    {
        throw std::invalid_argument("Material name should have at least one letter");
    }
    if (density <= 0.0)
    {
        throw std::invalid_argument("Material density should be positive");
    }
    if (thickness <= 0.0)
    {
        throw std::invalid_argument("Material thickness should be positive");
    }

    this->name = materialName;
    this->defaultDensity = density;
    this->defaultThickness = thickness;
    this->comment = comment;
    this->initialized = true;
}

void Material::setComposition(const std::map<std::string, double> & composition)
{
    std::map<std::string, double>::const_iterator c_it;
    std::vector<std::string> names;
    std::vector<double> amounts;

    for(c_it = composition.begin(); c_it != composition.end(); ++c_it)
    {
        names.push_back(c_it->first);
        amounts.push_back(c_it->second);
    }
    this->setComposition(names, amounts);
}

void Material::setComposition(const std::vector<std::string> & names, const std::vector<double> & amounts)
{
    std::vector<double>::size_type i;
    double total;

    if (names.size() != amounts.size())
    {
        for(i = 0; i < names.size(); i++)
        {
            std::cout << i << " name " << names[i] << std::endl;
        }
        for(i = 0; i < amounts.size(); i++)
        {
            std::cout << i << " amount " << amounts[i] << std::endl;
        }
        throw std::invalid_argument("Number of substances does not match number of amounts");
    }

    total = 0.0;

    for (i = 0; i < amounts.size(); ++i)
    {
        if (amounts[i] <= 0.0)
        {
            throw std::invalid_argument("Mass fractions cannot be negative");
        }
        total += amounts[i];
    }

    this->composition.clear();

    for (i = 0; i < amounts.size(); ++i)
    {
        this->composition[names[i]] = amounts[i] / total;
    }

}

std::map<std::string, double> Material::getComposition() const
{
    return this->composition;
}

std::string Material::getName() const
{
    return this->name;
}

std::string Material::getComment() const
{
    return this->comment;
}

} // namespace fisx


text:
using namespace std;

// Abstract base class declared by Framework
class Document {
public:
    Document(char *fn) {
        strcpy(name, fn);
    }

    virtual void open() = 0;
    virtual void close() = 0;

    char* getName() {
        return name;
    }

private:
    char name[20];
};

// Concrete derive class defined by client
class MyDocument: public Document {
public:
    MyDocument(char *fn) : Document(fn) {}

    void open() {
        cout << "   MyDocument:open()" << endl;
    }

    void close() {
        cout << "   MyDocument:close()" << endl;
    }
};

// Framework declaration
class Application {
public:
    Application() : _index(0) {
        cout << "Application:ctor" << endl;
    }

    // The client will call this "entry point" of the framework
    void newDocument(char *name) {
        cout << "Application: NewDocument()" << endl;
        // Framework calls the "hole" reserved for client customization
        _docs[_index] = createDocument(name);
        _docs[_index++]->open();
    }

    void openDocument() {}
    void reportDocs();

    //Framework declared a "hole" for the client to customize
    virtual Document* createDocument(char*) = 0;

private:
    int _index;
    // Framework uses Document's base class
    Document *_docs[10];
};

void Application::reportDocs() {
    cout << "Application:reportDocs()" << endl;
    for (int i = 0; i < _index; i++)
        cout << "  " << _docs[i]->getName() << endl;
}

// Customization of framework define by client
class MyApplication : public Application {
public:
    MyApplication() {
        cout << "MyApplication:ctor" << endl;
    }

    // Client defines Framework's "hole"
    Document* createDocument(char *fn) {
        cout << "   MyApplication:createDocument()" << endl;
        return new MyDocument(fn);
    }
};

int main() {
    // Client's customization of the Framework
    MyApplication myApp;

    myApp.newDocument("foo");
    myApp.newDocument("bar");
    myApp.reportDocs();
}


text:
NAMESPACE_BEGIN(CryptoPP)

#ifdef USE_WINDOWS_STYLE_SOCKETS
typedef ::SOCKET socket_t;
#else
typedef int socket_t;
const socket_t INVALID_SOCKET = -1;
// cygwin 1.1.4 doesn't have SHUT_RD
const int SD_RECEIVE = 0;
const int SD_SEND = 1;
const int SD_BOTH = 2;
const int SOCKET_ERROR = -1;
#endif

#ifndef socklen_t
typedef TYPE_OF_SOCKLEN_T socklen_t;	// see config.h
#endif

//! wrapper for Windows or Berkeley Sockets
class Socket
{
public:
	//! exception thrown by Socket class
	class Err : public OS_Error
	{
	public:
		Err(socket_t s, const std::string& operation, int error);
		socket_t GetSocket() const {return m_s;}

	private:
		socket_t m_s;
	};

	Socket(socket_t s = INVALID_SOCKET, bool own=false) : m_s(s), m_own(own) {}
	Socket(const Socket &s) : m_s(s.m_s), m_own(false) {}
	virtual ~Socket();

	bool GetOwnership() const {return m_own;}
	void SetOwnership(bool own) {m_own = own;}

	operator socket_t() {return m_s;}
	socket_t GetSocket() const {return m_s;}
	void AttachSocket(socket_t s, bool own=false);
	socket_t DetachSocket();
	void CloseSocket();

	void Create(int nType = SOCK_STREAM);
	void Bind(unsigned int port, const char *addr=NULL);
	void Bind(const sockaddr* psa, socklen_t saLen);
	void Listen(int backlog=5);
	// the next three functions return false if the socket is in nonblocking mode
	// and the operation cannot be completed immediately
	bool Connect(const char *addr, unsigned int port);
	bool Connect(const sockaddr* psa, socklen_t saLen);
	bool Accept(Socket& s, sockaddr *psa=NULL, socklen_t *psaLen=NULL);
	void GetSockName(sockaddr *psa, socklen_t *psaLen);
	void GetPeerName(sockaddr *psa, socklen_t *psaLen);
	unsigned int Send(const byte* buf, size_t bufLen, int flags=0);
	unsigned int Receive(byte* buf, size_t bufLen, int flags=0);
	void ShutDown(int how = SD_SEND);

	void IOCtl(long cmd, unsigned long *argp);
	bool SendReady(const timeval *timeout);
	bool ReceiveReady(const timeval *timeout);

	virtual void HandleError(const char *operation) const;
	void CheckAndHandleError_int(const char *operation, int result) const
		{if (result == SOCKET_ERROR) HandleError(operation);}
	void CheckAndHandleError(const char *operation, socket_t result) const
		{if (result == static_cast<socket_t>(SOCKET_ERROR)) HandleError(operation);}
#ifdef USE_WINDOWS_STYLE_SOCKETS
	void CheckAndHandleError(const char *operation, BOOL result) const
		{assert(result==TRUE || result==FALSE); if (!result) HandleError(operation);}
	void CheckAndHandleError(const char *operation, bool result) const
		{if (!result) HandleError(operation);}
#endif

	//! look up the port number given its name, returns 0 if not found
	static unsigned int PortNameToNumber(const char *name, const char *protocol="tcp");
	//! start Windows Sockets 2
	static void StartSockets();
	//! calls WSACleanup for Windows Sockets
	static void ShutdownSockets();
	//! returns errno or WSAGetLastError
	static int GetLastError();
	//! sets errno or calls WSASetLastError
	static void SetLastError(int errorCode);

protected:
	virtual void SocketChanged() {}

	socket_t m_s;
	bool m_own;
};

class SocketsInitializer
{
public:
	SocketsInitializer() {Socket::StartSockets();}
	~SocketsInitializer() {try {Socket::ShutdownSockets();} catch (const Exception&) {assert(0);}}
};

class SocketReceiver : public NetworkReceiver
{
public:
	SocketReceiver(Socket &s);

#ifdef USE_BERKELEY_STYLE_SOCKETS
	bool MustWaitToReceive() {return true;}
#else
	~SocketReceiver();
	bool MustWaitForResult() {return true;}
#endif
	bool Receive(byte* buf, size_t bufLen);
	unsigned int GetReceiveResult();
	bool EofReceived() const {return m_eofReceived;}

	unsigned int GetMaxWaitObjectCount() const {return 1;}
	void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);

private:
	Socket &m_s;
	bool m_eofReceived;

#ifdef USE_WINDOWS_STYLE_SOCKETS
	WindowsHandle m_event;
	OVERLAPPED m_overlapped;
	bool m_resultPending;
	DWORD m_lastResult;
#else
	unsigned int m_lastResult;
#endif
};

class SocketSender : public NetworkSender
{
public:
	SocketSender(Socket &s);

#ifdef USE_BERKELEY_STYLE_SOCKETS
	bool MustWaitToSend() {return true;}
#else
	~SocketSender();
	bool MustWaitForResult() {return true;}
	bool MustWaitForEof() { return true; }
	bool EofSent();
#endif
	void Send(const byte* buf, size_t bufLen);
	unsigned int GetSendResult();
	void SendEof();

	unsigned int GetMaxWaitObjectCount() const {return 1;}
	void GetWaitObjects(WaitObjectContainer &container, CallStack const& callStack);

private:
	Socket &m_s;
#ifdef USE_WINDOWS_STYLE_SOCKETS
	WindowsHandle m_event;
	OVERLAPPED m_overlapped;
	bool m_resultPending;
	DWORD m_lastResult;
#else
	unsigned int m_lastResult;
#endif
};

//! socket-based implementation of NetworkSource
class SocketSource : public NetworkSource, public Socket
{
public:
	SocketSource(socket_t s = INVALID_SOCKET, bool pumpAll = false, BufferedTransformation *attachment = NULL)
		: NetworkSource(attachment), Socket(s), m_receiver(*this)
	{
		if (pumpAll)
			PumpAll();
	}

private:
	NetworkReceiver & AccessReceiver() {return m_receiver;}
	SocketReceiver m_receiver;
};

//! socket-based implementation of NetworkSink
class SocketSink : public NetworkSink, public Socket
{
public:
	SocketSink(socket_t s=INVALID_SOCKET, unsigned int maxBufferSize=0, unsigned int autoFlushBound=16*1024)
		: NetworkSink(maxBufferSize, autoFlushBound), Socket(s), m_sender(*this) {}

	void SendEof() {ShutDown(SD_SEND);}

private:
	NetworkSender & AccessSender() {return m_sender;}
	SocketSender m_sender;
};

NAMESPACE_END

#endif	// #ifdef SOCKETS_AVAILABLE

#endif


text:
package com.czequered.promocodes.service;

import com.czequered.promocodes.model.Code;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author Martin Varga
 */
@Service
@Profile("dev")
@Primary
public class CodeServiceDev implements CodeService {

    Map<Code, Code> localCache;

    public CodeServiceDev() {
        localCache = new HashMap<>();
        for (int i = 1; i <= 99; i++) {
            Code code = new Code();
            String gameId = "GAME" + (i % 3);
            code.setGameId(gameId);
            String codeId = gameId + "CODE" + i;
            code.setCodeId(codeId);
            code.setFrom(Instant.now().minus(i, ChronoUnit.DAYS).toString());
            code.setTo(Instant.now().plus(i, ChronoUnit.DAYS).toString());
            code.setPub(i > 50);
            code.setPayload("Payload: " + gameId + " - " + codeId);
            saveCode(code);
        }
    }

    @Override
    public List<Code> getCodes(String gameId) {
        return localCache.keySet().stream()
                .filter(k -> k.getGameId().equals(gameId))
                .map(localCache::get)
            .collect(Collectors.toList());
    }

    @Override
    public Code getCode(String gameId, String codeId) {
        return localCache.get(new Code(gameId, codeId));
    }

    @Override
    public void deleteCode(String gameId, String codeId) {
        localCache.remove(new Code(gameId, codeId));
    }

    @Override
    public Code saveCode(Code code) {
        Code key = new Code(code.getGameId(), code.getCodeId());
        localCache.put(key, code);
        return code;
    }
}


text:
``` diff
 {
+    namespace Mono.WebAssembly.Interop {
+        public class MonoWebAssemblyJSRuntime : JSInProcessRuntime {
+            public MonoWebAssemblyJSRuntime();
+            protected override void BeginInvokeJS(long asyncHandle, string identifier, string argsJson);
+            protected override void EndInvokeDotNet(DotNetInvocationInfo callInfo, in DotNetInvocationResult dispatchResult);
+            protected static void Initialize(MonoWebAssemblyJSRuntime jsRuntime);
+            protected override string InvokeJS(string identifier, string argsJson);
+            public TRes InvokeUnmarshalled<T0, T1, T2, TRes>(string identifier, T0 arg0, T1 arg1, T2 arg2);
+            public TRes InvokeUnmarshalled<T0, T1, TRes>(string identifier, T0 arg0, T1 arg1);
+            public TRes InvokeUnmarshalled<T0, TRes>(string identifier, T0 arg0);
+            public TRes InvokeUnmarshalled<TRes>(string identifier);
+        }
+    }
+}
```


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">

<meta http-equiv="content-type" content="text/html; charset=US-ASCII">
<title>Keen</title>
<link rel="previous" href="filling.html">
<link rel="ToC" href="index.html">
<link rel="up" href="index.html">
<link rel="index" href="docindex.html">
<link rel="next" href="towers.html">

Previous | Contents | Index | Next

Chapter 30: Keen

You have a square grid; each square may contain a digit from 1 to the size of the grid. The grid is divided into blocks of varying shape and size, with arithmetic clues written in them. Your aim is to fully populate the grid with digits such that:

Each row contains only one occurrence of each digit

Each column contains only one occurrence of each digit

The digits in each block can be combined to form the number stated in the clue, using the arithmetic operation given in the clue. That is:

An addition clue means that the sum of the digits in the block must be the given number. For example, ‘15+’ means the contents of the block adds up to fifteen.

A multiplication clue (e.g. ‘60×’), similarly, means that the product of the digits in the block must be the given number.

A subtraction clue will always be written in a block of size two, and it means that one of the digits in the block is greater than the other by the given amount. For example, ‘2−’ means that one of the digits in the block is 2 more than the other, or equivalently that one digit minus the other one is 2. The two digits could be either way round, though.

A division clue (e.g. ‘3÷’), similarly, is always in a block of size two and means that one digit divided by the other is equal to the given amount.

Note that a block may contain the same digit more than once (provided the identical ones are not in the same row and column). This rule is precisely the opposite of the rule in Solo's ‘Killer’ mode (see chapter 11).

This puzzle appears in the Times under the name ‘KenKen’.

30.1 Keen controls

Keen shares much of its control system with Solo (and Unequal).

To play Keen, simply click the mouse in any empty square and then type a digit on the keyboard to fill that square. If you make a mistake, click the mouse in the incorrect square and press Space to clear it again (or use the Undo feature).

If you right-click in a square and then type a number, that number will be entered in the square as a ‘pencil mark’. You can have pencil marks for multiple numbers in the same square. Squares containing filled-in numbers cannot also contain pencil marks.

The game pays no attention to pencil marks, so exactly what you use them for is up to you: you can use them as reminders that a particular square needs to be re-examined once you know more about a particular number, or you can use them as lists of the possible numbers in a given square, or anything else you feel like.

To erase a single pencil mark, right-click in the square and type the same number again.

All pencil marks in a square are erased when you left-click and type a number, or when you left-click and press space. Right-clicking and pressing space will also erase pencil marks.

As for Solo, the cursor keys can be used in conjunction with the digit keys to set numbers or pencil marks. Use the cursor keys to move a highlight around the grid, and type a digit to enter it in the highlighted square. Pressing return toggles the highlight into a mode in which you can enter or remove pencil marks.

Pressing M will fill in a full set of pencil marks in every square that does not have a main digit in it.

(All the actions described in section 2.2 are also available.)

30.2 Keen parameters

These parameters are available from the ‘Custom...’ option on the ‘Type’ menu.

Grid size

Specifies the size of the grid. Lower limit is 3; upper limit is 9 (because the user interface would become more difficult with ‘digits’ bigger than 9!).

Difficulty

Controls the difficulty of the generated puzzle. At Unreasonable level, some backtracking will be required, but the solution should still be unique. The remaining levels require increasingly complex reasoning to avoid having to backtrack.

<address>
[Puzzles S60 version 1.5.r9411]</address>


text:
[![Join the chat at https://gitter.im/angular/angular-cli](https://badges.gitter.im/angular/angular-cli.svg)](https://gitter.im/angular/angular-cli?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)

[![Build Status][travis-badge]][travis-badge-url]
[![Dependency Status][david-badge]][david-badge-url]
[![devDependency Status][david-dev-badge]][david-dev-badge-url]
[![npm][npm-badge]][npm-badge-url]

Prototype of a CLI for Angular 2 applications based on the [ember-cli](http://www.ember-cli.com/) project.

## Note

This project is very much still a work in progress.

We still have a long way before getting out of our alpha stage.
If you wish to collaborate while the project is still young, check out [our issue list](https://github.com/angular/angular-cli/issues).

## Prerequisites

The generated project has dependencies that require **Node 4 or greater**.

## Table of Contents

* [Installation](#installation)
* [Usage](#usage)
* [Generating a New Project](#generating-and-serving-an-angular2-project-via-a-development-server)
* [Generating Components, Directives, Pipes and Services](#generating-other-scaffolds)
* [Generating a Route](#generating-a-route)
* [Creating a Build](#creating-a-build)
* [Running Unit Tests](#running-unit-tests)
* [Running End-to-End Tests](#running-end-to-end-tests)
* [Deploying the App via GitHub Pages](#deploying-the-app-via-github-pages)
* [Linting and formatting code](#linting-and-formatting-code)
* [Support for offline applications](#support-for-offline-applications)
* [Commands autocompletion](#commands-autocompletion)
* [CSS preprocessor integration](#css-preprocessor-integration)
* [3rd Party Library Installation](#3rd-party-library-installation)
* [Known Issues](#known-issues)

## Installation

**BEFORE YOU INSTALL:** please read the [prerequisites](#prerequisites)
```bash
npm install -g angular-cli
```

## Usage

```bash
ng --help
```

### Generating and serving an Angular2 project via a development server

```bash
ng new PROJECT_NAME
cd PROJECT_NAME
ng serve
```
Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files.

You can configure the default HTTP port and the one used by the LiveReload server with two command-line options :

```bash
ng serve --port 4201 --live-reload-port 49153
```

### Generating other scaffolds

You can use the `ng generate` (or just `ng g`) command to generate Angular components:

```bash
ng generate component my-new-component
ng g component my-new-component # using the alias

# components support relative path generation
# if in the directory src/app/feature/ and you run
ng g component new-cmp
# your component will be generated in src/app/feature/new-cmp
# but if you were to run
ng g component ../newer-cmp
# your component will be generated in src/app/newer-cmp
```
You can find all possible blueprints in the table below:

Scaffold  | Usage
---       | ---
Component | `ng g component my-new-component`
Directive | `ng g directive my-new-directive`
Pipe      | `ng g pipe my-new-pipe`
Service   | `ng g service my-new-service`

### Generating a route

You can generate a new route by with the following command (note the singular
used in `hero`):

```bash
ng generate route hero
```

This will create a folder which will contain the hero component and related test and style files.

The generated route will also be registered with the parent component's `@RouteConfig` decorator.

By default the route will be designated as a **lazy** route which means that it will be loaded into the browser when needed, not upfront as part of a bundle.

In order to visually distinguish lazy routes from other routes the folder for the route will be prefixed with a `+` per the above example the folder will be named `+hero`.
This is done in accordance with the [style guide](https://angular.io/styleguide#!#prefix-lazy-loaded-folders-with-).

The default lazy nature of routes can be turned off via the lazy flag (`--lazy false`)

There is an optional flag for `skip-router-generation` which will not add the route to the parent component's `@RouteConfig` decorator.

### Creating a build

```bash
ng build
```

The build artifacts will be stored in the `dist/` directory.

### Environments

At build time, the `src/client/app/environment.ts` will be replaced by either
`config/environment.dev.ts` or `config/environment.prod.ts`, depending on the
current cli environment.

Environment defaults to `dev`, but you can generate a production build via
the `-prod` flag in either `ng build -prod` or `ng serve -prod`.

### Running unit tests

```bash
ng test
```

Tests will execute after a build is executed via [Karma](http://karma-runner.github.io/0.13/index.html)

If run with the watch argument `--watch` (shorthand `-w`) builds will run when source files have changed
and tests will run after each successful build

### Running end-to-end tests

```bash
ng e2e
```

Before running the tests make sure you are serving the app via `ng serve`.

End-to-end tests are ran via [Protractor](https://angular.github.io/protractor/).

### Deploying the app via GitHub Pages

You can deploy your apps quickly via:

```
ng github-pages:deploy --message "Optional commit message"
```

This will do the following:

- creates GitHub repo for the current project if one doesn't exist
- rebuilds the app in production mode at the current `HEAD`
- creates a local `gh-pages` branch if one doesn't exist
- moves your app to the `gh-pages` branch and creates a commit
- edit the base tag in index.html to support github pages
- pushes the `gh-pages` branch to github
- returns back to the original `HEAD`

Creating the repo requires a token from github, and the remaining functionality
relies on ssh authentication for all git operations that communicate with github.com.
To simplify the authentication, be sure to [setup your ssh keys](https://help.github.com/articles/generating-ssh-keys/).

If you are deploying a [user or organization page](https://help.github.com/articles/user-organization-and-project-pages/), you can instead use the following command:

```
ng github-pages:deploy --user-page --message "Optional commit message"
```

This command pushes the app to the `master` branch on the github repo instead
of pushing to `gh-pages`, since user and organization pages require this.

### Linting and formatting code

You can lint your app code by running `ng lint`.
This will use the `lint` npm script that in generated projects uses `tslint`.

You can modify the these scripts in `package.json` to run whatever tool you prefer.

### Support for offline applications

The index.html file includes a commented-out code snippet for installing the angular2-service-worker. This support is experimental, please see the angular/mobile-toolkit project for documentation on how to make use of this functionality.

### Commands autocompletion

To turn on auto completion use the following commands:

For bash:
```bash
ng completion >> ~/.bashrc
source ~/.bashrc
```

For zsh:
```bash
ng completion >> ~/.zshrc
source ~/.zshrc
```

Windows users using gitbash:
```bash
ng completion >> ~/.bash_profile
source ~/.bash_profile
```

### CSS Preprocessor integration

We support all major CSS preprocessors:
- sass (node-sass)
- less (less)
- compass (compass-importer + node-sass)
- stylus (stylus)

To use one just install for example `npm install node-sass` and rename `.css` files in your project to `.scss` or `.sass`. They will be compiled automatically.

The `Angular2App`'s options argument has `sassCompiler`, `lessCompiler`, `stylusCompiler` and `compassCompiler` options that are passed directly to their respective CSS preprocessors.

### 3rd Party Library Installation

The installation of 3rd party libraries are well described at our [Wiki Page](https://github.com/angular/angular-cli/wiki/3rd-party-libs)

## Known issues

This project is currently a prototype so there are many known issues. Just to mention a few:

- All blueprints/scaffolds are in TypeScript only, in the future blueprints in all dialects officially supported by Angular will be available.
- On Windows you need to run the `build` and `serve` commands with Admin permissions, otherwise the performance is not good.
- [Protractor](https://angular.github.io/protractor/) integration is missing.
- The initial installation as well as `ng new` take too long because of lots of npm dependencies.
- Many existing ember addons are not compatible with Angular apps built via angular-cli.
- When you `ng serve` remember that the generated project has dependencies that require **Node 4 or greater**.

## Development Hints for hacking on angular-cli

### Working with master

```bash
git clone https://github.com/angular/angular-cli.git
cd angular-cli
npm link
```

`npm link` is very similar to `npm install -g` except that instead of downloading the package
from the repo, the just cloned `angular-cli/` folder becomes the global package.
Any changes to the files in the `angular-cli/` folder will immediately affect the global `angular-cli` package,
allowing you to quickly test any changes you make to the cli project.

Now you can use `angular-cli` via the command line:

```bash
ng new foo
cd foo
npm link angular-cli
ng server
```

`npm link angular-cli` is needed because by default the globally installed `angular-cli` just loads
the local `angular-cli` from the project which was fetched remotely from npm.
`npm link angular-cli` symlinks the global `angular-cli` package to the local `angular-cli` package.
Now the `angular-cli` you cloned before is in three places:
The folder you cloned it into, npm's folder where it stores global packages and the `angular-cli` project you just created.

Please read the official [npm-link documentation](https://www.npmjs.org/doc/cli/npm-link.html)
and the [npm-link cheatsheet](http://browsenpm.org/help#linkinganynpmpackagelocally) for more information.

## License

MIT

[travis-badge]: https://travis-ci.org/angular/angular-cli.svg?branch=master
[travis-badge-url]: https://travis-ci.org/angular/angular-cli
[david-badge]: https://david-dm.org/angular/angular-cli.svg
[david-badge-url]: https://david-dm.org/angular/angular-cli
[david-dev-badge]: https://david-dm.org/angular/angular-cli/dev-status.svg
[david-dev-badge-url]: https://david-dm.org/angular/angular-cli#info=devDependencies
[npm-badge]: https://img.shields.io/npm/v/angular-cli.svg
[npm-badge-url]: https://www.npmjs.com/package/angular-cli


text:
package org.algohub.engine.judge;

import org.algohub.engine.type.LanguageType;
import org.junit.Test;

@SuppressWarnings({"PMD.CommentRequired"})
public class PythonJudgeTest {

  @Test public void judgeTest() {
    JudgeEngineTestUtil.batchJudge(LanguageType.PYTHON);
  }
}


text:
export const BLUEPRINTS_SORT_SET_KEY = "BLUEPRINTS_SORT_SET_KEY";
export const blueprintsSortSetKey = (key) => ({
  type: BLUEPRINTS_SORT_SET_KEY,
  payload: {
    key,
  },
});

export const BLUEPRINTS_SORT_SET_VALUE = "BLUEPRINTS_SORT_SET_VALUE";
export const blueprintsSortSetValue = (value) => ({
  type: BLUEPRINTS_SORT_SET_VALUE,
  payload: {
    value,
  },
});

export const DEPENDENCIES_SORT_SET_KEY = "DEPENDENCIES_SORT_SET_KEY";
export const dependenciesSortSetKey = (key) => ({
  type: DEPENDENCIES_SORT_SET_KEY,
  payload: {
    key,
  },
});

export const DEPENDENCIES_SORT_SET_VALUE = "DEPENDENCIES_SORT_SET_VALUE";
export const dependenciesSortSetValue = (value) => ({
  type: DEPENDENCIES_SORT_SET_VALUE,
  payload: {
    value,
  },
});

export const COMPONENTS_SORT_SET_KEY = "COMPONENTS_SORT_SET_KEY";
export const componentsSortSetKey = (key) => ({
  type: COMPONENTS_SORT_SET_KEY,
  payload: {
    key,
  },
});

export const COMPONENTS_SORT_SET_VALUE = "COMPONENTS_SORT_SET_VALUE";
export const componentsSortSetValue = (value) => ({
  type: COMPONENTS_SORT_SET_VALUE,
  payload: {
    value,
  },
});


text:
var errors = require('restify-errors');

var process = function (controller) {
    return function (req, res, next) {
        try {
            if (!controller.authorize(req)) {
                return next(new errors.NotAuthorizedError('not authorized'));
            } else {
                controller.processing(req)
                .then(function (result) {
                    res.send(result);
                    return next();
                })
                .catch(function (err) {
                    return next(new errors.InternalError(err.message));
                });
            }
        } catch(ex) {
            next(new errors.InternalError(ex.message));
        }
    };
};

module.exports = {
    process: process
};