text:
package io.github.jeddict.source;

import com.github.javaparser.ast.CompilationUnit;
import com.github.javaparser.ast.ImportDeclaration;
import com.github.javaparser.ast.Modifier;
import com.github.javaparser.ast.NodeList;
import com.github.javaparser.ast.body.BodyDeclaration;
import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration;
import com.github.javaparser.ast.body.FieldDeclaration;
import com.github.javaparser.ast.body.MethodDeclaration;
import com.github.javaparser.ast.body.TypeDeclaration;
import com.github.javaparser.ast.nodeTypes.NodeWithAnnotations;
import com.github.javaparser.ast.type.ClassOrInterfaceType;
import com.github.javaparser.resolution.declarations.ResolvedReferenceTypeDeclaration;
import static io.github.jeddict.jcode.util.JavaIdentifiers.unqualify;
import static io.github.jeddict.jcode.util.JavaUtil.getFieldName;
import static io.github.jeddict.jcode.util.JavaUtil.isGetterMethod;
import static io.github.jeddict.jcode.util.JavaUtil.isSetterMethod;
import io.github.jeddict.jpa.spec.EntityMappings;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Collection;
import static java.util.Collections.emptyMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import static java.util.Objects.isNull;
import static java.util.Objects.nonNull;
import java.util.Optional;
import java.util.function.Function;
import static java.util.function.Function.identity;
import static java.util.logging.Level.WARNING;
import java.util.logging.Logger;
import static java.util.stream.Collectors.toMap;
import org.openide.util.Exceptions;

/**
 *
 * @author jGauravGupta
 */
public class ClassExplorer extends AnnotatedMember {

    private final TypeDeclaration type;
    private final Map<String, ImportDeclaration> imports;
    private Boolean fieldAccess;
    private final SourceExplorer source;
    private static final Logger LOG = Logger.getLogger(ClassExplorer.class.getName());

    public ClassExplorer(SourceExplorer source, CompilationUnit compilationUnit) {
        this.type = compilationUnit.getPrimaryType().orElseThrow(IllegalArgumentException::new);
        this.imports = compilationUnit.getImports().stream()
                .collect(toMap(importDec -> unqualify(importDec.getNameAsString()), identity()));
        this.source = source;
    }

    public ClassExplorer(SourceExplorer source, ClassOrInterfaceDeclaration clazz) {
        this.type = clazz;
        this.imports = emptyMap();
        this.source = source;
    }

    public EntityMappings getEntityMappings() {
        return source.getEntityMappings();
    }

    public boolean isIncludeReference() {
        return source.isIncludeReference();
    }

    public SourceExplorer getSource() {
        return source;
    }

    public String getName() {
        return type.getNameAsString();
    }

    public Optional<ResolvedReferenceTypeDeclaration> getSuperClass() {
        ResolvedReferenceTypeDeclaration superClassType = null;
        if (type instanceof ClassOrInterfaceDeclaration) {
            ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) type;
            if (!clazz.getExtendedTypes().isEmpty()) {
                superClassType = clazz.getExtendedTypes().get(0).resolve().asReferenceType().getTypeDeclaration();
            }
        }
        return Optional.ofNullable(superClassType);
    }

    public Boolean isFieldAccess() {
        if (fieldAccess == null) {
            fieldAccess = findFieldAccess();
        }
        return fieldAccess;
    }

    public NodeList<Modifier> getModifiers() {
        return type.getModifiers();
    }

    public boolean isAbstract() {
        return type.getModifiers().contains(Modifier.abstractModifier());
    }

    public Collection<MemberExplorer> getMembers() {
        Map<String, MemberExplorer> members = new LinkedHashMap<>();
        Function<String, MemberExplorer> memberValue = (attributeName) -> {
            MemberExplorer classMember = members.get(attributeName);
            if (classMember == null) {
                classMember = new MemberExplorer(this);
                members.put(attributeName, classMember);
            }
            return classMember;
        };
        if (type instanceof ClassOrInterfaceDeclaration) {
            for (BodyDeclaration<?> member : ((ClassOrInterfaceDeclaration) type).getMembers()) {
                if (member instanceof FieldDeclaration) { //isLombokSupport ??
                    FieldDeclaration field = (FieldDeclaration) member;
                    String attributeName = field.getVariable(0).getNameAsString();
                    MemberExplorer classMember = memberValue.apply(attributeName);
                    if(field.getModifiers().contains(Modifier.staticModifier())) {
                        continue;
                    }
                    classMember.setField(field);
                    if (isFieldAccess() || classMember.getAnnotatedMember() == null) {
                        classMember.setAnnotatedMember(field);
                    }
                } else if (member instanceof MethodDeclaration) {
                    MethodDeclaration method = (MethodDeclaration) member;
                    String methodName = method.getNameAsString();
                    if (isGetterMethod(methodName)) {
                        String attributeName = getFieldName(methodName);
                        MemberExplorer classMember = memberValue.apply(attributeName);
                        classMember.setGetter(method);
                        if (!isFieldAccess()) {
                            classMember.setAnnotatedMember(method);
                        }
                    } else if (isSetterMethod(methodName)) {
                        String attributeName = getFieldName(methodName);
                        MemberExplorer classMember = memberValue.apply(attributeName);
                        classMember.setSetter(method);
                    }
                }
            }
        }

        List<MemberExplorer> memberExplorers = new ArrayList<>();
        for (MemberExplorer member : members.values()) {
            if (nonNull(member.getField()) && nonNull(member.getAnnotatedMember())) {
                memberExplorers.add(member);
            } else if (nonNull(member.getGetter()) && nonNull(member.getSetter())) {
                if (isNull(member.getAnnotatedMember())) {
                    member.setAnnotatedMember(member.getGetter());
                }
                memberExplorers.add(member);
            }
        }
        return memberExplorers;
    }

    private boolean findFieldAccess() {
        boolean fieldAccessValue = false;
        boolean accessTypeDetected = false;
        NodeList<BodyDeclaration<?>> members = type.getMembers();

        if (isEntity() || isMappedSuperclass() || isEmbeddable()) {
            for (BodyDeclaration<?> member : members) {
                if (member.isAnnotationPresent(javax.persistence.Id.class)
                        || member.isAnnotationPresent(javax.persistence.Basic.class)
                        || member.isAnnotationPresent(javax.persistence.Transient.class)
                        || member.isAnnotationPresent(javax.persistence.Version.class)
                        || member.isAnnotationPresent(javax.persistence.ElementCollection.class)
                        || member.isAnnotationPresent(javax.persistence.Embedded.class)
                        || member.isAnnotationPresent(javax.persistence.EmbeddedId.class)
                        || member.isAnnotationPresent(javax.persistence.OneToMany.class)
                        || member.isAnnotationPresent(javax.persistence.OneToOne.class)
                        || member.isAnnotationPresent(javax.persistence.ManyToMany.class)
                        || member.isAnnotationPresent(javax.persistence.ManyToOne.class)
                        || member.isAnnotationPresent(javax.persistence.Column.class)) {
                    if (member instanceof FieldDeclaration) {
                        fieldAccessValue = true;
                    }
                    accessTypeDetected = true;
                }
                if (accessTypeDetected) {
                    break;
                }
            }
        } else {
            if (type instanceof ClassOrInterfaceDeclaration) {
                ClassOrInterfaceDeclaration clazz = (ClassOrInterfaceDeclaration) type;
                if (!clazz.getExtendedTypes().isEmpty()) {
                    ClassOrInterfaceType parentClassType = clazz.getExtendedTypes().get(0);
                    String parentClassQualifiedName = parentClassType.resolve().asReferenceType().getQualifiedName();
                    try {
                        fieldAccessValue = getSource().createClass(parentClassQualifiedName)
                                .map(ClassExplorer::isFieldAccess)
                                .orElse(true);
                    } catch (FileNotFoundException ex) {
                        Exceptions.printStackTrace(ex);
                        fieldAccessValue = true;
                    }
                } else {
                    fieldAccessValue = true;
                }
            }
        }
        if (!accessTypeDetected) {
            LOG.log(WARNING, "Failed to detect correct access type for class: {0}", type.getName());
        }
        return fieldAccessValue;
    }

    public boolean isManagedClass() {
        return isEntity() || isMappedSuperclass() || isEmbeddable();
    }

    public boolean isMappedSuperclass() {
        return type.isAnnotationPresent(javax.persistence.MappedSuperclass.class);
    }

    public boolean isEntity() {
        return type.isAnnotationPresent(javax.persistence.Entity.class);
    }

    public boolean isEmbeddable() {
        return type.isAnnotationPresent(javax.persistence.Embeddable.class);
    }

    public boolean isClass() {
        return type.isClassOrInterfaceDeclaration()
                && !type.asClassOrInterfaceDeclaration().isInterface();
    }

    public boolean isInterface() {
        return type.isClassOrInterfaceDeclaration()
                && type.asClassOrInterfaceDeclaration().isInterface();
    }

    public boolean isEnum() {
        return type.isEnumDeclaration();
    }

    public Map<String, ImportDeclaration> getImports() {
        return imports;
    }

    @Override
    protected NodeWithAnnotations getAnnotatedMember() {
        return type;
    }

}


text:
import os
from setuptools import setup, find_packages

DESCRIPTION = """\
Centinel is a tool used to detect network interference, \
online information controls, and Internet censorship."""

setup(
    name="centinel",
    version="0.1.5.7",
    author="ICLab Developers",
    author_email="info@iclab.org",
    description=DESCRIPTION,
    license="MIT",
    keywords="censorship information controls network interference",
    url="https://www.github.com/iclab/centinel",
    packages=["centinel", "centinel.primitives",
              "centinel.vpn"],
    install_requires=["argparse >= 1.2.1",
                      "dnspython >= 1.11.0",
                      "requests >= 2.9.1",
                      "trparse >= 0.2.1",
                      "pycurl >= 7.19.5",
                      "urllib3 >= 1.9.1",
                      "dnspython >= 1.12.0",
                      "BeautifulSoup >= 3.2.1",
                      "httplib2 >= 0.9.2",
                      "bs4 >= 0.0.1",
                      "geopy >= 1.11.0"],
    include_package_data=True,
    entry_points={
        'console_scripts': ['centinel=centinel.cli:run',
                            'centinel-vpn=centinel.vpn.cli:run']
    },
)

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Phalcon Framework
 * This source file is subject to the New BSD License that is bundled
 * with this package in the file docs/LICENSE.txt.
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@phalconphp.com so we can send you a copy immediately.
 *
 * @author Nikita Vershinin <endeveit@gmail.com>
 */
namespace Phalcon\Mvc\Model\MetaData;

use Phalcon\Cache\Backend\Redis as CacheBackend;
use Phalcon\Cache\Frontend\Data as CacheFrontend;
use Phalcon\Mvc\Model\Exception;

/**
 * \Phalcon\Mvc\Model\MetaData\Redis
 * Redis adapter for \Phalcon\Mvc\Model\MetaData
 */
class Redis extends Base
{

    /**
     * Redis backend instance.
     *
     * @var \Phalcon\Cache\Backend\Redis
     */
    protected $redis = null;

    /**
     * {@inheritdoc}
     *
     * @param  null|array                   $options
     * @throws \Phalcon\Mvc\Model\Exception
     */
    public function __construct($options = null)
    {
        if (is_array($options)) {
            if (!isset($options['redis'])) {
                throw new Exception('Parameter "redis" is required');
            }
        } else {
            throw new Exception('No configuration given');
        }

        parent::__construct($options);
    }

    /**
     * {@inheritdoc}
     *
     * @return \Phalcon\Cache\Backend\Redis
     */
    protected function getCacheBackend()
    {
        if (null === $this->redis) {
            $this->redis = new CacheBackend(
                new CacheFrontend(array('lifetime' => $this->options['lifetime'])),
                array(
                    'redis' => $this->options['redis'],
                )
            );
        }

        return $this->redis;
    }

    /**
     * {@inheritdoc}
     * @param  string $key
     * @return array
     */
    public function read($key)
    {
        return parent::read($key) ?: null;
    }

    /**
     * Returns the sessionId with prefix
     *
     * @param  string $id
     * @return string
     */
    protected function getId($id)
    {
        return str_replace('\\', ':', parent::getId($id));
    }
}


text:
class WXDLLIMPEXP_FWD_CORE wxBitmap;
class WXDLLIMPEXP_FWD_CORE wxBrush;

//-----------------------------------------------------------------------------
// wxBrush
//-----------------------------------------------------------------------------

class WXDLLIMPEXP_CORE wxBrush : public wxBrushBase
{
public:
    wxBrush() {}
    wxBrush(const wxColour &colour, wxBrushStyle style = wxBRUSHSTYLE_SOLID);
#if FUTURE_WXWIN_COMPATIBILITY_3_0
    wxDEPRECATED_FUTURE( wxBrush(const wxColour& col, int style) );
#endif
    wxBrush(const wxBitmap &stippleBitmap);

    bool operator==(const wxBrush& brush) const;
    bool operator!=(const wxBrush& brush) const { return !(*this == brush); }

    wxBrushStyle GetStyle() const;
    wxColour GetColour() const;
    wxBitmap *GetStipple() const;

    void SetColour(const wxColour& col);
    void SetColour(unsigned char r, unsigned char g, unsigned char b);
    void SetStyle(wxBrushStyle style);
    void SetStipple(const wxBitmap& stipple);

#if FUTURE_WXWIN_COMPATIBILITY_3_0
    wxDEPRECATED_FUTURE( void SetStyle(int style) )
        { SetStyle((wxBrushStyle)style); }
#endif

protected:
    virtual wxGDIRefData *CreateGDIRefData() const;
    virtual wxGDIRefData *CloneGDIRefData(const wxGDIRefData *data) const;

    DECLARE_DYNAMIC_CLASS(wxBrush)
};

#endif // _WX_DFB_BRUSH_H_


text:
"""Hybrid Monte Carlo for Python

This package is a straight-forward port of the functions ``hmc2.m`` and
``hmc2_opt.m`` from the
`MCMCstuff <http://www.lce.hut.fi/research/mm/mcmcstuff/>`__ matlab
toolbox written by Aki Vehtari. The code is originally based on the
functions ``hmc.m`` from the `netlab
toolbox <http://www.ncrg.aston.ac.uk/netlab/index.php>`__ written by Ian
T Nabney. The portion of algorithm involving "windows" is derived from
the C code for this function included in the `Software for Flexible
Bayesian
Modeling <http://www.cs.toronto.edu/~radford/fbm.software.html>`__
written by Radford Neal.

The original Python `port <https://github.com/koepsell/pyhmc>`__ was
made by Kilian Koepsell, and subsequently modernized by Robert T.
McGibbon.

Authors
-------

-  Kilian Koepsell kilian@berkeley.edu
-  Robert T. McGibbon rmcgibbo@gmail.com

This software is distributed under the BSD License (see LICENSE file).
"""
from setuptools import find_packages, setup, Extension
import numpy as np
from Cython.Distutils import build_ext
import versioneer
versioneer.VCS = 'git'
versioneer.versionfile_source = 'pyhmc/_version.py'
versioneer.versionfile_build = 'pyhmc/_version.py'
versioneer.tag_prefix = '' # tags are like 1.2.0
versioneer.parentdir_prefix = 'pyhmc-' # dirname like 'myproject-1.2.0'

DOCLINES = __doc__.split("\n")
CLASSIFIERS = """\
Development Status :: 3 - Alpha
Intended Audience :: Science/Research
Intended Audience :: Developers
License :: OSI Approved :: BSD
Programming Language :: Python
Operating System :: OS Independent
"""

cmdclass = versioneer.get_cmdclass()
cmdclass['build_ext'] = build_ext
extensions = [
    Extension('pyhmc._hmc', ['pyhmc/_hmc.pyx'],
              include_dirs=[np.get_include()]),
    Extension('pyhmc._utils', ['pyhmc/_utils.pyx'],
              include_dirs=[np.get_include()]),
]

setup(
    name='pyhmc',
    author="Robert T. McGibbon",
    author_email='rmcgibbo@gmail.com',
    version=versioneer.get_version(),
    cmdclass=cmdclass,
    url="https://github.com/rmcgibbo/pyhmc",
    description=DOCLINES[0],
    long_description="\n".join(DOCLINES[2:]),
    license='BSD',
    install_requires=['numpy'],
    packages=find_packages(),
    zip_safe=False,
    ext_modules=extensions,
)


text:
package bio.terra.buffer.service.resource.flight;

import static bio.terra.buffer.service.resource.FlightMapKeys.GOOGLE_PROJECT_ID;
import static bio.terra.buffer.service.resource.flight.CreateSubnetsStep.REGION_TO_IP_RANGE;
import static bio.terra.buffer.service.resource.flight.GoogleProjectConfigUtils.blockBatchInternetAccess;
import static bio.terra.buffer.service.resource.flight.GoogleProjectConfigUtils.keepDefaultNetwork;
import static bio.terra.buffer.service.resource.flight.GoogleUtils.*;

import bio.terra.buffer.generated.model.GcpProjectConfig;
import bio.terra.cloudres.google.api.services.common.OperationCow;
import bio.terra.cloudres.google.compute.CloudComputeCow;
import bio.terra.stairway.FlightContext;
import bio.terra.stairway.Step;
import bio.terra.stairway.StepResult;
import bio.terra.stairway.StepStatus;
import bio.terra.stairway.exception.RetryException;
import com.google.api.services.compute.model.Firewall;
import com.google.api.services.compute.model.Network;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableMap;
import java.io.IOException;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** Creates firewall rules for the GCP project. */
public class CreateFirewallRuleStep implements Step {
  /** Names for firewall rules on the high-security network (called 'network'). */
  @VisibleForTesting
  public static final String ALLOW_INTERNAL_FOR_VPC_NETWORK_RULE_NAME = "leonardo-allow-internal";

  @VisibleForTesting
  public static final String LEONARDO_SSL_FOR_VPC_NETWORK_RULE_NAME = "leonardo-ssl";

  /**
   * Names for firewall rules on the default network (called 'default'). Rule names must be unique
   * within a project, so prefix these rule names with 'default-vpc'.
   */
  @VisibleForTesting
  public static final String ALLOW_INTERNAL_FOR_DEFAULT_NETWORK_RULE_NAME =
      DEFAULT_NETWORK_NAME + "-vpc-" + ALLOW_INTERNAL_FOR_VPC_NETWORK_RULE_NAME;

  @VisibleForTesting
  public static final String LEONARDO_SSL_FOR_DEFAULT_NETWORK_RULE_NAME =
      DEFAULT_NETWORK_NAME + "-vpc-" + LEONARDO_SSL_FOR_VPC_NETWORK_RULE_NAME;

  /**
   * Firewall rules to make VM private but still allowing leonardo can access internet(exclude
   * leonardo-private which is used by Leo created dataproc worker).
   */
  @VisibleForTesting public static final String DENY_EGRESS_RULE_NAME = "deny-egress-all";

  @VisibleForTesting
  public static final String DENY_EGRESS_LEONARDO_WORKER_RULE_NAME = "deny-egress-leonardo-private";

  @VisibleForTesting
  public static final String ALLOW_EGRESS_LEONARDO_RULE_NAME = "allow-egress-leonardo";

  @VisibleForTesting
  public static final String ALLOW_EGRESS_PRIVATE_ACCESS_RULE_NAME = "allow-egress-private-access";

  @VisibleForTesting
  public static final String ALLOW_EGRESS_INTERNAL_RULE_NAME = "allow-egress-internal";

  /**
   * Firewall rule to priority map. The lower number is, the higher priority.
   *
   *
To make sure only Leo VMs have private internet access when {@code blockBatchInternetAccess}
   * is true, the priority of egress firewall rules need to be:
   *
   *

   *
ALLOW_EGRESS_PRIVATE_ACCESS_RULE_NAME
   *
ALLOW_EGRESS_INTERNAL(equal)
   *
DENY_EGRESS_LEONARDO_WORKER_RULE_NAME
   *
ALLOW_EGRESS_LEONARDO
   *
DENY_EGRESS_RULE_NAME
   *

   */
  @VisibleForTesting
  public static final ImmutableMap<String, Integer> FIREWALL_RULE_PRIORITY_MAP =
      ImmutableMap.<String, Integer>builder()
          .put(ALLOW_INTERNAL_FOR_VPC_NETWORK_RULE_NAME, 1000)
          .put(LEONARDO_SSL_FOR_VPC_NETWORK_RULE_NAME, 1000)
          .put(ALLOW_INTERNAL_FOR_DEFAULT_NETWORK_RULE_NAME, 1000)
          .put(LEONARDO_SSL_FOR_DEFAULT_NETWORK_RULE_NAME, 1000)
          .put(ALLOW_EGRESS_PRIVATE_ACCESS_RULE_NAME, 1000)
          .put(ALLOW_EGRESS_INTERNAL_RULE_NAME, 1000)
          .put(DENY_EGRESS_LEONARDO_WORKER_RULE_NAME, 2000)
          .put(ALLOW_EGRESS_LEONARDO_RULE_NAME, 3000)
          .put(DENY_EGRESS_RULE_NAME, 4000)
          .build();

  @VisibleForTesting
  public static final Firewall ALLOW_INTERNAL_VPC_NETWORK =
      new Firewall()
          .setName(ALLOW_INTERNAL_FOR_VPC_NETWORK_RULE_NAME)
          .setDescription("Allow internal ingress traffic on the network.")
          .setDirection("INGRESS")
          .setTargetTags(Arrays.asList("leonardo"))
          .setSourceRanges(new ArrayList(REGION_TO_IP_RANGE.values()))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(ALLOW_INTERNAL_FOR_VPC_NETWORK_RULE_NAME))
          .setAllowed(
              Arrays.asList(
                  new Firewall.Allowed().setIPProtocol("icmp"),
                  new Firewall.Allowed().setIPProtocol("tcp").setPorts(Arrays.asList("0-65535")),
                  new Firewall.Allowed().setIPProtocol("udp").setPorts(Arrays.asList("0-65535"))));

  @VisibleForTesting
  public static final Firewall ALLOW_INTERNAL_DEFAULT_NETWORK =
      new Firewall()
          .setName(ALLOW_INTERNAL_FOR_DEFAULT_NETWORK_RULE_NAME)
          .setDescription("Allow internal ingress traffic on the default VPC network.")
          .setDirection("INGRESS")
          .setTargetTags(Arrays.asList("leonardo"))
          .setSourceRanges(new ArrayList(REGION_TO_IP_RANGE.values()))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(ALLOW_INTERNAL_FOR_DEFAULT_NETWORK_RULE_NAME))
          .setAllowed(
              Arrays.asList(
                  new Firewall.Allowed().setIPProtocol("icmp"),
                  new Firewall.Allowed().setIPProtocol("tcp").setPorts(Arrays.asList("0-65535")),
                  new Firewall.Allowed().setIPProtocol("udp").setPorts(Arrays.asList("0-65535"))));

  @VisibleForTesting
  public static final Firewall ALLOW_INGRESS_LEONARDO_SSL_NETWORK =
      new Firewall()
          .setName(LEONARDO_SSL_FOR_VPC_NETWORK_RULE_NAME)
          .setDescription("Allow SSL traffic from Leonardo-managed VMs.")
          .setDirection("INGRESS")
          .setSourceRanges(Arrays.asList("0.0.0.0/0"))
          .setTargetTags(Arrays.asList("leonardo"))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(LEONARDO_SSL_FOR_VPC_NETWORK_RULE_NAME))
          .setAllowed(
              Arrays.asList(
                  new Firewall.Allowed().setIPProtocol("tcp").setPorts(Arrays.asList("443"))));

  @VisibleForTesting
  public static final Firewall ALLOW_INGRESS_LEONARDO_SSL_DEFAULT =
      new Firewall()
          .setName(LEONARDO_SSL_FOR_DEFAULT_NETWORK_RULE_NAME)
          .setDescription("Allow SSL traffic from Leonardo-managed VMs for default VPC network.")
          .setDirection("INGRESS")
          .setSourceRanges(Arrays.asList("0.0.0.0/0"))
          .setTargetTags(Arrays.asList("leonardo"))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(LEONARDO_SSL_FOR_DEFAULT_NETWORK_RULE_NAME))
          .setAllowed(
              Arrays.asList(
                  new Firewall.Allowed().setIPProtocol("tcp").setPorts(Arrays.asList("443"))));

  @VisibleForTesting
  public static final Firewall ALLOW_EGRESS_PRIVATE_ACCESS =
      new Firewall()
          .setName(ALLOW_EGRESS_PRIVATE_ACCESS_RULE_NAME)
          .setDescription("Allow accessing internet using private Google Access.")
          .setDirection("EGRESS")
          .setDestinationRanges(Arrays.asList(RESTRICTED_GOOGLE_IP_ADDRESS))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(ALLOW_EGRESS_PRIVATE_ACCESS_RULE_NAME))
          .setAllowed(Arrays.asList(new Firewall.Allowed().setIPProtocol("all")));

  @VisibleForTesting
  public static final Firewall ALLOW_EGRESS_INTERNAL =
      new Firewall()
          .setName(ALLOW_EGRESS_INTERNAL_RULE_NAME)
          .setDescription("Allow internal egress traffic on the network.")
          .setDirection("EGRESS")
          .setDestinationRanges(new ArrayList(REGION_TO_IP_RANGE.values()))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(ALLOW_EGRESS_INTERNAL_RULE_NAME))
          .setAllowed(
              Arrays.asList(
                  new Firewall.Allowed().setIPProtocol("icmp"),
                  new Firewall.Allowed().setIPProtocol("tcp").setPorts(Arrays.asList("0-65535")),
                  new Firewall.Allowed().setIPProtocol("udp").setPorts(Arrays.asList("0-65535"))));

  @VisibleForTesting
  public static final Firewall ALLOW_EGRESS_LEONARDO =
      new Firewall()
          .setName(ALLOW_EGRESS_LEONARDO_RULE_NAME)
          .setDescription("Allow Leonardo created VMs accessing internet")
          .setDirection("EGRESS")
          .setDestinationRanges(Arrays.asList("0.0.0.0/0"))
          .setTargetTags(Arrays.asList("leonardo"))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(ALLOW_EGRESS_LEONARDO_RULE_NAME))
          .setAllowed(Arrays.asList(new Firewall.Allowed().setIPProtocol("all")));

  @VisibleForTesting
  public static final Firewall DENY_EGRESS_LEONARDO_WORKER =
      new Firewall()
          .setName(DENY_EGRESS_LEONARDO_WORKER_RULE_NAME)
          .setDescription("Block leonardo-private VMs accessing internet")
          .setDirection("EGRESS")
          .setDestinationRanges(Arrays.asList("0.0.0.0/0"))
          .setTargetTags(Arrays.asList("leonardo-private"))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(DENY_EGRESS_LEONARDO_WORKER_RULE_NAME))
          .setDenied(Arrays.asList(new Firewall.Denied().setIPProtocol("all")));

  public static final Firewall DENY_EGRESS =
      new Firewall()
          .setName(DENY_EGRESS_RULE_NAME)
          .setDescription("Block egress for all VMs")
          .setDirection("EGRESS")
          .setDestinationRanges(Arrays.asList("0.0.0.0/0"))
          .setPriority(FIREWALL_RULE_PRIORITY_MAP.get(DENY_EGRESS_RULE_NAME))
          .setDenied(Arrays.asList(new Firewall.Denied().setIPProtocol("all")));

  private final Logger logger = LoggerFactory.getLogger(CreateFirewallRuleStep.class);
  private final CloudComputeCow computeCow;
  private final GcpProjectConfig gcpProjectConfig;

  public CreateFirewallRuleStep(CloudComputeCow computeCow, GcpProjectConfig gcpProjectConfig) {
    this.computeCow = computeCow;
    this.gcpProjectConfig = gcpProjectConfig;
  }

  @Override
  public StepResult doStep(FlightContext flightContext) throws RetryException {
    String projectId = flightContext.getWorkingMap().get(GOOGLE_PROJECT_ID, String.class);
    try {
      // Keep track of operations to poll for completion.
      List<OperationCow<?>> operationsToPoll = new ArrayList<>();

      // Network is already created and checked in previous step so here won't be empty.
      // If we got NPE, that means something went wrong with GCP, fine to just throw NPE here.
      Network highSecurityNetwork =
          getResource(() -> computeCow.networks().get(projectId, NETWORK_NAME).execute(), 404)
              .get();

      addFirewallRule(
              projectId, appendNetworkOnFirewall(highSecurityNetwork, ALLOW_INTERNAL_VPC_NETWORK))
          .ifPresent(operationsToPoll::add);
      addFirewallRule(
              projectId,
              appendNetworkOnFirewall(highSecurityNetwork, ALLOW_INGRESS_LEONARDO_SSL_NETWORK))
          .ifPresent(operationsToPoll::add);

      // TODO(PF-538): revisit whether we still need this flag after NF allows specifying a network
      // If the default network was not deleted, then create identical firewall rules for it.
      if (keepDefaultNetwork(gcpProjectConfig)) {
        Network defaultNetwork =
            getResource(
                    () -> computeCow.networks().get(projectId, DEFAULT_NETWORK_NAME).execute(), 404)
                .get();

        addFirewallRule(
                projectId, appendNetworkOnFirewall(defaultNetwork, ALLOW_INTERNAL_DEFAULT_NETWORK))
            .ifPresent(operationsToPoll::add);
        addFirewallRule(
                projectId,
                appendNetworkOnFirewall(defaultNetwork, ALLOW_INGRESS_LEONARDO_SSL_DEFAULT))
            .ifPresent(operationsToPoll::add);
      }

      if (blockBatchInternetAccess(gcpProjectConfig)) {
        addFirewallRule(
                projectId, appendNetworkOnFirewall(highSecurityNetwork, ALLOW_EGRESS_INTERNAL))
            .ifPresent(operationsToPoll::add);
        addFirewallRule(
                projectId,
                appendNetworkOnFirewall(highSecurityNetwork, ALLOW_EGRESS_PRIVATE_ACCESS))
            .ifPresent(operationsToPoll::add);
        addFirewallRule(
                projectId, appendNetworkOnFirewall(highSecurityNetwork, ALLOW_EGRESS_LEONARDO))
            .ifPresent(operationsToPoll::add);
        addFirewallRule(
                projectId,
                appendNetworkOnFirewall(highSecurityNetwork, DENY_EGRESS_LEONARDO_WORKER))
            .ifPresent(operationsToPoll::add);
        addFirewallRule(projectId, appendNetworkOnFirewall(highSecurityNetwork, DENY_EGRESS))
            .ifPresent(operationsToPoll::add);
      }

      for (OperationCow<?> operation : operationsToPoll) {
        pollUntilSuccess(operation, Duration.ofSeconds(3), Duration.ofMinutes(5));
      }
    } catch (IOException | InterruptedException e) {
      logger.info("Error when creating firewall rule", e);
      return new StepResult(StepStatus.STEP_RESULT_FAILURE_RETRY, e);
    }
    return StepResult.getStepResultSuccess();
  }

  @Override
  public StepResult undoStep(FlightContext flightContext) {
    // Flight undo will just need to delete the project on GCP.
    return StepResult.getStepResultSuccess();
  }

  /**
   * Helper method to add a firewall rule to the project. Ignores conflicts if the rule already
   * exists.
   *
   * @param projectId project where the network lives
   * @param rule firewall rule object to add to the project
   * @return pointer to the operation to poll for completion
   */
  private Optional<OperationCow<?>> addFirewallRule(String projectId, Firewall rule)
      throws IOException {
    return createResourceAndIgnoreConflict(
            () -> computeCow.firewalls().insert(projectId, rule).execute())
        .map(
            insertOperation ->
                computeCow.globalOperations().operationCow(projectId, insertOperation));
  }

  /**
   * Helper method to build a new firewall rule that with network assosicated network.
   *
   * @param network the network to add the firewall rule to
   * @param firewall the firewall to be assosicated with a network
   * @return firewall rule object
   */
  @VisibleForTesting
  public static Firewall appendNetworkOnFirewall(Network network, Firewall firewall) {
    // Make a copy because the input is static and not thread safe.
    return firewall.clone().setNetwork(network.getSelfLink());
  }
}


text:
<!--
  ~
  -->

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.devsh.androidlogin.sample">

    <uses-permission android:name="android.permission.INTERNET"/>

    <application
        android:allowBackup="true"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme.NoActionBar">

        <meta-data
            android:name="io.fabric.ApiKey"
            android:value="386368c098573bf297ef6662593768bec0b8d084"
            />

        <meta-data android:name="com.facebook.sdk.ApplicationId" android:value="@string/facebook_app_id"/>

        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>


text:
package controllers

import org.vindinium.server._
import org.vindinium.server.system._

import akka.pattern.{ ask, pipe }
import akka.util.Timeout
import play.api._
import play.api.libs.json.Json
import play.api.mvc._
import scala.concurrent.duration._
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.Future
import user.{ User => U }

object Api extends Controller {

  def training = Action.async { implicit req =>
    implicit val timeout = Timeout(10.minutes)
    form.training.bindFromRequest.fold(
      err => Future successful BadRequest(
        "Did you forget the key parameter?"
      ),
      data => U findByKey data.key flatMap {
        case None => Future failed UserNotFoundException("Key not found")
        case Some(user) => (Server.actor ? Server.RequestToPlayAlone(user, data.config)) map {
          case input: PlayerInput => {
            Ok(JsonFormat(input, req.host)) as JSON
          }
        }
      } recover {
        case e: GameException => {
          play.api.Logger("API").warn(e.toString)
          BadRequest(e.getMessage)
        }
      }
    )
  }

  def arena = Action.async { implicit req =>
    implicit val timeout = Timeout(24.hours)
    form.arena.bindFromRequest.fold(
      err => Future successful BadRequest(
        "Did you forget the key parameter?"
      ),
      key => U findByKey key flatMap {
        case None => Future failed UserNotFoundException("Key not found")
        case Some(user) => (Server.actor ? Server.RequestToPlayArena(user)) map {
          case input: PlayerInput => {
            Ok(JsonFormat(input, req.host)) as JSON
          }
        }
      } recover {
        case e: GameException => {
          play.api.Logger("API").warn(e.toString)
          BadRequest(e.getMessage)
        }
      }
    )
  }

  def move(gameId: String, token: String) = Action.async { implicit req =>
    implicit val timeout = Timeout(10.seconds)
    form.move.bindFromRequest.fold(
      err => Future successful BadRequest,
      dir => Server.actor ? Server.Play(Pov(gameId, token), dir) map {
        case input: PlayerInput => {
          Ok(JsonFormat(input, req.host)) as JSON
        }
      } recover {
        case e: NotFoundException      => NotFound(e.getMessage)
        case e: RuleViolationException => BadRequest(e.getMessage)
        case e: TimeoutException       => BadRequest(e.getMessage)
      }
    )
  }
}


text:
package info.izumin.android.droidux.processor.model;

import com.google.auto.common.MoreTypes;
import com.google.common.base.Function;
import com.google.common.collect.FluentIterable;
import com.squareup.javapoet.ClassName;

import java.util.List;

import javax.lang.model.element.ExecutableElement;
import javax.lang.model.element.VariableElement;

import info.izumin.android.droidux.annotation.Dispatchable;
import info.izumin.android.droidux.processor.validator.DispatchableValidator;

import static com.google.auto.common.MoreTypes.asTypeElement;
import static info.izumin.android.droidux.processor.util.AnnotationUtils.getTypeFromAnnotation;

/**
 * Created by izumin on 11/3/15.
 */
public class DispatchableModel {
    public static final String TAG = DispatchableModel.class.getSimpleName();

    private final ExecutableElement element;
    private final ReducerModel reducerModel;
    private final ClassName action;
    private final String methodName;

    private final List<ClassName> arguments;

    public DispatchableModel(ExecutableElement element, ReducerModel reducerModel) {
        this.element = element;
        this.reducerModel = reducerModel;
        this.methodName = element.getSimpleName().toString();
        this.action = ClassName.get(asTypeElement(getTypeFromAnnotation(element, Dispatchable.class, "value")));
        this.arguments = FluentIterable.from(element.getParameters())
                .transform(new Function<VariableElement, ClassName>() {
                    @Override
                    public ClassName apply(VariableElement input) {
                        return ClassName.get(MoreTypes.asTypeElement(input.asType()));
                    }
                }).toList();

        DispatchableValidator.validate(this);
    }

    public ClassName getAction() {
        return action;
    }

    public String getMethodName() {
        return methodName;
    }

    public int argumentCount() {
        return element.getParameters().size();
    }

    public ExecutableElement getElement() {
        return element;
    }

    public List<ClassName> getArguments() {
        return arguments;
    }

    public ClassName getReducerClassName() {
        return reducerModel.getClassName();
    }
    public ClassName getState() {
        return reducerModel.getState();
    }
}


text:
import React from 'react'
import { Button } from 'semantic-ui-react'

const ButtonTrash = () => (
    <Button circular icon='trash' color='purple' size='tiny' />
)

export default ButtonTrash


text:
'use strict';

// Setting up route
angular.module('users').config(['$stateProvider',
	function($stateProvider) {
		// Users state routing
		$stateProvider.
		state('profile', {
			url: '/settings/profile',
			templateUrl: 'modules/users/views/settings/edit-profile.client.view.html'
		}).
		state('password', {
			url: '/settings/password',
			templateUrl: 'modules/users/views/settings/change-password.client.view.html'
		}).
		state('socialAccounts', {
			url: '/settings/accounts/social',
			templateUrl: 'modules/users/views/settings/social-accounts.client.view.html'
		}).
		state('signup', {
			url: '/signup',
			templateUrl: 'modules/users/views/authentication/signup.client.view.html'
		}).
		state('signin', {
			url: '/signin',
			templateUrl: 'modules/users/views/authentication/signin.client.view.html'
		}).
		state('forgot', {
			url: '/password/forgot',
			templateUrl: 'modules/users/views/password/forgot-password.client.view.html'
		}).
		state('reset-invalid', {
			url: '/password/reset/invalid',
			templateUrl: 'modules/users/views/password/reset-password-invalid.client.view.html'
		}).
		state('reset-success', {
			url: '/password/reset/success',
			templateUrl: 'modules/users/views/password/reset-password-success.client.view.html'
		}).
		state('reset', {
			url: '/password/reset/:token',
			templateUrl: 'modules/users/views/password/reset-password.client.view.html'
		}).
        state('editAccountsAdmin', {
			url: '/settings/accounts/:userId/edit/admin',
			templateUrl: 'modules/users/views/settings/edit-profile-admin.client.view.html'
		}).
        state('listAccounts', {
			url: '/settings/accounts',
			templateUrl: 'modules/users/views/settings/manage-user-accounts.client.view.html'
		}).
        state('createAccounts', {
			url: '/settings/accounts/create',
			templateUrl: 'modules/users/views/settings/create-user-accounts.client.view.html'
		}).
        state('resetAccounts', {
			url: '/settings/accounts/reset/:userId',
			templateUrl: 'modules/users/views/settings/reset-user-accounts.client.view.html'
		});
	}
]);


text:
"""Tests for `models.py` (model cloning, mainly)."""

from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import numpy as np

from tensorflow.python.keras._impl import keras
from tensorflow.python.platform import test

class TestModelCloning(test.TestCase):

  def test_clone_sequential_model(self):
    with self.test_session():
      val_a = np.random.random((10, 4))
      val_out = np.random.random((10, 4))

      model = keras.models.Sequential()
      model.add(keras.layers.Dense(4, input_shape=(4,)))
      model.add(keras.layers.Dropout(0.5))
      model.add(keras.layers.Dense(4))

    # Everything should work in a new session.
    keras.backend.clear_session()

    with self.test_session():
      # With placeholder creation
      new_model = keras.models.clone_model(model)
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch(val_a, val_out)

      # On top of new tensor
      input_a = keras.Input(shape=(4,))
      new_model = keras.models.clone_model(
          model, input_tensors=input_a)
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch(val_a, val_out)

      # On top of new, non-Keras tensor
      input_a = keras.backend.variable(val_a)
      new_model = keras.models.clone_model(
          model, input_tensors=input_a)
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch(None, val_out)

  def test_clone_functional_model(self):
    with self.test_session():
      val_a = np.random.random((10, 4))
      val_b = np.random.random((10, 4))
      val_out = np.random.random((10, 4))

      input_a = keras.Input(shape=(4,))
      input_b = keras.Input(shape=(4,))
      dense_1 = keras.layers.Dense(4,)
      dense_2 = keras.layers.Dense(4,)

      x_a = dense_1(input_a)
      x_a = keras.layers.Dropout(0.5)(x_a)
      x_b = dense_1(input_b)
      x_a = dense_2(x_a)
      outputs = keras.layers.add([x_a, x_b])
      model = keras.models.Model([input_a, input_b], outputs)

    # Everything should work in a new session.
    keras.backend.clear_session()

    with self.test_session():
      # With placeholder creation
      new_model = keras.models.clone_model(model)
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch([val_a, val_b], val_out)

      # On top of new tensors
      input_a = keras.Input(shape=(4,), name='a')
      input_b = keras.Input(shape=(4,), name='b')
      new_model = keras.models.clone_model(
          model, input_tensors=[input_a, input_b])
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch([val_a, val_b], val_out)

      # On top of new, non-Keras tensors
      input_a = keras.backend.variable(val_a)
      input_b = keras.backend.variable(val_b)
      new_model = keras.models.clone_model(
          model, input_tensors=[input_a, input_b])
      new_model.compile('rmsprop', 'mse')
      new_model.train_on_batch(None, val_out)

  def test_model_cloning_invalid_use_cases(self):
    seq_model = keras.models.Sequential()
    seq_model.add(keras.layers.Dense(4, input_shape=(4,)))

    x = keras.Input((4,))
    y = keras.layers.Dense(4)(x)
    fn_model = keras.models.Model(x, y)

    with self.assertRaises(ValueError):
      keras.models._clone_functional_model(seq_model)
    with self.assertRaises(ValueError):
      keras.models._clone_functional_model(None)
    with self.assertRaises(ValueError):
      keras.models._clone_sequential_model(fn_model)

    with self.assertRaises(ValueError):
      keras.models._clone_sequential_model(seq_model, input_tensors=[x, x])
    with self.assertRaises(ValueError):
      keras.models._clone_sequential_model(seq_model, input_tensors=y)

if __name__ == '__main__':
  test.main()


text:
"""
zang.domain.available_phone_number
~~~~~~~~~~~~~~~~~~~
`AvailablePhoneNumber` model
"""

from zang.domain.base_resource import BaseResource
from zang.domain.enums.available_number_type import AvailableNumberType

class AvailablePhoneNumber(BaseResource):

    _bools = [
        'sms_enabled',
        'supports_forwarded_from',
        'voice_enabled',
    ]

    _reals = [
        'monthly_cost',
        'per_minute_cost',
        'setup_cost',
    ]

    _strs = [
        'city',
        'country_code',
        'exchange',
        'friendly_name',
        'iso_country',
        'lata',
        'latitude',
        'longitude',
        'npa',
        'phone_number',
        'postal_code',
        'rate_center',
        'region',
    ]
    _enums = {
        'type': AvailableNumberType,
    }

    def __init__(self):
        super(AvailablePhoneNumber, self).__init__()

    def friendlyName(self):
        """Domestic format version of the available phone number.
        (e.g. 1234567890 to (123)-456-7890).
        :rtype: str
        """
        return self._friendly_name

    @property
    def phoneNumber(self):
        """The E.164 format number of each available number.
        :rtype: str
        """
        return self._phone_number

    @property
    def lata(self):
        """Local Access and Transportation Area of the available number.
        The LATA is determined by geographical region.
        :rtype: str
        """
        return self._lata

    @property
    def rateCenter(self):
        """The available phone numbers rate center.
        :rtype: str
        """
        return self._rate_center

    @property
    def latitude(self):
        """The latitude of the available phone number.
        :rtype: str
        """
        return self._latitude

    @property
    def longitude(self):
        """The longitude of the available phone number.
        :rtype: str
        """
        return self._longitude

    @property
    def countryCode(self):
        """Code used to identify the phone numbers geographic origin.
        Found at the beginning of the number.
        :rtype: str
        """
        return self._country_code

    @property
    def npa(self):
        """Numbering Plan Area of the available number.
        This is more commonly known as the area code.
        :rtype: str
        """
        return self._npa

    @property
    def exchange(self):
        """Three digits following the NPA (area code) in the available
        number.
        :rtype: str
        """
        return self._exchange

    @property
    def city(self):
        """The available phone numbers city.
        :rtype: str
        """
        return self._city

    @property
    def region(self):
        """The region of the available phone number.
        Usually a two letter abbreviation.
        :rtype: str
        """
        return self._region

    @property
    def postalCode(self):
        """The postal code (also known as zip code) of the available number.
        :rtype: str
        """
        return self._postal_code

    @property
    def isoCountry(self):
        """Two letter country code of the available phone number.
        :rtype: str
        """
        return self._iso_country

    @property
    def type_(self):
        """Type of phone number (local or tollfree).
        :rtype: zang.domain.enums.available_number_type.AvailableNumberType
        """
        return self._type

    @property
    def setupCost(self):
        """Cost of phone number setup.
        :rtype: float
        """
        return self._setup_cost

    @property
    def monthlyCost(self):
        """Cost of phone number per month.
        :rtype: float
        """
        return self._monthly_cost

    @property
    def perMinuteCost(self):
        """Cost of phone number per month.
        :rtype: float
        """
        return self._per_minute_cost

    @property
    def voiceEnabled(self):
        """Is voice enabled for this phone number? Can be true or false.
        :rtype: bool
        """
        return self._voice_enabled

    @property
    def smsEnabled(self):
        """Is SMS enabled for this phone number? Can be true or false.
        :rtype: bool
        """
        return self._sms_enabled

    @property
    def supportsForwardedFrom(self):
        """Does phone number support forwarded from? Can be true or false.
        :rtype: bool
        """
        return self._supports_forwarded_from


text:
from lxml import etree
from oslo.config import cfg

from nova import exception
from nova.network import model as network_model
from nova import test
from nova.tests.virt.libvirt import fakelibvirt
from nova import utils
from nova.virt.libvirt import config as vconfig
from nova.virt.libvirt import vif

CONF = cfg.CONF

class LibvirtVifTestCase(test.TestCase):

    net_bridge = {
             'cidr': '101.168.1.0/24',
             'cidr_v6': '101:1db9::/64',
             'gateway_v6': '101:1db9::1',
             'netmask_v6': '64',
             'netmask': '255.255.255.0',
             'bridge': 'br0',
             'bridge_interface': 'eth0',
             'vlan': 99,
             'gateway': '101.168.1.1',
             'broadcast': '101.168.1.255',
             'dns1': '8.8.8.8',
             'id': 'network-id-xxx-yyy-zzz'
    }

    net_bridge_quantum = {
             'cidr': '101.168.1.0/24',
             'cidr_v6': '101:1db9::/64',
             'gateway_v6': '101:1db9::1',
             'netmask_v6': '64',
             'netmask': '255.255.255.0',
             'bridge_interface': 'eth0',
             'vlan': 99,
             'gateway': '101.168.1.1',
             'broadcast': '101.168.1.255',
             'dns1': '8.8.8.8',
             'id': 'network-id-xxx-yyy-zzz'
    }

    mapping_bridge = {
        'mac': 'ca:fe:de:ad:be:ef',
        'gateway_v6': net_bridge['gateway_v6'],
        'ips': [{'ip': '101.168.1.9'}],
        'dhcp_server': '191.168.1.1',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
        'vif_type': network_model.VIF_TYPE_BRIDGE,
    }

    mapping_bridge_quantum = {
        'mac': 'ca:fe:de:ad:be:ef',
        'gateway_v6': net_bridge['gateway_v6'],
        'ips': [{'ip': '101.168.1.9'}],
        'dhcp_server': '191.168.1.1',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
    }

    net_ovs = {
             'cidr': '101.168.1.0/24',
             'cidr_v6': '101:1db9::/64',
             'gateway_v6': '101:1db9::1',
             'netmask_v6': '64',
             'netmask': '255.255.255.0',
             'bridge': 'br0',
             'vlan': 99,
             'gateway': '101.168.1.1',
             'broadcast': '101.168.1.255',
             'dns1': '8.8.8.8',
             'id': 'network-id-xxx-yyy-zzz'
    }

    mapping_ovs = {
        'mac': 'ca:fe:de:ad:be:ef',
        'gateway_v6': net_ovs['gateway_v6'],
        'ips': [{'ip': '101.168.1.9'}],
        'dhcp_server': '191.168.1.1',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
        'vif_type': network_model.VIF_TYPE_OVS,
        'ovs_interfaceid': 'aaa-bbb-ccc',
    }

    mapping_ovs_legacy = {
        'mac': 'ca:fe:de:ad:be:ef',
        'gateway_v6': net_ovs['gateway_v6'],
        'ips': [{'ip': '101.168.1.9'}],
        'dhcp_server': '191.168.1.1',
        'vif_uuid': 'vif-xxx-yyy-zzz',
    }

    net_8021 = {
             'cidr': '101.168.1.0/24',
             'cidr_v6': '101:1db9::/64',
             'gateway_v6': '101:1db9::1',
             'netmask_v6': '64',
             'netmask': '255.255.255.0',
             'interface': 'eth0',
             'vlan': 99,
             'gateway': '101.168.1.1',
             'broadcast': '101.168.1.255',
             'dns1': '8.8.8.8',
             'id': 'network-id-xxx-yyy-zzz'
    }

    mapping_8021qbh = {
        'mac': 'ca:fe:de:ad:be:ef',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
        'vif_type': network_model.VIF_TYPE_802_QBH,
        'qbh_params': network_model.VIF8021QbhParams(
            profileid="xxx-yyy-zzz"),
    }

    mapping_8021qbg = {
        'mac': 'ca:fe:de:ad:be:ef',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
        'vif_type': network_model.VIF_TYPE_802_QBG,
        'qbg_params': network_model.VIF8021QbgParams(
            managerid="xxx-yyy-zzz",
            typeid="aaa-bbb-ccc",
            typeidversion="1",
            instanceid="ddd-eee-fff")
    }

    mapping_none = {
        'mac': 'ca:fe:de:ad:be:ef',
        'gateway_v6': net_bridge['gateway_v6'],
        'ips': [{'ip': '101.168.1.9'}],
        'dhcp_server': '191.168.1.1',
        'vif_uuid': 'vif-xxx-yyy-zzz',
        'vif_devname': 'tap-xxx-yyy-zzz',
    }

    instance = {
        'name': 'instance-name',
        'uuid': 'instance-uuid'
    }

    def setUp(self):
        super(LibvirtVifTestCase, self).setUp()
        self.flags(allow_same_net_traffic=True)
        self.executes = []

        def fake_execute(*cmd, **kwargs):
            self.executes.append(cmd)
            return None, None

        self.stubs.Set(utils, 'execute', fake_execute)

    def _get_instance_xml(self, driver, net, mapping, image_meta=None):
        conf = vconfig.LibvirtConfigGuest()
        conf.virt_type = "qemu"
        conf.name = "fake-name"
        conf.uuid = "fake-uuid"
        conf.memory = 100 * 1024
        conf.vcpus = 4

        nic = driver.get_config(self.instance, net, mapping, image_meta)
        conf.add_device(nic)
        return conf.to_xml()

    def test_multiple_nics(self):
        conf = vconfig.LibvirtConfigGuest()
        conf.virt_type = "qemu"
        conf.name = "fake-name"
        conf.uuid = "fake-uuid"
        conf.memory = 100 * 1024
        conf.vcpus = 4

        # Tests multiple nic configuration and that target_dev is
        # set for each
        nics = [{'net_type': 'bridge',
                 'mac_addr': '00:00:00:00:00:0b',
                 'source_dev': 'b_source_dev',
                 'target_dev': 'b_target_dev'},
                {'net_type': 'ethernet',
                 'mac_addr': '00:00:00:00:00:0e',
                 'source_dev': 'e_source_dev',
                 'target_dev': 'e_target_dev'},
                {'net_type': 'direct',
                 'mac_addr': '00:00:00:00:00:0d',
                 'source_dev': 'd_source_dev',
                 'target_dev': 'd_target_dev'}]

        for nic in nics:
            nic_conf = vconfig.LibvirtConfigGuestInterface()
            nic_conf.net_type = nic['net_type']
            nic_conf.target_dev = nic['target_dev']
            nic_conf.mac_addr = nic['mac_addr']
            nic_conf.source_dev = nic['source_dev']
            conf.add_device(nic_conf)

        xml = conf.to_xml()
        doc = etree.fromstring(xml)
        for nic in nics:
            path = "./devices/interface/[@type='%s']" % nic['net_type']
            node = doc.find(path)
            self.assertEqual(nic['net_type'], node.get("type"))
            self.assertEqual(nic['mac_addr'],
                             node.find("mac").get("address"))
            self.assertEqual(nic['target_dev'],
                             node.find("target").get("dev"))

    def test_model_novirtio(self):
        self.flags(libvirt_use_virtio_for_bridges=False,
                   libvirt_type='kvm')

        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_bridge,
                                     self.mapping_bridge)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]

        ret = node.findall("model")
        self.assertEqual(len(ret), 0)
        ret = node.findall("driver")
        self.assertEqual(len(ret), 0)

    def test_model_kvm(self):
        self.flags(libvirt_use_virtio_for_bridges=True,
                   libvirt_type='kvm')

        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_bridge,
                                     self.mapping_bridge)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]

        model = node.find("model").get("type")
        self.assertEqual(model, "virtio")
        ret = node.findall("driver")
        self.assertEqual(len(ret), 0)

    def test_model_kvm_custom(self):
        self.flags(libvirt_use_virtio_for_bridges=True,
                   libvirt_type='kvm')

        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        image_meta = {'properties': {'hw_vif_model': 'e1000'}}
        xml = self._get_instance_xml(d,
                                     self.net_bridge,
                                     self.mapping_bridge,
                                     image_meta)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]

        model = node.find("model").get("type")
        self.assertEqual(model, "e1000")
        ret = node.findall("driver")
        self.assertEqual(len(ret), 0)

    def test_model_kvm_bogus(self):
        self.flags(libvirt_use_virtio_for_bridges=True,
                   libvirt_type='kvm')

        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        image_meta = {'properties': {'hw_vif_model': 'acme'}}
        self.assertRaises(exception.UnsupportedHardware,
                          self._get_instance_xml,
                          d,
                          self.net_bridge,
                          self.mapping_bridge,
                          image_meta)

    def test_model_qemu(self):
        self.flags(libvirt_use_virtio_for_bridges=True,
                   libvirt_type='qemu')

        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_bridge,
                                     self.mapping_bridge)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]

        model = node.find("model").get("type")
        self.assertEqual(model, "virtio")
        driver = node.find("driver").get("name")
        self.assertEqual(driver, "qemu")

    def test_model_xen(self):
        self.flags(libvirt_use_virtio_for_bridges=True,
                   libvirt_type='xen')

        def get_connection():
            return fakelibvirt.Connection("xen:///system",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_bridge,
                                     self.mapping_bridge)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]

        ret = node.findall("model")
        self.assertEqual(len(ret), 0)
        ret = node.findall("driver")
        self.assertEqual(len(ret), 0)

    def test_generic_driver_none(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        self.assertRaises(exception.NovaException,
                          self._get_instance_xml,
                          d,
                          self.net_bridge,
                          self.mapping_none)

    def _check_bridge_driver(self, d, net, mapping, br_want):
        xml = self._get_instance_xml(d, net, mapping)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        ret = node.findall("filterref")
        self.assertEqual(len(ret), 1)
        self.assertEqual(node.get("type"), "bridge")
        br_name = node.find("source").get("bridge")
        self.assertEqual(br_name, br_want)
        mac = node.find("mac").get("address")
        self.assertEqual(mac, self.mapping_bridge['mac'])

    def test_bridge_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtBridgeDriver(get_connection)
        self._check_bridge_driver(d,
                                  self.net_bridge,
                                  self.mapping_bridge,
                                  self.net_bridge['bridge'])

    def test_generic_driver_bridge(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        self._check_bridge_driver(d,
                                  self.net_bridge,
                                  self.mapping_bridge,
                                  self.net_bridge['bridge'])

    def test_quantum_bridge_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.QuantumLinuxBridgeVIFDriver(get_connection)
        br_want = 'brq' + self.net_bridge_quantum['id']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_bridge_driver(d,
                                  self.net_bridge_quantum,
                                  self.mapping_bridge_quantum,
                                  br_want)

    def _check_ovs_ethernet_driver(self, d, net, mapping, dev_prefix):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, net, mapping)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        ret = node.findall("filterref")
        self.assertEqual(len(ret), 0)
        self.assertEqual(node.get("type"), "ethernet")
        dev_name = node.find("target").get("dev")
        self.assertTrue(dev_name.startswith(dev_prefix))
        mac = node.find("mac").get("address")
        self.assertEqual(mac, self.mapping_ovs['mac'])
        script = node.find("script").get("path")
        self.assertEquals(script, "")

    def test_ovs_ethernet_driver_legacy(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False,
                                          9010)
        d = vif.LibvirtOpenVswitchDriver(get_connection)
        self._check_ovs_ethernet_driver(d,
                                        self.net_ovs,
                                        self.mapping_ovs_legacy,
                                        "nic")

    def test_ovs_ethernet_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False,
                                          9010)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        self._check_ovs_ethernet_driver(d,
                                        self.net_ovs,
                                        self.mapping_ovs,
                                        "tap")

    def _check_ovs_virtualport_driver(self, d, net, mapping, want_iface_id):
        self.flags(firewall_driver="nova.virt.firewall.NoopFirewallDriver")
        xml = self._get_instance_xml(d, net, mapping)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        ret = node.findall("filterref")
        self.assertEqual(len(ret), 0)
        self.assertEqual(node.get("type"), "bridge")

        br_name = node.find("source").get("bridge")
        self.assertEqual(br_name, "br0")
        mac = node.find("mac").get("address")
        self.assertEqual(mac, mapping['mac'])
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "openvswitch")
        iface_id_found = False
        for p_elem in vp.findall("parameters"):
            iface_id = p_elem.get("interfaceid", None)
            if iface_id:
                self.assertEqual(iface_id, want_iface_id)
                iface_id_found = True

        self.assertTrue(iface_id_found)

    def test_ovs_virtualport_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False,
                                          9011)
        d = vif.LibvirtOpenVswitchVirtualPortDriver(get_connection)
        want_iface_id = 'vif-xxx-yyy-zzz'
        self._check_ovs_virtualport_driver(d,
                                           self.net_ovs,
                                           self.mapping_ovs_legacy,
                                           want_iface_id)

    def test_generic_ovs_virtualport_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False,
                                          9011)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        want_iface_id = self.mapping_ovs['ovs_interfaceid']
        self._check_ovs_virtualport_driver(d,
                                           self.net_ovs,
                                           self.mapping_ovs,
                                           want_iface_id)

    def _check_quantum_hybrid_driver(self, d, net, mapping, br_want):
        self.flags(firewall_driver="nova.virt.firewall.IptablesFirewallDriver")
        xml = self._get_instance_xml(d, net, mapping)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        ret = node.findall("filterref")
        self.assertEqual(len(ret), 1)
        self.assertEqual(node.get("type"), "bridge")
        br_name = node.find("source").get("bridge")
        self.assertEqual(br_name, br_want)
        mac = node.find("mac").get("address")
        self.assertEqual(mac, mapping['mac'])

    def test_quantum_hybrid_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        br_want = "qbr" + self.mapping_ovs['vif_uuid']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        d = vif.LibvirtHybridOVSBridgeDriver(get_connection)
        self._check_quantum_hybrid_driver(d,
                                          self.net_ovs,
                                          self.mapping_ovs_legacy,
                                          br_want)

    def test_generic_hybrid_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        br_want = "qbr" + self.mapping_ovs['vif_uuid']
        br_want = br_want[:network_model.NIC_NAME_LEN]
        self._check_quantum_hybrid_driver(d,
                                          self.net_ovs,
                                          self.mapping_ovs,
                                          br_want)

    def test_generic_8021qbh_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_8021,
                                     self.mapping_8021qbh)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        self.assertEqual(node.get("type"), "direct")

        br_name = node.find("source").get("dev")
        self.assertEqual(br_name, "eth0")
        mac = node.find("mac").get("address")
        self.assertEqual(mac, self.mapping_8021qbh['mac'])
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbh")
        profile_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.mapping_8021qbh['qbh_params']
            profile_id = p_elem.get("profileid", None)
            if profile_id:
                self.assertEqual(profile_id,
                                 wantparams['profileid'])
                profile_id_found = True

        self.assertTrue(profile_id_found)

    def test_generic_8021qbg_driver(self):
        def get_connection():
            return fakelibvirt.Connection("qemu:///session",
                                          False)
        d = vif.LibvirtGenericVIFDriver(get_connection)
        xml = self._get_instance_xml(d,
                                     self.net_8021,
                                     self.mapping_8021qbg)

        doc = etree.fromstring(xml)
        ret = doc.findall('./devices/interface')
        self.assertEqual(len(ret), 1)
        node = ret[0]
        self.assertEqual(node.get("type"), "direct")

        br_name = node.find("source").get("dev")
        self.assertEqual(br_name, "eth0")
        mac = node.find("mac").get("address")
        self.assertEqual(mac, self.mapping_8021qbg['mac'])
        vp = node.find("virtualport")
        self.assertEqual(vp.get("type"), "802.1Qbg")
        manager_id_found = False
        type_id_found = False
        typeversion_id_found = False
        instance_id_found = False
        for p_elem in vp.findall("parameters"):
            wantparams = self.mapping_8021qbg['qbg_params']
            manager_id = p_elem.get("managerid", None)
            type_id = p_elem.get("typeid", None)
            typeversion_id = p_elem.get("typeidversion", None)
            instance_id = p_elem.get("instanceid", None)
            if manager_id:
                self.assertEqual(manager_id,
                                 wantparams['managerid'])
                manager_id_found = True
            if type_id:
                self.assertEqual(type_id,
                                 wantparams['typeid'])
                type_id_found = True
            if typeversion_id:
                self.assertEqual(typeversion_id,
                                 wantparams['typeidversion'])
                typeversion_id_found = True
            if instance_id:
                self.assertEqual(instance_id,
                                 wantparams['instanceid'])
                instance_id_found = True

        self.assertTrue(manager_id_found)
        self.assertTrue(type_id_found)
        self.assertTrue(typeversion_id_found)
        self.assertTrue(instance_id_found)


text:
export { default as accounts } from './accounts.json';
export { default as accountsMultiple } from './accounts-multiple.json';
export { default as clients } from './clients.json';
export { default as clientsNoAFC } from './clients-no-afc.json';
export { default as urlchannels } from './urlchannels.json';
export { default as adunits } from './adunits.json';
export { default as alerts } from './alerts.json';
export { default as alertsGraylisted } from './alerts-graylisted.json';
export { default as sites } from './sites.json';


text:
IPC_ENUM_TRAITS_MAX_VALUE(gfx::ColorSpace::PrimaryID,
                          gfx::ColorSpace::PrimaryID::LAST);
IPC_ENUM_TRAITS_MAX_VALUE(gfx::ColorSpace::TransferID,
                          gfx::ColorSpace::TransferID::LAST);
IPC_ENUM_TRAITS_MAX_VALUE(gfx::ColorSpace::MatrixID,
                          gfx::ColorSpace::MatrixID::LAST);
IPC_ENUM_TRAITS_MAX_VALUE(gfx::ColorSpace::RangeID,
                          gfx::ColorSpace::RangeID::LAST);

IPC_STRUCT_TRAITS_BEGIN(gfx::ICCProfile)
  IPC_STRUCT_TRAITS_MEMBER(valid_)
  IPC_STRUCT_TRAITS_MEMBER(data_)
  IPC_STRUCT_TRAITS_MEMBER(id_)
IPC_STRUCT_TRAITS_END()

#endif  // UI_GFX_IPC_COLOR_GFX_PARAM_TRAITS_MACROS_H_


text:
package io.github.greyp9.arwo.core.xed.table;

import io.github.greyp9.arwo.core.date.DurationU;
import io.github.greyp9.arwo.core.date.XsdDateU;
import io.github.greyp9.arwo.core.glyph.UTF16;
import io.github.greyp9.arwo.core.html.Html;
import io.github.greyp9.arwo.core.lang.TypeU;
import io.github.greyp9.arwo.core.table.cell.Duration;
import io.github.greyp9.arwo.core.table.cell.TableViewLink;
import io.github.greyp9.arwo.core.table.filter.Filters;
import io.github.greyp9.arwo.core.table.metadata.RowSetMetaData;
import io.github.greyp9.arwo.core.table.row.Row;
import io.github.greyp9.arwo.core.table.row.RowSet;
import io.github.greyp9.arwo.core.table.sort.Sorts;
import io.github.greyp9.arwo.core.value.Value;
import io.github.greyp9.arwo.core.xed.bundle.XsdBundle;
import io.github.greyp9.arwo.core.xed.cursor.XedCursor;
import io.github.greyp9.arwo.core.xed.nav.XedNav;
import io.github.greyp9.arwo.core.xsd.core.XsdTypeU;
import io.github.greyp9.arwo.core.xsd.data.DataType;
import io.github.greyp9.arwo.core.xsd.instance.ChoiceTypeInstance;
import io.github.greyp9.arwo.core.xsd.instance.TypeInstance;
import io.github.greyp9.arwo.core.xsd.instance.TypeInstanceX;
import org.w3c.dom.Element;

import javax.xml.namespace.QName;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class XedRowSetFactory {
    private final String baseURI;
    private final String submitID;
    private final TypeInstance typeInstance;
    private final RowSetMetaData metaData;
    private final Sorts sorts;
    private final Filters filters;

    public XedRowSetFactory(final String baseURI, final String submitID, final TypeInstance typeInstance,
                            final RowSetMetaData metaData, final Sorts sorts, final Filters filters) {
        this.baseURI = baseURI;
        this.submitID = submitID;
        this.typeInstance = typeInstance;
        this.metaData = metaData;
        this.sorts = sorts;
        this.filters = filters;
    }

    public final RowSet create(final XedCursor cursor, final Collection<Element> children, final Element selected) {
        submitID.getClass();

        final XedNav nav = new XedNav(cursor.getXed());
        final RowSet rowSet = new RowSet(metaData, sorts, filters);
        for (final Element child : children) {
            final XedCursor cursorRow = nav.find(child, cursor);
            iterateCursor(cursorRow, selected, rowSet);
        }
        return rowSet;
    }

    private void iterateCursor(final XedCursor cursorRow, final Element selected, final RowSet rowSet) {
        if ((cursorRow.getTypeInstance().equals(typeInstance)) && (cursorRow.getNode() != null)) {
            final boolean isSelected = Value.equal(cursorRow.getElement(), selected);
            iterateRow(rowSet.getRows(), cursorRow, rowSet, isSelected);
        }
    }

    private void iterateRow(final int ordinal, final XedCursor cursor, final RowSet rowSet, final boolean isSelected) {
        int i = -1;
        final Row row = new Row(ordinal, isSelected, metaData.size());
        if (baseURI != null) {  // uncommented to handle display of metrics
            addRowLink(row, ++i, cursor);
        }
        final Collection<TypeInstance> typeInstances = new TypeInstanceX(cursor.getTypeInstance()).getTableInstances();
        for (final TypeInstance typeInstanceIt : typeInstances) {
            iterateColumn(row, ++i, cursor, typeInstanceIt, cursor.getValue(typeInstanceIt));
        }
        rowSet.add(row, true);
    }

    private void iterateColumn(
            final Row row, final int i, final XedCursor cursor, final TypeInstance typeInstanceC, final String value) {
        final DataType dataType = typeInstanceC.getDataType();
        final QName qname = ((dataType == null) ? null : dataType.getQName());
        if (XsdTypeU.Const.BOOLEAN.equals(qname)) {
            row.setColumn(i, TypeU.toBoolean(value));
        } else if (XsdTypeU.Const.INTEGER.equals(qname)) {
            row.setColumn(i, TypeU.toInteger(value));
        } else if (XsdTypeU.Const.UNSIGNED_INT.equals(qname)) {
            row.setColumn(i, TypeU.toInteger(value));
        } else if (XsdTypeU.Const.DATE_TIME.equals(qname)) {
            row.setColumn(i, XsdDateU.fromXSDZ(value));
        } else if (XsdTypeU.Const.DURATION.equals(qname)) {
            row.setColumn(i, new Duration(DurationU.toMillis(value)));
        } else if (typeInstanceC instanceof ChoiceTypeInstance) {
            row.setColumn(i, getChoiceText(value, cursor, (ChoiceTypeInstance) typeInstanceC));
        } else if (typeInstanceC.isMasked()) {
            row.setColumn(i, Html.MASK);
        } else {
            row.setColumn(i, value);
        }
    }

    private void addRowLink(final Row row, final int i, final XedCursor cursor) {
        final String resource = baseURI + cursor.getURI();
        row.setColumn(i, new TableViewLink(UTF16.SELECT, null, resource));
    }

    private String getChoiceText(final String value, final XedCursor cursor, final ChoiceTypeInstance choiceInstance) {
        String choiceText = null;
        final Collection<TypeInstance> typeInstances = choiceInstance.getInstances();
        for (final TypeInstance typeInstanceIt : typeInstances) {
            if (typeInstanceIt.getName().equals(value)) {
                choiceText = getChoiceText(cursor, typeInstanceIt);
            }
        }
        return choiceText;
    }

    private String getChoiceText(final XedCursor cursor, final TypeInstance childInstance) {
        final List<String> tokens = new ArrayList<String>();
        // choice instance name
        final TypeInstance parentInstance = cursor.getTypeInstance();
        final XsdBundle bundle = cursor.getXed().getXsdBundle();
        tokens.add(bundle.getLabel(parentInstance, childInstance));
        // choice instance attributes
        final XedNav nav = new XedNav(cursor.getXed());
        final Collection<Element> children = cursor.getChildren(childInstance);
        for (final Element child : children) {
            final XedCursor cursorIt = nav.find(child, cursor);
            final Collection<TypeInstance> typeInstances = cursorIt.getTypeInstance().getInstances();
            for (final TypeInstance typeInstanceIt : typeInstances) {
                final String name = bundle.getLabel(childInstance, typeInstanceIt);
                final String value = typeInstanceIt.isMasked() ? Html.MASK : cursorIt.getValue(typeInstanceIt);
                tokens.add(String.format("[%s=\"%s\"]", name, value));  // i18n internal
            }
        }
        // render
        return Value.joinCollection(Html.SPACE, tokens);
    }
}


text:
<?xml version="1.0"?>

<!--

	SUPERMAP ICLIENT FOR FLEX 6R
	Copyright 2005-2010 SuperMap Software Co., Ltd
	All Rights Reserved.

-->

<componentPackage>
<!--resources -->
	<component id="SmServerResource" class="com.supermap.web.resources.SmServerResource"/>

<!--common -->
	<component id="JoinItem" class="com.supermap.web.iServerJava2.JoinItem"/>
	<component id="JoinType" class="com.supermap.web.iServerJava2.JoinType"/>

<!-- component -->
	<component id="Legend" class="com.supermap.web.iServerJava2.components.Legend"/>
	<component id="LegendSkin" class="com.supermap.web.iServerJava2.components.skins.LegendSkin"/>
	<component id="LegendItemInfo" class="com.supermap.web.iServerJava2.components.LegendItemInfo"/>
	<component id="LegendEvent" class="com.supermap.web.iServerJava2.components.LegendEvent"/>

<!-- mapping -->
	<component id="DynamicIServerLayer" class="com.supermap.web.mapping.DynamicIServerLayer"/>
	<component id="TiledCachedIServerLayer" class="com.supermap.web.mapping.TiledCachedIServerLayer"/>
	<component id="TiledDynamicIServerLayer" class="com.supermap.web.mapping.TiledDynamicIServerLayer"/>
	<component id="DynamicHighlightLayer" class="com.supermap.web.mapping.DynamicHighlightLayer"/>

	<!--iserverjava2-->
	<component id="ServerGeometry" class="com.supermap.web.iServerJava2.ServerGeometry"/>
	<component id="ServerFeatureType" class="com.supermap.web.iServerJava2.ServerFeatureType"/>

	<!-- mapServices -->
	<component id="GetMapStatusParameters" class="com.supermap.web.iServerJava2.mapServices.GetMapStatusParameters"/>
	<component id="GetMapStatusResult" class="com.supermap.web.iServerJava2.mapServices.GetMapStatusResult"/>
	<component id="GetMapStatusService" class="com.supermap.web.iServerJava2.mapServices.GetMapStatusService"/>
	<component id="ServerLayer" class="com.supermap.web.iServerJava2.mapServices.ServerLayer"/>
	<component id="ServerLayerSettingType" class="com.supermap.web.iServerJava2.mapServices.ServerLayerSettingType"/>
	<component id="SuperMapCollectionLayerSetting" class="com.supermap.web.iServerJava2.mapServices.SuperMapCollectionLayerSetting"/>
	<component id="SuperMapLayerType" class="com.supermap.web.iServerJava2.mapServices.SuperMapLayerType"/>
	<component id="LayerStatus" class="com.supermap.web.iServerJava2.mapServices.LayerStatus"/>
	<component id="SetLayerStatusParameters" class="com.supermap.web.iServerJava2.mapServices.SetLayerStatusParameters"/>
	<component id="SetLayerStatusResult" class="com.supermap.web.iServerJava2.mapServices.SetLayerStatusResult"/>
	<component id="SetLayerStatusService" class="com.supermap.web.iServerJava2.mapServices.SetLayerStatusService"/>

	<!-- queryServices -->
	<component id="QueryByCenterParameters" class="com.supermap.web.iServerJava2.queryServices.QueryByCenterParameters"/>
	<component id="QueryByCenterService" class="com.supermap.web.iServerJava2.queryServices.QueryByCenterService"/>
	<component id="QueryByGeometryParameters" class="com.supermap.web.iServerJava2.queryServices.QueryByGeometryParameters"/>
	<component id="QueryByGeometryService" class="com.supermap.web.iServerJava2.queryServices.QueryByGeometryService"/>
	<component id="QueryBySqlParameters" class="com.supermap.web.iServerJava2.queryServices.QueryBySqlParameters"/>
	<component id="QueryBySqlService" class="com.supermap.web.iServerJava2.queryServices.QueryBySqlService"/>
	<component id="ReturnResultSetInfo" class="com.supermap.web.iServerJava2.queryServices.ReturnResultSetInfo"/>
	<component id="QueryLayerParam" class="com.supermap.web.iServerJava2.queryServices.QueryLayerParam"/>
	<component id="QueryParam" class="com.supermap.web.iServerJava2.queryServices.QueryParam"/>
	<component id="QueryParametersBase" class="com.supermap.web.iServerJava2.queryServices.QueryParametersBase"/>
	<component id="Record" class="com.supermap.web.iServerJava2.queryServices.Record"/>
	<component id="RecordSet" class="com.supermap.web.iServerJava2.queryServices.RecordSet"/>
	<component id="ResultSet" class="com.supermap.web.iServerJava2.queryServices.ResultSet"/>
	<component id="SqlParam" class="com.supermap.web.iServerJava2.queryServices.SqlParam"/>
	<component id="BufferAnalystParam" class="com.supermap.web.iServerJava2.queryServices.BufferAnalystParam"/>
	<component id="BufferEndType" class="com.supermap.web.iServerJava2.queryServices.BufferEndType"/>
	<component id="BufferQueryParameters" class="com.supermap.web.iServerJava2.queryServices.BufferQueryParameters"/>
	<component id="BufferQueryService" class="com.supermap.web.iServerJava2.queryServices.BufferQueryService"/>
	<component id="BufferSideType" class="com.supermap.web.iServerJava2.queryServices.BufferSideType"/>
	<component id="EntityBufferQueryParameters" class="com.supermap.web.iServerJava2.queryServices.EntityBufferQueryParameters"/>
	<component id="EntityBufferQueryService" class="com.supermap.web.iServerJava2.queryServices.EntityBufferQueryService"/>
	<component id="SpatialQueryMode" class="com.supermap.web.iServerJava2.queryServices.SpatialQueryMode"/>

	<!-- measureServices -->
	<component id="MeasureService" class="com.supermap.web.iServerJava2.measureServices.MeasureService"/>
	<component id="MeasureParameters" class="com.supermap.web.iServerJava2.measureServices.MeasureParameters"/>
	<component id="MeasureResult" class="com.supermap.web.iServerJava2.measureServices.MeasureResult"/>

	<!-- networkAnalystServices -->

	<component id="ClosestFacilityParameters" class="com.supermap.web.iServerJava2.networkAnalystServices.ClosestFacilityParameters"/>
	<component id="ClosestFacilityService" class="com.supermap.web.iServerJava2.networkAnalystServices.ClosestFacilityService"/>
	<component id="FindPathParameters" class="com.supermap.web.iServerJava2.networkAnalystServices.FindPathParameters"/>
	<component id="FindPathService" class="com.supermap.web.iServerJava2.networkAnalystServices.FindPathService"/>
	<component id="FindTSPPathParameters" class="com.supermap.web.iServerJava2.networkAnalystServices.FindTSPPathParameters"/>
	<component id="FindTSPPathService" class="com.supermap.web.iServerJava2.networkAnalystServices.FindTSPPathService"/>
	<component id="NetworkAnalystParam" class="com.supermap.web.iServerJava2.networkAnalystServices.NetworkAnalystParam"/>
	<component id="NetworkAnalystResult" class="com.supermap.web.iServerJava2.networkAnalystServices.NetworkAnalystResult"/>
	<component id="NetworkModelSetting" class="com.supermap.web.iServerJava2.networkAnalystServices.NetworkModelSetting"/>
	<component id="PathGuide" class="com.supermap.web.iServerJava2.networkAnalystServices.PathGuide"/>

	<component id="PathGuideItem" class="com.supermap.web.iServerJava2.networkAnalystServices.PathGuideItem"/>
	<component id="PathParam" class="com.supermap.web.iServerJava2.networkAnalystServices.PathParam"/>
	<component id="ProximityParam" class="com.supermap.web.iServerJava2.networkAnalystServices.ProximityParam"/>
	<component id="ServiceAreaParam" class="com.supermap.web.iServerJava2.networkAnalystServices.ServiceAreaParam"/>
	<component id="ServiceAreaParameters" class="com.supermap.web.iServerJava2.networkAnalystServices.ServiceAreaParameters"/>
	<component id="ServiceAreaResult" class="com.supermap.web.iServerJava2.networkAnalystServices.ServiceAreaResult"/>
	<component id="ServiceAreaService" class="com.supermap.web.iServerJava2.networkAnalystServices.ServiceAreaService"/>
	<component id="SideType" class="com.supermap.web.iServerJava2.networkAnalystServices.SideType"/>
	<component id="TSPPathParam" class="com.supermap.web.iServerJava2.networkAnalystServices.TSPPathParam"/>
	<component id="TurnTableSetting" class="com.supermap.web.iServerJava2.networkAnalystServices.TurnTableSetting"/>
	<component id="TurnType" class="com.supermap.web.iServerJava2.networkAnalystServices.TurnType"/>
	<component id="WeightFieldInfo" class="com.supermap.web.iServerJava2.networkAnalystServices.WeightFieldInfo"/>

	<!-- themeServices -->
	<component id="ColorGradientType" class="com.supermap.web.iServerJava2.themeServices.ColorGradientType"/>
	<component id="FillGradientMode" class="com.supermap.web.iServerJava2.themeServices.FillGradientMode"/>
	<component id="GraduatedMode" class="com.supermap.web.iServerJava2.themeServices.GraduatedMode"/>
	<component id="GraphTextFormat" class="com.supermap.web.iServerJava2.themeServices.GraphTextFormat"/>
	<component id="GraphType" class="com.supermap.web.iServerJava2.themeServices.GraphType"/>
	<component id="LabelBackShape" class="com.supermap.web.iServerJava2.themeServices.LabelBackShape"/>
	<component id="OverLengthLabelMode" class="com.supermap.web.iServerJava2.themeServices.OverLengthLabelMode"/>
	<component id="RangeMode" class="com.supermap.web.iServerJava2.themeServices.RangeMode"/>
	<component id="RemoveThemesParameters" class="com.supermap.web.iServerJava2.themeServices.RemoveThemesParameters"/>
	<component id="RemoveThemesResult" class="com.supermap.web.iServerJava2.themeServices.RemoveThemesResult"/>

	<component id="RemoveThemesService" class="com.supermap.web.iServerJava2.themeServices.RemoveThemesService"/>
	<component id="ServerColor" class="com.supermap.web.iServerJava2.themeServices.ServerColor"/>
	<component id="ServerStyle" class="com.supermap.web.iServerJava2.themeServices.ServerStyle"/>
	<component id="ServerTextAlignment" class="com.supermap.web.iServerJava2.themeServices.ServerTextAlignment"/>
	<component id="ServerTextStyle" class="com.supermap.web.iServerJava2.themeServices.ServerTextStyle"/>
	<component id="Theme" class="com.supermap.web.iServerJava2.themeServices.Theme"/>

	<component id="ThemeDotDensity" class="com.supermap.web.iServerJava2.themeServices.ThemeDotDensity"/>
	<component id="ThemeGraduatedSymbol" class="com.supermap.web.iServerJava2.themeServices.ThemeGraduatedSymbol"/>
	<component id="ThemeGraph" class="com.supermap.web.iServerJava2.themeServices.ThemeGraph"/>
	<component id="ThemeGraphItem" class="com.supermap.web.iServerJava2.themeServices.ThemeGraphItem"/>
	<component id="ThemeLabel" class="com.supermap.web.iServerJava2.themeServices.ThemeLabel"/>
	<component id="ThemeLabelItem" class="com.supermap.web.iServerJava2.themeServices.ThemeLabelItem"/>

	<component id="ThemeParameters" class="com.supermap.web.iServerJava2.themeServices.ThemeParameters"/>
	<component id="ThemeRange" class="com.supermap.web.iServerJava2.themeServices.ThemeRange"/>
	<component id="ThemeRangeItem" class="com.supermap.web.iServerJava2.themeServices.ThemeRangeItem"/>
	<component id="ThemeRangeParam" class="com.supermap.web.iServerJava2.themeServices.ThemeRangeParam"/>
	<component id="ThemeResult" class="com.supermap.web.iServerJava2.themeServices.ThemeResult"/>
	<component id="ThemeService" class="com.supermap.web.iServerJava2.themeServices.ThemeService"/>

	<component id="ThemeType" class="com.supermap.web.iServerJava2.themeServices.ThemeType"/>
	<component id="ThemeUnique" class="com.supermap.web.iServerJava2.themeServices.ThemeUnique"/>
	<component id="ThemeUniqueItem" class="com.supermap.web.iServerJava2.themeServices.ThemeUniqueItem"/>
	<component id="ThemeUniqueParam" class="com.supermap.web.iServerJava2.themeServices.ThemeUniqueParam"/>

	<!-- editServices -->
	<component id="AddEntityParameters" class="com.supermap.web.iServerJava2.editServices.AddEntityParameters"/>
	<component id="AddEntityService" class="com.supermap.web.iServerJava2.editServices.AddEntityService"/>
	<component id="DeleteEntityParameters" class="com.supermap.web.iServerJava2.editServices.DeleteEntityParameters"/>
	<component id="DeleteEntityService" class="com.supermap.web.iServerJava2.editServices.DeleteEntityService"/>
	<component id="EditResult" class="com.supermap.web.iServerJava2.editServices.EditResult"/>
	<component id="Entity" class="com.supermap.web.iServerJava2.editServices.Entity"/>
	<component id="GetEntityParameters" class="com.supermap.web.iServerJava2.editServices.GetEntityParameters"/>
	<component id="GetEntityService" class="com.supermap.web.iServerJava2.editServices.GetEntityService"/>
	<component id="UpdateEntityParameters" class="com.supermap.web.iServerJava2.editServices.UpdateEntityParameters"/>
	<component id="UpdateEntityService" class="com.supermap.web.iServerJava2.editServices.UpdateEntityService"/>

</componentPackage>


text:
module Viewable
  class PagePresenter < ViewPresenter

    # build page tree from specified root_depth, default second level root with sitemap property to render a sitemap from top root of current page
    def tree(root_depth: 1, sitemap: false, nav_class: 'tree')
      return if m.parent_at_depth(root_depth).nil?
      @sitemap = sitemap
      h.content_tag :nav, class: nav_class do
        h.concat render_tree_master_ul(m.parent_at_depth(root_depth))
      end
    end

    # build page breadcrumbs from specified root_depth, default root
    def breadcrumbs(root_depth: 0, last_page_title: nil, nav_class: 'breadcrumbs', div_class: 'scrollable')
      return if m.parent_at_depth(root_depth).nil?
      h.content_tag :nav, class: nav_class do
        h.concat h.content_tag(:div, breadcrumbs_ul(breadcrumbs_list(root_depth, last_page_title)), class: div_class)
      end
    end

    private

    def breadcrumbs_list(root_depth = 0, last_page_title = nil, page = m)
      pages = []
      while page.present? && page.depth >= root_depth
        pages.unshift(page)
        page = page.parent
      end
      pages.push(OpenStruct.new({title: last_page_title})) if last_page_title.present?
      pages
    end

    def breadcrumbs_ul(pages)
      h.content_tag :ul do
        pages.each do |page|
          h.concat(breadcrumbs_li(page, (pages.last == page)))
        end
      end
    end

    def breadcrumbs_li(page, last_page)
      h.content_tag :li do
        h.concat (page.show_link && !last_page) ? h.link_to(page.title, page.url) : h.content_tag(:span, page.title)
      end
    end

    def render_tree_master_li(page)
      h.content_tag :li do
        h.concat h.content_tag(:span, (@sitemap ? h.link_to(page.title, page.url) : page.title), data: {:'js-drawer-mobile' => true})
        h.concat render_tree_ul_wrapper(page)
      end
    end

    def render_tree_ul_wrapper(page)
      h.content_tag :div do
        page.children.order(:tree_position).each do |child|
          h.concat render_tree_ul(child)
        end if (page.has_children? && (page != m || @sitemap))
      end
    end

    def render_tree_li(page)
      h.content_tag(:li, class: ('active' if (page.subtree.include?(m) && !@sitemap))) do
        if page.show_link?
          h.concat h.link_to(page.title, page.url, class: ('active' if (page == m && !@sitemap)))
        else
          h.concat h.content_tag(:span, page.title, class: '-disable')
        end
        page.children.order(:tree_position).each do |child|
          h.concat render_tree_ul(child)
        end if page.has_children? && (m.ancestors.include?(page) || m.subtree.include?(page) || @sitemap)
      end
    end

    def render_tree_master_ul(page)
      h.content_tag :ul do
        h.concat(render_tree_master_li(page))
      end
    end

    def render_tree_ul(page)
      h.content_tag :ul do
        h.concat(render_tree_li(page))
      end
    end
  end
end


text:
package data_struct.in_class.d09_25;
import java.util.Scanner;

public class PlayingWithShapes {

	/**
	 * @author Eddie Gurnee
	 * @param args
	 */
	public static void main(String[] args) {
		Scanner kb = new Scanner(System.in);

		Shape otherShape = new Shape(5, "blue", true);

		System.out.print("Enter number of sides: ");
		int sides = kb.nextInt();
		System.out.print("Enter color of shape: ");
		String color = kb.next();
		System.out.print("Enter if filled with color [y/n]: ");
		String filled = kb.next();

		Shape myShape = new Shape(sides, color, filled.equalsIgnoreCase("y"));

		System.out.println("\n" + myShape.toString());
		System.out.println(myShape.equals(otherShape));

		Rectangle myRectangle = new Rectangle(4, "blue", true, 5.0, 3.5);
		System.out.println("\n" + myRectangle);

		kb.close();
	}
}