/*
//////////////////////////////////////////////////////////
Stax2, Factory methods
//////////////////////////////////////////////////////////
773325
@Override
    public XMLValidationSchema createSchema(InputStream in, String encoding,
    		String publicId, String systemId)
        throws XMLStreamException
    {
        ReaderConfig rcfg = createPrivateReaderConfig();
        return doCreateSchema(rcfg, StreamBootstrapper.getInstance
        		(publicId, SystemId.construct(systemId), in), publicId, systemId, null);
    }
1153754
function write_obj_str(factory) {
	return function write_str(wb, o) {
		var idx = 0;
		for(var i=0;i<wb.SheetNames.length;++i) if(wb.SheetNames[i] == o.sheet) idx=i;
		if(idx == 0 && !!o.sheet && wb.SheetNames[0] != o.sheet) throw new Error("Sheet not found: " + o.sheet);
		return factory.from_sheet(wb.Sheets[wb.SheetNames[idx]], o, wb);
	};
}
636604
private synchronized static XPathFactory createXPathFactory() {
        XPathFactory factory = null;

        // read system property and see if there is a factory set
        Properties properties = System.getProperties();
        for (Map.Entry<Object, Object> prop : properties.entrySet()) {
            String key = (String) prop.getKey();
            if (key.startsWith(XPathFactory.DEFAULT_PROPERTY_NAME)) {
                String uri = key.indexOf(":") > 0 ? key.substring(key.indexOf(":") + 1) : null;
                if (uri != null) {
                    try {
                        factory = XPathFactory.newInstance(uri);
                    } catch (XPathFactoryConfigurationException e) {
                        log.warn("Failed to instantiate xpath factory", e);
                        factory = XPathFactory.newInstance();
                    }
                    log.info("Created xpath factory {} using system property {} with value {}", factory, key, uri);
                }
            }
        }

        if (factory == null) {
            factory = XPathFactory.newInstance();
            log.info("Created default xpath factory {}", factory);
        }

        return factory;
    }
168733
public static TypeAdapterFactory create() {

    if (geometryTypeFactory == null) {
      geometryTypeFactory = RuntimeTypeAdapterFactory.of(Geometry.class, "type", true)
        .registerSubtype(GeometryCollection.class, "GeometryCollection")
        .registerSubtype(Point.class, "Point")
        .registerSubtype(MultiPoint.class, "MultiPoint")
        .registerSubtype(LineString.class, "LineString")
        .registerSubtype(MultiLineString.class, "MultiLineString")
        .registerSubtype(Polygon.class, "Polygon")
         .registerSubtype(MultiPolygon.class, "MultiPolygon");
    }
    return geometryTypeFactory;
  }
914233
static BaseLongColumnValueSelector makeColumnValueSelectorWithLongDefault(
      final ColumnSelectorFactory metricFactory,
      final ExprMacroTable macroTable,
      @Nullable final String fieldName,
      @Nullable final String fieldExpression,
      final long nullValue
  )
  {
    if ((fieldName == null) == (fieldExpression == null)) {
      throw new IllegalArgumentException("");
    }
    if (fieldName != null) {
      return metricFactory.makeColumnValueSelector(fieldName);
    } else {
      final Expr expr = Parser.parse(fieldExpression, macroTable);
      final ColumnValueSelector<ExprEval> baseSelector = ExpressionSelectors.makeExprEvalSelector(metricFactory, expr);
      class ExpressionLongColumnSelector implements LongColumnSelector
      {
        @Override
        public long getLong()
        {
          final ExprEval exprEval = baseSelector.getObject();
          return exprEval.isNumericNull() ? nullValue : exprEval.asLong();
        }

        @Override
        public void inspectRuntimeShape(RuntimeShapeInspector inspector)
        {
          inspector.visit("baseSelector", baseSelector);
        }

        @Override
        public boolean isNull()
        {
          final ExprEval exprEval = baseSelector.getObject();
          return exprEval == null || exprEval.isNumericNull();
        }
      }
      return new ExpressionLongColumnSelector();
    }
  }
1006337
@Override
  public final synchronized void makeWith(final Map<String, Object> pReqVars,
    final FactoryAndServlet pFactoryAndServlet) throws Exception {
    @SuppressWarnings("unchecked")
    AFactoryAppBeans<RS> factoryAppBeans =
      (AFactoryAppBeans<RS>) pFactoryAndServlet.getFactoryAppBeans();
    File webAppPath = new File(pFactoryAndServlet.getHttpServlet().
      getServletContext().getRealPath(""));
    factoryAppBeans.setWebAppPath(webAppPath.getPath());
    String isShowDebugMessagesStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("isShowDebugMessages");
    factoryAppBeans.setIsShowDebugMessages(Boolean
      .valueOf(isShowDebugMessagesStr));
    String detailLevelStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("detailLevel");
    factoryAppBeans.setDetailLevel(Integer.parseInt(detailLevelStr));
    String newDatabaseIdStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("newDatabaseId");
    factoryAppBeans.setNewDatabaseId(Integer.parseInt(newDatabaseIdStr));
    String ormSettingsDir = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("ormSettingsDir");
    factoryAppBeans.setOrmSettingsDir(ormSettingsDir);
    String ormSettingsBaseFile = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("ormSettingsBaseFile");
    factoryAppBeans.setOrmSettingsBaseFile(ormSettingsBaseFile);
    String uvdSettingsDir = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("uvdSettingsDir");
    factoryAppBeans.setUvdSettingsDir(uvdSettingsDir);
    String uvdSettingsBaseFile = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("uvdSettingsBaseFile");
    factoryAppBeans.setUvdSettingsBaseFile(uvdSettingsBaseFile);
    String writeTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("writeTi");
    factoryAppBeans.setWriteTi(Integer.parseInt(writeTi));
    String readTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("readTi");
    factoryAppBeans.setReadTi(Integer.parseInt(readTi));
    String writeReTi = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("writeReTi");
    factoryAppBeans.setWriteReTi(Integer.parseInt(writeReTi));
    String wrReSpTr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("wrReSpTr");
    factoryAppBeans.setWrReSpTr(Boolean.valueOf(wrReSpTr));
    String fastLoc = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("fastLoc");
    factoryAppBeans.setFastLoc(Boolean.parseBoolean(fastLoc));
    String jdbcUrl = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databaseName");
    if (jdbcUrl != null && jdbcUrl.contains(ASrvOrm.WORD_CURRENT_DIR)) {
      jdbcUrl = jdbcUrl.replace(ASrvOrm.WORD_CURRENT_DIR,
        factoryAppBeans.getWebAppPath() + File.separator);
    } else if (jdbcUrl != null
      && jdbcUrl.contains(ASrvOrm.WORD_CURRENT_PARENT_DIR)) {
      File fcd = new File(factoryAppBeans.getWebAppPath());
      jdbcUrl = jdbcUrl.replace(ASrvOrm.WORD_CURRENT_PARENT_DIR,
        fcd.getParent() + File.separator);
    }
    String langCountriesStr = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("langCountries");
    List<String> lngCntLst = new ArrayList<String>();
    for (String str : langCountriesStr.split(",")) {
      lngCntLst.add(str);
    }
    String[] lngCntArr = new String[lngCntLst.size()];
    factoryAppBeans.lazyGetSrvI18n().add(lngCntLst.toArray(lngCntArr));
    LstnDbChanged<RS> lstnDbChanged = new LstnDbChanged<RS>();
    lstnDbChanged.setFactoryAndServlet(pFactoryAndServlet);
    factoryAppBeans.getListenersDbChanged().add(lstnDbChanged);
    factoryAppBeans.setDatabaseName(jdbcUrl);
    String databaseUser = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databaseUser");
    factoryAppBeans.setDatabaseUser(databaseUser);
    String databasePassword = pFactoryAndServlet.getHttpServlet()
      .getInitParameter("databasePassword");
    factoryAppBeans.setDatabasePassword(databasePassword);
    pFactoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("srvI18n", factoryAppBeans.lazyGet("ISrvI18n"));
    pFactoryAndServlet.getHttpServlet().getServletContext()
      .setAttribute("sessionTracker",
        factoryAppBeans.lazyGet("ISessionTracker"));
    //to create/initialize database if need:
    factoryAppBeans.lazyGet("ISrvOrm");
  }
1362624
@Override
    protected List<Driver> createDrivers(TaskContext taskContext)
    {
        ImmutableList.Builder<OperatorFactory> driversBuilder = ImmutableList.builder();
        driversBuilder.add(ordersTableScan);
        List<Type> sourceTypes = ordersTableTypes;
        OptionalInt hashChannel = OptionalInt.empty();
        if (hashEnabled) {
            driversBuilder.add(createHashProjectOperator(1, new PlanNodeId("test"), sourceTypes));
            sourceTypes = ImmutableList.<Type>builder()
                    .addAll(sourceTypes)
                    .add(BIGINT)
                    .build();
            hashChannel = OptionalInt.of(sourceTypes.size() - 1);
        }

        // hash build
        JoinBridgeManager<PartitionedLookupSourceFactory> lookupSourceFactoryManager = JoinBridgeManager.lookupAllAtOnce(new PartitionedLookupSourceFactory(
                sourceTypes,
                ImmutableList.of(0, 1).stream()
                        .map(sourceTypes::get)
                        .collect(toImmutableList()),
                Ints.asList(0).stream()
                        .map(sourceTypes::get)
                        .collect(toImmutableList()),
                1,
                requireNonNull(ImmutableMap.of(), "layout is null"),
                false));
        HashBuilderOperatorFactory hashBuilder = new HashBuilderOperatorFactory(
                2,
                new PlanNodeId("test"),
                lookupSourceFactoryManager,
                ImmutableList.of(0, 1),
                Ints.asList(0),
                hashChannel,
                Optional.empty(),
                Optional.empty(),
                ImmutableList.of(),
                1_500_000,
                new PagesIndex.TestingFactory(false),
                false,
                SingleStreamSpillerFactory.unsupportedSingleStreamSpillerFactory());
        driversBuilder.add(hashBuilder);
        DriverFactory hashBuildDriverFactory = new DriverFactory(0, true, false, driversBuilder.build(), OptionalInt.empty(), UNGROUPED_EXECUTION);

        // join
        ImmutableList.Builder<OperatorFactory> joinDriversBuilder = ImmutableList.builder();
        joinDriversBuilder.add(lineItemTableScan);
        sourceTypes = lineItemTableTypes;
        hashChannel = OptionalInt.empty();
        if (hashEnabled) {
            joinDriversBuilder.add(createHashProjectOperator(1, new PlanNodeId("test"), sourceTypes));
            sourceTypes = ImmutableList.<Type>builder()
                    .addAll(sourceTypes)
                    .add(BIGINT)
                    .build();
            hashChannel = OptionalInt.of(sourceTypes.size() - 1);
        }

        OperatorFactory joinOperator = LOOKUP_JOIN_OPERATORS.innerJoin(
                2,
                new PlanNodeId("test"),
                lookupSourceFactoryManager,
                sourceTypes,
                Ints.asList(0),
                hashChannel,
                Optional.empty(),
                OptionalInt.empty(),
                unsupportedPartitioningSpillerFactory());
        joinDriversBuilder.add(joinOperator);
        joinDriversBuilder.add(new NullOutputOperatorFactory(3, new PlanNodeId("test")));
        DriverFactory joinDriverFactory = new DriverFactory(1, true, true, joinDriversBuilder.build(), OptionalInt.empty(), UNGROUPED_EXECUTION);

        Driver hashBuildDriver = hashBuildDriverFactory.createDriver(taskContext.addPipelineContext(0, true, false, false).addDriverContext());
        hashBuildDriverFactory.noMoreDrivers();
        Driver joinDriver = joinDriverFactory.createDriver(taskContext.addPipelineContext(1, true, true, false).addDriverContext());
        joinDriverFactory.noMoreDrivers();

        return ImmutableList.of(hashBuildDriver, joinDriver);
    }
119179
public Option xAxis(Axis... values) {
        if (values == null || values.length == 0) {
            return this;
        }
        if (this.xAxis().size() == 2) {
            throw new RuntimeException("xAxis已经存在2个，无法继续添加!");
        }
        if (this.xAxis().size() + values.length > 2) {
            throw new RuntimeException("添加的xAxis超出了最大允许的范围:2!");
        }
        this.xAxis().addAll(Arrays.asList(values));
        return this;
    }
310870
static SelectTraceIdsFromSpan.Factory initialiseSelectTraceIdsFromSpan(Session session) {
    try {
      return new SelectTraceIdsFromSpan.Factory(session);
    } catch (DriverException ex) {
      LOG.warn("failed to prepare annotation_query index statements: " + ex.getMessage());
      return null;
    }
  }
261330
static double usingXAndYTables(final double[] xArr, final double[] yArr,
      final double x) {
    assert (xArr.length >= 4) && (xArr.length == yArr.length);
    if ((x < xArr[0]) || (x > xArr[xArr.length - 1])) {
      throw new SketchesArgumentException("X value out of range: " + x);
    }
    if (x == xArr[xArr.length - 1]) {
      return yArr[yArr.length - 1]; // corner case
    }
    final int offset = findStraddle(xArr, x); //uses recursion
    assert (offset >= 0) && (offset <= (xArr.length - 2));
    if (offset == 0) {
      return interpolateUsingXAndYTables(xArr, yArr, offset, x); // corner case
    }
    if (offset == (xArr.length - 2)) {
      return interpolateUsingXAndYTables(xArr, yArr, offset - 2, x); // corner case
    }
    return interpolateUsingXAndYTables(xArr, yArr, offset - 1, x);
  }
1003774
@ExperimentalApi("https://github.com/grpc/grpc-java/issues/2861")
  public CallOptions withStreamTracerFactory(ClientStreamTracer.Factory factory) {
    CallOptions newOptions = new CallOptions(this);
    ArrayList<ClientStreamTracer.Factory> newList =
        new ArrayList<>(streamTracerFactories.size() + 1);
    newList.addAll(streamTracerFactories);
    newList.add(factory);
    newOptions.streamTracerFactories = Collections.unmodifiableList(newList);
    return newOptions;
  }
942500
public static void main(String[] args) throws TransformerConfigurationException, SAXException{
        XSDocument xsd = new XSDocument(new StreamResult(System.out), false, 4, null);
        xsd.startDocument();
        {
            String n1 = "http://www.example.com/N1";
            String n2 = "http://www.example.com/N2";
            xsd.xml().declarePrefix("n1", n1);
            xsd.xml().declarePrefix("n2", n2);
            xsd.startSchema(n1);
            {
                xsd.addImport(n2, "imports/b.xsd");
                xsd.startComplexType().name("MyType");
                {
                    xsd.startCompositor(Compositor.SEQUENCE);
                    xsd.startElement().ref(n1, "e1").endElement();
                    xsd.endCompositor();
                }
                xsd.endComplexType();
                xsd.startElement().name("root").type(n1, "MyType").endElement();
            }
            xsd.endSchema();
        }
        xsd.endDocument();
    }
765746
@Override
    public LazyData createGenotypeMap(String str, List<Allele> alleles, String chr, int pos) {
        if (genotypeParts == null) {
            genotypeParts = new String[header.getColumnCount() - NUM_STANDARD_FIELDS];
        }

        int nParts = ParsingUtils.split(str, genotypeParts, VCFConstants.FIELD_SEPARATOR_CHAR);
        if (nParts != genotypeParts.length) {
            generateException("there are " + (nParts - 1)
                    + " genotypes while the header requires that " + (genotypeParts.length - 1)
                    + " genotypes be present for all records at " + chr + ":" + pos, lineNo);
        }

        ArrayList<Genotype> genotypes = new ArrayList<>(nParts);
        // get the format keys
        List<String> genotypeKeys = ParsingUtils.split(genotypeParts[0], VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR);

        // cycle through the sample names
        Iterator<String> sampleNameIterator = header.getGenotypeSamples().iterator();

        // clear out our allele mapping
        alleleMap.clear();

        // cycle through the genotype strings
        for (int genotypeOffset = 1; genotypeOffset < nParts; genotypeOffset++) {
            List<String> genotypeValues = ParsingUtils.split(genotypeParts[genotypeOffset], VCFConstants.GENOTYPE_FIELD_SEPARATOR_CHAR);

            final String sampleName = sampleNameIterator.next();
            final GenotypeBuilder gb = new GenotypeBuilder(sampleName);

            // check to see if the value list is longer than the key list, which is a problem
            if (genotypeKeys.size() < genotypeValues.size()) {
                generateException("There are too many keys for the sample " + sampleName + ", "
                        + "keys = " + parts[8] + ", "
                        + "values = " + parts[genotypeOffset]);
            }

            int genotypeAlleleLocation = -1;
            if (!genotypeKeys.isEmpty()) {
                gb.maxAttributes(genotypeKeys.size() - 1);


                for (int i = 0; i < genotypeKeys.size(); i++) {
                    final String gtKey = genotypeKeys.get(i);
                    boolean missing = i >= genotypeValues.size();

                    // todo -- all of these on the fly parsing of the missing value should be static constants
                    if (gtKey.equals(VCFConstants.GENOTYPE_KEY)) {
                        genotypeAlleleLocation = i;
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, genotypeValues.get(i));
                    } else if (missing) {
                        // if its truly missing (there no provided value) skip adding it to the attributes
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, null);
                    } else if (gtKey.equals(VCFConstants.GENOTYPE_FILTER_KEY)) {
                        final List<String> filters = parseFilters(getCachedString(genotypeValues.get(i)));
                        if (filters != null) {
                            gb.filters(filters);
                        }
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, filters);
                    } else if (genotypeValues.get(i).equals(VCFConstants.MISSING_VALUE_v4)) {
                        // don't add missing values to the map
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, null);
                    } else {
                        if (gtKey.equals(VCFConstants.GENOTYPE_QUALITY_KEY)) {
                            if (genotypeValues.get(i).equals(VCFConstants.MISSING_GENOTYPE_QUALITY_v3)) {
                                gb.noGQ();
                            } else {
                                gb.GQ((int)Math.round(Double.valueOf(genotypeValues.get(i))));
                            }
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_ALLELE_DEPTHS)) {
                            gb.AD(decodeInts(genotypeValues.get(i)));
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_PL_KEY)) {
                            gb.PL(decodeInts(genotypeValues.get(i)));
                        } else if (gtKey.equals(VCFConstants.GENOTYPE_LIKELIHOODS_KEY)) {
                            gb.PL(GenotypeLikelihoods.fromGLField(genotypeValues.get(i)).getAsPLs());
                        } else if (gtKey.equals(VCFConstants.DEPTH_KEY)) {
                            gb.DP(Integer.valueOf(genotypeValues.get(i)));
                        }
                        // opencb modification: add ALL the fields to the attributes. null for missing values!
                        gb.attribute(gtKey, genotypeValues.get(i));
                    }
                }
            }

            // check to make sure we found a genotype field if our version is less than 4.1 file
            if (!version.isAtLeastAsRecentAs(VCFHeaderVersion.VCF4_1) && genotypeAlleleLocation == -1) {
                generateException("Unable to find the GT field for the record; the GT field is required before VCF4.1");
            }
            if (genotypeAlleleLocation > 0) {
                generateException("Saw GT field at position "
                        + genotypeAlleleLocation + ", but it must be at the first position for genotypes when present");
            }

            final List<Allele> gTalleles = (genotypeAlleleLocation == -1
                    ? new ArrayList<>(0)
                    : parseGenotypeAlleles(genotypeValues.get(genotypeAlleleLocation), alleles, alleleMap));
            gb.alleles(gTalleles);
            gb.phased(genotypeAlleleLocation != -1
                    && genotypeValues.get(genotypeAlleleLocation).indexOf(VCFConstants.PHASED) != -1);

            // add it to the list
            try {
                genotypes.add(gb.make());
            } catch (TribbleException e) {
                throw new TribbleException.InternalCodecException(e.getMessage() + ", at position " + chr + ":" + pos);
            }
        }

        return new LazyGenotypesContext.LazyData(genotypes, header.getSampleNamesInOrder(), header.getSampleNameToOffset());
    }
83636
@SuppressWarnings("unchecked")
	public <T> T createInstance(Object arg0, Method arg1, Object[] arg2, MethodProxy arg3) 
			throws FMSException {
		Object obj = null;
		Class<?> type = arg1.getReturnType();
		if (String.class.equals(type)) {
			obj = null;
		} else if (Integer.class.equals(type) || int.class.equals(type)) {
			obj = Integer.valueOf(0);
		} else if (Byte.class.equals(type) || byte.class.equals(type)) {
			obj = Integer.valueOf(0);
		} else if (java.util.Date.class.equals(type)) {
			obj = new Date();
		} else if (java.sql.Timestamp.class.equals(type)) {
			obj = new Timestamp(System.currentTimeMillis());
		} else if (java.sql.Date.class.equals(type)) {
			obj = new java.sql.Date(System.currentTimeMillis());
		} else if (java.sql.Time.class.equals(type)) {
			obj = new java.sql.Time(System.currentTimeMillis());
		} else if (Long.class.equals(type) || long.class.equals(type)) {
			obj = Long.valueOf(0);
		} else if (Short.class.equals(type) || short.class.equals(type)) {
			obj = Short.valueOf("0");
		} else if (Double.class.equals(type) || double.class.equals(type)) {
			obj = Double.valueOf(0);
		} else if (Float.class.equals(type) || float.class.equals(type)) {
			obj = Float.valueOf(0);
		} else if (BigInteger.class.equals(type)) {
			obj = BigInteger.valueOf(0);
		} else if (BigDecimal.class.equals(type)) {
			obj = BigDecimal.valueOf(0);
		} else if (Boolean.class.equals(type) || boolean.class.equals(type)) {
			obj = Boolean.TRUE;
		} else if (List.class.isAssignableFrom(type)) {
			try {
				Type t = arg1.getGenericReturnType();
				Object value = getObject(t);
				Object queryValue = GenerateQuery.createQueryEntity(value);
				obj = arg3.invokeSuper(arg0, arg2);
				((List<Object>) obj).add(queryValue);
			} catch (Throwable t) {
				throw new FMSException(t);
			}
		} else if (Enum.class.isAssignableFrom(type)) {
			LOG.debug("Create instance for Enum");
			// Create EnumObject
		} else if (type.isArray()) {
			// Create ArrayObject
			LOG.debug("Create instance for Array Object");
		} else if (!Modifier.isFinal(type.getModifiers())) {
			obj = GenerateQuery.createQueryEntity(type);
		} else {
			obj = null;
		}
		return (T) obj;
	}
808926
private E createUsingConstructor() throws CheckedAnalysisException {
        Constructor<E> constructor;
        try {
            constructor = databaseClass.getConstructor(new Class[0]);
        } catch (NoSuchMethodException e) {
            return null;
        }

        try {
            return constructor.newInstance(new Object[0]);
        } catch (InstantiationException e) {
            throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
        } catch (IllegalAccessException e) {
            throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
        } catch (InvocationTargetException e) {
            throw new CheckedAnalysisException("Could not create " + databaseClass.getName(), e);
        }
    }
931978
function createPlatformFactory(parentPlatformFactory, name, providers) {
    if (providers === void 0) { providers = []; }
    var desc = "Platform: " + name;
    var marker = new InjectionToken(desc);
    return function (extraProviders) {
        if (extraProviders === void 0) { extraProviders = []; }
        var platform = getPlatform();
        if (!platform || platform.injector.get(ALLOW_MULTIPLE_PLATFORMS, false)) {
            if (parentPlatformFactory) {
                parentPlatformFactory(providers.concat(extraProviders).concat({ provide: marker, useValue: true }));
            }
            else {
                var injectedProviders = providers.concat(extraProviders).concat({ provide: marker, useValue: true });
                createPlatform(Injector.create({ providers: injectedProviders, name: desc }));
            }
        }
        return assertPlatform(marker);
    };
}
510073
function forceAtlas2Worker() {
    var vec2 = {
        create: function() {
            return new Float32Array(2);
        },
        dist: function(a, b) {
            var x = b[0] - a[0];
            var y = b[1] - a[1];
            return Math.sqrt(x*x + y*y);
        },
        len: function(a) {
            var x = a[0];
            var y = a[1];
            return Math.sqrt(x*x + y*y);
        },
        scaleAndAdd: function(out, a, b, scale) {
            out[0] = a[0] + b[0] * scale;
            out[1] = a[1] + b[1] * scale;
            return out;
        },
        scale: function(out, a, b) {
            out[0] = a[0] * b;
            out[1] = a[1] * b;
            return out;
        },
        add: function(out, a, b) {
            out[0] = a[0] + b[0];
            out[1] = a[1] + b[1];
            return out;
        },
        sub: function(out, a, b) {
            out[0] = a[0] - b[0];
            out[1] = a[1] - b[1];
            return out;
        },
        normalize: function(out, a) {
            var x = a[0];
            var y = a[1];
            var len = x*x + y*y;
            if (len > 0) {
                //TODO: evaluate use of glm_invsqrt here?
                len = 1 / Math.sqrt(len);
                out[0] = a[0] * len;
                out[1] = a[1] * len;
            }
            return out;
        },
        negate: function(out, a) {
            out[0] = -a[0];
            out[1] = -a[1];
            return out;
        },
        copy: function(out, a) {
            out[0] = a[0];
            out[1] = a[1];
            return out;
        },
        set: function(out, x, y) {
            out[0] = x;
            out[1] = y;
            return out;
        }
    }

    /****************************
     * Class: Region
     ***************************/

    function Region() {

        this.subRegions = [];

        this.nSubRegions = 0;

        this.node = null;

        this.mass = 0;

        this.centerOfMass = null;

        this.bbox = new Float32Array(4);

        this.size = 0;
    }

    var regionProto = Region.prototype;

    // Reset before update
    regionProto.beforeUpdate = function() {
        for (var i = 0; i < this.nSubRegions; i++) {
            this.subRegions[i].beforeUpdate();
        }
        this.mass = 0;
        if (this.centerOfMass) {
            this.centerOfMass[0] = 0;
            this.centerOfMass[1] = 0;
        }
        this.nSubRegions = 0;
        this.node = null;
    };
    // Clear after update
    regionProto.afterUpdate = function() {
        this.subRegions.length = this.nSubRegions;
        for (var i = 0; i < this.nSubRegions; i++) {
            this.subRegions[i].afterUpdate();
        }
    };

    regionProto.addNode = function(node) {
        if (this.nSubRegions === 0) {
            if (this.node == null) {
                this.node = node;
                return;
            }
            // Already have node, subdivide self.
            else {
                this._addNodeToSubRegion(this.node);
                this.node = null;
            }
        }
        this._addNodeToSubRegion(node);

        this._updateCenterOfMass(node);
    };

    regionProto.findSubRegion = function(x, y) {
        for (var i = 0; i < this.nSubRegions; i++) {
            var region = this.subRegions[i];
            if (region.contain(x, y)) {
                return region;
            }
        }
    };

    regionProto.contain = function(x, y) {
        return this.bbox[0] <= x
            && this.bbox[2] >= x
            && this.bbox[1] <= y
            && this.bbox[3] >= y;
    };

    regionProto.setBBox = function(minX, minY, maxX, maxY) {
        // Min
        this.bbox[0] = minX;
        this.bbox[1] = minY;
        // Max
        this.bbox[2] = maxX;
        this.bbox[3] = maxY;

        this.size = (maxX - minX + maxY - minY) / 2;
    };

    regionProto._newSubRegion = function() {
        var subRegion = this.subRegions[this.nSubRegions];
        if (!subRegion) {
            subRegion = new Region();
            this.subRegions[this.nSubRegions] = subRegion;
        }
        this.nSubRegions++;
        return subRegion;
    };

    regionProto._addNodeToSubRegion = function(node) {
        var subRegion = this.findSubRegion(node.position[0], node.position[1]);
        var bbox = this.bbox;
        if (!subRegion) {
            var cx = (bbox[0] + bbox[2]) / 2;
            var cy = (bbox[1] + bbox[3]) / 2;
            var w = (bbox[2] - bbox[0]) / 2;
            var h = (bbox[3] - bbox[1]) / 2;

            var xi = node.position[0] >= cx ? 1 : 0;
            var yi = node.position[1] >= cy ? 1 : 0;

            var subRegion = this._newSubRegion();
            // Min
            subRegion.setBBox(
                // Min
                xi * w + bbox[0],
                yi * h + bbox[1],
                // Max
                (xi + 1) * w + bbox[0],
                (yi + 1) * h + bbox[1]
            );
        }

        subRegion.addNode(node);
    };

    regionProto._updateCenterOfMass = function(node) {
        // Incrementally update
        if (this.centerOfMass == null) {
            this.centerOfMass = new Float32Array(2);
        }
        var x = this.centerOfMass[0] * this.mass;
        var y = this.centerOfMass[1] * this.mass;
        x += node.position[0] * node.mass;
        y += node.position[1] * node.mass;
        this.mass += node.mass;
        this.centerOfMass[0] = x / this.mass;
        this.centerOfMass[1] = y / this.mass;
    };

    /****************************
     * Class: Graph Node
     ***************************/
    function GraphNode() {
        this.position = new Float32Array(2);

        this.force = vec2.create();
        this.forcePrev = vec2.create();

        // If repulsionByDegree is true
        //  mass = inDegree + outDegree + 1
        // Else
        //  mass is manually set
        this.mass = 1;

        this.inDegree = 0;
        this.outDegree = 0;

        // Optional
        // this.size = 1;
    }

    /****************************
     * Class: Graph Edge
     ***************************/
    function GraphEdge(source, target) {
        this.source = source;
        this.target = target;

        this.weight = 1;
    }

    /****************************
     * Class: ForceStlas2
     ***************************/
    function ForceAtlas2() {
        //-------------
        // Configs

        // If auto settings is true
        //  barnesHutOptimize,
        //  barnesHutTheta,
        //  scaling,
        //  jitterTolerence
        // Will be set by the system automatically
        //  preventOverlap will be set false
        //  if node size is not given
        this.autoSettings = true;

        // Barnes Hut
        // http://arborjs.org/docs/barnes-hut
        this.barnesHutOptimize = true;
        this.barnesHutTheta = 1.5;

        // Force Atlas2 Configs
        this.repulsionByDegree = true;

        this.linLogMode = false;

        this.strongGravityMode = false;
        this.gravity = 1.0;

        this.scaling = 1.0;

        this.edgeWeightInfluence = 1.0;
        this.jitterTolerence = 0.1;

        // TODO
        this.preventOverlap = false;
        this.dissuadeHubs = false;

        //
        this.rootRegion = new Region();
        this.rootRegion.centerOfMass = vec2.create();

        this.nodes = [];

        this.edges = [];

        this.bbox = new Float32Array(4);

        this.gravityCenter = null;

        this._massArr = null;

        this._swingingArr = null;

        this._sizeArr = null;

        this._globalSpeed = 0;
    }

    var forceAtlas2Proto = ForceAtlas2.prototype;

    forceAtlas2Proto.initNodes = function(positionArr, massArr, sizeArr) {
        var nNodes = massArr.length;
        this.nodes.length = 0;
        var haveSize = typeof(sizeArr) != 'undefined';
        for (var i = 0; i < nNodes; i++) {
            var node = new GraphNode();
            node.position[0] = positionArr[i * 2];
            node.position[1] = positionArr[i * 2 + 1];
            node.mass = massArr[i];
            if (haveSize) {
                node.size = sizeArr[i];
            }
            this.nodes.push(node);
        }

        this._massArr = massArr;
        this._swingingArr = new Float32Array(nNodes);

        if (haveSize) {
            this._sizeArr = sizeArr;
        }
    };

    forceAtlas2Proto.initEdges = function(edgeArr, edgeWeightArr) {
        var nEdges = edgeArr.length / 2;
        this.edges.length = 0;
        for (var i = 0; i < nEdges; i++) {
            var sIdx = edgeArr[i * 2];
            var tIdx = edgeArr[i * 2 + 1];
            var sNode = this.nodes[sIdx];
            var tNode = this.nodes[tIdx];

            if (!sNode || !tNode) {
                console.error('Node not exists, try initNodes before initEdges');
                return;
            }
            sNode.outDegree++;
            tNode.inDegree++;
            var edge = new GraphEdge(sNode, tNode);

            if (edgeWeightArr) {
                edge.weight = edgeWeightArr[i];
            }

            this.edges.push(edge);
        }
    }

    forceAtlas2Proto.updateSettings = function() {
        if (this.repulsionByDegree) {
            for (var i = 0; i < this.nodes.length; i++) {
                var node = this.nodes[i];
                node.mass = node.inDegree + node.outDegree + 1;
            }
        }
        else {
            for (var i = 0; i < this.nodes.length; i++) {
                var node = this.nodes[i];
                node.mass = this._massArr[i];
            }
        }
    };

    forceAtlas2Proto.update = function() {
        var nNodes = this.nodes.length;

        this.updateSettings();

        this.updateBBox();

        // Update region
        if (this.barnesHutOptimize) {
            this.rootRegion.setBBox(
                this.bbox[0], this.bbox[1],
                this.bbox[2], this.bbox[3]
            );

            this.rootRegion.beforeUpdate();
            for (var i = 0; i < nNodes; i++) {
                this.rootRegion.addNode(this.nodes[i]);
            }
            this.rootRegion.afterUpdate();
        }

        // Reset forces
        for (var i = 0; i < nNodes; i++) {
            var node = this.nodes[i];
            vec2.copy(node.forcePrev, node.force);
            vec2.set(node.force, 0, 0);
        }

        // Compute forces
        // Repulsion
        for (var i = 0; i < nNodes; i++) {
            var na = this.nodes[i];
            if (this.barnesHutOptimize) {
                this.applyRegionToNodeRepulsion(this.rootRegion, na);
            }
            else {
                for (var j = i + 1; j < nNodes; j++) {
                    var nb = this.nodes[j];
                    this.applyNodeToNodeRepulsion(na, nb, false);
                }
            }

            // Gravity
            if (this.gravity > 0) {
                if (this.strongGravityMode) {
                    this.applyNodeStrongGravity(na);
                }
                else {
                    this.applyNodeGravity(na);
                }
            }
        }

        // Attraction
        for (var i = 0; i < this.edges.length; i++) {
            this.applyEdgeAttraction(this.edges[i]);
        }

        // Handle swinging
        var swingWeightedSum = 0;
        var tractionWeightedSum = 0;
        var tmp = vec2.create();
        for (var i = 0; i < nNodes; i++) {
            var node = this.nodes[i];
            var swing = vec2.dist(node.force, node.forcePrev);
            swingWeightedSum += swing * node.mass;

            vec2.add(tmp, node.force, node.forcePrev);
            var traction = vec2.len(tmp) * 0.5;
            tractionWeightedSum += traction * node.mass;

            // Save the value for using later
            this._swingingArr[i] = swing;
        }
        var globalSpeed = this.jitterTolerence * this.jitterTolerence
                        * tractionWeightedSum / swingWeightedSum;
        // NB: During our tests we observed that an excessive rise of the global speed could have a negative impact.
        // That’s why we limited the increase of global speed s(t)(G) to 50% of the previous step s(t−1)(G).
        if (this._globalSpeed > 0) {
            globalSpeed = Math.min(globalSpeed / this._globalSpeed, 1.5) * this._globalSpeed;
        }
        this._globalSpeed = globalSpeed;

        // Apply forces
        for (var i = 0; i < nNodes; i++) {
            var node = this.nodes[i];
            var swing = this._swingingArr[i];

            var speed = 0.1 * globalSpeed / (1 + globalSpeed * Math.sqrt(swing));

            // Additional constraint to prevent local speed gets too high
            var df = vec2.len(node.force);
            if (df > 0) {
                speed = Math.min(df * speed, 10) / df;
                vec2.scaleAndAdd(node.position, node.position, node.force, speed);
            }
        }
    };

    forceAtlas2Proto.applyRegionToNodeRepulsion = (function() {
        var v = vec2.create();
        return function applyRegionToNodeRepulsion(region, node) {
            if (region.node) { // Region is a leaf
                this.applyNodeToNodeRepulsion(region.node, node, true);
            }
            else {
                vec2.sub(v, node.position, region.centerOfMass);
                var d2 = v[0] * v[0] + v[1] * v[1];
                if (d2 > this.barnesHutTheta * region.size * region.size) {
                    var factor = this.scaling * node.mass * region.mass / d2;
                    vec2.scaleAndAdd(node.force, node.force, v, factor);
                }
                else {
                    for (var i = 0; i < region.nSubRegions; i++) {
                        this.applyRegionToNodeRepulsion(region.subRegions[i], node);
                    }
                }
            }
        }
    })();

    forceAtlas2Proto.applyNodeToNodeRepulsion = (function() {
        var v = vec2.create();
        return function applyNodeToNodeRepulsion(na, nb, oneWay) {
            if (na == nb) {
                return;
            }
            vec2.sub(v, na.position, nb.position);
            var d2 = v[0] * v[0] + v[1] * v[1];

            // PENDING
            if (d2 === 0) {
                return;
            }

            var factor;
            if (this.preventOverlap) {
                var d = Math.sqrt(d2);
                d = d - na.size - nb.size;
                if (d > 0) {
                    factor = this.scaling * na.mass * nb.mass / (d * d);
                }
                else if (d < 0) {
                    // A stronger repulsion if overlap
                    factor = this.scaling * 100 * na.mass * nb.mass;
                }
                else {
                    // No repulsion
                    return;
                }
            }
            else {
                // Divide factor by an extra `d` to normalize the `v`
                factor = this.scaling * na.mass * nb.mass / d2;
            }

            vec2.scaleAndAdd(na.force, na.force, v, factor);
            vec2.scaleAndAdd(nb.force, nb.force, v, -factor);
        }
    })();

    forceAtlas2Proto.applyEdgeAttraction = (function() {
        var v = vec2.create();
        return function applyEdgeAttraction(edge) {
            var na = edge.source;
            var nb = edge.target;

            vec2.sub(v, na.position, nb.position);
            var d = vec2.len(v);

            var w;
            if (this.edgeWeightInfluence === 0) {
                w = 1;
            }
            else if (this.edgeWeightInfluence === 1) {
                w = edge.weight;
            }
            else {
                w = Math.pow(edge.weight, this.edgeWeightInfluence);
            }

            var factor;

            if (this.preventOverlap) {
                d = d - na.size - nb.size;
                if (d <= 0) {
                    // No attraction
                    return;
                }
            }

            if (this.linLogMode) {
                // Divide factor by an extra `d` to normalize the `v`
                factor = - w * Math.log(d + 1) / (d + 1);
            }
            else {
                factor = - w;
            }
            vec2.scaleAndAdd(na.force, na.force, v, factor);
            vec2.scaleAndAdd(nb.force, nb.force, v, -factor);
        }
    })();

    forceAtlas2Proto.applyNodeGravity = (function() {
        var v = vec2.create();
        return function(node) {
            vec2.sub(v, this.gravityCenter, node.position);
            var d = vec2.len(v);
            vec2.scaleAndAdd(node.force, node.force, v, this.gravity * node.mass / (d + 1));
        }
    })();

    forceAtlas2Proto.applyNodeStrongGravity = (function() {
        var v = vec2.create();
        return function(node) {
            vec2.sub(v, this.gravityCenter, node.position);
            vec2.scaleAndAdd(node.force, node.force, v, this.gravity * node.mass);
        }
    })();

    forceAtlas2Proto.updateBBox = function() {
        var minX = Infinity;
        var minY = Infinity;
        var maxX = -Infinity;
        var maxY = -Infinity;
        for (var i = 0; i < this.nodes.length; i++) {
            var pos = this.nodes[i].position;
            minX = Math.min(minX, pos[0]);
            minY = Math.min(minY, pos[1]);
            maxX = Math.max(maxX, pos[0]);
            maxY = Math.max(maxY, pos[1]);
        }
        this.bbox[0] = minX;
        this.bbox[1] = minY;
        this.bbox[2] = maxX;
        this.bbox[3] = maxY;
    };

    forceAtlas2Proto.getGlobalSpeed = function () {
        return this._globalSpeed;
    }

    /****************************
     * Main process
     ***************************/

    var forceAtlas2 = null;

    self.onmessage = function(e) {
        switch(e.data.cmd) {
            case 'init':
                forceAtlas2 = new ForceAtlas2();
                forceAtlas2.initNodes(e.data.nodesPosition, e.data.nodesMass, e.data.nodesSize);
                forceAtlas2.initEdges(e.data.edges, e.data.edgesWeight);
                break;
            case 'updateConfig':
                if (forceAtlas2) {
                    for (var name in e.data.config) {
                        forceAtlas2[name] = e.data.config[name];
                    }
                }
                break;
            case 'update':
                var steps = e.data.steps;
                if (forceAtlas2) {
                    for (var i = 0; i < steps; i++) {
                        forceAtlas2.update();
                    }

                    var nNodes = forceAtlas2.nodes.length;
                    var positionArr = new Float32Array(nNodes * 2);
                    // Callback
                    for (var i = 0; i < nNodes; i++) {
                        var node = forceAtlas2.nodes[i];
                        positionArr[i * 2] = node.position[0];
                        positionArr[i * 2 + 1] = node.position[1];
                    }
                    self.postMessage({
                        buffer: positionArr.buffer,
                        globalSpeed: forceAtlas2.getGlobalSpeed()
                    }, [positionArr.buffer]);
                }
                else {
                    // Not initialzied yet
                    var emptyArr = new Float32Array();
                    // Post transfer object
                    self.postMessage({
                        buffer: emptyArr.buffer,
                        globalSpeed: forceAtlas2.getGlobalSpeed()
                    }, [emptyArr.buffer]);
                }
                break;
        }
    }
}