code
stringlengths
4
1.01M
language
stringclasses
2 values
/** * Copyright (c) 2010 RedEngine Ltd, http://www.redengine.co.nz. All rights reserved. * * This program is licensed to you under the Apache License Version 2.0, * and you may not use this file except in compliance with the Apache License Version 2.0. * You may obtain a copy of the Apache License Version 2.0 at http://www.apache.org/licenses/LICENSE-2.0. * * Unless required by applicable law or agreed to in writing, * software distributed under the Apache License Version 2.0 is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Apache License Version 2.0 for the specific language governing permissions and limitations there under. */ package net.stickycode.deploy.sample.helloworld; public class HelloWorld implements Runnable { public void hello() { System.out.println("Hello World!"); } @Override public void run() { System.out.println("Hello Embedded World!"); try { Thread.sleep(5000); } catch (InterruptedException e) { throw new RuntimeException(e); } } }
Java
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Kafka.Tests")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Kafka.Tests")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("66f1ff2f-b823-4438-89ce-5cbb46893242")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: InternalsVisibleTo("Kafka.Console")] [assembly: log4net.Config.XmlConfigurator(Watch = true)]
Java
<include file='public:header'/> <div class="mainBt"> <ul> <li class="li1">系统</li> <li class="li2">数据库</li> <li class="li2 li3">数据库还原</li> </ul> </div> <div class="main-jsgl"> <p class="attention"><span>注意:</span>谨慎操作!</p> <div class="jsglNr"> <div class="selectNr"> <div class="left"> <a href="<{:U('database/index')}>">备份数据库</a> </div> <div class="right"> </div> </div> <form id="export-form" target="baocms_frm" method="post" action="<{:U('export')}>"> <div class="tableBox"> <table bordercolor="#e1e6eb" cellspacing="0" width="100%" border="1px" style=" border-collapse: collapse; margin:0px; vertical-align:middle; background-color:#FFF;" > <tr> <td>备份名称</td> <td>卷数</td> <td>压缩</td> <td>数据大小</td> <td>备份时间</td> <td>状态</th> <td>操作</td> </tr> <volist name="list" id="data"> <tr> <td><{$data.time|date='Ymd-His',###}></td> <td><{$data.part}></td> <td><{$data.compress}></td> <td><{$data.size|format_bytes}></td> <td><{$key}></td> <td>-</td> <td class="action"> <a class="db-import" href="<{:U('import?time='.$data['time'])}>">还原</a>&nbsp; <a class="ajax-get confirm" href="<{:U('del?time='.$data['time'])}>">删除</a> </td> </tr> </volist> </table> <{$page}> </div> </form> </div> </div> <script type="text/javascript"> $(".db-import").click(function(){ var self = this, status = "."; $.get(self.href, success, "json"); window.onbeforeunload = function(){ return "正在还原数据库,请不要关闭!" } return false; function success(data){ if(data.status){ if(data.gz){ data.info += status; if(status.length === 5){ status = "."; } else { status += "."; } } $(self).parent().prev().text(data.info); if(data.part){ $.get(self.href, {"part" : data.part, "start" : data.start}, success, "json" ); } else { window.onbeforeunload = function(){ return null; } } } else { alert(data.info); } } }); </script>
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.shardingsphere.parser.rule; import lombok.Getter; import org.apache.shardingsphere.infra.rule.identifier.scope.GlobalRule; import org.apache.shardingsphere.parser.config.SQLParserRuleConfiguration; import org.apache.shardingsphere.sql.parser.api.CacheOption; /** * SQL parser rule. */ @Getter public final class SQLParserRule implements GlobalRule { private final boolean sqlCommentParseEnabled; private final CacheOption sqlStatementCache; private final CacheOption parseTreeCache; public SQLParserRule(final SQLParserRuleConfiguration ruleConfig) { sqlCommentParseEnabled = ruleConfig.isSqlCommentParseEnabled(); sqlStatementCache = ruleConfig.getSqlStatementCache(); parseTreeCache = ruleConfig.getParseTreeCache(); } @Override public String getType() { return SQLParserRule.class.getSimpleName(); } }
Java
package org.locationtech.geomesa.core.process.proximity import com.typesafe.scalalogging.slf4j.Logging import com.vividsolutions.jts.geom.GeometryFactory import org.geotools.data.Query import org.geotools.data.simple.{SimpleFeatureCollection, SimpleFeatureSource} import org.geotools.data.store.ReTypingFeatureCollection import org.geotools.factory.CommonFactoryFinder import org.geotools.feature.DefaultFeatureCollection import org.geotools.feature.visitor.{AbstractCalcResult, CalcResult, FeatureCalc} import org.geotools.process.factory.{DescribeParameter, DescribeProcess, DescribeResult} import org.geotools.util.NullProgressListener import org.locationtech.geomesa.core.data.AccumuloFeatureCollection import org.locationtech.geomesa.utils.geotools.Conversions._ import org.opengis.feature.Feature import org.opengis.feature.simple.SimpleFeature import org.opengis.filter.Filter @DescribeProcess( title = "Geomesa-enabled Proximity Search", description = "Performs a proximity search on a Geomesa feature collection using another feature collection as input" ) class ProximitySearchProcess extends Logging { @DescribeResult(description = "Output feature collection") def execute( @DescribeParameter( name = "inputFeatures", description = "Input feature collection that defines the proximity search") inputFeatures: SimpleFeatureCollection, @DescribeParameter( name = "dataFeatures", description = "The data set to query for matching features") dataFeatures: SimpleFeatureCollection, @DescribeParameter( name = "bufferDistance", description = "Buffer size in meters") bufferDistance: java.lang.Double ): SimpleFeatureCollection = { logger.info("Attempting Geomesa Proximity Search on collection type " + dataFeatures.getClass.getName) if(!dataFeatures.isInstanceOf[AccumuloFeatureCollection]) { logger.warn("The provided data feature collection type may not support geomesa proximity search: "+dataFeatures.getClass.getName) } if(dataFeatures.isInstanceOf[ReTypingFeatureCollection]) { logger.warn("WARNING: layer name in geoserver must match feature type name in geomesa") } val visitor = new ProximityVisitor(inputFeatures, dataFeatures, bufferDistance) dataFeatures.accepts(visitor, new NullProgressListener) visitor.getResult.asInstanceOf[ProximityResult].results } } class ProximityVisitor(inputFeatures: SimpleFeatureCollection, dataFeatures: SimpleFeatureCollection, bufferDistance: java.lang.Double) extends FeatureCalc with Logging { val geoFac = new GeometryFactory val ff = CommonFactoryFinder.getFilterFactory2 var manualFilter: Filter = _ val manualVisitResults = new DefaultFeatureCollection(null, dataFeatures.getSchema) // Called for non AccumuloFeactureCollections - here we use degrees for our filters // since we are manually evaluating them. def visit(feature: Feature): Unit = { manualFilter = Option(manualFilter).getOrElse(dwithinFilters("degrees")) val sf = feature.asInstanceOf[SimpleFeature] if(manualFilter.evaluate(sf)) { manualVisitResults.add(sf) } } var resultCalc: ProximityResult = new ProximityResult(manualVisitResults) override def getResult: CalcResult = resultCalc def setValue(r: SimpleFeatureCollection) = resultCalc = ProximityResult(r) def proximitySearch(source: SimpleFeatureSource, query: Query) = { logger.info("Running Geomesa Proximity Search on source type "+source.getClass.getName) val combinedFilter = ff.and(query.getFilter, dwithinFilters("meters")) source.getFeatures(combinedFilter) } def dwithinFilters(requestedUnit: String) = { import org.locationtech.geomesa.utils.geotools.Conversions.RichGeometry import scala.collection.JavaConversions._ val geomProperty = ff.property(dataFeatures.getSchema.getGeometryDescriptor.getName) val geomFilters = inputFeatures.features().map { sf => val dist: Double = requestedUnit match { case "degrees" => sf.geometry.distanceDegrees(bufferDistance) case _ => bufferDistance } ff.dwithin(geomProperty, ff.literal(sf.geometry), dist, "meters") } ff.or(geomFilters.toSeq) } } case class ProximityResult(results: SimpleFeatureCollection) extends AbstractCalcResult
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.hyracks.algebricks.runtime.operators.sort; import java.nio.ByteBuffer; import java.util.List; import org.apache.hyracks.algebricks.common.exceptions.NotImplementedException; import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputPushRuntime; import org.apache.hyracks.algebricks.runtime.operators.base.AbstractOneInputOneOutputRuntimeFactory; import org.apache.hyracks.api.comm.IFrameWriter; import org.apache.hyracks.api.context.IHyracksTaskContext; import org.apache.hyracks.api.dataflow.value.IBinaryComparator; import org.apache.hyracks.api.dataflow.value.IBinaryComparatorFactory; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputer; import org.apache.hyracks.api.dataflow.value.INormalizedKeyComputerFactory; import org.apache.hyracks.api.exceptions.HyracksDataException; import org.apache.hyracks.api.resources.IDeallocatable; import org.apache.hyracks.api.util.CleanupUtils; import org.apache.hyracks.dataflow.common.io.GeneratedRunFileReader; import org.apache.hyracks.dataflow.std.buffermanager.EnumFreeSlotPolicy; import org.apache.hyracks.dataflow.std.sort.Algorithm; import org.apache.hyracks.dataflow.std.sort.ExternalSortRunGenerator; import org.apache.hyracks.dataflow.std.sort.ExternalSortRunMerger; public class MicroSortRuntimeFactory extends AbstractOneInputOneOutputRuntimeFactory { private static final long serialVersionUID = 1L; private final int framesLimit; private final int[] sortFields; private final INormalizedKeyComputerFactory[] keyNormalizerFactories; private final IBinaryComparatorFactory[] comparatorFactories; public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory firstKeyNormalizerFactory, IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) { this(sortFields, firstKeyNormalizerFactory != null ? new INormalizedKeyComputerFactory[] { firstKeyNormalizerFactory } : null, comparatorFactories, projectionList, framesLimit); } public MicroSortRuntimeFactory(int[] sortFields, INormalizedKeyComputerFactory[] keyNormalizerFactories, IBinaryComparatorFactory[] comparatorFactories, int[] projectionList, int framesLimit) { super(projectionList); // Obs: the projection list is currently ignored. if (projectionList != null) { throw new NotImplementedException("Cannot push projection into InMemorySortRuntime."); } this.sortFields = sortFields; this.keyNormalizerFactories = keyNormalizerFactories; this.comparatorFactories = comparatorFactories; this.framesLimit = framesLimit; } @Override public AbstractOneInputOneOutputPushRuntime createOneOutputPushRuntime(final IHyracksTaskContext ctx) throws HyracksDataException { InMemorySortPushRuntime pushRuntime = new InMemorySortPushRuntime(ctx); ctx.registerDeallocatable(pushRuntime); return pushRuntime; } private class InMemorySortPushRuntime extends AbstractOneInputOneOutputPushRuntime implements IDeallocatable { final IHyracksTaskContext ctx; ExternalSortRunGenerator runsGenerator = null; ExternalSortRunMerger runsMerger = null; IFrameWriter wrappingWriter = null; private InMemorySortPushRuntime(IHyracksTaskContext ctx) { this.ctx = ctx; } @Override public void open() throws HyracksDataException { if (runsGenerator == null) { runsGenerator = new ExternalSortRunGenerator(ctx, sortFields, keyNormalizerFactories, comparatorFactories, outputRecordDesc, Algorithm.MERGE_SORT, EnumFreeSlotPolicy.LAST_FIT, framesLimit, Integer.MAX_VALUE); } // next writer will be opened later when preparing the merger isOpen = true; runsGenerator.open(); runsGenerator.getSorter().reset(); } @Override public void nextFrame(ByteBuffer buffer) throws HyracksDataException { runsGenerator.nextFrame(buffer); } @Override public void close() throws HyracksDataException { Throwable failure = null; if (isOpen) { try { if (!failed) { runsGenerator.close(); createOrResetRunsMerger(); if (runsGenerator.getRuns().isEmpty()) { wrappingWriter = runsMerger.prepareSkipMergingFinalResultWriter(writer); wrappingWriter.open(); if (runsGenerator.getSorter().hasRemaining()) { runsGenerator.getSorter().flush(wrappingWriter); } } else { wrappingWriter = runsMerger.prepareFinalMergeResultWriter(writer); wrappingWriter.open(); runsMerger.process(wrappingWriter); } } } catch (Throwable th) { failure = th; fail(th); } finally { failure = CleanupUtils.close(wrappingWriter, failure); wrappingWriter = null; } } isOpen = false; if (failure != null) { throw HyracksDataException.create(failure); } } @Override public void fail() throws HyracksDataException { failed = true; // clean up the runs if some have been generated. double close should be idempotent. if (runsGenerator != null) { List<GeneratedRunFileReader> runs = runsGenerator.getRuns(); for (int i = 0, size = runs.size(); i < size; i++) { try { runs.get(i).close(); } catch (Throwable th) { // ignore } } } if (wrappingWriter != null) { wrappingWriter.fail(); } } @Override public void deallocate() { if (runsGenerator != null) { try { runsGenerator.getSorter().close(); } catch (Exception e) { // ignore } } } private void createOrResetRunsMerger() { if (runsMerger == null) { IBinaryComparator[] comparators = new IBinaryComparator[comparatorFactories.length]; for (int i = 0; i < comparatorFactories.length; ++i) { comparators[i] = comparatorFactories[i].createBinaryComparator(); } INormalizedKeyComputer nmkComputer = keyNormalizerFactories == null ? null : keyNormalizerFactories[0].createNormalizedKeyComputer(); runsMerger = new ExternalSortRunMerger(ctx, runsGenerator.getRuns(), sortFields, comparators, nmkComputer, outputRecordDesc, framesLimit, Integer.MAX_VALUE); } else { runsMerger.reset(runsGenerator.getRuns()); } } } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.core; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.apache.solr.cloud.ZkController; import org.apache.solr.cloud.ZkSolrResourceLoader; import org.apache.solr.common.SolrException; import org.apache.solr.common.SolrException.ErrorCode; import org.apache.solr.common.util.ExecutorUtil; import org.apache.solr.handler.RequestHandlerBase; import org.apache.solr.handler.admin.CollectionsHandler; import org.apache.solr.handler.admin.CoreAdminHandler; import org.apache.solr.handler.admin.InfoHandler; import org.apache.solr.handler.component.ShardHandlerFactory; import org.apache.solr.logging.LogWatcher; import org.apache.solr.request.SolrRequestHandler; import org.apache.solr.update.UpdateShardHandler; import org.apache.solr.util.DefaultSolrThreadFactory; import org.apache.solr.util.FileUtils; import org.apache.zookeeper.KeeperException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import static com.google.common.base.Preconditions.checkNotNull; /** * * @since solr 1.3 */ public class CoreContainer { protected static final Logger log = LoggerFactory.getLogger(CoreContainer.class); final SolrCores solrCores = new SolrCores(this); public static class CoreLoadFailure { public final CoreDescriptor cd; public final Exception exception; public CoreLoadFailure(CoreDescriptor cd, Exception loadFailure) { this.cd = cd; this.exception = loadFailure; } } protected final Map<String, CoreLoadFailure> coreInitFailures = new ConcurrentHashMap<>(); protected CoreAdminHandler coreAdminHandler = null; protected CollectionsHandler collectionsHandler = null; private InfoHandler infoHandler; protected Properties containerProperties; private ConfigSetService coreConfigService; protected ZkContainer zkSys = new ZkContainer(); protected ShardHandlerFactory shardHandlerFactory; private UpdateShardHandler updateShardHandler; protected LogWatcher logging = null; private CloserThread backgroundCloser = null; protected final ConfigSolr cfg; protected final SolrResourceLoader loader; protected final String solrHome; protected final CoresLocator coresLocator; private String hostName; private final JarRepository jarRepository = new JarRepository(this); public static final String CORES_HANDLER_PATH = "/admin/cores"; public static final String COLLECTIONS_HANDLER_PATH = "/admin/collections"; public static final String INFO_HANDLER_PATH = "/admin/info"; private Map<String, SolrRequestHandler> containerHandlers = new HashMap<>(); public SolrRequestHandler getRequestHandler(String path) { return RequestHandlerBase.getRequestHandler(path, containerHandlers); } public Map<String, SolrRequestHandler> getRequestHandlers(){ return this.containerHandlers; } // private ClientConnectionManager clientConnectionManager = new PoolingClientConnectionManager(); { log.info("New CoreContainer " + System.identityHashCode(this)); } /** * Create a new CoreContainer using system properties to detect the solr home * directory. The container's cores are not loaded. * @see #load() */ public CoreContainer() { this(new SolrResourceLoader(SolrResourceLoader.locateSolrHome())); } /** * Create a new CoreContainer using the given SolrResourceLoader. The container's * cores are not loaded. * @param loader the SolrResourceLoader * @see #load() */ public CoreContainer(SolrResourceLoader loader) { this(ConfigSolr.fromSolrHome(loader, loader.getInstanceDir())); } /** * Create a new CoreContainer using the given solr home directory. The container's * cores are not loaded. * @param solrHome a String containing the path to the solr home directory * @see #load() */ public CoreContainer(String solrHome) { this(new SolrResourceLoader(solrHome)); } /** * Create a new CoreContainer using the given SolrResourceLoader, * configuration and CoresLocator. The container's cores are * not loaded. * @param config a ConfigSolr representation of this container's configuration * @see #load() */ public CoreContainer(ConfigSolr config) { this(config, config.getCoresLocator()); } public CoreContainer(ConfigSolr config, CoresLocator locator) { this.loader = config.getSolrResourceLoader(); this.solrHome = loader.getInstanceDir(); this.cfg = checkNotNull(config); this.coresLocator = locator; } /** * This method allows subclasses to construct a CoreContainer * without any default init behavior. * * @param testConstructor pass (Object)null. * @lucene.experimental */ protected CoreContainer(Object testConstructor) { solrHome = null; loader = null; coresLocator = null; cfg = null; } /** * Create a new CoreContainer and load its cores * @param solrHome the solr home directory * @param configFile the file containing this container's configuration * @return a loaded CoreContainer */ public static CoreContainer createAndLoad(String solrHome, File configFile) { SolrResourceLoader loader = new SolrResourceLoader(solrHome); CoreContainer cc = new CoreContainer(ConfigSolr.fromFile(loader, configFile)); try { cc.load(); } catch (Exception e) { cc.shutdown(); throw e; } return cc; } public Properties getContainerProperties() { return containerProperties; } //------------------------------------------------------------------- // Initialization / Cleanup //------------------------------------------------------------------- /** * Load the cores defined for this CoreContainer */ public void load() { log.info("Loading cores into CoreContainer [instanceDir={}]", loader.getInstanceDir()); // add the sharedLib to the shared resource loader before initializing cfg based plugins String libDir = cfg.getSharedLibDirectory(); if (libDir != null) { File f = FileUtils.resolvePath(new File(solrHome), libDir); log.info("loading shared library: " + f.getAbsolutePath()); loader.addToClassLoader(libDir, null, false); loader.reloadLuceneSPI(); } shardHandlerFactory = ShardHandlerFactory.newInstance(cfg.getShardHandlerFactoryPluginInfo(), loader); updateShardHandler = new UpdateShardHandler(cfg); solrCores.allocateLazyCores(cfg.getTransientCacheSize(), loader); logging = LogWatcher.newRegisteredLogWatcher(cfg.getLogWatcherConfig(), loader); hostName = cfg.getHost(); log.info("Host Name: " + hostName); zkSys.initZooKeeper(this, solrHome, cfg); collectionsHandler = createHandler(cfg.getCollectionsHandlerClass(), CollectionsHandler.class); containerHandlers.put(COLLECTIONS_HANDLER_PATH, collectionsHandler); infoHandler = createHandler(cfg.getInfoHandlerClass(), InfoHandler.class); containerHandlers.put(INFO_HANDLER_PATH, infoHandler); coreAdminHandler = createHandler(cfg.getCoreAdminHandlerClass(), CoreAdminHandler.class); containerHandlers.put(CORES_HANDLER_PATH, coreAdminHandler); coreConfigService = cfg.createCoreConfigService(loader, zkSys.getZkController()); containerProperties = cfg.getSolrProperties(); // setup executor to load cores in parallel // do not limit the size of the executor in zk mode since cores may try and wait for each other. ExecutorService coreLoadExecutor = Executors.newFixedThreadPool( ( zkSys.getZkController() == null ? cfg.getCoreLoadThreadCount() : Integer.MAX_VALUE ), new DefaultSolrThreadFactory("coreLoadExecutor") ); try { List<CoreDescriptor> cds = coresLocator.discover(this); checkForDuplicateCoreNames(cds); List<Callable<SolrCore>> creators = new ArrayList<>(); for (final CoreDescriptor cd : cds) { if (cd.isTransient() || !cd.isLoadOnStartup()) { solrCores.putDynamicDescriptor(cd.getName(), cd); } if (cd.isLoadOnStartup()) { creators.add(new Callable<SolrCore>() { @Override public SolrCore call() throws Exception { if (zkSys.getZkController() != null) { zkSys.getZkController().throwErrorIfReplicaReplaced(cd); } return create(cd, false); } }); } } try { coreLoadExecutor.invokeAll(creators); } catch (InterruptedException e) { throw new SolrException(SolrException.ErrorCode.SERVICE_UNAVAILABLE, "Interrupted while loading cores"); } // Start the background thread backgroundCloser = new CloserThread(this, solrCores, cfg); backgroundCloser.start(); } finally { ExecutorUtil.shutdownNowAndAwaitTermination(coreLoadExecutor); } if (isZooKeeperAware()) { // register in zk in background threads Collection<SolrCore> cores = getCores(); if (cores != null) { for (SolrCore core : cores) { try { zkSys.registerInZk(core, true); } catch (Throwable t) { SolrException.log(log, "Error registering SolrCore", t); } } } zkSys.getZkController().checkOverseerDesignate(); } } private static void checkForDuplicateCoreNames(List<CoreDescriptor> cds) { Map<String, String> addedCores = Maps.newHashMap(); for (CoreDescriptor cd : cds) { final String name = cd.getName(); if (addedCores.containsKey(name)) throw new SolrException(ErrorCode.SERVER_ERROR, String.format(Locale.ROOT, "Found multiple cores with the name [%s], with instancedirs [%s] and [%s]", name, addedCores.get(name), cd.getInstanceDir())); addedCores.put(name, cd.getInstanceDir()); } } private volatile boolean isShutDown = false; public boolean isShutDown() { return isShutDown; } /** * Stops all cores. */ public void shutdown() { log.info("Shutting down CoreContainer instance=" + System.identityHashCode(this)); isShutDown = true; if (isZooKeeperAware()) { cancelCoreRecoveries(); zkSys.publishCoresAsDown(solrCores.getCores()); } try { if (coreAdminHandler != null) coreAdminHandler.shutdown(); } catch (Exception e) { log.warn("Error shutting down CoreAdminHandler. Continuing to close CoreContainer.", e); } try { // First wake up the closer thread, it'll terminate almost immediately since it checks isShutDown. synchronized (solrCores.getModifyLock()) { solrCores.getModifyLock().notifyAll(); // wake up anyone waiting } if (backgroundCloser != null) { // Doesn't seem right, but tests get in here without initializing the core. try { backgroundCloser.join(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (log.isDebugEnabled()) { log.debug("backgroundCloser thread was interrupted before finishing"); } } } // Now clear all the cores that are being operated upon. solrCores.close(); // It's still possible that one of the pending dynamic load operation is waiting, so wake it up if so. // Since all the pending operations queues have been drained, there should be nothing to do. synchronized (solrCores.getModifyLock()) { solrCores.getModifyLock().notifyAll(); // wake up the thread } } finally { try { if (shardHandlerFactory != null) { shardHandlerFactory.close(); } } finally { try { if (updateShardHandler != null) { updateShardHandler.close(); } } finally { // we want to close zk stuff last zkSys.close(); } } } org.apache.lucene.util.IOUtils.closeWhileHandlingException(loader); // best effort } public void cancelCoreRecoveries() { List<SolrCore> cores = solrCores.getCores(); // we must cancel without holding the cores sync // make sure we wait for any recoveries to stop for (SolrCore core : cores) { try { core.getSolrCoreState().cancelRecovery(); } catch (Exception e) { SolrException.log(log, "Error canceling recovery for core", e); } } } @Override protected void finalize() throws Throwable { try { if(!isShutDown){ log.error("CoreContainer was not close prior to finalize(), indicates a bug -- POSSIBLE RESOURCE LEAK!!! instance=" + System.identityHashCode(this)); } } finally { super.finalize(); } } public CoresLocator getCoresLocator() { return coresLocator; } protected SolrCore registerCore(String name, SolrCore core, boolean registerInZk) { if( core == null ) { throw new RuntimeException( "Can not register a null core." ); } if( name == null || name.indexOf( '/' ) >= 0 || name.indexOf( '\\' ) >= 0 ){ throw new RuntimeException( "Invalid core name: "+name ); } // We can register a core when creating them via the admin UI, so we need to insure that the dynamic descriptors // are up to date CoreDescriptor cd = core.getCoreDescriptor(); if ((cd.isTransient() || ! cd.isLoadOnStartup()) && solrCores.getDynamicDescriptor(name) == null) { // Store it away for later use. includes non-transient but not // loaded at startup cores. solrCores.putDynamicDescriptor(name, cd); } SolrCore old = null; if (isShutDown) { core.close(); throw new IllegalStateException("This CoreContainer has been close"); } if (cd.isTransient()) { old = solrCores.putTransientCore(cfg, name, core, loader); } else { old = solrCores.putCore(name, core); } /* * set both the name of the descriptor and the name of the * core, since the descriptors name is used for persisting. */ core.setName(name); coreInitFailures.remove(name); if( old == null || old == core) { log.info( "registering core: "+name ); if (registerInZk) { zkSys.registerInZk(core, false); } return null; } else { log.info( "replacing core: "+name ); old.close(); if (registerInZk) { zkSys.registerInZk(core, false); } return old; } } /** * Creates a new core based on a CoreDescriptor, publishing the core state to the cluster * @param cd the CoreDescriptor * @return the newly created core */ public SolrCore create(CoreDescriptor cd) { return create(cd, true); } /** * Creates a new core based on a CoreDescriptor. * * @param dcore a core descriptor * @param publishState publish core state to the cluster if true * * @return the newly created core */ public SolrCore create(CoreDescriptor dcore, boolean publishState) { if (isShutDown) { throw new SolrException(ErrorCode.SERVICE_UNAVAILABLE, "Solr has close."); } try { if (zkSys.getZkController() != null) { zkSys.getZkController().preRegister(dcore); } ConfigSet coreConfig = coreConfigService.getConfig(dcore); log.info("Creating SolrCore '{}' using configuration from {}", dcore.getName(), coreConfig.getName()); SolrCore core = new SolrCore(dcore, coreConfig); solrCores.addCreated(core); // always kick off recovery if we are in non-Cloud mode if (!isZooKeeperAware() && core.getUpdateHandler().getUpdateLog() != null) { core.getUpdateHandler().getUpdateLog().recoverFromLog(); } registerCore(dcore.getName(), core, publishState); return core; } catch (Exception e) { coreInitFailures.put(dcore.getName(), new CoreLoadFailure(dcore, e)); log.error("Error creating core [{}]: {}", dcore.getName(), e.getMessage(), e); throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to create core [" + dcore.getName() + "]", e); } catch (Throwable t) { SolrException e = new SolrException(ErrorCode.SERVER_ERROR, "JVM Error creating core [" + dcore.getName() + "]: " + t.getMessage(), t); log.error("Error creating core [{}]: {}", dcore.getName(), t.getMessage(), t); coreInitFailures.put(dcore.getName(), new CoreLoadFailure(dcore, e)); throw t; } } /** * @return a Collection of registered SolrCores */ public Collection<SolrCore> getCores() { return solrCores.getCores(); } /** * @return a Collection of the names that cores are mapped to */ public Collection<String> getCoreNames() { return solrCores.getCoreNames(); } /** This method is currently experimental. * @return a Collection of the names that a specific core is mapped to. */ public Collection<String> getCoreNames(SolrCore core) { return solrCores.getCoreNames(core); } /** * get a list of all the cores that are currently loaded * @return a list of al lthe available core names in either permanent or transient core lists. */ public Collection<String> getAllCoreNames() { return solrCores.getAllCoreNames(); } /** * Returns an immutable Map of Exceptions that occured when initializing * SolrCores (either at startup, or do to runtime requests to create cores) * keyed off of the name (String) of the SolrCore that had the Exception * during initialization. * <p> * While the Map returned by this method is immutable and will not change * once returned to the client, the source data used to generate this Map * can be changed as various SolrCore operations are performed: * </p> * <ul> * <li>Failed attempts to create new SolrCores will add new Exceptions.</li> * <li>Failed attempts to re-create a SolrCore using a name already contained in this Map will replace the Exception.</li> * <li>Failed attempts to reload a SolrCore will cause an Exception to be added to this list -- even though the existing SolrCore with that name will continue to be available.</li> * <li>Successful attempts to re-created a SolrCore using a name already contained in this Map will remove the Exception.</li> * <li>Registering an existing SolrCore with a name already contained in this Map (ie: ALIAS or SWAP) will remove the Exception.</li> * </ul> */ public Map<String, CoreLoadFailure> getCoreInitFailures() { return ImmutableMap.copyOf(coreInitFailures); } // ---------------- Core name related methods --------------- /** * Recreates a SolrCore. * While the new core is loading, requests will continue to be dispatched to * and processed by the old core * * @param name the name of the SolrCore to reload */ public void reload(String name) { SolrCore core = solrCores.getCoreFromAnyList(name, false); if (core == null) throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "No such core: " + name ); CoreDescriptor cd = core.getCoreDescriptor(); try { solrCores.waitAddPendingCoreOps(name); ConfigSet coreConfig = coreConfigService.getConfig(cd); log.info("Reloading SolrCore '{}' using configuration from {}", cd.getName(), coreConfig.getName()); SolrCore newCore = core.reload(coreConfig); registerCore(name, newCore, false); } catch (Exception e) { coreInitFailures.put(cd.getName(), new CoreLoadFailure(cd, e)); throw new SolrException(ErrorCode.SERVER_ERROR, "Unable to reload core [" + cd.getName() + "]", e); } finally { solrCores.removeFromPendingOps(name); } } /** * Swaps two SolrCore descriptors. */ public void swap(String n0, String n1) { if( n0 == null || n1 == null ) { throw new SolrException( SolrException.ErrorCode.BAD_REQUEST, "Can not swap unnamed cores." ); } solrCores.swap(n0, n1); coresLocator.swap(this, solrCores.getCoreDescriptor(n0), solrCores.getCoreDescriptor(n1)); log.info("swapped: "+n0 + " with " + n1); } /** * Unload a core from this container, leaving all files on disk * @param name the name of the core to unload */ public void unload(String name) { unload(name, false, false, false); } /** * Unload a core from this container, optionally removing the core's data and configuration * * @param name the name of the core to unload * @param deleteIndexDir if true, delete the core's index on close * @param deleteDataDir if true, delete the core's data directory on close * @param deleteInstanceDir if true, delete the core's instance directory on close */ public void unload(String name, boolean deleteIndexDir, boolean deleteDataDir, boolean deleteInstanceDir) { // check for core-init errors first CoreLoadFailure loadFailure = coreInitFailures.remove(name); if (loadFailure != null) { // getting the index directory requires opening a DirectoryFactory with a SolrConfig, etc, // which we may not be able to do because of the init error. So we just go with what we // can glean from the CoreDescriptor - datadir and instancedir SolrCore.deleteUnloadedCore(loadFailure.cd, deleteDataDir, deleteInstanceDir); return; } CoreDescriptor cd = solrCores.getCoreDescriptor(name); if (cd == null) throw new SolrException(ErrorCode.BAD_REQUEST, "Cannot unload non-existent core [" + name + "]"); boolean close = solrCores.isLoadedNotPendingClose(name); SolrCore core = solrCores.remove(name); coresLocator.delete(this, cd); if (core == null) { // transient core SolrCore.deleteUnloadedCore(cd, deleteDataDir, deleteInstanceDir); return; } if (zkSys.getZkController() != null) { // cancel recovery in cloud mode core.getSolrCoreState().cancelRecovery(); } String configSetZkPath = core.getResourceLoader() instanceof ZkSolrResourceLoader ? ((ZkSolrResourceLoader)core.getResourceLoader()).getConfigSetZkPath() : null; core.unloadOnClose(deleteIndexDir, deleteDataDir, deleteInstanceDir); if (close) core.close(); if (zkSys.getZkController() != null) { try { zkSys.getZkController().unregister(name, cd, configSetZkPath); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new SolrException(ErrorCode.SERVER_ERROR, "Interrupted while unregistering core [" + name + "] from cloud state"); } catch (KeeperException e) { throw new SolrException(ErrorCode.SERVER_ERROR, "Error unregistering core [" + name + "] from cloud state", e); } } } public void rename(String name, String toName) { try (SolrCore core = getCore(name)) { if (core != null) { registerCore(toName, core, true); SolrCore old = solrCores.remove(name); coresLocator.rename(this, old.getCoreDescriptor(), core.getCoreDescriptor()); } } } /** * Get the CoreDescriptors for all cores managed by this container * @return a List of CoreDescriptors */ public List<CoreDescriptor> getCoreDescriptors() { return solrCores.getCoreDescriptors(); } public CoreDescriptor getCoreDescriptor(String coreName) { // TODO make this less hideous! for (CoreDescriptor cd : getCoreDescriptors()) { if (cd.getName().equals(coreName)) return cd; } return null; } public String getCoreRootDirectory() { return cfg.getCoreRootDirectory(); } /** * Gets a core by name and increase its refcount. * * @see SolrCore#close() * @param name the core name * @return the core if found, null if a SolrCore by this name does not exist * @exception SolrException if a SolrCore with this name failed to be initialized */ public SolrCore getCore(String name) { // Do this in two phases since we don't want to lock access to the cores over a load. SolrCore core = solrCores.getCoreFromAnyList(name, true); if (core != null) { return core; } // OK, it's not presently in any list, is it in the list of dynamic cores but not loaded yet? If so, load it. CoreDescriptor desc = solrCores.getDynamicDescriptor(name); if (desc == null) { //Nope, no transient core with this name // if there was an error initalizing this core, throw a 500 // error with the details for clients attempting to access it. CoreLoadFailure loadFailure = getCoreInitFailures().get(name); if (null != loadFailure) { throw new SolrException(ErrorCode.SERVER_ERROR, "SolrCore '" + name + "' is not available due to init failure: " + loadFailure.exception.getMessage(), loadFailure.exception); } // otherwise the user is simply asking for something that doesn't exist. return null; } // This will put an entry in pending core ops if the core isn't loaded core = solrCores.waitAddPendingCoreOps(name); if (isShutDown) return null; // We're quitting, so stop. This needs to be after the wait above since we may come off // the wait as a consequence of shutting down. try { if (core == null) { if (zkSys.getZkController() != null) { zkSys.getZkController().throwErrorIfReplicaReplaced(desc); } core = create(desc); // This should throw an error if it fails. } core.open(); } finally { solrCores.removeFromPendingOps(name); } return core; } public JarRepository getJarRepository(){ return jarRepository; } // ---------------- CoreContainer request handlers -------------- protected <T> T createHandler(String handlerClass, Class<T> clazz) { return loader.newInstance(handlerClass, clazz, null, new Class[] { CoreContainer.class }, new Object[] { this }); } public CoreAdminHandler getMultiCoreHandler() { return coreAdminHandler; } public CollectionsHandler getCollectionsHandler() { return collectionsHandler; } public InfoHandler getInfoHandler() { return infoHandler; } public String getHostName() { return this.hostName; } /** * Gets the alternate path for multicore handling: * This is used in case there is a registered unnamed core (aka name is "") to * declare an alternate way of accessing named cores. * This can also be used in a pseudo single-core environment so admins can prepare * a new version before swapping. */ public String getManagementPath() { return cfg.getManagementPath(); } public LogWatcher getLogging() { return logging; } /** * Determines whether the core is already loaded or not but does NOT load the core * */ public boolean isLoaded(String name) { return solrCores.isLoaded(name); } public boolean isLoadedNotPendingClose(String name) { return solrCores.isLoadedNotPendingClose(name); } /** * Gets a solr core descriptor for a core that is not loaded. Note that if the caller calls this on a * loaded core, the unloaded descriptor will be returned. * * @param cname - name of the unloaded core descriptor to load. NOTE: * @return a coreDescriptor. May return null */ public CoreDescriptor getUnloadedCoreDescriptor(String cname) { return solrCores.getUnloadedCoreDescriptor(cname); } public String getSolrHome() { return solrHome; } public boolean isZooKeeperAware() { return zkSys.getZkController() != null; } public ZkController getZkController() { return zkSys.getZkController(); } public ConfigSolr getConfig() { return cfg; } /** The default ShardHandlerFactory used to communicate with other solr instances */ public ShardHandlerFactory getShardHandlerFactory() { return shardHandlerFactory; } public UpdateShardHandler getUpdateShardHandler() { return updateShardHandler; } public SolrResourceLoader getResourceLoader() { return loader; } } class CloserThread extends Thread { CoreContainer container; SolrCores solrCores; ConfigSolr cfg; CloserThread(CoreContainer container, SolrCores solrCores, ConfigSolr cfg) { this.container = container; this.solrCores = solrCores; this.cfg = cfg; } // It's important that this be the _only_ thread removing things from pendingDynamicCloses! // This is single-threaded, but I tried a multi-threaded approach and didn't see any performance gains, so // there's no good justification for the complexity. I suspect that the locking on things like DefaultSolrCoreState // essentially create a single-threaded process anyway. @Override public void run() { while (! container.isShutDown()) { synchronized (solrCores.getModifyLock()) { // need this so we can wait and be awoken. try { solrCores.getModifyLock().wait(); } catch (InterruptedException e) { // Well, if we've been told to stop, we will. Otherwise, continue on and check to see if there are // any cores to close. } } for (SolrCore removeMe = solrCores.getCoreToClose(); removeMe != null && !container.isShutDown(); removeMe = solrCores.getCoreToClose()) { try { removeMe.close(); } finally { solrCores.removeFromPendingOps(removeMe.getName()); } } } } }
Java
<!doctype html><html lang=en><head><title>Redirecting&hellip;</title><link rel=canonical href=/v1.2/docs/tasks/traffic-management/egress/egress-control/><meta name=robots content=noindex><meta charset=utf-8><meta http-equiv=refresh content="0; url=/v1.2/docs/tasks/traffic-management/egress/egress-control/"></head><body><h1>Redirecting&hellip;</h1><a href=/v1.2/docs/tasks/traffic-management/egress/egress-control/>Click here if you are not redirected.</a></body></html>
Java
package gov.va.medora.mdws.emrsvc; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="fromDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="toDate" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="nNotes" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "fromDate", "toDate", "nNotes" }) @XmlRootElement(name = "getDischargeSummaries") public class GetDischargeSummaries { protected String fromDate; protected String toDate; protected int nNotes; /** * Gets the value of the fromDate property. * * @return * possible object is * {@link String } * */ public String getFromDate() { return fromDate; } /** * Sets the value of the fromDate property. * * @param value * allowed object is * {@link String } * */ public void setFromDate(String value) { this.fromDate = value; } /** * Gets the value of the toDate property. * * @return * possible object is * {@link String } * */ public String getToDate() { return toDate; } /** * Sets the value of the toDate property. * * @param value * allowed object is * {@link String } * */ public void setToDate(String value) { this.toDate = value; } /** * Gets the value of the nNotes property. * */ public int getNNotes() { return nNotes; } /** * Sets the value of the nNotes property. * */ public void setNNotes(int value) { this.nNotes = value; } }
Java
# Systemd Unit If you are using distribution packages or the copr repository, you don't need to deal with these files! The unit file in this directory is to be put into `/etc/systemd/system`. It needs a user named `node_exporter`, whose shell should be `/sbin/nologin` and should not have any special privileges. It needs a sysconfig file in `/etc/sysconfig/node_exporter`. It needs a directory named `/var/lib/node_exporter/textfile_collector`, whose owner should be `node_exporter`:`node_exporter`. A sample file can be found in `sysconfig.node_exporter`.
Java
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.test; import static java.util.regex.Matcher.quoteReplacement; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.FileReader; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.PrintStream; import java.io.PrintWriter; import java.io.StringReader; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.commons.io.FileUtils; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataInputStream; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.PathFilter; import org.apache.log4j.Appender; import org.apache.log4j.FileAppender; import org.apache.log4j.Level; import org.apache.log4j.Logger; import org.apache.log4j.PatternLayout; import org.apache.log4j.SimpleLayout; import org.apache.log4j.WriterAppender; import org.apache.pig.ExecType; import org.apache.pig.ExecTypeProvider; import org.apache.pig.LoadCaster; import org.apache.pig.PigException; import org.apache.pig.PigServer; import org.apache.pig.ResourceSchema.ResourceFieldSchema; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.backend.hadoop.datastorage.ConfigurationUtil; import org.apache.pig.backend.hadoop.executionengine.HExecutionEngine; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRConfiguration; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher; import org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.plans.MROperPlan; import org.apache.pig.backend.hadoop.executionengine.physicalLayer.plans.PhysicalPlan; import org.apache.pig.backend.hadoop.executionengine.tez.TezResourceManager; import org.apache.pig.backend.hadoop.executionengine.util.MapRedUtil; import org.apache.pig.builtin.Utf8StorageConverter; import org.apache.pig.data.BagFactory; import org.apache.pig.data.DataBag; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.DefaultBagFactory; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.PigContext; import org.apache.pig.impl.io.FileLocalizer; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; import org.apache.pig.impl.logicalLayer.schema.Schema.FieldSchema; import org.apache.pig.impl.util.LogUtils; import org.apache.pig.newplan.logical.optimizer.LogicalPlanPrinter; import org.apache.pig.newplan.logical.optimizer.SchemaResetter; import org.apache.pig.newplan.logical.optimizer.UidResetter; import org.apache.pig.newplan.logical.relational.LogToPhyTranslationVisitor; import org.apache.pig.newplan.logical.relational.LogicalPlan; import org.apache.pig.newplan.logical.relational.LogicalSchema; import org.apache.pig.newplan.logical.relational.LogicalSchema.LogicalFieldSchema; import org.apache.pig.newplan.logical.visitor.DanglingNestedNodeRemover; import org.apache.pig.newplan.logical.visitor.SortInfoSetter; import org.apache.pig.newplan.logical.visitor.StoreAliasSetter; import org.apache.pig.parser.ParserException; import org.apache.pig.parser.QueryParserDriver; import org.apache.pig.tools.grunt.GruntParser; import org.apache.pig.tools.pigstats.ScriptState; import org.apache.spark.package$; import org.junit.Assert; import com.google.common.base.Function; import com.google.common.collect.Lists; public class Util { private static BagFactory mBagFactory = BagFactory.getInstance(); private static TupleFactory mTupleFactory = TupleFactory.getInstance(); // Commonly-checked system state // ================= public static final boolean WINDOWS /* borrowed from Path.WINDOWS, Shell.WINDOWS */ = System.getProperty("os.name").startsWith("Windows"); public static final String TEST_DIR = System.getProperty("test.build.dir", "build/test"); // Helper Functions // ================= static public Tuple loadFlatTuple(Tuple t, int[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, new Integer(input[i])); } return t; } static public Tuple loadTuple(Tuple t, String[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadTuple(Tuple t, DataByteArray[] input) throws ExecException { for (int i = 0; i < input.length; i++) { t.set(i, input[i]); } return t; } static public Tuple loadNestTuple(Tuple t, int[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } static public Tuple loadNestTuple(Tuple t, long[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, new Long(input[i])); bag.add(f); } t.set(0, bag); return t; } // this one should handle String, DataByteArray, Long, Integer etc.. static public <T> Tuple loadNestTuple(Tuple t, T[] input) throws ExecException { DataBag bag = BagFactory.getInstance().newDefaultBag(); for(int i = 0; i < input.length; i++) { Tuple f = TupleFactory.getInstance().newTuple(1); f.set(0, input[i]); bag.add(f); } t.set(0, bag); return t; } /** * Create an array of tuple bags with specified size created by splitting * the input array of primitive types * * @param input Array of primitive types * @param bagSize The number of tuples to be split and copied into each bag * * @return an array of tuple bags with each bag containing bagSize tuples split from the input */ static public <T> Tuple[] splitCreateBagOfTuples(T[] input, int bagSize) throws ExecException { List<Tuple> result = new ArrayList<Tuple>(); for (int from = 0; from < input.length; from += bagSize) { Tuple t = TupleFactory.getInstance().newTuple(1); int to = from + bagSize < input.length ? from + bagSize : input.length; T[] array = Arrays.copyOfRange(input, from, to); result.add(loadNestTuple(t, array)); } return result.toArray(new Tuple[0]); } static public <T>void addToTuple(Tuple t, T[] b) { for(int i = 0; i < b.length; i++) t.append(b[i]); } static public Tuple buildTuple(Object... args) throws ExecException { return TupleFactory.getInstance().newTupleNoCopy(Lists.newArrayList(args)); } static public Tuple buildBinTuple(final Object... args) throws IOException { return TupleFactory.getInstance().newTuple(Lists.transform( Lists.newArrayList(args), new Function<Object, DataByteArray>() { @Override public DataByteArray apply(Object o) { if (o == null) { return null; } try { return new DataByteArray(DataType.toBytes(o)); } catch (ExecException e) { return null; } } })); } static public <T>Tuple createTuple(T[] s) { Tuple t = mTupleFactory.newTuple(); addToTuple(t, s); return t; } static public DataBag createBag(Tuple[] t) { DataBag b = mBagFactory.newDefaultBag(); for(int i = 0; i < t.length; i++)b.add(t[i]); return b; } static public<T> DataBag createBagOfOneColumn(T[] input) throws ExecException { DataBag result = mBagFactory.newDefaultBag(); for (int i = 0; i < input.length; i++) { Tuple t = mTupleFactory.newTuple(1); t.set(0, input[i]); result.add(t); } return result; } static public Map<String, Object> createMap(String[] contents) { Map<String, Object> m = new HashMap<String, Object>(); for(int i = 0; i < contents.length; ) { m.put(contents[i], contents[i+1]); i += 2; } return m; } static public<T> DataByteArray[] toDataByteArrays(T[] input) { DataByteArray[] dbas = new DataByteArray[input.length]; for (int i = 0; i < input.length; i++) { dbas[i] = (input[i] == null)?null:new DataByteArray(input[i].toString().getBytes()); } return dbas; } static public Tuple loadNestTuple(Tuple t, int[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadFlatTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } static public Tuple loadTuple(Tuple t, String[][] input) throws ExecException { for (int i = 0; i < input.length; i++) { DataBag bag = BagFactory.getInstance().newDefaultBag(); Tuple f = loadTuple(TupleFactory.getInstance().newTuple(input[i].length), input[i]); bag.add(f); t.set(i, bag); } return t; } /** * Helper to remove colons (if any exist) from paths to sanitize them for * consumption by hdfs. * * @param origPath original path name * @return String sanitized path with anything prior to : removed * @throws IOException */ static public String removeColon(String origPath) { return origPath.replaceAll(":", ""); } /** * Helper to convert \r\n to \n for cross-platform string * matching with checked-in baselines. * * @param origPath original string * @return String newline-standardized string * @throws IOException */ static public String standardizeNewline(String origPath) { return origPath.replaceAll("\r\n", "\n"); } /** * Helper to create a temporary file with given input data for use in test cases. * * @param tmpFilenamePrefix file-name prefix * @param tmpFilenameSuffix file-name suffix * @param inputData input for test cases, each string in inputData[] is written * on one line * @return {@link File} handle to the created temporary file * @throws IOException */ static public File createInputFile(String tmpFilenamePrefix, String tmpFilenameSuffix, String[] inputData) throws IOException { File f = File.createTempFile(tmpFilenamePrefix, tmpFilenameSuffix); f.deleteOnExit(); writeToFile(f, inputData); return f; } static public File createLocalInputFile(String filename, String[] inputData) throws IOException { File f = new File(filename); f.deleteOnExit(); writeToFile(f, inputData); return f; } public static void writeToFile(File f, String[] inputData) throws IOException { PrintWriter pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(f), "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } /** * Helper to create a dfs file on the Minicluster DFS with given * input data for use in test cases. * * @param miniCluster reference to the Minicluster where the file should be created * @param fileName pathname of the file to be created * @param inputData input for test cases, each string in inputData[] is written * on one line * @throws IOException */ static public void createInputFile(MiniGenericCluster miniCluster, String fileName, String[] inputData) throws IOException { FileSystem fs = miniCluster.getFileSystem(); createInputFile(fs, fileName, inputData); } static public void createInputFile(FileSystem fs, String fileName, String[] inputData) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if(fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the FileSystem"); } FSDataOutputStream stream = fs.create(new Path(fileName)); PrintWriter pw = new PrintWriter(new OutputStreamWriter(stream, "UTF-8")); for (int i=0; i<inputData.length; i++){ pw.print(inputData[i]); pw.print("\n"); } pw.close(); } static public String[] readOutput(FileSystem fs, String fileName) throws IOException { if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } Path path = new Path(fileName); if(!fs.exists(path)) { throw new IOException("Path " + fileName + " does not exist on the FileSystem"); } FileStatus fileStatus = fs.getFileStatus(path); FileStatus[] files; if (fileStatus.isDirectory()) { files = fs.listStatus(path, new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }); } else { files = new FileStatus[] { fileStatus }; } List<String> result = new ArrayList<String>(); for (FileStatus f : files) { FSDataInputStream stream = fs.open(f.getPath()); BufferedReader br = new BufferedReader(new InputStreamReader(stream, "UTF-8")); String line; while ((line = br.readLine()) != null) { result.add(line); } br.close(); } return result.toArray(new String[result.size()]); } /** * Helper to create a dfs file on the MiniCluster dfs. This returns an * outputstream that can be used in test cases to write data. * * @param cluster * reference to the MiniCluster where the file should be created * @param fileName * pathname of the file to be created * @return OutputStream to write any data to the file created on the * MiniCluster. * @throws IOException */ static public OutputStream createInputFile(MiniGenericCluster cluster, String fileName) throws IOException { FileSystem fs = cluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } if (fs.exists(new Path(fileName))) { throw new IOException("File " + fileName + " already exists on the minicluster"); } return fs.create(new Path(fileName)); } /** * Helper to create an empty temp file on local file system * which will be deleted on exit * @param prefix * @param suffix * @return File denoting a newly-created empty file * @throws IOException */ static public File createTempFileDelOnExit(String prefix, String suffix) throws IOException { File tmpFile = File.createTempFile(prefix, suffix); tmpFile.deleteOnExit(); return tmpFile; } /** * Helper to remove a dfs file from the minicluster DFS * * @param miniCluster reference to the Minicluster where the file should be deleted * @param fileName pathname of the file to be deleted * @throws IOException */ static public void deleteFile(MiniGenericCluster miniCluster, String fileName) throws IOException { FileSystem fs = miniCluster.getFileSystem(); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } /** * Deletes a dfs file from the MiniCluster DFS quietly * * @param miniCluster the MiniCluster where the file should be deleted * @param fileName the path of the file to be deleted */ public static void deleteQuietly(MiniGenericCluster miniCluster, String fileName) { try { deleteFile(miniCluster, fileName); } catch (IOException ignored) { } } static public void deleteFile(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } fs.delete(new Path(fileName), true); } static public boolean exists(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); FileSystem fs = FileSystem.get(conf); if(Util.WINDOWS){ fileName = fileName.replace('\\','/'); } return fs.exists(new Path(fileName)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results Array to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Tuple[] expectedResults) { checkQueryOutputs(actualResults, Arrays.asList(expectedResults)); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults) { checkQueryOutputs(actualResults, expectedResults.iterator(), null ); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. * * @param actualResults Result of the executed Pig query * @param expectedResults Expected results List to validate against */ static public void checkQueryOutputs(Iterator<Tuple> actualResults, Iterator<Tuple> expectedResults, Integer expectedRows) { int count = 0; while (expectedResults.hasNext()) { Tuple expected = expectedResults.next(); Assert.assertTrue("Actual result has less records than expected results", actualResults.hasNext()); Tuple actual = actualResults.next(); // If this tuple contains any bags, bags will be sorted before comparisons if( !expected.equals(actual) ) { // Using string comparisons since error message is more readable // (only showing the part which differs) Assert.assertEquals(expected.toString(), actual.toString()); // if above goes through, simply failing with object comparisons Assert.assertEquals(expected, actual); } count++; } Assert.assertFalse("Actual result has more records than expected results", actualResults.hasNext()); if (expectedRows != null) { Assert.assertEquals((int)expectedRows, count); } } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResList Expected results to validate against */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, List<Tuple> expectedResList) { List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } checkQueryOutputsAfterSort(actualResList, expectedResList); } /** * Helper function to check if the result of Pig Query is in line with expected results. * It sorts actual and expected results before comparison. * The tuple size in the tuple list can vary. Pass by a two-dimension array, it will be converted to be a tuple list. * e.g. expectedTwoDimensionObjects is [{{10, "will_join", 10, "will_join"}, {11, "will_not_join", null}, {null, 12, "will_not_join"}}], * the field size of these 3 tuples are [4,3,3] * * @param actualResultsIt * @param expectedTwoDimensionObjects represents a tuple list, in which the tuple can have variable size. */ static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Object[][] expectedTwoDimensionObjects) { List<Tuple> expectedResTupleList = new ArrayList<Tuple>(); for (int i = 0; i < expectedTwoDimensionObjects.length; ++i) { Tuple t = TupleFactory.getInstance().newTuple(); for (int j = 0; j < expectedTwoDimensionObjects[i].length; ++j) { t.append(expectedTwoDimensionObjects[i][j]); } expectedResTupleList.add(t); } checkQueryOutputsAfterSort(actualResultsIt, expectedResTupleList); } static public void checkQueryOutputsAfterSort( List<Tuple> actualResList, List<Tuple> expectedResList) { Collections.sort(actualResList); Collections.sort(expectedResList); checkQueryOutputs(actualResList.iterator(), expectedResList); } /** * Check if subStr is a subString of str . calls org.junit.Assert.fail if it is not * @param str * @param subStr */ static public void checkStrContainsSubStr(String str, String subStr){ if(!str.contains(subStr)){ fail("String '"+ subStr + "' is not a substring of '" + str + "'"); } } /** * Check if query plan for alias argument produces exception with expected * error message in expectedErr argument. * @param query * @param alias * @param expectedErr * @throws IOException */ static public void checkExceptionMessage(String query, String alias, String expectedErr) throws IOException { PigServer pig = new PigServer(ExecType.LOCAL); boolean foundEx = false; try{ Util.registerMultiLineQuery(pig, query); pig.explain(alias, System.out); }catch(FrontendException e){ foundEx = true; checkMessageInException(e, expectedErr); } if(!foundEx) fail("No exception thrown. Exception is expected."); } public static void checkMessageInException(FrontendException e, String expectedErr) { PigException pigEx = LogUtils.getPigException(e); String message = pigEx.getMessage(); checkErrorMessageContainsExpected(message, expectedErr); } public static void checkErrorMessageContainsExpected(String message, String expectedMessage){ if(!message.contains(expectedMessage)){ String msg = "Expected error message containing '" + expectedMessage + "' but got '" + message + "'" ; fail(msg); } } static private String getFSMkDirCommand(String fileName) { Path parentDir = new Path(fileName).getParent(); String mkdirCommand = parentDir.getName().isEmpty() ? "" : "fs -mkdir -p " + parentDir + "\n"; return mkdirCommand; } /** * Utility method to copy a file form local filesystem to the dfs on * the minicluster for testing in mapreduce mode * @param cluster a reference to the minicluster * @param localFileName the pathname of local file * @param fileNameOnCluster the name with which the file should be created on the minicluster * @throws IOException */ static public void copyFromLocalToCluster(MiniGenericCluster cluster, String localFileName, String fileNameOnCluster) throws IOException { if(Util.WINDOWS){ if (!localFileName.contains(":")) { localFileName = localFileName.replace('\\','/'); } else { localFileName = localFileName.replace('/','\\'); } fileNameOnCluster = fileNameOnCluster.replace('\\','/'); } PigServer ps = new PigServer(cluster.getExecType(), cluster.getProperties()); String script = getFSMkDirCommand(fileNameOnCluster) + "fs -put " + localFileName + " " + fileNameOnCluster; GruntParser parser = new GruntParser(new StringReader(script), ps); parser.setInteractive(false); try { parser.parseStopOnError(); } catch (org.apache.pig.tools.pigscript.parser.ParseException e) { throw new IOException(e); } } static public void copyFromLocalToLocal(String fromLocalFileName, String toLocalFileName) throws IOException { FileUtils.copyFile(new File(fromLocalFileName), new File(toLocalFileName)); } static public void copyFromClusterToLocal(MiniGenericCluster cluster, String fileNameOnCluster, String localFileName) throws IOException { if(Util.WINDOWS){ fileNameOnCluster = fileNameOnCluster.replace('\\','/'); localFileName = localFileName.replace('\\','/'); } File parent = new File(localFileName).getParentFile(); if (!parent.exists()) { parent.mkdirs(); } PrintWriter writer = new PrintWriter(new FileWriter(localFileName)); FileSystem fs = FileSystem.get(ConfigurationUtil.toConfiguration( cluster.getProperties())); if(!fs.exists(new Path(fileNameOnCluster))) { throw new IOException("File " + fileNameOnCluster + " does not exists on the minicluster"); } String line = null; FileStatus fst = fs.getFileStatus(new Path(fileNameOnCluster)); if(fst.isDirectory()) { throw new IOException("Only files from cluster can be copied locally," + " " + fileNameOnCluster + " is a directory"); } FSDataInputStream stream = fs.open(new Path(fileNameOnCluster)); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); while( (line = reader.readLine()) != null) { writer.println(line); } reader.close(); writer.close(); } static public void printQueryOutput(Iterator<Tuple> actualResults, Tuple[] expectedResults) { System.out.println("Expected :") ; for (Tuple expected : expectedResults) { System.out.println(expected.toString()) ; } System.out.println("---End----") ; System.out.println("Actual :") ; while (actualResults.hasNext()) { System.out.println(actualResults.next().toString()) ; } System.out.println("---End----") ; } /** * Helper method to replace all occurrences of "\" with "\\" in a * string. This is useful to fix the file path string on Windows * where "\" is used as the path separator. * * @param str Any string * @return The resulting string */ public static String encodeEscape(String str) { String regex = "\\\\"; String replacement = quoteReplacement("\\\\"); return str.replaceAll(regex, replacement); } public static String generateURI(String filename, PigContext context) throws IOException { if(Util.WINDOWS){ filename = filename.replace('\\','/'); } if (context.getExecType() == ExecType.MAPREDUCE || context.getExecType().name().equals("TEZ") || context.getExecType().name().equals("SPARK")) { return FileLocalizer.hadoopify(filename, context); } else if (context.getExecType().isLocal()) { return filename; } else { throw new IllegalStateException("ExecType: " + context.getExecType()); } } public static Object getPigConstant(String pigConstantAsString) throws ParserException { QueryParserDriver queryParser = new QueryParserDriver( new PigContext(), "util", new HashMap<String, String>() ) ; return queryParser.parseConstant(pigConstantAsString); } /** * Parse list of strings in to list of tuples, convert quoted strings into * @param tupleConstants * @return * @throws ParserException */ public static List<Tuple> getTuplesFromConstantTupleStrings(String[] tupleConstants) throws ParserException { List<Tuple> result = new ArrayList<Tuple>(tupleConstants.length); for(int i = 0; i < tupleConstants.length; i++) { result.add((Tuple) getPigConstant(tupleConstants[i])); } return result; } /** * Parse list of strings in to list of tuples, convert quoted strings into * DataByteArray * @param tupleConstants * @return * @throws ParserException * @throws ExecException */ public static List<Tuple> getTuplesFromConstantTupleStringAsByteArray(String[] tupleConstants) throws ParserException, ExecException { List<Tuple> tuples = getTuplesFromConstantTupleStrings(tupleConstants); for(Tuple t : tuples){ convertStringToDataByteArray(t); } return tuples; } /** * Convert String objects in argument t to DataByteArray objects * @param t * @throws ExecException */ private static void convertStringToDataByteArray(Tuple t) throws ExecException { if(t == null) return; for(int i=0; i<t.size(); i++){ Object col = t.get(i); if(col == null) continue; if(col instanceof String){ DataByteArray dba = (col == null) ? null : new DataByteArray((String)col); t.set(i, dba); }else if(col instanceof Tuple){ convertStringToDataByteArray((Tuple)col); }else if(col instanceof DataBag){ Iterator<Tuple> it = ((DataBag)col).iterator(); while(it.hasNext()){ convertStringToDataByteArray(it.next()); } } } } public static File createFile(String[] data) throws Exception{ return createFile(null,data); } public static File createFile(String filePath, String[] data) throws Exception { File f; if( null == filePath || filePath.isEmpty() ) { f = File.createTempFile("tmp", ""); } else { f = new File(filePath); } if (f.getParent() != null && !(new File(f.getParent())).exists()) { (new File(f.getParent())).mkdirs(); } f.deleteOnExit(); PrintWriter pw = new PrintWriter(f); for (int i=0; i<data.length; i++){ pw.println(data[i]); } pw.close(); return f; } /** * Run default set of optimizer rules on new logical plan * @param lp * @return optimized logical plan * @throws FrontendException */ public static LogicalPlan optimizeNewLP( LogicalPlan lp) throws FrontendException{ DanglingNestedNodeRemover DanglingNestedNodeRemover = new DanglingNestedNodeRemover( lp ); DanglingNestedNodeRemover.visit(); UidResetter uidResetter = new UidResetter( lp ); uidResetter.visit(); SchemaResetter schemaResetter = new SchemaResetter( lp, true /*disable duplicate uid check*/ ); schemaResetter.visit(); StoreAliasSetter storeAliasSetter = new StoreAliasSetter( lp ); storeAliasSetter.visit(); // run optimizer org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer optimizer = new org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer(lp, 100, null); optimizer.optimize(); SortInfoSetter sortInfoSetter = new SortInfoSetter( lp ); sortInfoSetter.visit(); return lp; } /** * migrate old LP(logical plan) to new LP, optimize it, and build physical * plan * @param lp * @param pc PigContext * @return physical plan * @throws Exception */ public static PhysicalPlan buildPhysicalPlanFromNewLP( LogicalPlan lp, PigContext pc) throws Exception { LogToPhyTranslationVisitor visitor = new LogToPhyTranslationVisitor(lp); visitor.setPigContext(pc); visitor.visit(); return visitor.getPhysicalPlan(); } public static MROperPlan buildMRPlan(PhysicalPlan pp, PigContext pc) throws Exception{ MRCompiler comp = new MRCompiler(pp, pc); comp.compile(); comp.aggregateScalarsFiles(); comp.connectSoftLink(); return comp.getMRPlan(); } public static MROperPlan buildMRPlanWithOptimizer(PhysicalPlan pp, PigContext pc) throws Exception { MapRedUtil.checkLeafIsStore(pp, pc); MapReduceLauncher launcher = new MapReduceLauncher(); return launcher.compile(pp,pc); } public static MROperPlan buildMRPlan(String query, PigContext pc) throws Exception { LogicalPlan lp = Util.parse(query, pc); Util.optimizeNewLP(lp); PhysicalPlan pp = Util.buildPhysicalPlanFromNewLP(lp, pc); MROperPlan mrp = Util.buildMRPlanWithOptimizer(pp, pc); return mrp; } public static void registerMultiLineQuery(PigServer pigServer, String query) throws IOException { File f = File.createTempFile("tmp", ""); PrintWriter pw = new PrintWriter(f); pw.println(query); pw.close(); pigServer.registerScript(f.getCanonicalPath()); } public static int executeJavaCommand(String cmd) throws Exception { return executeJavaCommandAndReturnInfo(cmd).exitCode; } public static class ReadStream implements Runnable { InputStream is; Thread thread; String message = ""; public ReadStream(InputStream is) { this.is = is; } public void start () { thread = new Thread (this); thread.start (); } @Override public void run () { try { InputStreamReader isr = new InputStreamReader (is); BufferedReader br = new BufferedReader (isr); while (true) { String s = br.readLine (); if (s == null) break; if (!message.isEmpty()) { message += "\n"; } message += s; } is.close (); } catch (Exception ex) { ex.printStackTrace (); } } public String getMessage() { return message; } } public static ProcessReturnInfo executeJavaCommandAndReturnInfo(String cmd) throws Exception { String javaHome = System.getenv("JAVA_HOME"); if(javaHome != null) { String fileSeparator = System.getProperty("file.separator"); cmd = javaHome + fileSeparator + "bin" + fileSeparator + cmd; } Process cmdProc = Runtime.getRuntime().exec(cmd); ProcessReturnInfo pri = new ProcessReturnInfo(); ReadStream stdoutStream = new ReadStream(cmdProc.getInputStream ()); ReadStream stderrStream = new ReadStream(cmdProc.getErrorStream ()); stdoutStream.start(); stderrStream.start(); cmdProc.waitFor(); pri.exitCode = cmdProc.exitValue(); pri.stdoutContents = stdoutStream.getMessage(); pri.stderrContents = stderrStream.getMessage(); return pri; } public static class ProcessReturnInfo { public int exitCode; public String stderrContents; public String stdoutContents; @Override public String toString() { return "[Exit code: " + exitCode + ", stdout: <" + stdoutContents + ">, " + "stderr: <" + stderrContents + ">"; } } static public boolean deleteDirectory(File path) { if(path.exists()) { File[] files = path.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { deleteDirectory(files[i]); } else { files[i].delete(); } } } return(path.delete()); } /** * @param pigContext * @param fileName * @param input * @throws IOException */ public static void createInputFile(PigContext pigContext, String fileName, String[] input) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); createInputFile(FileSystem.get(conf), fileName, input); } public static String[] readOutput(PigContext pigContext, String fileName) throws IOException { Configuration conf = ConfigurationUtil.toConfiguration( pigContext.getProperties()); return readOutput(FileSystem.get(conf), fileName); } public static void printPlan(LogicalPlan logicalPlan ) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); LogicalPlanPrinter pp = new LogicalPlanPrinter(logicalPlan,ps); pp.visit(); System.err.println(out.toString()); } public static void printPlan(PhysicalPlan physicalPlan) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(out); physicalPlan.explain(ps, "text", true); System.err.println(out.toString()); } public static List<Tuple> readFile2TupleList(String file, String delimiter) throws IOException{ List<Tuple> tuples=new ArrayList<Tuple>(); String line=null; BufferedReader reader=new BufferedReader(new InputStreamReader(new FileInputStream(file))); while((line=reader.readLine())!=null){ String[] tokens=line.split(delimiter); Tuple tuple=TupleFactory.getInstance().newTuple(Arrays.asList(tokens)); tuples.add(tuple); } reader.close(); return tuples; } /** * Delete the existing logFile for the class and set the logging to a * use a new log file and set log level to DEBUG * @param clazz class for which the log file is being set * @param logFile current log file * @return new log file * @throws Exception */ public static File resetLog(Class<?> clazz, File logFile) throws Exception { if (logFile != null) logFile.delete(); Logger logger = Logger.getLogger(clazz); logger.removeAllAppenders(); logger.setLevel(Level.DEBUG); SimpleLayout layout = new SimpleLayout(); File newLogFile = File.createTempFile("log", ""); FileAppender appender = new FileAppender(layout, newLogFile.toString(), false, false, 0); logger.addAppender(appender); return newLogFile; } /** * Check if logFile (does not/)contains the given list of messages. * @param logFile * @param messages * @param expected if true, the messages are expected in the logFile, * otherwise messages should not be there in the log */ public static void checkLogFileMessage(File logFile, String[] messages, boolean expected) { BufferedReader reader = null; try { reader = new BufferedReader(new FileReader(logFile)); String logMessage = ""; String line; while ((line = reader.readLine()) != null) { logMessage = logMessage + line + "\n"; } reader.close(); for (int i = 0; i < messages.length; i++) { boolean present = logMessage.contains(messages[i]); if (expected) { if(!present){ fail("The message " + messages[i] + " is not present in" + "log file contents: " + logMessage); } }else{ if(present){ fail("The message " + messages[i] + " is present in" + "log file contents: " + logMessage); } } } return ; } catch (IOException e) { fail("caught exception while checking log message :" + e); } } public static LogicalPlan buildLp(PigServer pigServer, String query) throws Exception { pigServer.setBatchOn(); pigServer.registerQuery( query ); java.lang.reflect.Method buildLp = pigServer.getClass().getDeclaredMethod("buildLp"); buildLp.setAccessible(true); return (LogicalPlan ) buildLp.invoke( pigServer ); } public static PhysicalPlan buildPp(PigServer pigServer, String query) throws Exception { LogicalPlan lp = buildLp( pigServer, query ); lp.optimize(pigServer.getPigContext()); return ((HExecutionEngine)pigServer.getPigContext().getExecutionEngine()).compile(lp, pigServer.getPigContext().getProperties()); } public static LogicalPlan parse(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } public static LogicalPlan parseAndPreprocess(String query, PigContext pc) throws FrontendException { Map<String, String> fileNameMap = new HashMap<String, String>(); QueryParserDriver parserDriver = new QueryParserDriver( pc, "test", fileNameMap ); org.apache.pig.newplan.logical.relational.LogicalPlan lp = parserDriver.parse( query ); lp.validate(pc, "test", false); return lp; } /** * Replaces any alias in given schema that has name that starts with * "NullAlias" with null . it does a case insensitive comparison of * the alias name * @param sch */ public static void schemaReplaceNullAlias(Schema sch){ if(sch == null) return ; for(FieldSchema fs : sch.getFields()){ if(fs.alias != null && fs.alias.toLowerCase().startsWith("nullalias")){ fs.alias = null; } schemaReplaceNullAlias(fs.schema); } } static public void checkQueryOutputsAfterSort(Iterator<Tuple> actualResultsIt, Tuple[] expectedResArray) { List<Tuple> list = new ArrayList<Tuple>(); Collections.addAll(list, expectedResArray); checkQueryOutputsAfterSort(actualResultsIt, list); } static public void convertBagToSortedBag(Tuple t) { for (int i=0;i<t.size();i++) { Object obj = null; try { obj = t.get(i); } catch (ExecException e) { // shall not happen } if (obj instanceof DataBag) { DataBag bag = (DataBag)obj; Iterator<Tuple> iter = bag.iterator(); DataBag sortedBag = DefaultBagFactory.getInstance().newSortedBag(null); while (iter.hasNext()) { Tuple t2 = iter.next(); sortedBag.add(t2); convertBagToSortedBag(t2); } try { t.set(i, sortedBag); } catch (ExecException e) { // shall not happen } } } } static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, String schemaString) throws IOException { LogicalSchema resultSchema = org.apache.pig.impl.util.Utils.parseSchema(schemaString); checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, resultSchema); } /** * Helper function to check if the result of a Pig Query is in line with * expected results. It sorts actual and expected string results before comparison * * @param actualResultsIt Result of the executed Pig query * @param expectedResArray Expected string results to validate against * @param schema fieldSchema of expecteResArray * @throws IOException */ static public void checkQueryOutputsAfterSortRecursive(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while(actualResultsIt.hasNext()){ actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Collections.sort(actualResList); Collections.sort(expectedResList); Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static String readFile(File file) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(file)); String result = ""; String line; while ((line=reader.readLine())!=null) { result += line; result += "\n"; } reader.close(); return result; } /** * this removes the signature from the serialized plan changing the way the * unique signature is generated should not break this test * @param plan the plan to canonicalize * @return the cleaned up plan */ public static String removeSignature(String plan) { return plan.replaceAll("','','[^']*','scope','true'\\)\\)", "','','','scope','true'))"); } public static boolean isHadoop203plus() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.2\\b")) return false; return true; } public static boolean isHadoop205() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b0\\.20\\.205\\..+")) return true; return false; } public static boolean isHadoop1_x() { String version = org.apache.hadoop.util.VersionInfo.getVersion(); if (version.matches("\\b1\\.*\\..+")) return true; return false; } public static boolean isSpark2_2_plus() throws IOException { String sparkVersion = package$.MODULE$.SPARK_VERSION(); return sparkVersion != null && sparkVersion.matches("2\\.([\\d&&[^01]]|[\\d]{2,})\\..*"); } public static void sortQueryOutputsIfNeed(List<Tuple> actualResList, boolean toSort){ if( toSort == true) { for (Tuple t : actualResList) { Util.convertBagToSortedBag(t); } Collections.sort(actualResList); } } public static void checkQueryOutputs(Iterator<Tuple> actualResults, List<Tuple> expectedResults, boolean checkAfterSort) { if (checkAfterSort) { checkQueryOutputsAfterSort(actualResults, expectedResults); } else { checkQueryOutputs(actualResults, expectedResults); } } static public void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema, boolean checkAfterSort) throws IOException { if (checkAfterSort) { checkQueryOutputsAfterSortRecursive(actualResultsIt, expectedResArray, schema); } else { checkQueryOutputs(actualResultsIt, expectedResArray, schema); } } static void checkQueryOutputs(Iterator<Tuple> actualResultsIt, String[] expectedResArray, LogicalSchema schema) throws IOException { LogicalFieldSchema fs = new LogicalFieldSchema("tuple", schema, DataType.TUPLE); ResourceFieldSchema rfs = new ResourceFieldSchema(fs); LoadCaster caster = new Utf8StorageConverter(); List<Tuple> actualResList = new ArrayList<Tuple>(); while (actualResultsIt.hasNext()) { actualResList.add(actualResultsIt.next()); } List<Tuple> expectedResList = new ArrayList<Tuple>(); for (String str : expectedResArray) { Tuple newTuple = caster.bytesToTuple(str.getBytes(), rfs); expectedResList.add(newTuple); } for (Tuple t : actualResList) { convertBagToSortedBag(t); } for (Tuple t : expectedResList) { convertBagToSortedBag(t); } Assert.assertEquals("Comparing actual and expected results. ", expectedResList, actualResList); } public static void assertParallelValues(long defaultParallel, long requestedParallel, long estimatedParallel, long runtimeParallel, Configuration conf) { assertConfLong(conf, "pig.info.reducers.default.parallel", defaultParallel); assertConfLong(conf, "pig.info.reducers.requested.parallel", requestedParallel); assertConfLong(conf, "pig.info.reducers.estimated.parallel", estimatedParallel); assertConfLong(conf, MRConfiguration.REDUCE_TASKS, runtimeParallel); } public static void assertConfLong(Configuration conf, String param, long expected) { assertEquals("Unexpected value found in configs for " + param, expected, conf.getLong(param, -1)); } /** * Returns a PathFilter that filters out filenames that start with _. * @return PathFilter */ public static PathFilter getSuccessMarkerPathFilter() { return new PathFilter() { @Override public boolean accept(Path p) { return !p.getName().startsWith("_"); } }; } /** * * @param expected * Exception class that is expected to be thrown * @param found * Exception that occurred in the test * @param message * expected String to verify against */ public static void assertExceptionAndMessage(Class<?> expected, Exception found, String message) { assertEquals(expected, found.getClass()); assertEquals(found.getMessage(), message); } /** * Called to reset ThreadLocal or static states that PigServer depends on * when a test suite has testcases switching between LOCAL and MAPREDUCE/TEZ * execution modes */ public static void resetStateForExecModeSwitch() { FileLocalizer.setInitialized(false); // For tez testing, we want to avoid TezResourceManager/LocalResource reuse // (when switching between local and mapreduce/tez) TezResourceManager.dropInstance(); // TODO: once we have Tez local mode, we can get rid of this. For now, // if we run this test suite in Tez mode and there are some tests // in LOCAL mode, we need to set ScriptState to // null to force ScriptState gets initialized every time. ScriptState.start(null); } public static boolean isMapredExecType(ExecType execType) { return execType == ExecType.MAPREDUCE; } public static boolean isTezExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("tez")) { return true; } return false; } public static boolean isSparkExecType(ExecType execType) { if (execType.name().toLowerCase().startsWith("spark")) { return true; } return false; } public static String findPigJarName() { final String suffix = System.getProperty("hadoopversion").equals("20") ? "1" : "2"; File baseDir = new File("."); String[] jarNames = baseDir.list(new FilenameFilter() { @Override public boolean accept(File dir, String name) { if (!name.matches("pig.*h" + suffix + "\\.jar")) { return false; } if (name.contains("all")) { return false; } return true; } }); if (jarNames==null || jarNames.length!=1) { throw new RuntimeException("Cannot find pig.jar"); } return jarNames[0]; } public static ExecType getLocalTestMode() throws Exception { String execType = System.getProperty("test.exec.type"); if (execType != null) { if (execType.equals("tez")) { return ExecTypeProvider.fromString("tez_local"); } else if (execType.equals("spark")) { return ExecTypeProvider.fromString("spark_local"); } } return ExecTypeProvider.fromString("local"); } public static void createLogAppender(String appenderName, Writer writer, Class...clazzes) { WriterAppender writerAppender = new WriterAppender(new PatternLayout("%d [%t] %-5p %c %x - %m%n"), writer); writerAppender.setName(appenderName); for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); logger.addAppender(writerAppender); } } public static void removeLogAppender(String appenderName, Class...clazzes) { for (Class clazz : clazzes) { Logger logger = Logger.getLogger(clazz); Appender appender = logger.getAppender(appenderName); appender.close(); logger.removeAppender(appenderName); } } public static Path getFirstPartFile(Path path) throws Exception { FileStatus[] parts = FileSystem.get(path.toUri(), new Configuration()).listStatus(path, new PathFilter() { @Override public boolean accept(Path path) { return path.getName().startsWith("part-"); } }); return parts[0].getPath(); } public static File getFirstPartFile(File dir) throws Exception { File[] parts = dir.listFiles(new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.startsWith("part-"); }; }); return parts[0]; } @SuppressWarnings("rawtypes") public static String getTestDirectory(Class testClass) { return TEST_DIR + Path.SEPARATOR + "testdata" + Path.SEPARATOR +testClass.getSimpleName(); } }
Java
FROM balenalib/amd64-alpine:3.6 RUN apk add --update \ openrc \ && rm -rf /var/cache/apk/* # Config OpenRC RUN sed -i '/tty/d' /etc/inittab COPY rc.conf /etc/ COPY resin /etc/init.d/ RUN rc-update add resin default COPY entry.sh /usr/bin/entry.sh ENTRYPOINT ["/usr/bin/entry.sh"]
Java
import os import sys import argparse from pandaharvester.harvesterconfig import harvester_config from pandaharvester.harvestermisc.selfcheck import harvesterPackageInfo def main(): oparser = argparse.ArgumentParser(prog='prescript', add_help=True) oparser.add_argument('-f', '--local_info_file', action='store', dest='local_info_file', help='path of harvester local info file') if len(sys.argv) == 1: print('No argument or flag specified. Did nothing') sys.exit(0) args = oparser.parse_args(sys.argv[1:]) local_info_file = os.path.normpath(args.local_info_file) hpi = harvesterPackageInfo(local_info_file=local_info_file) if hpi.package_changed: print('Harvester package changed') #TODO pass hpi.renew_local_info() else: print('Harvester package unchanged. Skipped') if __name__ == '__main__': main()
Java
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.CSharp.UnitTests.CodeGen { public class StringConcatTests : CSharpTestBase { [Fact] public void ConcatConsts() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""A"" + ""B""); Console.WriteLine(""A"" + (string)null); Console.WriteLine(""A"" + (object)null); Console.WriteLine(""A"" + (object)null + ""A"" + (object)null); Console.WriteLine((string)null + ""B""); Console.WriteLine((object)null + ""B""); Console.WriteLine((string)null + (object)null); Console.WriteLine(""#""); Console.WriteLine((object)null + (string)null); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"AB A A AA B B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 101 (0x65) .maxstack 1 IL_0000: ldstr ""AB"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""A"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""A"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr ""AA"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""B"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""B"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr """" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""#"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr """" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""#"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } "); } [Fact] public void ConcatDefaults() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""A"" + ""B""); Console.WriteLine(""A"" + default(string)); Console.WriteLine(""A"" + default(object)); Console.WriteLine(""A"" + default(object) + ""A"" + default(object)); Console.WriteLine(default(string) + ""B""); Console.WriteLine(default(object) + ""B""); Console.WriteLine(default(string) + default(object)); Console.WriteLine(""#""); Console.WriteLine(default(object) + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"AB A A AA B B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 101 (0x65) .maxstack 1 IL_0000: ldstr ""AB"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""A"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""A"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr ""AA"" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""B"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr ""B"" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr """" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""#"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr """" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""#"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ret } "); } [Fact] public void ConcatFour() { var source = @" using System; public class Test { static void Main() { var s = ""qq""; var ss = s + s + s + s; Console.WriteLine(ss); } } "; var comp = CompileAndVerify(source, expectedOutput: @"qqqqqqqq" ); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 19 (0x13) .maxstack 4 IL_0000: ldstr ""qq"" IL_0005: dup IL_0006: dup IL_0007: dup IL_0008: call ""string string.Concat(string, string, string, string)"" IL_000d: call ""void System.Console.WriteLine(string)"" IL_0012: ret } "); } [Fact] public void ConcatMerge() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine( (S + ""A"") + (""B"" + S)); Console.WriteLine( (O + ""A"") + (""B"" + O)); Console.WriteLine( ((S + ""A"") + (""B"" + S)) + ((O + ""A"") + (""B"" + O))); Console.WriteLine( ((O + ""A"") + (S + ""A"")) + ((""B"" + O) + (S + ""A""))); } } "; var comp = CompileAndVerify(source, expectedOutput: @"FABF OABO FABFOABO OAFABOFA"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 259 (0x103) .maxstack 5 IL_0000: ldsfld ""string Test.S"" IL_0005: ldstr ""AB"" IL_000a: ldsfld ""string Test.S"" IL_000f: call ""string string.Concat(string, string, string)"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: ldsfld ""object Test.O"" IL_001e: dup IL_001f: brtrue.s IL_0025 IL_0021: pop IL_0022: ldnull IL_0023: br.s IL_002a IL_0025: callvirt ""string object.ToString()"" IL_002a: ldstr ""AB"" IL_002f: ldsfld ""object Test.O"" IL_0034: dup IL_0035: brtrue.s IL_003b IL_0037: pop IL_0038: ldnull IL_0039: br.s IL_0040 IL_003b: callvirt ""string object.ToString()"" IL_0040: call ""string string.Concat(string, string, string)"" IL_0045: call ""void System.Console.WriteLine(string)"" IL_004a: ldc.i4.6 IL_004b: newarr ""string"" IL_0050: dup IL_0051: ldc.i4.0 IL_0052: ldsfld ""string Test.S"" IL_0057: stelem.ref IL_0058: dup IL_0059: ldc.i4.1 IL_005a: ldstr ""AB"" IL_005f: stelem.ref IL_0060: dup IL_0061: ldc.i4.2 IL_0062: ldsfld ""string Test.S"" IL_0067: stelem.ref IL_0068: dup IL_0069: ldc.i4.3 IL_006a: ldsfld ""object Test.O"" IL_006f: dup IL_0070: brtrue.s IL_0076 IL_0072: pop IL_0073: ldnull IL_0074: br.s IL_007b IL_0076: callvirt ""string object.ToString()"" IL_007b: stelem.ref IL_007c: dup IL_007d: ldc.i4.4 IL_007e: ldstr ""AB"" IL_0083: stelem.ref IL_0084: dup IL_0085: ldc.i4.5 IL_0086: ldsfld ""object Test.O"" IL_008b: dup IL_008c: brtrue.s IL_0092 IL_008e: pop IL_008f: ldnull IL_0090: br.s IL_0097 IL_0092: callvirt ""string object.ToString()"" IL_0097: stelem.ref IL_0098: call ""string string.Concat(params string[])"" IL_009d: call ""void System.Console.WriteLine(string)"" IL_00a2: ldc.i4.7 IL_00a3: newarr ""string"" IL_00a8: dup IL_00a9: ldc.i4.0 IL_00aa: ldsfld ""object Test.O"" IL_00af: dup IL_00b0: brtrue.s IL_00b6 IL_00b2: pop IL_00b3: ldnull IL_00b4: br.s IL_00bb IL_00b6: callvirt ""string object.ToString()"" IL_00bb: stelem.ref IL_00bc: dup IL_00bd: ldc.i4.1 IL_00be: ldstr ""A"" IL_00c3: stelem.ref IL_00c4: dup IL_00c5: ldc.i4.2 IL_00c6: ldsfld ""string Test.S"" IL_00cb: stelem.ref IL_00cc: dup IL_00cd: ldc.i4.3 IL_00ce: ldstr ""AB"" IL_00d3: stelem.ref IL_00d4: dup IL_00d5: ldc.i4.4 IL_00d6: ldsfld ""object Test.O"" IL_00db: dup IL_00dc: brtrue.s IL_00e2 IL_00de: pop IL_00df: ldnull IL_00e0: br.s IL_00e7 IL_00e2: callvirt ""string object.ToString()"" IL_00e7: stelem.ref IL_00e8: dup IL_00e9: ldc.i4.5 IL_00ea: ldsfld ""string Test.S"" IL_00ef: stelem.ref IL_00f0: dup IL_00f1: ldc.i4.6 IL_00f2: ldstr ""A"" IL_00f7: stelem.ref IL_00f8: call ""string string.Concat(params string[])"" IL_00fd: call ""void System.Console.WriteLine(string)"" IL_0102: ret } "); } [Fact] public void ConcatMergeFromOne() { var source = @" using System; public class Test { private static string S = ""F""; static void Main() { Console.WriteLine( (S + null) + (S + ""A"") + (""B"" + S) + (S + null)); } } "; var comp = CompileAndVerify(source, expectedOutput: @"FFABFF"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 57 (0x39) .maxstack 4 IL_0000: ldc.i4.5 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldsfld ""string Test.S"" IL_000d: stelem.ref IL_000e: dup IL_000f: ldc.i4.1 IL_0010: ldsfld ""string Test.S"" IL_0015: stelem.ref IL_0016: dup IL_0017: ldc.i4.2 IL_0018: ldstr ""AB"" IL_001d: stelem.ref IL_001e: dup IL_001f: ldc.i4.3 IL_0020: ldsfld ""string Test.S"" IL_0025: stelem.ref IL_0026: dup IL_0027: ldc.i4.4 IL_0028: ldsfld ""string Test.S"" IL_002d: stelem.ref IL_002e: call ""string string.Concat(params string[])"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ret } "); } [Fact] public void ConcatOneArg() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + null); Console.WriteLine(S + null); Console.WriteLine(O?.ToString() + null); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O F O"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 82 (0x52) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ldsfld ""string Test.S"" IL_0024: dup IL_0025: brtrue.s IL_002d IL_0027: pop IL_0028: ldstr """" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldsfld ""object Test.O"" IL_0037: dup IL_0038: brtrue.s IL_003e IL_003a: pop IL_003b: ldnull IL_003c: br.s IL_0043 IL_003e: callvirt ""string object.ToString()"" IL_0043: dup IL_0044: brtrue.s IL_004c IL_0046: pop IL_0047: ldstr """" IL_004c: call ""void System.Console.WriteLine(string)"" IL_0051: ret } "); } [Fact] public void ConcatOneArgWithNullToString() { var source = @" using System; public class Test { private static object C = new C(); static void Main() { Console.WriteLine((C + null) == """" ? ""Y"" : ""N""); Console.WriteLine((C + null + null) == """" ? ""Y"" : ""N""); } } public class C { public override string ToString() => null; } "; var comp = CompileAndVerify(source, expectedOutput: @"Y Y"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 111 (0x6f) .maxstack 2 IL_0000: ldsfld ""object Test.C"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: ldstr """" IL_001f: call ""bool string.op_Equality(string, string)"" IL_0024: brtrue.s IL_002d IL_0026: ldstr ""N"" IL_002b: br.s IL_0032 IL_002d: ldstr ""Y"" IL_0032: call ""void System.Console.WriteLine(string)"" IL_0037: ldsfld ""object Test.C"" IL_003c: dup IL_003d: brtrue.s IL_0043 IL_003f: pop IL_0040: ldnull IL_0041: br.s IL_0048 IL_0043: callvirt ""string object.ToString()"" IL_0048: dup IL_0049: brtrue.s IL_0051 IL_004b: pop IL_004c: ldstr """" IL_0051: ldstr """" IL_0056: call ""bool string.op_Equality(string, string)"" IL_005b: brtrue.s IL_0064 IL_005d: ldstr ""N"" IL_0062: br.s IL_0069 IL_0064: ldstr ""Y"" IL_0069: call ""void System.Console.WriteLine(string)"" IL_006e: ret } "); } [Fact] public void ConcatOneArgWithExplicitConcatCall() { var source = @" using System; public class Test { private static object O = ""O""; static void Main() { Console.WriteLine(string.Concat(O) + null); Console.WriteLine(string.Concat(O) + null + null); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O O"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 49 (0x31) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: call ""string string.Concat(object)"" IL_000a: dup IL_000b: brtrue.s IL_0013 IL_000d: pop IL_000e: ldstr """" IL_0013: call ""void System.Console.WriteLine(string)"" IL_0018: ldsfld ""object Test.O"" IL_001d: call ""string string.Concat(object)"" IL_0022: dup IL_0023: brtrue.s IL_002b IL_0025: pop IL_0026: ldstr """" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ret } "); } [Fact] public void ConcatEmptyString() { var source = @" using System; public class Test { private static string S = ""F""; private static object O = ""O""; static void Main() { Console.WriteLine(O + """"); Console.WriteLine(S + """"); } } "; var comp = CompileAndVerify(source, expectedOutput: @"O F"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 51 (0x33) .maxstack 2 IL_0000: ldsfld ""object Test.O"" IL_0005: dup IL_0006: brtrue.s IL_000c IL_0008: pop IL_0009: ldnull IL_000a: br.s IL_0011 IL_000c: callvirt ""string object.ToString()"" IL_0011: dup IL_0012: brtrue.s IL_001a IL_0014: pop IL_0015: ldstr """" IL_001a: call ""void System.Console.WriteLine(string)"" IL_001f: ldsfld ""string Test.S"" IL_0024: dup IL_0025: brtrue.s IL_002d IL_0027: pop IL_0028: ldstr """" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ret } "); } [Fact] [WorkItem(679120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/679120")] public void ConcatEmptyArray() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""Start""); Console.WriteLine(string.Concat(new string[] {})); Console.WriteLine(string.Concat(new string[] {}) + string.Concat(new string[] {})); Console.WriteLine(""A"" + string.Concat(new string[] {})); Console.WriteLine(string.Concat(new string[] {}) + ""B""); Console.WriteLine(""End""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"Start A B End"); comp.VerifyDiagnostics(); // NOTE: Dev11 doesn't optimize away string.Concat(new string[0]) either. // We could add an optimization, but it's unlikely to occur in real code. comp.VerifyIL("Test.Main", @" { // Code size 67 (0x43) .maxstack 1 IL_0000: ldstr ""Start"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldc.i4.0 IL_000b: newarr ""string"" IL_0010: call ""string string.Concat(params string[])"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldstr """" IL_001f: call ""void System.Console.WriteLine(string)"" IL_0024: ldstr ""A"" IL_0029: call ""void System.Console.WriteLine(string)"" IL_002e: ldstr ""B"" IL_0033: call ""void System.Console.WriteLine(string)"" IL_0038: ldstr ""End"" IL_003d: call ""void System.Console.WriteLine(string)"" IL_0042: ret } "); } [WorkItem(529064, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529064")] [Fact] public void TestStringConcatOnLiteralAndCompound() { var source = @" public class Test { static string field01 = ""A""; static string field02 = ""B""; static void Main() { field01 += field02 + ""C"" + ""D""; } } "; var comp = CompileAndVerify(source); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 3 IL_0000: ldsfld ""string Test.field01"" IL_0005: ldsfld ""string Test.field02"" IL_000a: ldstr ""CD"" IL_000f: call ""string string.Concat(string, string, string)"" IL_0014: stsfld ""string Test.field01"" IL_0019: ret } "); } [Fact] public void ConcatGeneric() { var source = @" using System; public class Test { static void Main() { TestMethod<int>(); } private static void TestMethod<T>() { Console.WriteLine(""A"" + default(T)); Console.WriteLine(""A"" + default(T) + ""A"" + default(T)); Console.WriteLine(default(T) + ""B""); Console.WriteLine(default(string) + default(T)); Console.WriteLine(""#""); Console.WriteLine(default(T) + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"A0 A0A0 0B 0 # 0 #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.TestMethod<T>()", @" { // Code size 291 (0x123) .maxstack 4 .locals init (T V_0) IL_0000: ldstr ""A"" IL_0005: ldloca.s V_0 IL_0007: initobj ""T"" IL_000d: ldloc.0 IL_000e: box ""T"" IL_0013: brtrue.s IL_0018 IL_0015: ldnull IL_0016: br.s IL_0025 IL_0018: ldloca.s V_0 IL_001a: constrained. ""T"" IL_0020: callvirt ""string object.ToString()"" IL_0025: call ""string string.Concat(string, string)"" IL_002a: call ""void System.Console.WriteLine(string)"" IL_002f: ldstr ""A"" IL_0034: ldloca.s V_0 IL_0036: initobj ""T"" IL_003c: ldloc.0 IL_003d: box ""T"" IL_0042: brtrue.s IL_0047 IL_0044: ldnull IL_0045: br.s IL_0054 IL_0047: ldloca.s V_0 IL_0049: constrained. ""T"" IL_004f: callvirt ""string object.ToString()"" IL_0054: ldstr ""A"" IL_0059: ldloca.s V_0 IL_005b: initobj ""T"" IL_0061: ldloc.0 IL_0062: box ""T"" IL_0067: brtrue.s IL_006c IL_0069: ldnull IL_006a: br.s IL_0079 IL_006c: ldloca.s V_0 IL_006e: constrained. ""T"" IL_0074: callvirt ""string object.ToString()"" IL_0079: call ""string string.Concat(string, string, string, string)"" IL_007e: call ""void System.Console.WriteLine(string)"" IL_0083: ldloca.s V_0 IL_0085: initobj ""T"" IL_008b: ldloc.0 IL_008c: box ""T"" IL_0091: brtrue.s IL_0096 IL_0093: ldnull IL_0094: br.s IL_00a3 IL_0096: ldloca.s V_0 IL_0098: constrained. ""T"" IL_009e: callvirt ""string object.ToString()"" IL_00a3: ldstr ""B"" IL_00a8: call ""string string.Concat(string, string)"" IL_00ad: call ""void System.Console.WriteLine(string)"" IL_00b2: ldloca.s V_0 IL_00b4: initobj ""T"" IL_00ba: ldloc.0 IL_00bb: box ""T"" IL_00c0: brtrue.s IL_00c5 IL_00c2: ldnull IL_00c3: br.s IL_00d2 IL_00c5: ldloca.s V_0 IL_00c7: constrained. ""T"" IL_00cd: callvirt ""string object.ToString()"" IL_00d2: dup IL_00d3: brtrue.s IL_00db IL_00d5: pop IL_00d6: ldstr """" IL_00db: call ""void System.Console.WriteLine(string)"" IL_00e0: ldstr ""#"" IL_00e5: call ""void System.Console.WriteLine(string)"" IL_00ea: ldloca.s V_0 IL_00ec: initobj ""T"" IL_00f2: ldloc.0 IL_00f3: box ""T"" IL_00f8: brtrue.s IL_00fd IL_00fa: ldnull IL_00fb: br.s IL_010a IL_00fd: ldloca.s V_0 IL_00ff: constrained. ""T"" IL_0105: callvirt ""string object.ToString()"" IL_010a: dup IL_010b: brtrue.s IL_0113 IL_010d: pop IL_010e: ldstr """" IL_0113: call ""void System.Console.WriteLine(string)"" IL_0118: ldstr ""#"" IL_011d: call ""void System.Console.WriteLine(string)"" IL_0122: ret } "); } [Fact] public void ConcatGenericConstrained() { var source = @" using System; public class Test { static void Main() { TestMethod<Exception, Exception>(); } private static void TestMethod<T, U>() where T:class where U: class { Console.WriteLine(""A"" + default(T)); Console.WriteLine(""A"" + default(T) + ""A"" + default(T)); Console.WriteLine(default(T) + ""B""); Console.WriteLine(default(string) + default(T)); Console.WriteLine(""#""); Console.WriteLine(default(T) + default(string)); Console.WriteLine(""#""); Console.WriteLine(""A"" + (U)null); Console.WriteLine(""A"" + (U)null + ""A"" + (U)null); Console.WriteLine((U)null + ""B""); Console.WriteLine(default(string) + (U)null); Console.WriteLine(""#""); Console.WriteLine((U)null + default(string)); Console.WriteLine(""#""); } } "; var comp = CompileAndVerify(source, expectedOutput: @"A AA B # # A AA B # #"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.TestMethod<T, U>()", @" { // Code size 141 (0x8d) .maxstack 1 IL_0000: ldstr ""A"" IL_0005: call ""void System.Console.WriteLine(string)"" IL_000a: ldstr ""AA"" IL_000f: call ""void System.Console.WriteLine(string)"" IL_0014: ldstr ""B"" IL_0019: call ""void System.Console.WriteLine(string)"" IL_001e: ldstr """" IL_0023: call ""void System.Console.WriteLine(string)"" IL_0028: ldstr ""#"" IL_002d: call ""void System.Console.WriteLine(string)"" IL_0032: ldstr """" IL_0037: call ""void System.Console.WriteLine(string)"" IL_003c: ldstr ""#"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldstr ""A"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ldstr ""AA"" IL_0055: call ""void System.Console.WriteLine(string)"" IL_005a: ldstr ""B"" IL_005f: call ""void System.Console.WriteLine(string)"" IL_0064: ldstr """" IL_0069: call ""void System.Console.WriteLine(string)"" IL_006e: ldstr ""#"" IL_0073: call ""void System.Console.WriteLine(string)"" IL_0078: ldstr """" IL_007d: call ""void System.Console.WriteLine(string)"" IL_0082: ldstr ""#"" IL_0087: call ""void System.Console.WriteLine(string)"" IL_008c: ret } "); } [Fact] public void ConcatGenericUnconstrained() { var source = @" using System; class Test { static void Main() { var p1 = new Printer<string>(""F""); p1.Print(""P""); p1.Print(null); var p2 = new Printer<string>(null); p2.Print(""P""); p2.Print(null); var p3 = new Printer<MutableStruct>(new MutableStruct()); MutableStruct m = new MutableStruct(); p3.Print(m); p3.Print(m); } } class Printer<T> { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); } "; var comp = CompileAndVerify(source, expectedOutput: @"PPFF FF PP 1111 1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 125 (0x7d) .maxstack 4 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloc.0 IL_0003: box ""T"" IL_0008: brtrue.s IL_000d IL_000a: ldnull IL_000b: br.s IL_001a IL_000d: ldloca.s V_0 IL_000f: constrained. ""T"" IL_0015: callvirt ""string object.ToString()"" IL_001a: ldarg.1 IL_001b: stloc.0 IL_001c: ldloc.0 IL_001d: box ""T"" IL_0022: brtrue.s IL_0027 IL_0024: ldnull IL_0025: br.s IL_0034 IL_0027: ldloca.s V_0 IL_0029: constrained. ""T"" IL_002f: callvirt ""string object.ToString()"" IL_0034: ldarg.0 IL_0035: ldfld ""T Printer<T>.field"" IL_003a: stloc.0 IL_003b: ldloc.0 IL_003c: box ""T"" IL_0041: brtrue.s IL_0046 IL_0043: ldnull IL_0044: br.s IL_0053 IL_0046: ldloca.s V_0 IL_0048: constrained. ""T"" IL_004e: callvirt ""string object.ToString()"" IL_0053: ldarg.0 IL_0054: ldfld ""T Printer<T>.field"" IL_0059: stloc.0 IL_005a: ldloc.0 IL_005b: box ""T"" IL_0060: brtrue.s IL_0065 IL_0062: ldnull IL_0063: br.s IL_0072 IL_0065: ldloca.s V_0 IL_0067: constrained. ""T"" IL_006d: callvirt ""string object.ToString()"" IL_0072: call ""string string.Concat(string, string, string, string)"" IL_0077: call ""void System.Console.WriteLine(string)"" IL_007c: ret } "); } [Fact] public void ConcatGenericConstrainedClass() { var source = @" using System; class Test { static void Main() { var p1 = new Printer<string>(""F""); p1.Print(""P""); p1.Print(null); var p2 = new Printer<string>(null); p2.Print(""P""); p2.Print(null); } } class Printer<T> where T : class { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } }"; var comp = CompileAndVerify(source, expectedOutput: @"PPFF FF PP "); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 93 (0x5d) .maxstack 5 IL_0000: ldarg.1 IL_0001: box ""T"" IL_0006: dup IL_0007: brtrue.s IL_000d IL_0009: pop IL_000a: ldnull IL_000b: br.s IL_0012 IL_000d: callvirt ""string object.ToString()"" IL_0012: ldarg.1 IL_0013: box ""T"" IL_0018: dup IL_0019: brtrue.s IL_001f IL_001b: pop IL_001c: ldnull IL_001d: br.s IL_0024 IL_001f: callvirt ""string object.ToString()"" IL_0024: ldarg.0 IL_0025: ldfld ""T Printer<T>.field"" IL_002a: box ""T"" IL_002f: dup IL_0030: brtrue.s IL_0036 IL_0032: pop IL_0033: ldnull IL_0034: br.s IL_003b IL_0036: callvirt ""string object.ToString()"" IL_003b: ldarg.0 IL_003c: ldfld ""T Printer<T>.field"" IL_0041: box ""T"" IL_0046: dup IL_0047: brtrue.s IL_004d IL_0049: pop IL_004a: ldnull IL_004b: br.s IL_0052 IL_004d: callvirt ""string object.ToString()"" IL_0052: call ""string string.Concat(string, string, string, string)"" IL_0057: call ""void System.Console.WriteLine(string)"" IL_005c: ret } "); } [Fact] public void ConcatGenericConstrainedStruct() { var source = @" using System; class Test { static void Main() { MutableStruct m = new MutableStruct(); var p1 = new Printer<MutableStruct>(new MutableStruct()); p1.Print(m); p1.Print(m); } } class Printer<T> where T : struct { private T field; public Printer(T field) => this.field = field; public void Print(T p) { Console.WriteLine("""" + p + p + field + field); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); }"; var comp = CompileAndVerify(source, expectedOutput: @"1111 1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Printer<T>.Print", @" { // Code size 81 (0x51) .maxstack 4 .locals init (T V_0) IL_0000: ldarg.1 IL_0001: stloc.0 IL_0002: ldloca.s V_0 IL_0004: constrained. ""T"" IL_000a: callvirt ""string object.ToString()"" IL_000f: ldarg.1 IL_0010: stloc.0 IL_0011: ldloca.s V_0 IL_0013: constrained. ""T"" IL_0019: callvirt ""string object.ToString()"" IL_001e: ldarg.0 IL_001f: ldfld ""T Printer<T>.field"" IL_0024: stloc.0 IL_0025: ldloca.s V_0 IL_0027: constrained. ""T"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldarg.0 IL_0033: ldfld ""T Printer<T>.field"" IL_0038: stloc.0 IL_0039: ldloca.s V_0 IL_003b: constrained. ""T"" IL_0041: callvirt ""string object.ToString()"" IL_0046: call ""string string.Concat(string, string, string, string)"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret } "); } [Fact] public void ConcatWithOtherOptimizations() { var source = @" using System; public class Test { static void Main() { var expr1 = ""hi""; var expr2 = ""bye""; // expr1 is optimized away // only expr2 should be lifted!! Func<string> f = () => (""abc"" + ""def"" + null ?? expr1 + ""moo"" + ""baz"") + expr2; System.Console.WriteLine(f()); } } "; var comp = CompileAndVerify(source, expectedOutput: @"abcdefbye"); comp.VerifyDiagnostics(); // IMPORTANT!! only c__DisplayClass0.expr2 should be initialized, // there should not be such thing as c__DisplayClass0.expr1 comp.VerifyIL("Test.Main", @" { // Code size 38 (0x26) .maxstack 3 IL_0000: newobj ""Test.<>c__DisplayClass0_0..ctor()"" IL_0005: dup IL_0006: ldstr ""bye"" IL_000b: stfld ""string Test.<>c__DisplayClass0_0.expr2"" IL_0010: ldftn ""string Test.<>c__DisplayClass0_0.<Main>b__0()"" IL_0016: newobj ""System.Func<string>..ctor(object, System.IntPtr)"" IL_001b: callvirt ""string System.Func<string>.Invoke()"" IL_0020: call ""void System.Console.WriteLine(string)"" IL_0025: ret } "); } [Fact, WorkItem(1092853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092853")] public void ConcatWithNullCoalescedNullLiteral() { const string source = @" class Repro { static string Bug(string s) { string x = """"; x += s ?? null; return x; } static void Main() { System.Console.Write(""\""{0}\"""", Bug(null)); } }"; var comp = CompileAndVerify(source, expectedOutput: "\"\""); comp.VerifyDiagnostics(); comp.VerifyIL("Repro.Bug", @" { // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldarg.0 IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldnull IL_000b: call ""string string.Concat(string, string)"" IL_0010: ret } "); } [Fact, WorkItem(1092853, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1092853")] public void ConcatWithNullCoalescedNullLiteral_2() { const string source = @" class Repro { static string Bug(string s) { string x = """"; x += s ?? ((string)null ?? null); return x; } static void Main() { System.Console.Write(""\""{0}\"""", Bug(null)); } }"; var comp = CompileAndVerify(source, expectedOutput: "\"\""); comp.VerifyIL("Repro.Bug", @" { // Code size 17 (0x11) .maxstack 3 IL_0000: ldstr """" IL_0005: ldarg.0 IL_0006: dup IL_0007: brtrue.s IL_000b IL_0009: pop IL_000a: ldnull IL_000b: call ""string string.Concat(string, string)"" IL_0010: ret } "); } [Fact] public void ConcatMutableStruct() { var source = @" using System; class Test { static MutableStruct f = new MutableStruct(); static void Main() { MutableStruct l = new MutableStruct(); Console.WriteLine("""" + l + l + f + f); } } struct MutableStruct { private int i; public override string ToString() => (++i).ToString(); } "; var comp = CompileAndVerify(source, expectedOutput: @"1111"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 87 (0x57) .maxstack 4 .locals init (MutableStruct V_0, //l MutableStruct V_1) IL_0000: ldloca.s V_0 IL_0002: initobj ""MutableStruct"" IL_0008: ldloc.0 IL_0009: stloc.1 IL_000a: ldloca.s V_1 IL_000c: constrained. ""MutableStruct"" IL_0012: callvirt ""string object.ToString()"" IL_0017: ldloc.0 IL_0018: stloc.1 IL_0019: ldloca.s V_1 IL_001b: constrained. ""MutableStruct"" IL_0021: callvirt ""string object.ToString()"" IL_0026: ldsfld ""MutableStruct Test.f"" IL_002b: stloc.1 IL_002c: ldloca.s V_1 IL_002e: constrained. ""MutableStruct"" IL_0034: callvirt ""string object.ToString()"" IL_0039: ldsfld ""MutableStruct Test.f"" IL_003e: stloc.1 IL_003f: ldloca.s V_1 IL_0041: constrained. ""MutableStruct"" IL_0047: callvirt ""string object.ToString()"" IL_004c: call ""string string.Concat(string, string, string, string)"" IL_0051: call ""void System.Console.WriteLine(string)"" IL_0056: ret }"); } [Fact] public void ConcatMutableStructsSideEffects() { const string source = @" using System; using static System.Console; struct Mutable { int x; public override string ToString() => (x++).ToString(); } class Test { static Mutable m = new Mutable(); static void Main() { Write(""("" + m + "")""); // (0) Write(""("" + m + "")""); // (0) Write(""("" + m.ToString() + "")""); // (0) Write(""("" + m.ToString() + "")""); // (1) Write(""("" + m.ToString() + "")""); // (2) Nullable<Mutable> n = new Mutable(); Write(""("" + n + "")""); // (0) Write(""("" + n + "")""); // (0) Write(""("" + n.ToString() + "")""); // (0) Write(""("" + n.ToString() + "")""); // (1) Write(""("" + n.ToString() + "")""); // (2) } }"; CompileAndVerify(source, expectedOutput: "(0)(0)(0)(1)(2)(0)(0)(0)(1)(2)"); } [Fact] public void ConcatReadonlyStruct() { var source = @" using System; class Test { static ReadonlyStruct f = new ReadonlyStruct(); static void Main() { ReadonlyStruct l = new ReadonlyStruct(); Console.WriteLine("""" + l + l + f + f); } } readonly struct ReadonlyStruct { public override string ToString() => ""R""; } "; var comp = CompileAndVerify(source, expectedOutput: @"RRRR"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (ReadonlyStruct V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""ReadonlyStruct"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""ReadonlyStruct"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""ReadonlyStruct"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""ReadonlyStruct Test.f"" IL_0027: constrained. ""ReadonlyStruct"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""ReadonlyStruct Test.f"" IL_0037: constrained. ""ReadonlyStruct"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatStructWithReadonlyToString() { var source = @" using System; class Test { static StructWithReadonlyToString f = new StructWithReadonlyToString(); static void Main() { StructWithReadonlyToString l = new StructWithReadonlyToString(); Console.WriteLine("""" + l + l + f + f); } } struct StructWithReadonlyToString { public readonly override string ToString() => ""R""; } "; var comp = CompileAndVerify(source, expectedOutput: @"RRRR"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (StructWithReadonlyToString V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""StructWithReadonlyToString"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""StructWithReadonlyToString"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""StructWithReadonlyToString"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""StructWithReadonlyToString Test.f"" IL_0027: constrained. ""StructWithReadonlyToString"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""StructWithReadonlyToString Test.f"" IL_0037: constrained. ""StructWithReadonlyToString"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatStructWithNoToString() { var source = @" using System; class Test { static S f = new S(); static void Main() { S l = new S(); Console.WriteLine("""" + l + l + f + f); } } struct S { } "; var comp = CompileAndVerify(source, expectedOutput: @"SSSS"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 77 (0x4d) .maxstack 4 .locals init (S V_0) //l IL_0000: ldloca.s V_0 IL_0002: initobj ""S"" IL_0008: ldloca.s V_0 IL_000a: constrained. ""S"" IL_0010: callvirt ""string object.ToString()"" IL_0015: ldloca.s V_0 IL_0017: constrained. ""S"" IL_001d: callvirt ""string object.ToString()"" IL_0022: ldsflda ""S Test.f"" IL_0027: constrained. ""S"" IL_002d: callvirt ""string object.ToString()"" IL_0032: ldsflda ""S Test.f"" IL_0037: constrained. ""S"" IL_003d: callvirt ""string object.ToString()"" IL_0042: call ""string string.Concat(string, string, string, string)"" IL_0047: call ""void System.Console.WriteLine(string)"" IL_004c: ret } "); } [Fact] public void ConcatWithImplicitOperator() { var source = @" using System; public class Test { static void Main() { Console.WriteLine(""S"" + new Test()); } public static implicit operator string(Test test) => ""T""; } "; var comp = CompileAndVerify(source, expectedOutput: @"ST"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 26 (0x1a) .maxstack 2 IL_0000: ldstr ""S"" IL_0005: newobj ""Test..ctor()"" IL_000a: call ""string Test.op_Implicit(Test)"" IL_000f: call ""string string.Concat(string, string)"" IL_0014: call ""void System.Console.WriteLine(string)"" IL_0019: ret } "); } [Fact] public void ConcatWithNull() { var source = @" using System; public class Test { public static Test T = null; static void Main() { Console.WriteLine(""S"" + T); } } "; var comp = CompileAndVerify(source, expectedOutput: @"S"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 33 (0x21) .maxstack 3 IL_0000: ldstr ""S"" IL_0005: ldsfld ""Test Test.T"" IL_000a: dup IL_000b: brtrue.s IL_0011 IL_000d: pop IL_000e: ldnull IL_000f: br.s IL_0016 IL_0011: callvirt ""string object.ToString()"" IL_0016: call ""string string.Concat(string, string)"" IL_001b: call ""void System.Console.WriteLine(string)"" IL_0020: ret } "); } [Fact] public void ConcatWithSpecialValueTypes() { var source = @" using System; public class Test { static void Main() { const char a = 'a', b = 'b'; char c = 'c', d = 'd'; Console.WriteLine(a + ""1""); Console.WriteLine(""2"" + b); Console.WriteLine(c + ""3""); Console.WriteLine(""4"" + d); Console.WriteLine(true + ""5"" + c); Console.WriteLine(""6"" + d + (IntPtr)7); Console.WriteLine(""8"" + (UIntPtr)9 + false); Console.WriteLine(c + ""10"" + d + ""11""); Console.WriteLine(""12"" + c + ""13"" + d); Console.WriteLine(a + ""14"" + b + ""15"" + a + ""16""); Console.WriteLine(c + ""17"" + d + ""18"" + c + ""19""); Console.WriteLine(""20"" + 21 + c + d + c + d); Console.WriteLine(""22"" + c + ""23"" + d + c + d); } } "; var comp = CompileAndVerify(source, expectedOutput: @"a1 2b c3 4d True5c 6d7 89False c10d11 12c13d a14b15a16 c17d18c19 2021cdcd 22c23dcd"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 477 (0x1dd) .maxstack 4 .locals init (char V_0, //c char V_1, //d bool V_2, System.IntPtr V_3, System.UIntPtr V_4, int V_5) IL_0000: ldc.i4.s 99 IL_0002: stloc.0 IL_0003: ldc.i4.s 100 IL_0005: stloc.1 IL_0006: ldstr ""a1"" IL_000b: call ""void System.Console.WriteLine(string)"" IL_0010: ldstr ""2b"" IL_0015: call ""void System.Console.WriteLine(string)"" IL_001a: ldloca.s V_0 IL_001c: call ""string char.ToString()"" IL_0021: ldstr ""3"" IL_0026: call ""string string.Concat(string, string)"" IL_002b: call ""void System.Console.WriteLine(string)"" IL_0030: ldstr ""4"" IL_0035: ldloca.s V_1 IL_0037: call ""string char.ToString()"" IL_003c: call ""string string.Concat(string, string)"" IL_0041: call ""void System.Console.WriteLine(string)"" IL_0046: ldc.i4.1 IL_0047: stloc.2 IL_0048: ldloca.s V_2 IL_004a: call ""string bool.ToString()"" IL_004f: ldstr ""5"" IL_0054: ldloca.s V_0 IL_0056: call ""string char.ToString()"" IL_005b: call ""string string.Concat(string, string, string)"" IL_0060: call ""void System.Console.WriteLine(string)"" IL_0065: ldstr ""6"" IL_006a: ldloca.s V_1 IL_006c: call ""string char.ToString()"" IL_0071: ldc.i4.7 IL_0072: call ""System.IntPtr System.IntPtr.op_Explicit(int)"" IL_0077: stloc.3 IL_0078: ldloca.s V_3 IL_007a: call ""string System.IntPtr.ToString()"" IL_007f: call ""string string.Concat(string, string, string)"" IL_0084: call ""void System.Console.WriteLine(string)"" IL_0089: ldstr ""8"" IL_008e: ldc.i4.s 9 IL_0090: conv.i8 IL_0091: call ""System.UIntPtr System.UIntPtr.op_Explicit(ulong)"" IL_0096: stloc.s V_4 IL_0098: ldloca.s V_4 IL_009a: call ""string System.UIntPtr.ToString()"" IL_009f: ldc.i4.0 IL_00a0: stloc.2 IL_00a1: ldloca.s V_2 IL_00a3: call ""string bool.ToString()"" IL_00a8: call ""string string.Concat(string, string, string)"" IL_00ad: call ""void System.Console.WriteLine(string)"" IL_00b2: ldloca.s V_0 IL_00b4: call ""string char.ToString()"" IL_00b9: ldstr ""10"" IL_00be: ldloca.s V_1 IL_00c0: call ""string char.ToString()"" IL_00c5: ldstr ""11"" IL_00ca: call ""string string.Concat(string, string, string, string)"" IL_00cf: call ""void System.Console.WriteLine(string)"" IL_00d4: ldstr ""12"" IL_00d9: ldloca.s V_0 IL_00db: call ""string char.ToString()"" IL_00e0: ldstr ""13"" IL_00e5: ldloca.s V_1 IL_00e7: call ""string char.ToString()"" IL_00ec: call ""string string.Concat(string, string, string, string)"" IL_00f1: call ""void System.Console.WriteLine(string)"" IL_00f6: ldstr ""a14b15a16"" IL_00fb: call ""void System.Console.WriteLine(string)"" IL_0100: ldc.i4.6 IL_0101: newarr ""string"" IL_0106: dup IL_0107: ldc.i4.0 IL_0108: ldloca.s V_0 IL_010a: call ""string char.ToString()"" IL_010f: stelem.ref IL_0110: dup IL_0111: ldc.i4.1 IL_0112: ldstr ""17"" IL_0117: stelem.ref IL_0118: dup IL_0119: ldc.i4.2 IL_011a: ldloca.s V_1 IL_011c: call ""string char.ToString()"" IL_0121: stelem.ref IL_0122: dup IL_0123: ldc.i4.3 IL_0124: ldstr ""18"" IL_0129: stelem.ref IL_012a: dup IL_012b: ldc.i4.4 IL_012c: ldloca.s V_0 IL_012e: call ""string char.ToString()"" IL_0133: stelem.ref IL_0134: dup IL_0135: ldc.i4.5 IL_0136: ldstr ""19"" IL_013b: stelem.ref IL_013c: call ""string string.Concat(params string[])"" IL_0141: call ""void System.Console.WriteLine(string)"" IL_0146: ldc.i4.6 IL_0147: newarr ""string"" IL_014c: dup IL_014d: ldc.i4.0 IL_014e: ldstr ""20"" IL_0153: stelem.ref IL_0154: dup IL_0155: ldc.i4.1 IL_0156: ldc.i4.s 21 IL_0158: stloc.s V_5 IL_015a: ldloca.s V_5 IL_015c: call ""string int.ToString()"" IL_0161: stelem.ref IL_0162: dup IL_0163: ldc.i4.2 IL_0164: ldloca.s V_0 IL_0166: call ""string char.ToString()"" IL_016b: stelem.ref IL_016c: dup IL_016d: ldc.i4.3 IL_016e: ldloca.s V_1 IL_0170: call ""string char.ToString()"" IL_0175: stelem.ref IL_0176: dup IL_0177: ldc.i4.4 IL_0178: ldloca.s V_0 IL_017a: call ""string char.ToString()"" IL_017f: stelem.ref IL_0180: dup IL_0181: ldc.i4.5 IL_0182: ldloca.s V_1 IL_0184: call ""string char.ToString()"" IL_0189: stelem.ref IL_018a: call ""string string.Concat(params string[])"" IL_018f: call ""void System.Console.WriteLine(string)"" IL_0194: ldc.i4.6 IL_0195: newarr ""string"" IL_019a: dup IL_019b: ldc.i4.0 IL_019c: ldstr ""22"" IL_01a1: stelem.ref IL_01a2: dup IL_01a3: ldc.i4.1 IL_01a4: ldloca.s V_0 IL_01a6: call ""string char.ToString()"" IL_01ab: stelem.ref IL_01ac: dup IL_01ad: ldc.i4.2 IL_01ae: ldstr ""23"" IL_01b3: stelem.ref IL_01b4: dup IL_01b5: ldc.i4.3 IL_01b6: ldloca.s V_1 IL_01b8: call ""string char.ToString()"" IL_01bd: stelem.ref IL_01be: dup IL_01bf: ldc.i4.4 IL_01c0: ldloca.s V_0 IL_01c2: call ""string char.ToString()"" IL_01c7: stelem.ref IL_01c8: dup IL_01c9: ldc.i4.5 IL_01ca: ldloca.s V_1 IL_01cc: call ""string char.ToString()"" IL_01d1: stelem.ref IL_01d2: call ""string string.Concat(params string[])"" IL_01d7: call ""void System.Console.WriteLine(string)"" IL_01dc: ret } "); } [Fact] public void ConcatExpressions() { var source = @" using System; class Test { static int X = 3; static int Y = 4; static void Main() { Console.WriteLine(X + ""+"" + Y + ""="" + (X + Y)); } } "; var comp = CompileAndVerify(source, expectedOutput: "3+4=7"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Main", @" { // Code size 81 (0x51) .maxstack 5 .locals init (int V_0) IL_0000: ldc.i4.5 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldsflda ""int Test.X"" IL_000d: call ""string int.ToString()"" IL_0012: stelem.ref IL_0013: dup IL_0014: ldc.i4.1 IL_0015: ldstr ""+"" IL_001a: stelem.ref IL_001b: dup IL_001c: ldc.i4.2 IL_001d: ldsflda ""int Test.Y"" IL_0022: call ""string int.ToString()"" IL_0027: stelem.ref IL_0028: dup IL_0029: ldc.i4.3 IL_002a: ldstr ""="" IL_002f: stelem.ref IL_0030: dup IL_0031: ldc.i4.4 IL_0032: ldsfld ""int Test.X"" IL_0037: ldsfld ""int Test.Y"" IL_003c: add IL_003d: stloc.0 IL_003e: ldloca.s V_0 IL_0040: call ""string int.ToString()"" IL_0045: stelem.ref IL_0046: call ""string string.Concat(params string[])"" IL_004b: call ""void System.Console.WriteLine(string)"" IL_0050: ret }"); } [Fact] public void ConcatRefs() { var source = @" using System; class Test { static void Main() { string s1 = ""S1""; string s2 = ""S2""; int i1 = 3; int i2 = 4; object o1 = ""O1""; object o2 = ""O2""; Print(ref s1, ref i1, ref o1, ref s2, ref i2, ref o2); } static void Print<T1, T2, T3>(ref string s, ref int i, ref object o, ref T1 t1, ref T2 t2, ref T3 t3) where T1 : class where T2 : struct { Console.WriteLine(s + i + o + t1 + t2 + t3); } } "; var comp = CompileAndVerify(source, expectedOutput: "S13O1S24O2"); comp.VerifyDiagnostics(); comp.VerifyIL("Test.Print<T1, T2, T3>", @" { // Code size 133 (0x85) .maxstack 5 .locals init (T2 V_0, T3 V_1) IL_0000: ldc.i4.6 IL_0001: newarr ""string"" IL_0006: dup IL_0007: ldc.i4.0 IL_0008: ldarg.0 IL_0009: ldind.ref IL_000a: stelem.ref IL_000b: dup IL_000c: ldc.i4.1 IL_000d: ldarg.1 IL_000e: call ""string int.ToString()"" IL_0013: stelem.ref IL_0014: dup IL_0015: ldc.i4.2 IL_0016: ldarg.2 IL_0017: ldind.ref IL_0018: dup IL_0019: brtrue.s IL_001f IL_001b: pop IL_001c: ldnull IL_001d: br.s IL_0024 IL_001f: callvirt ""string object.ToString()"" IL_0024: stelem.ref IL_0025: dup IL_0026: ldc.i4.3 IL_0027: ldarg.3 IL_0028: ldobj ""T1"" IL_002d: box ""T1"" IL_0032: dup IL_0033: brtrue.s IL_0039 IL_0035: pop IL_0036: ldnull IL_0037: br.s IL_003e IL_0039: callvirt ""string object.ToString()"" IL_003e: stelem.ref IL_003f: dup IL_0040: ldc.i4.4 IL_0041: ldarg.s V_4 IL_0043: ldobj ""T2"" IL_0048: stloc.0 IL_0049: ldloca.s V_0 IL_004b: constrained. ""T2"" IL_0051: callvirt ""string object.ToString()"" IL_0056: stelem.ref IL_0057: dup IL_0058: ldc.i4.5 IL_0059: ldarg.s V_5 IL_005b: ldobj ""T3"" IL_0060: stloc.1 IL_0061: ldloc.1 IL_0062: box ""T3"" IL_0067: brtrue.s IL_006c IL_0069: ldnull IL_006a: br.s IL_0079 IL_006c: ldloca.s V_1 IL_006e: constrained. ""T3"" IL_0074: callvirt ""string object.ToString()"" IL_0079: stelem.ref IL_007a: call ""string string.Concat(params string[])"" IL_007f: call ""void System.Console.WriteLine(string)"" IL_0084: ret }"); } } }
Java
/*! * LESS - Leaner CSS v1.7.0 * http://lesscss.org * * Copyright (c) 2009-2014, Alexis Sellier <[email protected]> * Licensed under the Apache v2 License. * */ /** * @license Apache v2 */ (function (window, undefined) {// // Stub out `require` in the browser // function require(arg) { return window.less[arg.split('/')[1]]; }; if (typeof(window.less) === 'undefined' || typeof(window.less.nodeType) !== 'undefined') { window.less = {}; } less = window.less; tree = window.less.tree = {}; less.mode = 'browser'; var less, tree; // Node.js does not have a header file added which defines less if (less === undefined) { less = exports; tree = require('./tree'); less.mode = 'node'; } // // less.js - parser // // A relatively straight-forward predictive parser. // There is no tokenization/lexing stage, the input is parsed // in one sweep. // // To make the parser fast enough to run in the browser, several // optimization had to be made: // // - Matching and slicing on a huge input is often cause of slowdowns. // The solution is to chunkify the input into smaller strings. // The chunks are stored in the `chunks` var, // `j` holds the current chunk index, and `currentPos` holds // the index of the current chunk in relation to `input`. // This gives us an almost 4x speed-up. // // - In many cases, we don't need to match individual tokens; // for example, if a value doesn't hold any variables, operations // or dynamic references, the parser can effectively 'skip' it, // treating it as a literal. // An example would be '1px solid #000' - which evaluates to itself, // we don't need to know what the individual components are. // The drawback, of course is that you don't get the benefits of // syntax-checking on the CSS. This gives us a 50% speed-up in the parser, // and a smaller speed-up in the code-gen. // // // Token matching is done with the `$` function, which either takes // a terminal string or regexp, or a non-terminal function to call. // It also takes care of moving all the indices forwards. // // less.Parser = function Parser(env) { var input, // LeSS input string i, // current index in `input` j, // current chunk saveStack = [], // holds state for backtracking furthest, // furthest index the parser has gone to chunks, // chunkified input current, // current chunk currentPos, // index of current chunk, in `input` parser, parsers, rootFilename = env && env.filename; // Top parser on an import tree must be sure there is one "env" // which will then be passed around by reference. if (!(env instanceof tree.parseEnv)) { env = new tree.parseEnv(env); } var imports = this.imports = { paths: env.paths || [], // Search paths, when importing queue: [], // Files which haven't been imported yet files: env.files, // Holds the imported parse trees contents: env.contents, // Holds the imported file contents contentsIgnoredChars: env.contentsIgnoredChars, // lines inserted, not in the original less mime: env.mime, // MIME type of .less files error: null, // Error in parsing/evaluating an import push: function (path, currentFileInfo, importOptions, callback) { var parserImports = this; this.queue.push(path); var fileParsedFunc = function (e, root, fullPath) { parserImports.queue.splice(parserImports.queue.indexOf(path), 1); // Remove the path from the queue var importedPreviously = fullPath === rootFilename; parserImports.files[fullPath] = root; // Store the root if (e && !parserImports.error) { parserImports.error = e; } callback(e, root, importedPreviously, fullPath); }; if (less.Parser.importer) { less.Parser.importer(path, currentFileInfo, fileParsedFunc, env); } else { less.Parser.fileLoader(path, currentFileInfo, function(e, contents, fullPath, newFileInfo) { if (e) {fileParsedFunc(e); return;} var newEnv = new tree.parseEnv(env); newEnv.currentFileInfo = newFileInfo; newEnv.processImports = false; newEnv.contents[fullPath] = contents; if (currentFileInfo.reference || importOptions.reference) { newFileInfo.reference = true; } if (importOptions.inline) { fileParsedFunc(null, contents, fullPath); } else { new(less.Parser)(newEnv).parse(contents, function (e, root) { fileParsedFunc(e, root, fullPath); }); } }, env); } } }; function save() { currentPos = i; saveStack.push( { current: current, i: i, j: j }); } function restore() { var state = saveStack.pop(); current = state.current; currentPos = i = state.i; j = state.j; } function forget() { saveStack.pop(); } function sync() { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } } function isWhitespace(str, pos) { var code = str.charCodeAt(pos | 0); return (code <= 32) && (code === 32 || code === 10 || code === 9); } // // Parse from a token, regexp or string, and move forward if match // function $(tok) { var tokType = typeof tok, match, length; // Either match a single character in the input, // or match a regexp in the current chunk (`current`). // if (tokType === "string") { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } // regexp sync (); if (! (match = tok.exec(current))) { return null; } length = match[0].length; // The match is confirmed, add the match length to `i`, // and consume any extra white-space characters (' ' || '\n') // which come after that. The reason for this is that LeSS's // grammar is mostly white-space insensitive. // skipWhitespace(length); if(typeof(match) === 'string') { return match; } else { return match.length === 1 ? match[0] : match; } } // Specialization of $(tok) function $re(tok) { if (i > currentPos) { current = current.slice(i - currentPos); currentPos = i; } var m = tok.exec(current); if (!m) { return null; } skipWhitespace(m[0].length); if(typeof m === "string") { return m; } return m.length === 1 ? m[0] : m; } var _$re = $re; // Specialization of $(tok) function $char(tok) { if (input.charAt(i) !== tok) { return null; } skipWhitespace(1); return tok; } function skipWhitespace(length) { var oldi = i, oldj = j, curr = i - currentPos, endIndex = i + current.length - curr, mem = (i += length), inp = input, c; for (; i < endIndex; i++) { c = inp.charCodeAt(i); if (c > 32) { break; } if ((c !== 32) && (c !== 10) && (c !== 9) && (c !== 13)) { break; } } current = current.slice(length + i - mem + curr); currentPos = i; if (!current.length && (j < chunks.length - 1)) { current = chunks[++j]; skipWhitespace(0); // skip space at the beginning of a chunk return true; // things changed } return oldi !== i || oldj !== j; } function expect(arg, msg) { // some older browsers return typeof 'function' for RegExp var result = (Object.prototype.toString.call(arg) === '[object Function]') ? arg.call(parsers) : $(arg); if (result) { return result; } error(msg || (typeof(arg) === 'string' ? "expected '" + arg + "' got '" + input.charAt(i) + "'" : "unexpected token")); } // Specialization of expect() function expectChar(arg, msg) { if (input.charAt(i) === arg) { skipWhitespace(1); return arg; } error(msg || "expected '" + arg + "' got '" + input.charAt(i) + "'"); } function error(msg, type) { var e = new Error(msg); e.index = i; e.type = type || 'Syntax'; throw e; } // Same as $(), but don't change the state of the parser, // just return the match. function peek(tok) { if (typeof(tok) === 'string') { return input.charAt(i) === tok; } else { return tok.test(current); } } // Specialization of peek() function peekChar(tok) { return input.charAt(i) === tok; } function getInput(e, env) { if (e.filename && env.currentFileInfo.filename && (e.filename !== env.currentFileInfo.filename)) { return parser.imports.contents[e.filename]; } else { return input; } } function getLocation(index, inputStream) { var n = index + 1, line = null, column = -1; while (--n >= 0 && inputStream.charAt(n) !== '\n') { column++; } if (typeof index === 'number') { line = (inputStream.slice(0, index).match(/\n/g) || "").length; } return { line: line, column: column }; } function getDebugInfo(index, inputStream, env) { var filename = env.currentFileInfo.filename; if(less.mode !== 'browser' && less.mode !== 'rhino') { filename = require('path').resolve(filename); } return { lineNumber: getLocation(index, inputStream).line + 1, fileName: filename }; } function LessError(e, env) { var input = getInput(e, env), loc = getLocation(e.index, input), line = loc.line, col = loc.column, callLine = e.call && getLocation(e.call, input).line, lines = input.split('\n'); this.type = e.type || 'Syntax'; this.message = e.message; this.filename = e.filename || env.currentFileInfo.filename; this.index = e.index; this.line = typeof(line) === 'number' ? line + 1 : null; this.callLine = callLine + 1; this.callExtract = lines[callLine]; this.stack = e.stack; this.column = col; this.extract = [ lines[line - 1], lines[line], lines[line + 1] ]; } LessError.prototype = new Error(); LessError.prototype.constructor = LessError; this.env = env = env || {}; // The optimization level dictates the thoroughness of the parser, // the lower the number, the less nodes it will create in the tree. // This could matter for debugging, or if you want to access // the individual nodes in the tree. this.optimization = ('optimization' in this.env) ? this.env.optimization : 1; // // The Parser // parser = { imports: imports, // // Parse an input string into an abstract syntax tree, // @param str A string containing 'less' markup // @param callback call `callback` when done. // @param [additionalData] An optional map which can contains vars - a map (key, value) of variables to apply // parse: function (str, callback, additionalData) { var root, line, lines, error = null, globalVars, modifyVars, preText = ""; i = j = currentPos = furthest = 0; globalVars = (additionalData && additionalData.globalVars) ? less.Parser.serializeVars(additionalData.globalVars) + '\n' : ''; modifyVars = (additionalData && additionalData.modifyVars) ? '\n' + less.Parser.serializeVars(additionalData.modifyVars) : ''; if (globalVars || (additionalData && additionalData.banner)) { preText = ((additionalData && additionalData.banner) ? additionalData.banner : "") + globalVars; parser.imports.contentsIgnoredChars[env.currentFileInfo.filename] = preText.length; } str = str.replace(/\r\n/g, '\n'); // Remove potential UTF Byte Order Mark input = str = preText + str.replace(/^\uFEFF/, '') + modifyVars; parser.imports.contents[env.currentFileInfo.filename] = str; // Split the input into chunks. chunks = (function (input) { var len = input.length, level = 0, parenLevel = 0, lastOpening, lastOpeningParen, lastMultiComment, lastMultiCommentEndBrace, chunks = [], emitFrom = 0, parserCurrentIndex, currentChunkStartIndex, cc, cc2, matched; function fail(msg, index) { error = new(LessError)({ index: index || parserCurrentIndex, type: 'Parse', message: msg, filename: env.currentFileInfo.filename }, env); } function emitChunk(force) { var len = parserCurrentIndex - emitFrom; if (((len < 512) && !force) || !len) { return; } chunks.push(input.slice(emitFrom, parserCurrentIndex + 1)); emitFrom = parserCurrentIndex + 1; } for (parserCurrentIndex = 0; parserCurrentIndex < len; parserCurrentIndex++) { cc = input.charCodeAt(parserCurrentIndex); if (((cc >= 97) && (cc <= 122)) || (cc < 34)) { // a-z or whitespace continue; } switch (cc) { case 40: // ( parenLevel++; lastOpeningParen = parserCurrentIndex; continue; case 41: // ) if (--parenLevel < 0) { return fail("missing opening `(`"); } continue; case 59: // ; if (!parenLevel) { emitChunk(); } continue; case 123: // { level++; lastOpening = parserCurrentIndex; continue; case 125: // } if (--level < 0) { return fail("missing opening `{`"); } if (!level && !parenLevel) { emitChunk(); } continue; case 92: // \ if (parserCurrentIndex < len - 1) { parserCurrentIndex++; continue; } return fail("unescaped `\\`"); case 34: case 39: case 96: // ", ' and ` matched = 0; currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 1; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 > 96) { continue; } if (cc2 == cc) { matched = 1; break; } if (cc2 == 92) { // \ if (parserCurrentIndex == len - 1) { return fail("unescaped `\\`"); } parserCurrentIndex++; } } if (matched) { continue; } return fail("unmatched `" + String.fromCharCode(cc) + "`", currentChunkStartIndex); case 47: // /, check for comment if (parenLevel || (parserCurrentIndex == len - 1)) { continue; } cc2 = input.charCodeAt(parserCurrentIndex + 1); if (cc2 == 47) { // //, find lnfeed for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if ((cc2 <= 13) && ((cc2 == 10) || (cc2 == 13))) { break; } } } else if (cc2 == 42) { // /*, find */ lastMultiComment = currentChunkStartIndex = parserCurrentIndex; for (parserCurrentIndex = parserCurrentIndex + 2; parserCurrentIndex < len - 1; parserCurrentIndex++) { cc2 = input.charCodeAt(parserCurrentIndex); if (cc2 == 125) { lastMultiCommentEndBrace = parserCurrentIndex; } if (cc2 != 42) { continue; } if (input.charCodeAt(parserCurrentIndex + 1) == 47) { break; } } if (parserCurrentIndex == len - 1) { return fail("missing closing `*/`", currentChunkStartIndex); } parserCurrentIndex++; } continue; case 42: // *, check for unmatched */ if ((parserCurrentIndex < len - 1) && (input.charCodeAt(parserCurrentIndex + 1) == 47)) { return fail("unmatched `/*`"); } continue; } } if (level !== 0) { if ((lastMultiComment > lastOpening) && (lastMultiCommentEndBrace > lastMultiComment)) { return fail("missing closing `}` or `*/`", lastOpening); } else { return fail("missing closing `}`", lastOpening); } } else if (parenLevel !== 0) { return fail("missing closing `)`", lastOpeningParen); } emitChunk(true); return chunks; })(str); if (error) { return callback(new(LessError)(error, env)); } current = chunks[0]; // Start with the primary rule. // The whole syntax tree is held under a Ruleset node, // with the `root` property set to true, so no `{}` are // output. The callback is called when the input is parsed. try { root = new(tree.Ruleset)(null, this.parsers.primary()); root.root = true; root.firstRoot = true; } catch (e) { return callback(new(LessError)(e, env)); } root.toCSS = (function (evaluate) { return function (options, variables) { options = options || {}; var evaldRoot, css, evalEnv = new tree.evalEnv(options); // // Allows setting variables with a hash, so: // // `{ color: new(tree.Color)('#f01') }` will become: // // new(tree.Rule)('@color', // new(tree.Value)([ // new(tree.Expression)([ // new(tree.Color)('#f01') // ]) // ]) // ) // if (typeof(variables) === 'object' && !Array.isArray(variables)) { variables = Object.keys(variables).map(function (k) { var value = variables[k]; if (! (value instanceof tree.Value)) { if (! (value instanceof tree.Expression)) { value = new(tree.Expression)([value]); } value = new(tree.Value)([value]); } return new(tree.Rule)('@' + k, value, false, null, 0); }); evalEnv.frames = [new(tree.Ruleset)(null, variables)]; } try { var preEvalVisitors = [], visitors = [ new(tree.joinSelectorVisitor)(), new(tree.processExtendsVisitor)(), new(tree.toCSSVisitor)({compress: Boolean(options.compress)}) ], i, root = this; if (options.plugins) { for(i =0; i < options.plugins.length; i++) { if (options.plugins[i].isPreEvalVisitor) { preEvalVisitors.push(options.plugins[i]); } else { if (options.plugins[i].isPreVisitor) { visitors.splice(0, 0, options.plugins[i]); } else { visitors.push(options.plugins[i]); } } } } for(i = 0; i < preEvalVisitors.length; i++) { preEvalVisitors[i].run(root); } evaldRoot = evaluate.call(root, evalEnv); for(i = 0; i < visitors.length; i++) { visitors[i].run(evaldRoot); } if (options.sourceMap) { evaldRoot = new tree.sourceMapOutput( { contentsIgnoredCharsMap: parser.imports.contentsIgnoredChars, writeSourceMap: options.writeSourceMap, rootNode: evaldRoot, contentsMap: parser.imports.contents, sourceMapFilename: options.sourceMapFilename, sourceMapURL: options.sourceMapURL, outputFilename: options.sourceMapOutputFilename, sourceMapBasepath: options.sourceMapBasepath, sourceMapRootpath: options.sourceMapRootpath, outputSourceFiles: options.outputSourceFiles, sourceMapGenerator: options.sourceMapGenerator }); } css = evaldRoot.toCSS({ compress: Boolean(options.compress), dumpLineNumbers: env.dumpLineNumbers, strictUnits: Boolean(options.strictUnits), numPrecision: 8}); } catch (e) { throw new(LessError)(e, env); } if (options.cleancss && less.mode === 'node') { var CleanCSS = require('clean-css'), cleancssOptions = options.cleancssOptions || {}; if (cleancssOptions.keepSpecialComments === undefined) { cleancssOptions.keepSpecialComments = "*"; } cleancssOptions.processImport = false; cleancssOptions.noRebase = true; if (cleancssOptions.noAdvanced === undefined) { cleancssOptions.noAdvanced = true; } return new CleanCSS(cleancssOptions).minify(css); } else if (options.compress) { return css.replace(/(^(\s)+)|((\s)+$)/g, ""); } else { return css; } }; })(root.eval); // If `i` is smaller than the `input.length - 1`, // it means the parser wasn't able to parse the whole // string, so we've got a parsing error. // // We try to extract a \n delimited string, // showing the line where the parse error occured. // We split it up into two parts (the part which parsed, // and the part which didn't), so we can color them differently. if (i < input.length - 1) { i = furthest; var loc = getLocation(i, input); lines = input.split('\n'); line = loc.line + 1; error = { type: "Parse", message: "Unrecognised input", index: i, filename: env.currentFileInfo.filename, line: line, column: loc.column, extract: [ lines[line - 2], lines[line - 1], lines[line] ] }; } var finish = function (e) { e = error || e || parser.imports.error; if (e) { if (!(e instanceof LessError)) { e = new(LessError)(e, env); } return callback(e); } else { return callback(null, root); } }; if (env.processImports !== false) { new tree.importVisitor(this.imports, finish) .run(root); } else { return finish(); } }, // // Here in, the parsing rules/functions // // The basic structure of the syntax tree generated is as follows: // // Ruleset -> Rule -> Value -> Expression -> Entity // // Here's some LESS code: // // .class { // color: #fff; // border: 1px solid #000; // width: @w + 4px; // > .child {...} // } // // And here's what the parse tree might look like: // // Ruleset (Selector '.class', [ // Rule ("color", Value ([Expression [Color #fff]])) // Rule ("border", Value ([Expression [Dimension 1px][Keyword "solid"][Color #000]])) // Rule ("width", Value ([Expression [Operation "+" [Variable "@w"][Dimension 4px]]])) // Ruleset (Selector [Element '>', '.child'], [...]) // ]) // // In general, most rules will try to parse a token with the `$()` function, and if the return // value is truly, will return a new node, of the relevant type. Sometimes, we need to check // first, before parsing, that's when we use `peek()`. // parsers: parsers = { // // The `primary` rule is the *entry* and *exit* point of the parser. // The rules here can appear at any level of the parse tree. // // The recursive nature of the grammar is an interplay between the `block` // rule, which represents `{ ... }`, the `ruleset` rule, and this `primary` rule, // as represented by this simplified grammar: // // primary → (ruleset | rule)+ // ruleset → selector+ block // block → '{' primary '}' // // Only at one point is the primary rule not called from the // block rule: at the root level. // primary: function () { var mixin = this.mixin, $re = _$re, root = [], node; while (current) { node = this.extendRule() || mixin.definition() || this.rule() || this.ruleset() || mixin.call() || this.comment() || this.rulesetCall() || this.directive(); if (node) { root.push(node); } else { if (!($re(/^[\s\n]+/) || $re(/^;+/))) { break; } } if (peekChar('}')) { break; } } return root; }, // We create a Comment node for CSS comments `/* */`, // but keep the LeSS comments `//` silent, by just skipping // over them. comment: function () { var comment; if (input.charAt(i) !== '/') { return; } if (input.charAt(i + 1) === '/') { return new(tree.Comment)($re(/^\/\/.*/), true, i, env.currentFileInfo); } comment = $re(/^\/\*(?:[^*]|\*+[^\/*])*\*+\/\n?/); if (comment) { return new(tree.Comment)(comment, false, i, env.currentFileInfo); } }, comments: function () { var comment, comments = []; while(true) { comment = this.comment(); if (!comment) { break; } comments.push(comment); } return comments; }, // // Entities are tokens which can be found inside an Expression // entities: { // // A string, which supports escaping " and ' // // "milky way" 'he\'s the one!' // quoted: function () { var str, j = i, e, index = i; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '"' && input.charAt(j) !== "'") { return; } if (e) { $char('~'); } str = $re(/^"((?:[^"\\\r\n]|\\.)*)"|'((?:[^'\\\r\n]|\\.)*)'/); if (str) { return new(tree.Quoted)(str[0], str[1] || str[2], e, index, env.currentFileInfo); } }, // // A catch-all word, such as: // // black border-collapse // keyword: function () { var k; k = $re(/^%|^[_A-Za-z-][_A-Za-z0-9-]*/); if (k) { var color = tree.Color.fromKeyword(k); if (color) { return color; } return new(tree.Keyword)(k); } }, // // A function call // // rgb(255, 0, 255) // // We also try to catch IE's `alpha()`, but let the `alpha` parser // deal with the details. // // The arguments are parsed with the `entities.arguments` parser. // call: function () { var name, nameLC, args, alpha_ret, index = i; name = /^([\w-]+|%|progid:[\w\.]+)\(/.exec(current); if (!name) { return; } name = name[1]; nameLC = name.toLowerCase(); if (nameLC === 'url') { return null; } i += name.length; if (nameLC === 'alpha') { alpha_ret = parsers.alpha(); if(typeof alpha_ret !== 'undefined') { return alpha_ret; } } $char('('); // Parse the '(' and consume whitespace. args = this.arguments(); if (! $char(')')) { return; } if (name) { return new(tree.Call)(name, args, index, env.currentFileInfo); } }, arguments: function () { var args = [], arg; while (true) { arg = this.assignment() || parsers.expression(); if (!arg) { break; } args.push(arg); if (! $char(',')) { break; } } return args; }, literal: function () { return this.dimension() || this.color() || this.quoted() || this.unicodeDescriptor(); }, // Assignments are argument entities for calls. // They are present in ie filter properties as shown below. // // filter: progid:DXImageTransform.Microsoft.Alpha( *opacity=50* ) // assignment: function () { var key, value; key = $re(/^\w+(?=\s?=)/i); if (!key) { return; } if (!$char('=')) { return; } value = parsers.entity(); if (value) { return new(tree.Assignment)(key, value); } }, // // Parse url() tokens // // We use a specific rule for urls, because they don't really behave like // standard function calls. The difference is that the argument doesn't have // to be enclosed within a string, so it can't be parsed as an Expression. // url: function () { var value; if (input.charAt(i) !== 'u' || !$re(/^url\(/)) { return; } value = this.quoted() || this.variable() || $re(/^(?:(?:\\[\(\)'"])|[^\(\)'"])+/) || ""; expectChar(')'); return new(tree.URL)((value.value != null || value instanceof tree.Variable) ? value : new(tree.Anonymous)(value), env.currentFileInfo); }, // // A Variable entity, such as `@fink`, in // // width: @fink + 2px // // We use a different parser for variable definitions, // see `parsers.variable`. // variable: function () { var name, index = i; if (input.charAt(i) === '@' && (name = $re(/^@@?[\w-]+/))) { return new(tree.Variable)(name, index, env.currentFileInfo); } }, // A variable entity useing the protective {} e.g. @{var} variableCurly: function () { var curly, index = i; if (input.charAt(i) === '@' && (curly = $re(/^@\{([\w-]+)\}/))) { return new(tree.Variable)("@" + curly[1], index, env.currentFileInfo); } }, // // A Hexadecimal color // // #4F3C2F // // `rgb` and `hsl` colors are parsed through the `entities.call` parser. // color: function () { var rgb; if (input.charAt(i) === '#' && (rgb = $re(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/))) { return new(tree.Color)(rgb[1]); } }, // // A Dimension, that is, a number and a unit // // 0.5em 95% // dimension: function () { var value, c = input.charCodeAt(i); //Is the first char of the dimension 0-9, '.', '+' or '-' if ((c > 57 || c < 43) || c === 47 || c == 44) { return; } value = $re(/^([+-]?\d*\.?\d+)(%|[a-z]+)?/); if (value) { return new(tree.Dimension)(value[1], value[2]); } }, // // A unicode descriptor, as is used in unicode-range // // U+0?? or U+00A1-00A9 // unicodeDescriptor: function () { var ud; ud = $re(/^U\+[0-9a-fA-F?]+(\-[0-9a-fA-F?]+)?/); if (ud) { return new(tree.UnicodeDescriptor)(ud[0]); } }, // // JavaScript code to be evaluated // // `window.location.href` // javascript: function () { var str, j = i, e; if (input.charAt(j) === '~') { j++; e = true; } // Escaped strings if (input.charAt(j) !== '`') { return; } if (env.javascriptEnabled !== undefined && !env.javascriptEnabled) { error("You are using JavaScript, which has been disabled."); } if (e) { $char('~'); } str = $re(/^`([^`]*)`/); if (str) { return new(tree.JavaScript)(str[1], i, e); } } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink: // variable: function () { var name; if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*:/))) { return name[1]; } }, // // The variable part of a variable definition. Used in the `rule` parser // // @fink(); // rulesetCall: function () { var name; if (input.charAt(i) === '@' && (name = $re(/^(@[\w-]+)\s*\(\s*\)\s*;/))) { return new tree.RulesetCall(name[1]); } }, // // extend syntax - used to extend selectors // extend: function(isRule) { var elements, e, index = i, option, extendList, extend; if (!(isRule ? $re(/^&:extend\(/) : $re(/^:extend\(/))) { return; } do { option = null; elements = null; while (! (option = $re(/^(all)(?=\s*(\)|,))/))) { e = this.element(); if (!e) { break; } if (elements) { elements.push(e); } else { elements = [ e ]; } } option = option && option[1]; extend = new(tree.Extend)(new(tree.Selector)(elements), option, index); if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } while($char(",")); expect(/^\)/); if (isRule) { expect(/^;/); } return extendList; }, // // extendRule - used in a rule to extend all the parent selectors // extendRule: function() { return this.extend(true); }, // // Mixins // mixin: { // // A Mixin call, with an optional argument list // // #mixins > .square(#fff); // .rounded(4px, black); // .button; // // The `while` loop is there because mixins can be // namespaced, but we only support the child and descendant // selector for now. // call: function () { var s = input.charAt(i), important = false, index = i, elemIndex, elements, elem, e, c, args; if (s !== '.' && s !== '#') { return; } save(); // stop us absorbing part of an invalid selector while (true) { elemIndex = i; e = $re(/^[#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/); if (!e) { break; } elem = new(tree.Element)(c, e, elemIndex, env.currentFileInfo); if (elements) { elements.push(elem); } else { elements = [ elem ]; } c = $char('>'); } if (elements) { if ($char('(')) { args = this.args(true).args; expectChar(')'); } if (parsers.important()) { important = true; } if (parsers.end()) { forget(); return new(tree.mixin.Call)(elements, args, index, env.currentFileInfo, important); } } restore(); }, args: function (isCall) { var parsers = parser.parsers, entities = parsers.entities, returner = { args:null, variadic: false }, expressions = [], argsSemiColon = [], argsComma = [], isSemiColonSeperated, expressionContainsNamed, name, nameLoop, value, arg; save(); while (true) { if (isCall) { arg = parsers.detachedRuleset() || parsers.expression(); } else { parsers.comments(); if (input.charAt(i) === '.' && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ variadic: true }); break; } arg = entities.variable() || entities.literal() || entities.keyword(); } if (!arg) { break; } nameLoop = null; if (arg.throwAwayComments) { arg.throwAwayComments(); } value = arg; var val = null; if (isCall) { // Variable if (arg.value && arg.value.length == 1) { val = arg.value[0]; } } else { val = arg; } if (val && val instanceof tree.Variable) { if ($char(':')) { if (expressions.length > 0) { if (isSemiColonSeperated) { error("Cannot mix ; and , as delimiter types"); } expressionContainsNamed = true; } // we do not support setting a ruleset as a default variable - it doesn't make sense // However if we do want to add it, there is nothing blocking it, just don't error // and remove isCall dependency below value = (isCall && parsers.detachedRuleset()) || parsers.expression(); if (!value) { if (isCall) { error("could not understand value for named argument"); } else { restore(); returner.args = []; return returner; } } nameLoop = (name = val.name); } else if (!isCall && $re(/^\.{3}/)) { returner.variadic = true; if ($char(";") && !isSemiColonSeperated) { isSemiColonSeperated = true; } (isSemiColonSeperated ? argsSemiColon : argsComma) .push({ name: arg.name, variadic: true }); break; } else if (!isCall) { name = nameLoop = val.name; value = null; } } if (value) { expressions.push(value); } argsComma.push({ name:nameLoop, value:value }); if ($char(',')) { continue; } if ($char(';') || isSemiColonSeperated) { if (expressionContainsNamed) { error("Cannot mix ; and , as delimiter types"); } isSemiColonSeperated = true; if (expressions.length > 1) { value = new(tree.Value)(expressions); } argsSemiColon.push({ name:name, value:value }); name = null; expressions = []; expressionContainsNamed = false; } } forget(); returner.args = isSemiColonSeperated ? argsSemiColon : argsComma; return returner; }, // // A Mixin definition, with a list of parameters // // .rounded (@radius: 2px, @color) { // ... // } // // Until we have a finer grained state-machine, we have to // do a look-ahead, to make sure we don't have a mixin call. // See the `rule` function for more information. // // We start by matching `.rounded (`, and then proceed on to // the argument list, which has optional default values. // We store the parameters in `params`, with a `value` key, // if there is a value, such as in the case of `@radius`. // // Once we've got our params list, and a closing `)`, we parse // the `{...}` block. // definition: function () { var name, params = [], match, ruleset, cond, variadic = false; if ((input.charAt(i) !== '.' && input.charAt(i) !== '#') || peek(/^[^{]*\}/)) { return; } save(); match = $re(/^([#.](?:[\w-]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+)\s*\(/); if (match) { name = match[1]; var argInfo = this.args(false); params = argInfo.args; variadic = argInfo.variadic; // .mixincall("@{a}"); // looks a bit like a mixin definition.. // also // .mixincall(@a: {rule: set;}); // so we have to be nice and restore if (!$char(')')) { furthest = i; restore(); return; } parsers.comments(); if ($re(/^when/)) { // Guard cond = expect(parsers.conditions, 'expected condition'); } ruleset = parsers.block(); if (ruleset) { forget(); return new(tree.mixin.Definition)(name, params, ruleset, cond, variadic); } else { restore(); } } else { forget(); } } }, // // Entities are the smallest recognized token, // and can be found inside a rule's value. // entity: function () { var entities = this.entities; return entities.literal() || entities.variable() || entities.url() || entities.call() || entities.keyword() || entities.javascript() || this.comment(); }, // // A Rule terminator. Note that we use `peek()` to check for '}', // because the `block` rule will be expecting it, but we still need to make sure // it's there, if ';' was ommitted. // end: function () { return $char(';') || peekChar('}'); }, // // IE's alpha function // // alpha(opacity=88) // alpha: function () { var value; if (! $re(/^\(opacity=/i)) { return; } value = $re(/^\d+/) || this.entities.variable(); if (value) { expectChar(')'); return new(tree.Alpha)(value); } }, // // A Selector Element // // div // + h1 // #socks // input[type="text"] // // Elements are the building blocks for Selectors, // they are made out of a `Combinator` (see combinator rule), // and an element name, such as a tag a class, or `*`. // element: function () { var e, c, v, index = i; c = this.combinator(); e = $re(/^(?:\d+\.\d+|\d+)%/) || $re(/^(?:[.#]?|:*)(?:[\w-]|[^\x00-\x9f]|\\(?:[A-Fa-f0-9]{1,6} ?|[^A-Fa-f0-9]))+/) || $char('*') || $char('&') || this.attribute() || $re(/^\([^()@]+\)/) || $re(/^[\.#](?=@)/) || this.entities.variableCurly(); if (! e) { save(); if ($char('(')) { if ((v = this.selector()) && $char(')')) { e = new(tree.Paren)(v); forget(); } else { restore(); } } else { forget(); } } if (e) { return new(tree.Element)(c, e, index, env.currentFileInfo); } }, // // Combinators combine elements together, in a Selector. // // Because our parser isn't white-space sensitive, special care // has to be taken, when parsing the descendant combinator, ` `, // as it's an empty space. We have to check the previous character // in the input, to see if it's a ` ` character. More info on how // we deal with this in *combinator.js*. // combinator: function () { var c = input.charAt(i); if (c === '>' || c === '+' || c === '~' || c === '|' || c === '^') { i++; if (input.charAt(i) === '^') { c = '^^'; i++; } while (isWhitespace(input, i)) { i++; } return new(tree.Combinator)(c); } else if (isWhitespace(input, i - 1)) { return new(tree.Combinator)(" "); } else { return new(tree.Combinator)(null); } }, // // A CSS selector (see selector below) // with less extensions e.g. the ability to extend and guard // lessSelector: function () { return this.selector(true); }, // // A CSS Selector // // .class > div + h1 // li a:hover // // Selectors are made out of one or more Elements, see above. // selector: function (isLess) { var index = i, $re = _$re, elements, extendList, c, e, extend, when, condition; while ((isLess && (extend = this.extend())) || (isLess && (when = $re(/^when/))) || (e = this.element())) { if (when) { condition = expect(this.conditions, 'expected condition'); } else if (condition) { error("CSS guard can only be used at the end of selector"); } else if (extend) { if (extendList) { extendList.push(extend); } else { extendList = [ extend ]; } } else { if (extendList) { error("Extend can only be used at the end of selector"); } c = input.charAt(i); if (elements) { elements.push(e); } else { elements = [ e ]; } e = null; } if (c === '{' || c === '}' || c === ';' || c === ',' || c === ')') { break; } } if (elements) { return new(tree.Selector)(elements, extendList, condition, index, env.currentFileInfo); } if (extendList) { error("Extend must be used to extend a selector, it cannot be used on its own"); } }, attribute: function () { if (! $char('[')) { return; } var entities = this.entities, key, val, op; if (!(key = entities.variableCurly())) { key = expect(/^(?:[_A-Za-z0-9-\*]*\|)?(?:[_A-Za-z0-9-]|\\.)+/); } op = $re(/^[|~*$^]?=/); if (op) { val = entities.quoted() || $re(/^[0-9]+%/) || $re(/^[\w-]+/) || entities.variableCurly(); } expectChar(']'); return new(tree.Attribute)(key, op, val); }, // // The `block` rule is used by `ruleset` and `mixin.definition`. // It's a wrapper around the `primary` rule, with added `{}`. // block: function () { var content; if ($char('{') && (content = this.primary()) && $char('}')) { return content; } }, blockRuleset: function() { var block = this.block(); if (block) { block = new tree.Ruleset(null, block); } return block; }, detachedRuleset: function() { var blockRuleset = this.blockRuleset(); if (blockRuleset) { return new tree.DetachedRuleset(blockRuleset); } }, // // div, .class, body > p {...} // ruleset: function () { var selectors, s, rules, debugInfo; save(); if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } while (true) { s = this.lessSelector(); if (!s) { break; } if (selectors) { selectors.push(s); } else { selectors = [ s ]; } this.comments(); if (s.condition && selectors.length > 1) { error("Guards are only currently allowed on a single selector."); } if (! $char(',')) { break; } if (s.condition) { error("Guards are only currently allowed on a single selector."); } this.comments(); } if (selectors && (rules = this.block())) { forget(); var ruleset = new(tree.Ruleset)(selectors, rules, env.strictImports); if (env.dumpLineNumbers) { ruleset.debugInfo = debugInfo; } return ruleset; } else { // Backtrack furthest = i; restore(); } }, rule: function (tryAnonymous) { var name, value, startOfRule = i, c = input.charAt(startOfRule), important, merge, isVariable; if (c === '.' || c === '#' || c === '&') { return; } save(); name = this.variable() || this.ruleProperty(); if (name) { isVariable = typeof name === "string"; if (isVariable) { value = this.detachedRuleset(); } if (!value) { // prefer to try to parse first if its a variable or we are compressing // but always fallback on the other one value = !tryAnonymous && (env.compress || isVariable) ? (this.value() || this.anonymousValue()) : (this.anonymousValue() || this.value()); important = this.important(); // a name returned by this.ruleProperty() is always an array of the form: // [string-1, ..., string-n, ""] or [string-1, ..., string-n, "+"] // where each item is a tree.Keyword or tree.Variable merge = !isVariable && name.pop().value; } if (value && this.end()) { forget(); return new (tree.Rule)(name, value, important, merge, startOfRule, env.currentFileInfo); } else { furthest = i; restore(); if (value && !tryAnonymous) { return this.rule(true); } } } else { forget(); } }, anonymousValue: function () { var match; match = /^([^@+\/'"*`(;{}-]*);/.exec(current); if (match) { i += match[0].length - 1; return new(tree.Anonymous)(match[1]); } }, // // An @import directive // // @import "lib"; // // Depending on our environemnt, importing is done differently: // In the browser, it's an XHR request, in Node, it would be a // file-system operation. The function used for importing is // stored in `import`, which we pass to the Import constructor. // "import": function () { var path, features, index = i; save(); var dir = $re(/^@import?\s+/); var options = (dir ? this.importOptions() : null) || {}; if (dir && (path = this.entities.quoted() || this.entities.url())) { features = this.mediaFeatures(); if ($char(';')) { forget(); features = features && new(tree.Value)(features); return new(tree.Import)(path, features, options, index, env.currentFileInfo); } } restore(); }, importOptions: function() { var o, options = {}, optionName, value; // list of options, surrounded by parens if (! $char('(')) { return null; } do { o = this.importOption(); if (o) { optionName = o; value = true; switch(optionName) { case "css": optionName = "less"; value = false; break; case "once": optionName = "multiple"; value = false; break; } options[optionName] = value; if (! $char(',')) { break; } } } while (o); expectChar(')'); return options; }, importOption: function() { var opt = $re(/^(less|css|multiple|once|inline|reference)/); if (opt) { return opt[1]; } }, mediaFeature: function () { var entities = this.entities, nodes = [], e, p; do { e = entities.keyword() || entities.variable(); if (e) { nodes.push(e); } else if ($char('(')) { p = this.property(); e = this.value(); if ($char(')')) { if (p && e) { nodes.push(new(tree.Paren)(new(tree.Rule)(p, e, null, null, i, env.currentFileInfo, true))); } else if (e) { nodes.push(new(tree.Paren)(e)); } else { return null; } } else { return null; } } } while (e); if (nodes.length > 0) { return new(tree.Expression)(nodes); } }, mediaFeatures: function () { var entities = this.entities, features = [], e; do { e = this.mediaFeature(); if (e) { features.push(e); if (! $char(',')) { break; } } else { e = entities.variable(); if (e) { features.push(e); if (! $char(',')) { break; } } } } while (e); return features.length > 0 ? features : null; }, media: function () { var features, rules, media, debugInfo; if (env.dumpLineNumbers) { debugInfo = getDebugInfo(i, input, env); } if ($re(/^@media/)) { features = this.mediaFeatures(); rules = this.block(); if (rules) { media = new(tree.Media)(rules, features, i, env.currentFileInfo); if (env.dumpLineNumbers) { media.debugInfo = debugInfo; } return media; } } }, // // A CSS Directive // // @charset "utf-8"; // directive: function () { var index = i, name, value, rules, nonVendorSpecificName, hasIdentifier, hasExpression, hasUnknown, hasBlock = true; if (input.charAt(i) !== '@') { return; } value = this['import']() || this.media(); if (value) { return value; } save(); name = $re(/^@[a-z-]+/); if (!name) { return; } nonVendorSpecificName = name; if (name.charAt(1) == '-' && name.indexOf('-', 2) > 0) { nonVendorSpecificName = "@" + name.slice(name.indexOf('-', 2) + 1); } switch(nonVendorSpecificName) { /* case "@font-face": case "@viewport": case "@top-left": case "@top-left-corner": case "@top-center": case "@top-right": case "@top-right-corner": case "@bottom-left": case "@bottom-left-corner": case "@bottom-center": case "@bottom-right": case "@bottom-right-corner": case "@left-top": case "@left-middle": case "@left-bottom": case "@right-top": case "@right-middle": case "@right-bottom": hasBlock = true; break; */ case "@charset": hasIdentifier = true; hasBlock = false; break; case "@namespace": hasExpression = true; hasBlock = false; break; case "@keyframes": hasIdentifier = true; break; case "@host": case "@page": case "@document": case "@supports": hasUnknown = true; break; } if (hasIdentifier) { value = this.entity(); if (!value) { error("expected " + name + " identifier"); } } else if (hasExpression) { value = this.expression(); if (!value) { error("expected " + name + " expression"); } } else if (hasUnknown) { value = ($re(/^[^{;]+/) || '').trim(); if (value) { value = new(tree.Anonymous)(value); } } if (hasBlock) { rules = this.blockRuleset(); } if (rules || (!hasBlock && value && $char(';'))) { forget(); return new(tree.Directive)(name, value, rules, index, env.currentFileInfo, env.dumpLineNumbers ? getDebugInfo(index, input, env) : null); } restore(); }, // // A Value is a comma-delimited list of Expressions // // font-family: Baskerville, Georgia, serif; // // In a Rule, a Value represents everything after the `:`, // and before the `;`. // value: function () { var e, expressions = []; do { e = this.expression(); if (e) { expressions.push(e); if (! $char(',')) { break; } } } while(e); if (expressions.length > 0) { return new(tree.Value)(expressions); } }, important: function () { if (input.charAt(i) === '!') { return $re(/^! *important/); } }, sub: function () { var a, e; if ($char('(')) { a = this.addition(); if (a) { e = new(tree.Expression)([a]); expectChar(')'); e.parens = true; return e; } } }, multiplication: function () { var m, a, op, operation, isSpaced; m = this.operand(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { if (peek(/^\/[*\/]/)) { break; } op = $char('/') || $char('*'); if (!op) { break; } a = this.operand(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, addition: function () { var m, a, op, operation, isSpaced; m = this.multiplication(); if (m) { isSpaced = isWhitespace(input, i - 1); while (true) { op = $re(/^[-+]\s+/) || (!isSpaced && ($char('+') || $char('-'))); if (!op) { break; } a = this.multiplication(); if (!a) { break; } m.parensInOp = true; a.parensInOp = true; operation = new(tree.Operation)(op, [operation || m, a], isSpaced); isSpaced = isWhitespace(input, i - 1); } return operation || m; } }, conditions: function () { var a, b, index = i, condition; a = this.condition(); if (a) { while (true) { if (!peek(/^,\s*(not\s*)?\(/) || !$char(',')) { break; } b = this.condition(); if (!b) { break; } condition = new(tree.Condition)('or', condition || a, b, index); } return condition || a; } }, condition: function () { var entities = this.entities, index = i, negate = false, a, b, c, op; if ($re(/^not/)) { negate = true; } expectChar('('); a = this.addition() || entities.keyword() || entities.quoted(); if (a) { op = $re(/^(?:>=|<=|=<|[<=>])/); if (op) { b = this.addition() || entities.keyword() || entities.quoted(); if (b) { c = new(tree.Condition)(op, a, b, index, negate); } else { error('expected expression'); } } else { c = new(tree.Condition)('=', a, new(tree.Keyword)('true'), index, negate); } expectChar(')'); return $re(/^and/) ? new(tree.Condition)('and', c, this.condition()) : c; } }, // // An operand is anything that can be part of an operation, // such as a Color, or a Variable // operand: function () { var entities = this.entities, p = input.charAt(i + 1), negate; if (input.charAt(i) === '-' && (p === '@' || p === '(')) { negate = $char('-'); } var o = this.sub() || entities.dimension() || entities.color() || entities.variable() || entities.call(); if (negate) { o.parensInOp = true; o = new(tree.Negative)(o); } return o; }, // // Expressions either represent mathematical operations, // or white-space delimited Entities. // // 1px solid black // @var * 2 // expression: function () { var entities = [], e, delim; do { e = this.addition() || this.entity(); if (e) { entities.push(e); // operations do not allow keyword "/" dimension (e.g. small/20px) so we support that here if (!peek(/^\/[\/*]/)) { delim = $char('/'); if (delim) { entities.push(new(tree.Anonymous)(delim)); } } } } while (e); if (entities.length > 0) { return new(tree.Expression)(entities); } }, property: function () { var name = $re(/^(\*?-?[_a-zA-Z0-9-]+)\s*:/); if (name) { return name[1]; } }, ruleProperty: function () { var c = current, name = [], index = [], length = 0, s, k; function match(re) { var a = re.exec(c); if (a) { index.push(i + length); length += a[0].length; c = c.slice(a[1].length); return name.push(a[1]); } } match(/^(\*?)/); while (match(/^((?:[\w-]+)|(?:@\{[\w-]+\}))/)); // ! if ((name.length > 1) && match(/^\s*((?:\+_|\+)?)\s*:/)) { // at last, we have the complete match now. move forward, // convert name particles to tree objects and return: skipWhitespace(length); if (name[0] === '') { name.shift(); index.shift(); } for (k = 0; k < name.length; k++) { s = name[k]; name[k] = (s.charAt(0) !== '@') ? new(tree.Keyword)(s) : new(tree.Variable)('@' + s.slice(2, -1), index[k], env.currentFileInfo); } return name; } } } }; return parser; }; less.Parser.serializeVars = function(vars) { var s = ''; for (var name in vars) { if (Object.hasOwnProperty.call(vars, name)) { var value = vars[name]; s += ((name[0] === '@') ? '' : '@') + name +': '+ value + ((('' + value).slice(-1) === ';') ? '' : ';'); } } return s; }; (function (tree) { tree.functions = { rgb: function (r, g, b) { return this.rgba(r, g, b, 1.0); }, rgba: function (r, g, b, a) { var rgb = [r, g, b].map(function (c) { return scaled(c, 255); }); a = number(a); return new(tree.Color)(rgb, a); }, hsl: function (h, s, l) { return this.hsla(h, s, l, 1.0); }, hsla: function (h, s, l, a) { function hue(h) { h = h < 0 ? h + 1 : (h > 1 ? h - 1 : h); if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } else if (h * 2 < 1) { return m2; } else if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } else { return m1; } } h = (number(h) % 360) / 360; s = clamp(number(s)); l = clamp(number(l)); a = clamp(number(a)); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; return this.rgba(hue(h + 1/3) * 255, hue(h) * 255, hue(h - 1/3) * 255, a); }, hsv: function(h, s, v) { return this.hsva(h, s, v, 1.0); }, hsva: function(h, s, v, a) { h = ((number(h) % 360) / 360) * 360; s = number(s); v = number(v); a = number(a); var i, f; i = Math.floor((h / 60) % 6); f = (h / 60) - i; var vs = [v, v * (1 - s), v * (1 - f * s), v * (1 - (1 - f) * s)]; var perm = [[0, 3, 1], [2, 0, 1], [1, 0, 3], [1, 2, 0], [3, 1, 0], [0, 1, 2]]; return this.rgba(vs[perm[i][0]] * 255, vs[perm[i][1]] * 255, vs[perm[i][2]] * 255, a); }, hue: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().h)); }, saturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().s * 100), '%'); }, lightness: function (color) { return new(tree.Dimension)(Math.round(color.toHSL().l * 100), '%'); }, hsvhue: function(color) { return new(tree.Dimension)(Math.round(color.toHSV().h)); }, hsvsaturation: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().s * 100), '%'); }, hsvvalue: function (color) { return new(tree.Dimension)(Math.round(color.toHSV().v * 100), '%'); }, red: function (color) { return new(tree.Dimension)(color.rgb[0]); }, green: function (color) { return new(tree.Dimension)(color.rgb[1]); }, blue: function (color) { return new(tree.Dimension)(color.rgb[2]); }, alpha: function (color) { return new(tree.Dimension)(color.toHSL().a); }, luma: function (color) { return new(tree.Dimension)(Math.round(color.luma() * color.alpha * 100), '%'); }, luminance: function (color) { var luminance = (0.2126 * color.rgb[0] / 255) + (0.7152 * color.rgb[1] / 255) + (0.0722 * color.rgb[2] / 255); return new(tree.Dimension)(Math.round(luminance * color.alpha * 100), '%'); }, saturate: function (color, amount) { // filter: saturate(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } var hsl = color.toHSL(); hsl.s += amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, desaturate: function (color, amount) { var hsl = color.toHSL(); hsl.s -= amount.value / 100; hsl.s = clamp(hsl.s); return hsla(hsl); }, lighten: function (color, amount) { var hsl = color.toHSL(); hsl.l += amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, darken: function (color, amount) { var hsl = color.toHSL(); hsl.l -= amount.value / 100; hsl.l = clamp(hsl.l); return hsla(hsl); }, fadein: function (color, amount) { var hsl = color.toHSL(); hsl.a += amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fadeout: function (color, amount) { var hsl = color.toHSL(); hsl.a -= amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, fade: function (color, amount) { var hsl = color.toHSL(); hsl.a = amount.value / 100; hsl.a = clamp(hsl.a); return hsla(hsl); }, spin: function (color, amount) { var hsl = color.toHSL(); var hue = (hsl.h + amount.value) % 360; hsl.h = hue < 0 ? 360 + hue : hue; return hsla(hsl); }, // // Copyright (c) 2006-2009 Hampton Catlin, Nathan Weizenbaum, and Chris Eppstein // http://sass-lang.com // mix: function (color1, color2, weight) { if (!weight) { weight = new(tree.Dimension)(50); } var p = weight.value / 100.0; var w = p * 2 - 1; var a = color1.toHSL().a - color2.toHSL().a; var w1 = (((w * a == -1) ? w : (w + a) / (1 + w * a)) + 1) / 2.0; var w2 = 1 - w1; var rgb = [color1.rgb[0] * w1 + color2.rgb[0] * w2, color1.rgb[1] * w1 + color2.rgb[1] * w2, color1.rgb[2] * w1 + color2.rgb[2] * w2]; var alpha = color1.alpha * p + color2.alpha * (1 - p); return new(tree.Color)(rgb, alpha); }, greyscale: function (color) { return this.desaturate(color, new(tree.Dimension)(100)); }, contrast: function (color, dark, light, threshold) { // filter: contrast(3.2); // should be kept as is, so check for color if (!color.rgb) { return null; } if (typeof light === 'undefined') { light = this.rgba(255, 255, 255, 1.0); } if (typeof dark === 'undefined') { dark = this.rgba(0, 0, 0, 1.0); } //Figure out which is actually light and dark! if (dark.luma() > light.luma()) { var t = light; light = dark; dark = t; } if (typeof threshold === 'undefined') { threshold = 0.43; } else { threshold = number(threshold); } if (color.luma() < threshold) { return light; } else { return dark; } }, e: function (str) { return new(tree.Anonymous)(str instanceof tree.JavaScript ? str.evaluated : str); }, escape: function (str) { return new(tree.Anonymous)(encodeURI(str.value).replace(/=/g, "%3D").replace(/:/g, "%3A").replace(/#/g, "%23").replace(/;/g, "%3B").replace(/\(/g, "%28").replace(/\)/g, "%29")); }, replace: function (string, pattern, replacement, flags) { var result = string.value; result = result.replace(new RegExp(pattern.value, flags ? flags.value : ''), replacement.value); return new(tree.Quoted)(string.quote || '', result, string.escaped); }, '%': function (string /* arg, arg, ...*/) { var args = Array.prototype.slice.call(arguments, 1), result = string.value; for (var i = 0; i < args.length; i++) { /*jshint loopfunc:true */ result = result.replace(/%[sda]/i, function(token) { var value = token.match(/s/i) ? args[i].value : args[i].toCSS(); return token.match(/[A-Z]$/) ? encodeURIComponent(value) : value; }); } result = result.replace(/%%/g, '%'); return new(tree.Quoted)(string.quote || '', result, string.escaped); }, unit: function (val, unit) { if(!(val instanceof tree.Dimension)) { throw { type: "Argument", message: "the first argument to unit must be a number" + (val instanceof tree.Operation ? ". Have you forgotten parenthesis?" : "") }; } if (unit) { if (unit instanceof tree.Keyword) { unit = unit.value; } else { unit = unit.toCSS(); } } else { unit = ""; } return new(tree.Dimension)(val.value, unit); }, convert: function (val, unit) { return val.convertTo(unit.value); }, round: function (n, f) { var fraction = typeof(f) === "undefined" ? 0 : f.value; return _math(function(num) { return num.toFixed(fraction); }, null, n); }, pi: function () { return new(tree.Dimension)(Math.PI); }, mod: function(a, b) { return new(tree.Dimension)(a.value % b.value, a.unit); }, pow: function(x, y) { if (typeof x === "number" && typeof y === "number") { x = new(tree.Dimension)(x); y = new(tree.Dimension)(y); } else if (!(x instanceof tree.Dimension) || !(y instanceof tree.Dimension)) { throw { type: "Argument", message: "arguments must be numbers" }; } return new(tree.Dimension)(Math.pow(x.value, y.value), x.unit); }, _minmax: function (isMin, args) { args = Array.prototype.slice.call(args); switch(args.length) { case 0: throw { type: "Argument", message: "one or more arguments required" }; } var i, j, current, currentUnified, referenceUnified, unit, unitStatic, unitClone, order = [], // elems only contains original argument values. values = {}; // key is the unit.toString() for unified tree.Dimension values, // value is the index into the order array. for (i = 0; i < args.length; i++) { current = args[i]; if (!(current instanceof tree.Dimension)) { if(Array.isArray(args[i].value)) { Array.prototype.push.apply(args, Array.prototype.slice.call(args[i].value)); } continue; } currentUnified = current.unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(current.value, unitClone).unify() : current.unify(); unit = currentUnified.unit.toString() === "" && unitStatic !== undefined ? unitStatic : currentUnified.unit.toString(); unitStatic = unit !== "" && unitStatic === undefined || unit !== "" && order[0].unify().unit.toString() === "" ? unit : unitStatic; unitClone = unit !== "" && unitClone === undefined ? current.unit.toString() : unitClone; j = values[""] !== undefined && unit !== "" && unit === unitStatic ? values[""] : values[unit]; if (j === undefined) { if(unitStatic !== undefined && unit !== unitStatic) { throw{ type: "Argument", message: "incompatible types" }; } values[unit] = order.length; order.push(current); continue; } referenceUnified = order[j].unit.toString() === "" && unitClone !== undefined ? new(tree.Dimension)(order[j].value, unitClone).unify() : order[j].unify(); if ( isMin && currentUnified.value < referenceUnified.value || !isMin && currentUnified.value > referenceUnified.value) { order[j] = current; } } if (order.length == 1) { return order[0]; } args = order.map(function (a) { return a.toCSS(this.env); }).join(this.env.compress ? "," : ", "); return new(tree.Anonymous)((isMin ? "min" : "max") + "(" + args + ")"); }, min: function () { return this._minmax(true, arguments); }, max: function () { return this._minmax(false, arguments); }, "get-unit": function (n) { return new(tree.Anonymous)(n.unit); }, argb: function (color) { return new(tree.Anonymous)(color.toARGB()); }, percentage: function (n) { return new(tree.Dimension)(n.value * 100, '%'); }, color: function (n) { if (n instanceof tree.Quoted) { var colorCandidate = n.value, returnColor; returnColor = tree.Color.fromKeyword(colorCandidate); if (returnColor) { return returnColor; } if (/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})/.test(colorCandidate)) { return new(tree.Color)(colorCandidate.slice(1)); } throw { type: "Argument", message: "argument must be a color keyword or 3/6 digit hex e.g. #FFF" }; } else { throw { type: "Argument", message: "argument must be a string" }; } }, iscolor: function (n) { return this._isa(n, tree.Color); }, isnumber: function (n) { return this._isa(n, tree.Dimension); }, isstring: function (n) { return this._isa(n, tree.Quoted); }, iskeyword: function (n) { return this._isa(n, tree.Keyword); }, isurl: function (n) { return this._isa(n, tree.URL); }, ispixel: function (n) { return this.isunit(n, 'px'); }, ispercentage: function (n) { return this.isunit(n, '%'); }, isem: function (n) { return this.isunit(n, 'em'); }, isunit: function (n, unit) { return (n instanceof tree.Dimension) && n.unit.is(unit.value || unit) ? tree.True : tree.False; }, _isa: function (n, Type) { return (n instanceof Type) ? tree.True : tree.False; }, tint: function(color, amount) { return this.mix(this.rgb(255,255,255), color, amount); }, shade: function(color, amount) { return this.mix(this.rgb(0, 0, 0), color, amount); }, extract: function(values, index) { index = index.value - 1; // (1-based index) // handle non-array values as an array of length 1 // return 'undefined' if index is invalid return Array.isArray(values.value) ? values.value[index] : Array(values)[index]; }, length: function(values) { var n = Array.isArray(values.value) ? values.value.length : 1; return new tree.Dimension(n); }, "data-uri": function(mimetypeNode, filePathNode) { if (typeof window !== 'undefined') { return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } var mimetype = mimetypeNode.value; var filePath = (filePathNode && filePathNode.value); var fs = require('fs'), path = require('path'), useBase64 = false; if (arguments.length < 2) { filePath = mimetype; } if (this.env.isPathRelative(filePath)) { if (this.currentFileInfo.relativeUrls) { filePath = path.join(this.currentFileInfo.currentDirectory, filePath); } else { filePath = path.join(this.currentFileInfo.entryPath, filePath); } } // detect the mimetype if not given if (arguments.length < 2) { var mime; try { mime = require('mime'); } catch (ex) { mime = tree._mime; } mimetype = mime.lookup(filePath); // use base 64 unless it's an ASCII or UTF-8 format var charset = mime.charsets.lookup(mimetype); useBase64 = ['US-ASCII', 'UTF-8'].indexOf(charset) < 0; if (useBase64) { mimetype += ';base64'; } } else { useBase64 = /;base64$/.test(mimetype); } var buf = fs.readFileSync(filePath); // IE8 cannot handle a data-uri larger than 32KB. If this is exceeded // and the --ieCompat flag is enabled, return a normal url() instead. var DATA_URI_MAX_KB = 32, fileSizeInKB = parseInt((buf.length / 1024), 10); if (fileSizeInKB >= DATA_URI_MAX_KB) { if (this.env.ieCompat !== false) { if (!this.env.silent) { console.warn("Skipped data-uri embedding of %s because its size (%dKB) exceeds IE8-safe %dKB!", filePath, fileSizeInKB, DATA_URI_MAX_KB); } return new tree.URL(filePathNode || mimetypeNode, this.currentFileInfo).eval(this.env); } } buf = useBase64 ? buf.toString('base64') : encodeURIComponent(buf); var uri = "\"data:" + mimetype + ',' + buf + "\""; return new(tree.URL)(new(tree.Anonymous)(uri)); }, "svg-gradient": function(direction) { function throwArgumentDescriptor() { throw { type: "Argument", message: "svg-gradient expects direction, start_color [start_position], [color position,]..., end_color [end_position]" }; } if (arguments.length < 3) { throwArgumentDescriptor(); } var stops = Array.prototype.slice.call(arguments, 1), gradientDirectionSvg, gradientType = "linear", rectangleDimension = 'x="0" y="0" width="1" height="1"', useBase64 = true, renderEnv = {compress: false}, returner, directionValue = direction.toCSS(renderEnv), i, color, position, positionValue, alpha; switch (directionValue) { case "to bottom": gradientDirectionSvg = 'x1="0%" y1="0%" x2="0%" y2="100%"'; break; case "to right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="0%"'; break; case "to bottom right": gradientDirectionSvg = 'x1="0%" y1="0%" x2="100%" y2="100%"'; break; case "to top right": gradientDirectionSvg = 'x1="0%" y1="100%" x2="100%" y2="0%"'; break; case "ellipse": case "ellipse at center": gradientType = "radial"; gradientDirectionSvg = 'cx="50%" cy="50%" r="75%"'; rectangleDimension = 'x="-50" y="-50" width="101" height="101"'; break; default: throw { type: "Argument", message: "svg-gradient direction must be 'to bottom', 'to right', 'to bottom right', 'to top right' or 'ellipse at center'" }; } returner = '<?xml version="1.0" ?>' + '<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="100%" height="100%" viewBox="0 0 1 1" preserveAspectRatio="none">' + '<' + gradientType + 'Gradient id="gradient" gradientUnits="userSpaceOnUse" ' + gradientDirectionSvg + '>'; for (i = 0; i < stops.length; i+= 1) { if (stops[i].value) { color = stops[i].value[0]; position = stops[i].value[1]; } else { color = stops[i]; position = undefined; } if (!(color instanceof tree.Color) || (!((i === 0 || i+1 === stops.length) && position === undefined) && !(position instanceof tree.Dimension))) { throwArgumentDescriptor(); } positionValue = position ? position.toCSS(renderEnv) : i === 0 ? "0%" : "100%"; alpha = color.alpha; returner += '<stop offset="' + positionValue + '" stop-color="' + color.toRGB() + '"' + (alpha < 1 ? ' stop-opacity="' + alpha + '"' : '') + '/>'; } returner += '</' + gradientType + 'Gradient>' + '<rect ' + rectangleDimension + ' fill="url(#gradient)" /></svg>'; if (useBase64) { try { returner = require('./encoder').encodeBase64(returner); // TODO browser implementation } catch(e) { useBase64 = false; } } returner = "'data:image/svg+xml" + (useBase64 ? ";base64" : "") + "," + returner + "'"; return new(tree.URL)(new(tree.Anonymous)(returner)); } }; // these static methods are used as a fallback when the optional 'mime' dependency is missing tree._mime = { // this map is intentionally incomplete // if you want more, install 'mime' dep _types: { '.htm' : 'text/html', '.html': 'text/html', '.gif' : 'image/gif', '.jpg' : 'image/jpeg', '.jpeg': 'image/jpeg', '.png' : 'image/png' }, lookup: function (filepath) { var ext = require('path').extname(filepath), type = tree._mime._types[ext]; if (type === undefined) { throw new Error('Optional dependency "mime" is required for ' + ext); } return type; }, charsets: { lookup: function (type) { // assumes all text types are UTF-8 return type && (/^text\//).test(type) ? 'UTF-8' : ''; } } }; // Math var mathFunctions = { // name, unit ceil: null, floor: null, sqrt: null, abs: null, tan: "", sin: "", cos: "", atan: "rad", asin: "rad", acos: "rad" }; function _math(fn, unit, n) { if (!(n instanceof tree.Dimension)) { throw { type: "Argument", message: "argument must be a number" }; } if (unit == null) { unit = n.unit; } else { n = n.unify(); } return new(tree.Dimension)(fn(parseFloat(n.value)), unit); } // ~ End of Math // Color Blending // ref: http://www.w3.org/TR/compositing-1 function colorBlend(mode, color1, color2) { var ab = color1.alpha, cb, // backdrop as = color2.alpha, cs, // source ar, cr, r = []; // result ar = as + ab * (1 - as); for (var i = 0; i < 3; i++) { cb = color1.rgb[i] / 255; cs = color2.rgb[i] / 255; cr = mode(cb, cs); if (ar) { cr = (as * cs + ab * (cb - as * (cb + cs - cr))) / ar; } r[i] = cr * 255; } return new(tree.Color)(r, ar); } var colorBlendMode = { multiply: function(cb, cs) { return cb * cs; }, screen: function(cb, cs) { return cb + cs - cb * cs; }, overlay: function(cb, cs) { cb *= 2; return (cb <= 1) ? colorBlendMode.multiply(cb, cs) : colorBlendMode.screen(cb - 1, cs); }, softlight: function(cb, cs) { var d = 1, e = cb; if (cs > 0.5) { e = 1; d = (cb > 0.25) ? Math.sqrt(cb) : ((16 * cb - 12) * cb + 4) * cb; } return cb - (1 - 2 * cs) * e * (d - cb); }, hardlight: function(cb, cs) { return colorBlendMode.overlay(cs, cb); }, difference: function(cb, cs) { return Math.abs(cb - cs); }, exclusion: function(cb, cs) { return cb + cs - 2 * cb * cs; }, // non-w3c functions: average: function(cb, cs) { return (cb + cs) / 2; }, negation: function(cb, cs) { return 1 - Math.abs(cb + cs - 1); } }; // ~ End of Color Blending tree.defaultFunc = { eval: function () { var v = this.value_, e = this.error_; if (e) { throw e; } if (v != null) { return v ? tree.True : tree.False; } }, value: function (v) { this.value_ = v; }, error: function (e) { this.error_ = e; }, reset: function () { this.value_ = this.error_ = null; } }; function initFunctions() { var f, tf = tree.functions; // math for (f in mathFunctions) { if (mathFunctions.hasOwnProperty(f)) { tf[f] = _math.bind(null, Math[f], mathFunctions[f]); } } // color blending for (f in colorBlendMode) { if (colorBlendMode.hasOwnProperty(f)) { tf[f] = colorBlend.bind(null, colorBlendMode[f]); } } // default f = tree.defaultFunc; tf["default"] = f.eval.bind(f); } initFunctions(); function hsla(color) { return tree.functions.hsla(color.h, color.s, color.l, color.a); } function scaled(n, size) { if (n instanceof tree.Dimension && n.unit.is('%')) { return parseFloat(n.value * size / 100); } else { return number(n); } } function number(n) { if (n instanceof tree.Dimension) { return parseFloat(n.unit.is('%') ? n.value / 100 : n.value); } else if (typeof(n) === 'number') { return n; } else { throw { error: "RuntimeError", message: "color functions take numbers as parameters" }; } } function clamp(val) { return Math.min(1, Math.max(0, val)); } tree.fround = function(env, value) { var p; if (env && (env.numPrecision != null)) { p = Math.pow(10, env.numPrecision); return Math.round(value * p) / p; } else { return value; } }; tree.functionCall = function(env, currentFileInfo) { this.env = env; this.currentFileInfo = currentFileInfo; }; tree.functionCall.prototype = tree.functions; })(require('./tree')); (function (tree) { tree.colors = { 'aliceblue':'#f0f8ff', 'antiquewhite':'#faebd7', 'aqua':'#00ffff', 'aquamarine':'#7fffd4', 'azure':'#f0ffff', 'beige':'#f5f5dc', 'bisque':'#ffe4c4', 'black':'#000000', 'blanchedalmond':'#ffebcd', 'blue':'#0000ff', 'blueviolet':'#8a2be2', 'brown':'#a52a2a', 'burlywood':'#deb887', 'cadetblue':'#5f9ea0', 'chartreuse':'#7fff00', 'chocolate':'#d2691e', 'coral':'#ff7f50', 'cornflowerblue':'#6495ed', 'cornsilk':'#fff8dc', 'crimson':'#dc143c', 'cyan':'#00ffff', 'darkblue':'#00008b', 'darkcyan':'#008b8b', 'darkgoldenrod':'#b8860b', 'darkgray':'#a9a9a9', 'darkgrey':'#a9a9a9', 'darkgreen':'#006400', 'darkkhaki':'#bdb76b', 'darkmagenta':'#8b008b', 'darkolivegreen':'#556b2f', 'darkorange':'#ff8c00', 'darkorchid':'#9932cc', 'darkred':'#8b0000', 'darksalmon':'#e9967a', 'darkseagreen':'#8fbc8f', 'darkslateblue':'#483d8b', 'darkslategray':'#2f4f4f', 'darkslategrey':'#2f4f4f', 'darkturquoise':'#00ced1', 'darkviolet':'#9400d3', 'deeppink':'#ff1493', 'deepskyblue':'#00bfff', 'dimgray':'#696969', 'dimgrey':'#696969', 'dodgerblue':'#1e90ff', 'firebrick':'#b22222', 'floralwhite':'#fffaf0', 'forestgreen':'#228b22', 'fuchsia':'#ff00ff', 'gainsboro':'#dcdcdc', 'ghostwhite':'#f8f8ff', 'gold':'#ffd700', 'goldenrod':'#daa520', 'gray':'#808080', 'grey':'#808080', 'green':'#008000', 'greenyellow':'#adff2f', 'honeydew':'#f0fff0', 'hotpink':'#ff69b4', 'indianred':'#cd5c5c', 'indigo':'#4b0082', 'ivory':'#fffff0', 'khaki':'#f0e68c', 'lavender':'#e6e6fa', 'lavenderblush':'#fff0f5', 'lawngreen':'#7cfc00', 'lemonchiffon':'#fffacd', 'lightblue':'#add8e6', 'lightcoral':'#f08080', 'lightcyan':'#e0ffff', 'lightgoldenrodyellow':'#fafad2', 'lightgray':'#d3d3d3', 'lightgrey':'#d3d3d3', 'lightgreen':'#90ee90', 'lightpink':'#ffb6c1', 'lightsalmon':'#ffa07a', 'lightseagreen':'#20b2aa', 'lightskyblue':'#87cefa', 'lightslategray':'#778899', 'lightslategrey':'#778899', 'lightsteelblue':'#b0c4de', 'lightyellow':'#ffffe0', 'lime':'#00ff00', 'limegreen':'#32cd32', 'linen':'#faf0e6', 'magenta':'#ff00ff', 'maroon':'#800000', 'mediumaquamarine':'#66cdaa', 'mediumblue':'#0000cd', 'mediumorchid':'#ba55d3', 'mediumpurple':'#9370d8', 'mediumseagreen':'#3cb371', 'mediumslateblue':'#7b68ee', 'mediumspringgreen':'#00fa9a', 'mediumturquoise':'#48d1cc', 'mediumvioletred':'#c71585', 'midnightblue':'#191970', 'mintcream':'#f5fffa', 'mistyrose':'#ffe4e1', 'moccasin':'#ffe4b5', 'navajowhite':'#ffdead', 'navy':'#000080', 'oldlace':'#fdf5e6', 'olive':'#808000', 'olivedrab':'#6b8e23', 'orange':'#ffa500', 'orangered':'#ff4500', 'orchid':'#da70d6', 'palegoldenrod':'#eee8aa', 'palegreen':'#98fb98', 'paleturquoise':'#afeeee', 'palevioletred':'#d87093', 'papayawhip':'#ffefd5', 'peachpuff':'#ffdab9', 'peru':'#cd853f', 'pink':'#ffc0cb', 'plum':'#dda0dd', 'powderblue':'#b0e0e6', 'purple':'#800080', 'red':'#ff0000', 'rosybrown':'#bc8f8f', 'royalblue':'#4169e1', 'saddlebrown':'#8b4513', 'salmon':'#fa8072', 'sandybrown':'#f4a460', 'seagreen':'#2e8b57', 'seashell':'#fff5ee', 'sienna':'#a0522d', 'silver':'#c0c0c0', 'skyblue':'#87ceeb', 'slateblue':'#6a5acd', 'slategray':'#708090', 'slategrey':'#708090', 'snow':'#fffafa', 'springgreen':'#00ff7f', 'steelblue':'#4682b4', 'tan':'#d2b48c', 'teal':'#008080', 'thistle':'#d8bfd8', 'tomato':'#ff6347', 'turquoise':'#40e0d0', 'violet':'#ee82ee', 'wheat':'#f5deb3', 'white':'#ffffff', 'whitesmoke':'#f5f5f5', 'yellow':'#ffff00', 'yellowgreen':'#9acd32' }; })(require('./tree')); (function (tree) { tree.debugInfo = function(env, ctx, lineSeperator) { var result=""; if (env.dumpLineNumbers && !env.compress) { switch(env.dumpLineNumbers) { case 'comments': result = tree.debugInfo.asComment(ctx); break; case 'mediaquery': result = tree.debugInfo.asMediaQuery(ctx); break; case 'all': result = tree.debugInfo.asComment(ctx) + (lineSeperator || "") + tree.debugInfo.asMediaQuery(ctx); break; } } return result; }; tree.debugInfo.asComment = function(ctx) { return '/* line ' + ctx.debugInfo.lineNumber + ', ' + ctx.debugInfo.fileName + ' */\n'; }; tree.debugInfo.asMediaQuery = function(ctx) { return '@media -sass-debug-info{filename{font-family:' + ('file://' + ctx.debugInfo.fileName).replace(/([.:\/\\])/g, function (a) { if (a == '\\') { a = '\/'; } return '\\' + a; }) + '}line{font-family:\\00003' + ctx.debugInfo.lineNumber + '}}\n'; }; tree.find = function (obj, fun) { for (var i = 0, r; i < obj.length; i++) { r = fun.call(obj, obj[i]); if (r) { return r; } } return null; }; tree.jsify = function (obj) { if (Array.isArray(obj.value) && (obj.value.length > 1)) { return '[' + obj.value.map(function (v) { return v.toCSS(false); }).join(', ') + ']'; } else { return obj.toCSS(false); } }; tree.toCSS = function (env) { var strs = []; this.genCSS(env, { add: function(chunk, fileInfo, index) { strs.push(chunk); }, isEmpty: function () { return strs.length === 0; } }); return strs.join(''); }; tree.outputRuleset = function (env, output, rules) { var ruleCnt = rules.length, i; env.tabLevel = (env.tabLevel | 0) + 1; // Compressed if (env.compress) { output.add('{'); for (i = 0; i < ruleCnt; i++) { rules[i].genCSS(env, output); } output.add('}'); env.tabLevel--; return; } // Non-compressed var tabSetStr = '\n' + Array(env.tabLevel).join(" "), tabRuleStr = tabSetStr + " "; if (!ruleCnt) { output.add(" {" + tabSetStr + '}'); } else { output.add(" {" + tabRuleStr); rules[0].genCSS(env, output); for (i = 1; i < ruleCnt; i++) { output.add(tabRuleStr); rules[i].genCSS(env, output); } output.add(tabSetStr + '}'); } env.tabLevel--; }; })(require('./tree')); (function (tree) { tree.Alpha = function (val) { this.value = val; }; tree.Alpha.prototype = { type: "Alpha", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new tree.Alpha(this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add("alpha(opacity="); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Anonymous = function (string, index, currentFileInfo, mapLines) { this.value = string.value || string; this.index = index; this.mapLines = mapLines; this.currentFileInfo = currentFileInfo; }; tree.Anonymous.prototype = { type: "Anonymous", eval: function () { return new tree.Anonymous(this.value, this.index, this.currentFileInfo, this.mapLines); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; }, genCSS: function (env, output) { output.add(this.value, this.currentFileInfo, this.index, this.mapLines); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Assignment = function (key, val) { this.key = key; this.value = val; }; tree.Assignment.prototype = { type: "Assignment", accept: function (visitor) { this.value = visitor.visit(this.value); }, eval: function (env) { if (this.value.eval) { return new(tree.Assignment)(this.key, this.value.eval(env)); } return this; }, genCSS: function (env, output) { output.add(this.key + '='); if (this.value.genCSS) { this.value.genCSS(env, output); } else { output.add(this.value); } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // A function call node. // tree.Call = function (name, args, index, currentFileInfo) { this.name = name; this.args = args; this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Call.prototype = { type: "Call", accept: function (visitor) { if (this.args) { this.args = visitor.visitArray(this.args); } }, // // When evaluating a function call, // we either find the function in `tree.functions` [1], // in which case we call it, passing the evaluated arguments, // if this returns null or we cannot find the function, we // simply print it out as it appeared originally [2]. // // The *functions.js* file contains the built-in functions. // // The reason why we evaluate the arguments, is in the case where // we try to pass a variable to a function, like: `saturate(@color)`. // The function should receive the value, not the variable. // eval: function (env) { var args = this.args.map(function (a) { return a.eval(env); }), nameLC = this.name.toLowerCase(), result, func; if (nameLC in tree.functions) { // 1. try { func = new tree.functionCall(env, this.currentFileInfo); result = func[nameLC].apply(func, args); if (result != null) { return result; } } catch (e) { throw { type: e.type || "Runtime", message: "error evaluating function `" + this.name + "`" + (e.message ? ': ' + e.message : ''), index: this.index, filename: this.currentFileInfo.filename }; } } return new tree.Call(this.name, args, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.name + "(", this.currentFileInfo, this.index); for(var i = 0; i < this.args.length; i++) { this.args[i].genCSS(env, output); if (i + 1 < this.args.length) { output.add(", "); } } output.add(")"); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { // // RGB Colors - #ff0014, #eee // tree.Color = function (rgb, a) { // // The end goal here, is to parse the arguments // into an integer triplet, such as `128, 255, 0` // // This facilitates operations and conversions. // if (Array.isArray(rgb)) { this.rgb = rgb; } else if (rgb.length == 6) { this.rgb = rgb.match(/.{2}/g).map(function (c) { return parseInt(c, 16); }); } else { this.rgb = rgb.split('').map(function (c) { return parseInt(c + c, 16); }); } this.alpha = typeof(a) === 'number' ? a : 1; }; var transparentKeyword = "transparent"; tree.Color.prototype = { type: "Color", eval: function () { return this; }, luma: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255; r = (r <= 0.03928) ? r / 12.92 : Math.pow(((r + 0.055) / 1.055), 2.4); g = (g <= 0.03928) ? g / 12.92 : Math.pow(((g + 0.055) / 1.055), 2.4); b = (b <= 0.03928) ? b / 12.92 : Math.pow(((b + 0.055) / 1.055), 2.4); return 0.2126 * r + 0.7152 * g + 0.0722 * b; }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env, doNotCompress) { var compress = env && env.compress && !doNotCompress, alpha = tree.fround(env, this.alpha); // If we have some transparency, the only way to represent it // is via `rgba`. Otherwise, we use the hex representation, // which has better compatibility with older browsers. // Values are capped between `0` and `255`, rounded and zero-padded. if (alpha < 1) { if (alpha === 0 && this.isTransparentKeyword) { return transparentKeyword; } return "rgba(" + this.rgb.map(function (c) { return clamp(Math.round(c), 255); }).concat(clamp(alpha, 1)) .join(',' + (compress ? '' : ' ')) + ")"; } else { var color = this.toRGB(); if (compress) { var splitcolor = color.split(''); // Convert color to short format if (splitcolor[1] === splitcolor[2] && splitcolor[3] === splitcolor[4] && splitcolor[5] === splitcolor[6]) { color = '#' + splitcolor[1] + splitcolor[3] + splitcolor[5]; } } return color; } }, // // Operations have to be done per-channel, if not, // channels will spill onto each other. Once we have // our result, in the form of an integer triplet, // we create a new Color node to hold the result. // operate: function (env, op, other) { var rgb = []; var alpha = this.alpha * (1 - other.alpha) + other.alpha; for (var c = 0; c < 3; c++) { rgb[c] = tree.operate(env, op, this.rgb[c], other.rgb[c]); } return new(tree.Color)(rgb, alpha); }, toRGB: function () { return toHex(this.rgb); }, toHSL: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, l = (max + min) / 2, d = max - min; if (max === min) { h = s = 0; } else { s = l > 0.5 ? d / (2 - max - min) : d / (max + min); switch (max) { case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, l: l, a: a }; }, //Adapted from http://mjijackson.com/2008/02/rgb-to-hsl-and-rgb-to-hsv-color-model-conversion-algorithms-in-javascript toHSV: function () { var r = this.rgb[0] / 255, g = this.rgb[1] / 255, b = this.rgb[2] / 255, a = this.alpha; var max = Math.max(r, g, b), min = Math.min(r, g, b); var h, s, v = max; var d = max - min; if (max === 0) { s = 0; } else { s = d / max; } if (max === min) { h = 0; } else { switch(max){ case r: h = (g - b) / d + (g < b ? 6 : 0); break; case g: h = (b - r) / d + 2; break; case b: h = (r - g) / d + 4; break; } h /= 6; } return { h: h * 360, s: s, v: v, a: a }; }, toARGB: function () { return toHex([this.alpha * 255].concat(this.rgb)); }, compare: function (x) { if (!x.rgb) { return -1; } return (x.rgb[0] === this.rgb[0] && x.rgb[1] === this.rgb[1] && x.rgb[2] === this.rgb[2] && x.alpha === this.alpha) ? 0 : -1; } }; tree.Color.fromKeyword = function(keyword) { keyword = keyword.toLowerCase(); if (tree.colors.hasOwnProperty(keyword)) { // detect named color return new(tree.Color)(tree.colors[keyword].slice(1)); } if (keyword === transparentKeyword) { var transparent = new(tree.Color)([0, 0, 0], 0); transparent.isTransparentKeyword = true; return transparent; } }; function toHex(v) { return '#' + v.map(function (c) { c = clamp(Math.round(c), 255); return (c < 16 ? '0' : '') + c.toString(16); }).join(''); } function clamp(v, max) { return Math.min(Math.max(v, 0), max); } })(require('../tree')); (function (tree) { tree.Comment = function (value, silent, index, currentFileInfo) { this.value = value; this.silent = !!silent; this.currentFileInfo = currentFileInfo; }; tree.Comment.prototype = { type: "Comment", genCSS: function (env, output) { if (this.debugInfo) { output.add(tree.debugInfo(env, this), this.currentFileInfo, this.index); } output.add(this.value.trim()); //TODO shouldn't need to trim, we shouldn't grab the \n }, toCSS: tree.toCSS, isSilent: function(env) { var isReference = (this.currentFileInfo && this.currentFileInfo.reference && !this.isReferenced), isCompressed = env.compress && !this.value.match(/^\/\*!/); return this.silent || isReference || isCompressed; }, eval: function () { return this; }, markReferenced: function () { this.isReferenced = true; } }; })(require('../tree')); (function (tree) { tree.Condition = function (op, l, r, i, negate) { this.op = op.trim(); this.lvalue = l; this.rvalue = r; this.index = i; this.negate = negate; }; tree.Condition.prototype = { type: "Condition", accept: function (visitor) { this.lvalue = visitor.visit(this.lvalue); this.rvalue = visitor.visit(this.rvalue); }, eval: function (env) { var a = this.lvalue.eval(env), b = this.rvalue.eval(env); var i = this.index, result; result = (function (op) { switch (op) { case 'and': return a && b; case 'or': return a || b; default: if (a.compare) { result = a.compare(b); } else if (b.compare) { result = b.compare(a); } else { throw { type: "Type", message: "Unable to perform comparison", index: i }; } switch (result) { case -1: return op === '<' || op === '=<' || op === '<='; case 0: return op === '=' || op === '>=' || op === '=<' || op === '<='; case 1: return op === '>' || op === '>='; } } })(this.op); return this.negate ? !result : result; } }; })(require('../tree')); (function (tree) { tree.DetachedRuleset = function (ruleset, frames) { this.ruleset = ruleset; this.frames = frames; }; tree.DetachedRuleset.prototype = { type: "DetachedRuleset", accept: function (visitor) { this.ruleset = visitor.visit(this.ruleset); }, eval: function (env) { var frames = this.frames || env.frames.slice(0); return new tree.DetachedRuleset(this.ruleset, frames); }, callEval: function (env) { return this.ruleset.eval(this.frames ? new(tree.evalEnv)(env, this.frames.concat(env.frames)) : env); } }; })(require('../tree')); (function (tree) { // // A number with a unit // tree.Dimension = function (value, unit) { this.value = parseFloat(value); this.unit = (unit && unit instanceof tree.Unit) ? unit : new(tree.Unit)(unit ? [unit] : undefined); }; tree.Dimension.prototype = { type: "Dimension", accept: function (visitor) { this.unit = visitor.visit(this.unit); }, eval: function (env) { return this; }, toColor: function () { return new(tree.Color)([this.value, this.value, this.value]); }, genCSS: function (env, output) { if ((env && env.strictUnits) && !this.unit.isSingular()) { throw new Error("Multiple units in dimension. Correct the units or use the unit function. Bad unit: "+this.unit.toString()); } var value = tree.fround(env, this.value), strValue = String(value); if (value !== 0 && value < 0.000001 && value > -0.000001) { // would be output 1e-6 etc. strValue = value.toFixed(20).replace(/0+$/, ""); } if (env && env.compress) { // Zero values doesn't need a unit if (value === 0 && this.unit.isLength()) { output.add(strValue); return; } // Float values doesn't need a leading zero if (value > 0 && value < 1) { strValue = (strValue).substr(1); } } output.add(strValue); this.unit.genCSS(env, output); }, toCSS: tree.toCSS, // In an operation between two Dimensions, // we default to the first Dimension's unit, // so `1px + 2` will yield `3px`. operate: function (env, op, other) { /*jshint noempty:false */ var value = tree.operate(env, op, this.value, other.value), unit = this.unit.clone(); if (op === '+' || op === '-') { if (unit.numerator.length === 0 && unit.denominator.length === 0) { unit.numerator = other.unit.numerator.slice(0); unit.denominator = other.unit.denominator.slice(0); } else if (other.unit.numerator.length === 0 && unit.denominator.length === 0) { // do nothing } else { other = other.convertTo(this.unit.usedUnits()); if(env.strictUnits && other.unit.toString() !== unit.toString()) { throw new Error("Incompatible units. Change the units or use the unit function. Bad units: '" + unit.toString() + "' and '" + other.unit.toString() + "'."); } value = tree.operate(env, op, this.value, other.value); } } else if (op === '*') { unit.numerator = unit.numerator.concat(other.unit.numerator).sort(); unit.denominator = unit.denominator.concat(other.unit.denominator).sort(); unit.cancel(); } else if (op === '/') { unit.numerator = unit.numerator.concat(other.unit.denominator).sort(); unit.denominator = unit.denominator.concat(other.unit.numerator).sort(); unit.cancel(); } return new(tree.Dimension)(value, unit); }, compare: function (other) { if (other instanceof tree.Dimension) { var a, b, aValue, bValue; if (this.unit.isEmpty() || other.unit.isEmpty()) { a = this; b = other; } else { a = this.unify(); b = other.unify(); if (a.unit.compare(b.unit) !== 0) { return -1; } } aValue = a.value; bValue = b.value; if (bValue > aValue) { return -1; } else if (bValue < aValue) { return 1; } else { return 0; } } else { return -1; } }, unify: function () { return this.convertTo({ length: 'px', duration: 's', angle: 'rad' }); }, convertTo: function (conversions) { var value = this.value, unit = this.unit.clone(), i, groupName, group, targetUnit, derivedConversions = {}, applyUnit; if (typeof conversions === 'string') { for(i in tree.UnitConversions) { if (tree.UnitConversions[i].hasOwnProperty(conversions)) { derivedConversions = {}; derivedConversions[i] = conversions; } } conversions = derivedConversions; } applyUnit = function (atomicUnit, denominator) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit)) { if (denominator) { value = value / (group[atomicUnit] / group[targetUnit]); } else { value = value * (group[atomicUnit] / group[targetUnit]); } return targetUnit; } return atomicUnit; }; for (groupName in conversions) { if (conversions.hasOwnProperty(groupName)) { targetUnit = conversions[groupName]; group = tree.UnitConversions[groupName]; unit.map(applyUnit); } } unit.cancel(); return new(tree.Dimension)(value, unit); } }; // http://www.w3.org/TR/css3-values/#absolute-lengths tree.UnitConversions = { length: { 'm': 1, 'cm': 0.01, 'mm': 0.001, 'in': 0.0254, 'px': 0.0254 / 96, 'pt': 0.0254 / 72, 'pc': 0.0254 / 72 * 12 }, duration: { 's': 1, 'ms': 0.001 }, angle: { 'rad': 1/(2*Math.PI), 'deg': 1/360, 'grad': 1/400, 'turn': 1 } }; tree.Unit = function (numerator, denominator, backupUnit) { this.numerator = numerator ? numerator.slice(0).sort() : []; this.denominator = denominator ? denominator.slice(0).sort() : []; this.backupUnit = backupUnit; }; tree.Unit.prototype = { type: "Unit", clone: function () { return new tree.Unit(this.numerator.slice(0), this.denominator.slice(0), this.backupUnit); }, genCSS: function (env, output) { if (this.numerator.length >= 1) { output.add(this.numerator[0]); } else if (this.denominator.length >= 1) { output.add(this.denominator[0]); } else if ((!env || !env.strictUnits) && this.backupUnit) { output.add(this.backupUnit); } }, toCSS: tree.toCSS, toString: function () { var i, returnStr = this.numerator.join("*"); for (i = 0; i < this.denominator.length; i++) { returnStr += "/" + this.denominator[i]; } return returnStr; }, compare: function (other) { return this.is(other.toString()) ? 0 : -1; }, is: function (unitString) { return this.toString() === unitString; }, isLength: function () { return Boolean(this.toCSS().match(/px|em|%|in|cm|mm|pc|pt|ex/)); }, isEmpty: function () { return this.numerator.length === 0 && this.denominator.length === 0; }, isSingular: function() { return this.numerator.length <= 1 && this.denominator.length === 0; }, map: function(callback) { var i; for (i = 0; i < this.numerator.length; i++) { this.numerator[i] = callback(this.numerator[i], false); } for (i = 0; i < this.denominator.length; i++) { this.denominator[i] = callback(this.denominator[i], true); } }, usedUnits: function() { var group, result = {}, mapUnit; mapUnit = function (atomicUnit) { /*jshint loopfunc:true */ if (group.hasOwnProperty(atomicUnit) && !result[groupName]) { result[groupName] = atomicUnit; } return atomicUnit; }; for (var groupName in tree.UnitConversions) { if (tree.UnitConversions.hasOwnProperty(groupName)) { group = tree.UnitConversions[groupName]; this.map(mapUnit); } } return result; }, cancel: function () { var counter = {}, atomicUnit, i, backup; for (i = 0; i < this.numerator.length; i++) { atomicUnit = this.numerator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) + 1; } for (i = 0; i < this.denominator.length; i++) { atomicUnit = this.denominator[i]; if (!backup) { backup = atomicUnit; } counter[atomicUnit] = (counter[atomicUnit] || 0) - 1; } this.numerator = []; this.denominator = []; for (atomicUnit in counter) { if (counter.hasOwnProperty(atomicUnit)) { var count = counter[atomicUnit]; if (count > 0) { for (i = 0; i < count; i++) { this.numerator.push(atomicUnit); } } else if (count < 0) { for (i = 0; i < -count; i++) { this.denominator.push(atomicUnit); } } } } if (this.numerator.length === 0 && this.denominator.length === 0 && backup) { this.backupUnit = backup; } this.numerator.sort(); this.denominator.sort(); } }; })(require('../tree')); (function (tree) { tree.Directive = function (name, value, rules, index, currentFileInfo, debugInfo) { this.name = name; this.value = value; if (rules) { this.rules = rules; this.rules.allowImports = true; } this.index = index; this.currentFileInfo = currentFileInfo; this.debugInfo = debugInfo; }; tree.Directive.prototype = { type: "Directive", accept: function (visitor) { var value = this.value, rules = this.rules; if (rules) { rules = visitor.visit(rules); } if (value) { value = visitor.visit(value); } }, genCSS: function (env, output) { var value = this.value, rules = this.rules; output.add(this.name, this.currentFileInfo, this.index); if (value) { output.add(' '); value.genCSS(env, output); } if (rules) { tree.outputRuleset(env, output, [rules]); } else { output.add(';'); } }, toCSS: tree.toCSS, eval: function (env) { var value = this.value, rules = this.rules; if (value) { value = value.eval(env); } if (rules) { rules = rules.eval(env); rules.root = true; } return new(tree.Directive)(this.name, value, rules, this.index, this.currentFileInfo, this.debugInfo); }, variable: function (name) { if (this.rules) return tree.Ruleset.prototype.variable.call(this.rules, name); }, find: function () { if (this.rules) return tree.Ruleset.prototype.find.apply(this.rules, arguments); }, rulesets: function () { if (this.rules) return tree.Ruleset.prototype.rulesets.apply(this.rules); }, markReferenced: function () { var i, rules; this.isReferenced = true; if (this.rules) { rules = this.rules.rules; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } } } }; })(require('../tree')); (function (tree) { tree.Element = function (combinator, value, index, currentFileInfo) { this.combinator = combinator instanceof tree.Combinator ? combinator : new(tree.Combinator)(combinator); if (typeof(value) === 'string') { this.value = value.trim(); } else if (value) { this.value = value; } else { this.value = ""; } this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Element.prototype = { type: "Element", accept: function (visitor) { var value = this.value; this.combinator = visitor.visit(this.combinator); if (typeof value === "object") { this.value = visitor.visit(value); } }, eval: function (env) { return new(tree.Element)(this.combinator, this.value.eval ? this.value.eval(env) : this.value, this.index, this.currentFileInfo); }, genCSS: function (env, output) { output.add(this.toCSS(env), this.currentFileInfo, this.index); }, toCSS: function (env) { var value = (this.value.toCSS ? this.value.toCSS(env) : this.value); if (value === '' && this.combinator.value.charAt(0) === '&') { return ''; } else { return this.combinator.toCSS(env || {}) + value; } } }; tree.Attribute = function (key, op, value) { this.key = key; this.op = op; this.value = value; }; tree.Attribute.prototype = { type: "Attribute", eval: function (env) { return new(tree.Attribute)(this.key.eval ? this.key.eval(env) : this.key, this.op, (this.value && this.value.eval) ? this.value.eval(env) : this.value); }, genCSS: function (env, output) { output.add(this.toCSS(env)); }, toCSS: function (env) { var value = this.key.toCSS ? this.key.toCSS(env) : this.key; if (this.op) { value += this.op; value += (this.value.toCSS ? this.value.toCSS(env) : this.value); } return '[' + value + ']'; } }; tree.Combinator = function (value) { if (value === ' ') { this.value = ' '; } else { this.value = value ? value.trim() : ""; } }; tree.Combinator.prototype = { type: "Combinator", _outputMap: { '' : '', ' ' : ' ', ':' : ' :', '+' : ' + ', '~' : ' ~ ', '>' : ' > ', '|' : '|', '^' : ' ^ ', '^^' : ' ^^ ' }, _outputMapCompressed: { '' : '', ' ' : ' ', ':' : ' :', '+' : '+', '~' : '~', '>' : '>', '|' : '|', '^' : '^', '^^' : '^^' }, genCSS: function (env, output) { output.add((env.compress ? this._outputMapCompressed : this._outputMap)[this.value]); }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Expression = function (value) { this.value = value; }; tree.Expression.prototype = { type: "Expression", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { var returnValue, inParenthesis = this.parens && !this.parensInOp, doubleParen = false; if (inParenthesis) { env.inParenthesis(); } if (this.value.length > 1) { returnValue = new(tree.Expression)(this.value.map(function (e) { return e.eval(env); })); } else if (this.value.length === 1) { if (this.value[0].parens && !this.value[0].parensInOp) { doubleParen = true; } returnValue = this.value[0].eval(env); } else { returnValue = this; } if (inParenthesis) { env.outOfParenthesis(); } if (this.parens && this.parensInOp && !(env.isMathOn()) && !doubleParen) { returnValue = new(tree.Paren)(returnValue); } return returnValue; }, genCSS: function (env, output) { for(var i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i + 1 < this.value.length) { output.add(" "); } } }, toCSS: tree.toCSS, throwAwayComments: function () { this.value = this.value.filter(function(v) { return !(v instanceof tree.Comment); }); } }; })(require('../tree')); (function (tree) { tree.Extend = function Extend(selector, option, index) { this.selector = selector; this.option = option; this.index = index; this.object_id = tree.Extend.next_id++; this.parent_ids = [this.object_id]; switch(option) { case "all": this.allowBefore = true; this.allowAfter = true; break; default: this.allowBefore = false; this.allowAfter = false; break; } }; tree.Extend.next_id = 0; tree.Extend.prototype = { type: "Extend", accept: function (visitor) { this.selector = visitor.visit(this.selector); }, eval: function (env) { return new(tree.Extend)(this.selector.eval(env), this.option, this.index); }, clone: function (env) { return new(tree.Extend)(this.selector, this.option, this.index); }, findSelfSelectors: function (selectors) { var selfElements = [], i, selectorElements; for(i = 0; i < selectors.length; i++) { selectorElements = selectors[i].elements; // duplicate the logic in genCSS function inside the selector node. // future TODO - move both logics into the selector joiner visitor if (i > 0 && selectorElements.length && selectorElements[0].combinator.value === "") { selectorElements[0].combinator.value = ' '; } selfElements = selfElements.concat(selectors[i].elements); } this.selfSelectors = [{ elements: selfElements }]; } }; })(require('../tree')); (function (tree) { // // CSS @import node // // The general strategy here is that we don't want to wait // for the parsing to be completed, before we start importing // the file. That's because in the context of a browser, // most of the time will be spent waiting for the server to respond. // // On creation, we push the import path to our import queue, though // `import,push`, we also pass it a callback, which it'll call once // the file has been fetched, and parsed. // tree.Import = function (path, features, options, index, currentFileInfo) { this.options = options; this.index = index; this.path = path; this.features = features; this.currentFileInfo = currentFileInfo; if (this.options.less !== undefined || this.options.inline) { this.css = !this.options.less || this.options.inline; } else { var pathValue = this.getPath(); if (pathValue && /css([\?;].*)?$/.test(pathValue)) { this.css = true; } } }; // // The actual import node doesn't return anything, when converted to CSS. // The reason is that it's used at the evaluation stage, so that the rules // it imports can be treated like any other rules. // // In `eval`, we make sure all Import nodes get evaluated, recursively, so // we end up with a flat structure, which can easily be imported in the parent // ruleset. // tree.Import.prototype = { type: "Import", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } this.path = visitor.visit(this.path); if (!this.options.inline && this.root) { this.root = visitor.visit(this.root); } }, genCSS: function (env, output) { if (this.css) { output.add("@import ", this.currentFileInfo, this.index); this.path.genCSS(env, output); if (this.features) { output.add(" "); this.features.genCSS(env, output); } output.add(';'); } }, toCSS: tree.toCSS, getPath: function () { if (this.path instanceof tree.Quoted) { var path = this.path.value; return (this.css !== undefined || /(\.[a-z]*$)|([\?;].*)$/.test(path)) ? path : path + '.less'; } else if (this.path instanceof tree.URL) { return this.path.value.value; } return null; }, evalForImport: function (env) { return new(tree.Import)(this.path.eval(env), this.features, this.options, this.index, this.currentFileInfo); }, evalPath: function (env) { var path = this.path.eval(env); var rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (!(path instanceof tree.URL)) { if (rootpath) { var pathValue = path.value; // Add the base path if the import is relative if (pathValue && env.isPathRelative(pathValue)) { path.value = rootpath +pathValue; } } path.value = env.normalizePath(path.value); } return path; }, eval: function (env) { var ruleset, features = this.features && this.features.eval(env); if (this.skip) { if (typeof this.skip === "function") { this.skip = this.skip(); } if (this.skip) { return []; } } if (this.options.inline) { //todo needs to reference css file not import var contents = new(tree.Anonymous)(this.root, 0, {filename: this.importedFilename}, true); return this.features ? new(tree.Media)([contents], this.features.value) : [contents]; } else if (this.css) { var newImport = new(tree.Import)(this.evalPath(env), features, this.options, this.index); if (!newImport.css && this.error) { throw this.error; } return newImport; } else { ruleset = new(tree.Ruleset)(null, this.root.rules.slice(0)); ruleset.evalImports(env); return this.features ? new(tree.Media)(ruleset.rules, this.features.value) : ruleset.rules; } } }; })(require('../tree')); (function (tree) { tree.JavaScript = function (string, index, escaped) { this.escaped = escaped; this.expression = string; this.index = index; }; tree.JavaScript.prototype = { type: "JavaScript", eval: function (env) { var result, that = this, context = {}; var expression = this.expression.replace(/@\{([\w-]+)\}/g, function (_, name) { return tree.jsify(new(tree.Variable)('@' + name, that.index).eval(env)); }); try { expression = new(Function)('return (' + expression + ')'); } catch (e) { throw { message: "JavaScript evaluation error: " + e.message + " from `" + expression + "`" , index: this.index }; } var variables = env.frames[0].variables(); for (var k in variables) { if (variables.hasOwnProperty(k)) { /*jshint loopfunc:true */ context[k.slice(1)] = { value: variables[k].value, toJS: function () { return this.value.eval(env).toCSS(); } }; } } try { result = expression.call(context); } catch (e) { throw { message: "JavaScript evaluation error: '" + e.name + ': ' + e.message.replace(/["]/g, "'") + "'" , index: this.index }; } if (typeof(result) === 'number') { return new(tree.Dimension)(result); } else if (typeof(result) === 'string') { return new(tree.Quoted)('"' + result + '"', result, this.escaped, this.index); } else if (Array.isArray(result)) { return new(tree.Anonymous)(result.join(', ')); } else { return new(tree.Anonymous)(result); } } }; })(require('../tree')); (function (tree) { tree.Keyword = function (value) { this.value = value; }; tree.Keyword.prototype = { type: "Keyword", eval: function () { return this; }, genCSS: function (env, output) { if (this.value === '%') { throw { type: "Syntax", message: "Invalid % without number" }; } output.add(this.value); }, toCSS: tree.toCSS, compare: function (other) { if (other instanceof tree.Keyword) { return other.value === this.value ? 0 : 1; } else { return -1; } } }; tree.True = new(tree.Keyword)('true'); tree.False = new(tree.Keyword)('false'); })(require('../tree')); (function (tree) { tree.Media = function (value, features, index, currentFileInfo) { this.index = index; this.currentFileInfo = currentFileInfo; var selectors = this.emptySelectors(); this.features = new(tree.Value)(features); this.rules = [new(tree.Ruleset)(selectors, value)]; this.rules[0].allowImports = true; }; tree.Media.prototype = { type: "Media", accept: function (visitor) { if (this.features) { this.features = visitor.visit(this.features); } if (this.rules) { this.rules = visitor.visitArray(this.rules); } }, genCSS: function (env, output) { output.add('@media ', this.currentFileInfo, this.index); this.features.genCSS(env, output); tree.outputRuleset(env, output, this.rules); }, toCSS: tree.toCSS, eval: function (env) { if (!env.mediaBlocks) { env.mediaBlocks = []; env.mediaPath = []; } var media = new(tree.Media)(null, [], this.index, this.currentFileInfo); if(this.debugInfo) { this.rules[0].debugInfo = this.debugInfo; media.debugInfo = this.debugInfo; } var strictMathBypass = false; if (!env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { media.features = this.features.eval(env); } finally { if (strictMathBypass) { env.strictMath = false; } } env.mediaPath.push(media); env.mediaBlocks.push(media); env.frames.unshift(this.rules[0]); media.rules = [this.rules[0].eval(env)]; env.frames.shift(); env.mediaPath.pop(); return env.mediaPath.length === 0 ? media.evalTop(env) : media.evalNested(env); }, variable: function (name) { return tree.Ruleset.prototype.variable.call(this.rules[0], name); }, find: function () { return tree.Ruleset.prototype.find.apply(this.rules[0], arguments); }, rulesets: function () { return tree.Ruleset.prototype.rulesets.apply(this.rules[0]); }, emptySelectors: function() { var el = new(tree.Element)('', '&', this.index, this.currentFileInfo), sels = [new(tree.Selector)([el], null, null, this.index, this.currentFileInfo)]; sels[0].mediaEmpty = true; return sels; }, markReferenced: function () { var i, rules = this.rules[0].rules; this.rules[0].markReferenced(); this.isReferenced = true; for (i = 0; i < rules.length; i++) { if (rules[i].markReferenced) { rules[i].markReferenced(); } } }, evalTop: function (env) { var result = this; // Render all dependent Media blocks. if (env.mediaBlocks.length > 1) { var selectors = this.emptySelectors(); result = new(tree.Ruleset)(selectors, env.mediaBlocks); result.multiMedia = true; } delete env.mediaBlocks; delete env.mediaPath; return result; }, evalNested: function (env) { var i, value, path = env.mediaPath.concat([this]); // Extract the media-query conditions separated with `,` (OR). for (i = 0; i < path.length; i++) { value = path[i].features instanceof tree.Value ? path[i].features.value : path[i].features; path[i] = Array.isArray(value) ? value : [value]; } // Trace all permutations to generate the resulting media-query. // // (a, b and c) with nested (d, e) -> // a and d // a and e // b and c and d // b and c and e this.features = new(tree.Value)(this.permute(path).map(function (path) { path = path.map(function (fragment) { return fragment.toCSS ? fragment : new(tree.Anonymous)(fragment); }); for(i = path.length - 1; i > 0; i--) { path.splice(i, 0, new(tree.Anonymous)("and")); } return new(tree.Expression)(path); })); // Fake a tree-node that doesn't output anything. return new(tree.Ruleset)([], []); }, permute: function (arr) { if (arr.length === 0) { return []; } else if (arr.length === 1) { return arr[0]; } else { var result = []; var rest = this.permute(arr.slice(1)); for (var i = 0; i < rest.length; i++) { for (var j = 0; j < arr[0].length; j++) { result.push([arr[0][j]].concat(rest[i])); } } return result; } }, bubbleSelectors: function (selectors) { if (!selectors) return; this.rules = [new(tree.Ruleset)(selectors.slice(0), [this.rules[0]])]; } }; })(require('../tree')); (function (tree) { tree.mixin = {}; tree.mixin.Call = function (elements, args, index, currentFileInfo, important) { this.selector = new(tree.Selector)(elements); this.arguments = (args && args.length) ? args : null; this.index = index; this.currentFileInfo = currentFileInfo; this.important = important; }; tree.mixin.Call.prototype = { type: "MixinCall", accept: function (visitor) { if (this.selector) { this.selector = visitor.visit(this.selector); } if (this.arguments) { this.arguments = visitor.visitArray(this.arguments); } }, eval: function (env) { var mixins, mixin, args, rules = [], match = false, i, m, f, isRecursive, isOneFound, rule, candidates = [], candidate, conditionResult = [], defaultFunc = tree.defaultFunc, defaultResult, defNone = 0, defTrue = 1, defFalse = 2, count; args = this.arguments && this.arguments.map(function (a) { return { name: a.name, value: a.value.eval(env) }; }); for (i = 0; i < env.frames.length; i++) { if ((mixins = env.frames[i].find(this.selector)).length > 0) { isOneFound = true; // To make `default()` function independent of definition order we have two "subpasses" here. // At first we evaluate each guard *twice* (with `default() == true` and `default() == false`), // and build candidate list with corresponding flags. Then, when we know all possible matches, // we make a final decision. for (m = 0; m < mixins.length; m++) { mixin = mixins[m]; isRecursive = false; for(f = 0; f < env.frames.length; f++) { if ((!(mixin instanceof tree.mixin.Definition)) && mixin === (env.frames[f].originalRuleset || env.frames[f])) { isRecursive = true; break; } } if (isRecursive) { continue; } if (mixin.matchArgs(args, env)) { candidate = {mixin: mixin, group: defNone}; if (mixin.matchCondition) { for (f = 0; f < 2; f++) { defaultFunc.value(f); conditionResult[f] = mixin.matchCondition(args, env); } if (conditionResult[0] || conditionResult[1]) { if (conditionResult[0] != conditionResult[1]) { candidate.group = conditionResult[1] ? defTrue : defFalse; } candidates.push(candidate); } } else { candidates.push(candidate); } match = true; } } defaultFunc.reset(); count = [0, 0, 0]; for (m = 0; m < candidates.length; m++) { count[candidates[m].group]++; } if (count[defNone] > 0) { defaultResult = defFalse; } else { defaultResult = defTrue; if ((count[defTrue] + count[defFalse]) > 1) { throw { type: 'Runtime', message: 'Ambiguous use of `default()` found when matching for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } } for (m = 0; m < candidates.length; m++) { candidate = candidates[m].group; if ((candidate === defNone) || (candidate === defaultResult)) { try { mixin = candidates[m].mixin; if (!(mixin instanceof tree.mixin.Definition)) { mixin = new tree.mixin.Definition("", [], mixin.rules, null, false); mixin.originalRuleset = mixins[m].originalRuleset || mixins[m]; } Array.prototype.push.apply( rules, mixin.evalCall(env, args, this.important).rules); } catch (e) { throw { message: e.message, index: this.index, filename: this.currentFileInfo.filename, stack: e.stack }; } } } if (match) { if (!this.currentFileInfo || !this.currentFileInfo.reference) { for (i = 0; i < rules.length; i++) { rule = rules[i]; if (rule.markReferenced) { rule.markReferenced(); } } } return rules; } } } if (isOneFound) { throw { type: 'Runtime', message: 'No matching definition was found for `' + this.format(args) + '`', index: this.index, filename: this.currentFileInfo.filename }; } else { throw { type: 'Name', message: this.selector.toCSS().trim() + " is undefined", index: this.index, filename: this.currentFileInfo.filename }; } }, format: function (args) { return this.selector.toCSS().trim() + '(' + (args ? args.map(function (a) { var argValue = ""; if (a.name) { argValue += a.name + ":"; } if (a.value.toCSS) { argValue += a.value.toCSS(); } else { argValue += "???"; } return argValue; }).join(', ') : "") + ")"; } }; tree.mixin.Definition = function (name, params, rules, condition, variadic, frames) { this.name = name; this.selectors = [new(tree.Selector)([new(tree.Element)(null, name, this.index, this.currentFileInfo)])]; this.params = params; this.condition = condition; this.variadic = variadic; this.arity = params.length; this.rules = rules; this._lookups = {}; this.required = params.reduce(function (count, p) { if (!p.name || (p.name && !p.value)) { return count + 1; } else { return count; } }, 0); this.parent = tree.Ruleset.prototype; this.frames = frames; }; tree.mixin.Definition.prototype = { type: "MixinDefinition", accept: function (visitor) { if (this.params && this.params.length) { this.params = visitor.visitArray(this.params); } this.rules = visitor.visitArray(this.rules); if (this.condition) { this.condition = visitor.visit(this.condition); } }, variable: function (name) { return this.parent.variable.call(this, name); }, variables: function () { return this.parent.variables.call(this); }, find: function () { return this.parent.find.apply(this, arguments); }, rulesets: function () { return this.parent.rulesets.apply(this); }, evalParams: function (env, mixinEnv, args, evaldArguments) { /*jshint boss:true */ var frame = new(tree.Ruleset)(null, null), varargs, arg, params = this.params.slice(0), i, j, val, name, isNamedFound, argIndex, argsLength = 0; mixinEnv = new tree.evalEnv(mixinEnv, [frame].concat(mixinEnv.frames)); if (args) { args = args.slice(0); argsLength = args.length; for(i = 0; i < argsLength; i++) { arg = args[i]; if (name = (arg && arg.name)) { isNamedFound = false; for(j = 0; j < params.length; j++) { if (!evaldArguments[j] && name === params[j].name) { evaldArguments[j] = arg.value.eval(env); frame.prependRule(new(tree.Rule)(name, arg.value.eval(env))); isNamedFound = true; break; } } if (isNamedFound) { args.splice(i, 1); i--; continue; } else { throw { type: 'Runtime', message: "Named argument for " + this.name + ' ' + args[i].name + ' not found' }; } } } } argIndex = 0; for (i = 0; i < params.length; i++) { if (evaldArguments[i]) { continue; } arg = args && args[argIndex]; if (name = params[i].name) { if (params[i].variadic) { varargs = []; for (j = argIndex; j < argsLength; j++) { varargs.push(args[j].value.eval(env)); } frame.prependRule(new(tree.Rule)(name, new(tree.Expression)(varargs).eval(env))); } else { val = arg && arg.value; if (val) { val = val.eval(env); } else if (params[i].value) { val = params[i].value.eval(mixinEnv); frame.resetCache(); } else { throw { type: 'Runtime', message: "wrong number of arguments for " + this.name + ' (' + argsLength + ' for ' + this.arity + ')' }; } frame.prependRule(new(tree.Rule)(name, val)); evaldArguments[i] = val; } } if (params[i].variadic && args) { for (j = argIndex; j < argsLength; j++) { evaldArguments[j] = args[j].value.eval(env); } } argIndex++; } return frame; }, eval: function (env) { return new tree.mixin.Definition(this.name, this.params, this.rules, this.condition, this.variadic, this.frames || env.frames.slice(0)); }, evalCall: function (env, args, important) { var _arguments = [], mixinFrames = this.frames ? this.frames.concat(env.frames) : env.frames, frame = this.evalParams(env, new(tree.evalEnv)(env, mixinFrames), args, _arguments), rules, ruleset; frame.prependRule(new(tree.Rule)('@arguments', new(tree.Expression)(_arguments).eval(env))); rules = this.rules.slice(0); ruleset = new(tree.Ruleset)(null, rules); ruleset.originalRuleset = this; ruleset = ruleset.eval(new(tree.evalEnv)(env, [this, frame].concat(mixinFrames))); if (important) { ruleset = this.parent.makeImportant.apply(ruleset); } return ruleset; }, matchCondition: function (args, env) { if (this.condition && !this.condition.eval( new(tree.evalEnv)(env, [this.evalParams(env, new(tree.evalEnv)(env, this.frames.concat(env.frames)), args, [])] // the parameter variables .concat(this.frames) // the parent namespace/mixin frames .concat(env.frames)))) { // the current environment frames return false; } return true; }, matchArgs: function (args, env) { var argsLength = (args && args.length) || 0, len; if (! this.variadic) { if (argsLength < this.required) { return false; } if (argsLength > this.params.length) { return false; } } else { if (argsLength < (this.required - 1)) { return false; } } len = Math.min(argsLength, this.arity); for (var i = 0; i < len; i++) { if (!this.params[i].name && !this.params[i].variadic) { if (args[i].value.eval(env).toCSS() != this.params[i].value.eval(env).toCSS()) { return false; } } } return true; } }; })(require('../tree')); (function (tree) { tree.Negative = function (node) { this.value = node; }; tree.Negative.prototype = { type: "Negative", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('-'); this.value.genCSS(env, output); }, toCSS: tree.toCSS, eval: function (env) { if (env.isMathOn()) { return (new(tree.Operation)('*', [new(tree.Dimension)(-1), this.value])).eval(env); } return new(tree.Negative)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Operation = function (op, operands, isSpaced) { this.op = op.trim(); this.operands = operands; this.isSpaced = isSpaced; }; tree.Operation.prototype = { type: "Operation", accept: function (visitor) { this.operands = visitor.visit(this.operands); }, eval: function (env) { var a = this.operands[0].eval(env), b = this.operands[1].eval(env); if (env.isMathOn()) { if (a instanceof tree.Dimension && b instanceof tree.Color) { a = a.toColor(); } if (b instanceof tree.Dimension && a instanceof tree.Color) { b = b.toColor(); } if (!a.operate) { throw { type: "Operation", message: "Operation on an invalid type" }; } return a.operate(env, this.op, b); } else { return new(tree.Operation)(this.op, [a, b], this.isSpaced); } }, genCSS: function (env, output) { this.operands[0].genCSS(env, output); if (this.isSpaced) { output.add(" "); } output.add(this.op); if (this.isSpaced) { output.add(" "); } this.operands[1].genCSS(env, output); }, toCSS: tree.toCSS }; tree.operate = function (env, op, a, b) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } }; })(require('../tree')); (function (tree) { tree.Paren = function (node) { this.value = node; }; tree.Paren.prototype = { type: "Paren", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add('('); this.value.genCSS(env, output); output.add(')'); }, toCSS: tree.toCSS, eval: function (env) { return new(tree.Paren)(this.value.eval(env)); } }; })(require('../tree')); (function (tree) { tree.Quoted = function (str, content, escaped, index, currentFileInfo) { this.escaped = escaped; this.value = content || ''; this.quote = str.charAt(0); this.index = index; this.currentFileInfo = currentFileInfo; }; tree.Quoted.prototype = { type: "Quoted", genCSS: function (env, output) { if (!this.escaped) { output.add(this.quote, this.currentFileInfo, this.index); } output.add(this.value); if (!this.escaped) { output.add(this.quote); } }, toCSS: tree.toCSS, eval: function (env) { var that = this; var value = this.value.replace(/`([^`]+)`/g, function (_, exp) { return new(tree.JavaScript)(exp, that.index, true).eval(env).value; }).replace(/@\{([\w-]+)\}/g, function (_, name) { var v = new(tree.Variable)('@' + name, that.index, that.currentFileInfo).eval(env, true); return (v instanceof tree.Quoted) ? v.value : v.toCSS(); }); return new(tree.Quoted)(this.quote + value + this.quote, value, this.escaped, this.index, this.currentFileInfo); }, compare: function (x) { if (!x.toCSS) { return -1; } var left = this.toCSS(), right = x.toCSS(); if (left === right) { return 0; } return left < right ? -1 : 1; } }; })(require('../tree')); (function (tree) { tree.Rule = function (name, value, important, merge, index, currentFileInfo, inline) { this.name = name; this.value = (value instanceof tree.Value || value instanceof tree.Ruleset) ? value : new(tree.Value)([value]); this.important = important ? ' ' + important.trim() : ''; this.merge = merge; this.index = index; this.currentFileInfo = currentFileInfo; this.inline = inline || false; this.variable = name.charAt && (name.charAt(0) === '@'); }; tree.Rule.prototype = { type: "Rule", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add(this.name + (env.compress ? ':' : ': '), this.currentFileInfo, this.index); try { this.value.genCSS(env, output); } catch(e) { e.index = this.index; e.filename = this.currentFileInfo.filename; throw e; } output.add(this.important + ((this.inline || (env.lastRule && env.compress)) ? "" : ";"), this.currentFileInfo, this.index); }, toCSS: tree.toCSS, eval: function (env) { var strictMathBypass = false, name = this.name, evaldValue; if (typeof name !== "string") { // expand 'primitive' name directly to get // things faster (~10% for benchmark.less): name = (name.length === 1) && (name[0] instanceof tree.Keyword) ? name[0].value : evalName(env, name); } if (name === "font" && !env.strictMath) { strictMathBypass = true; env.strictMath = true; } try { evaldValue = this.value.eval(env); if (!this.variable && evaldValue.type === "DetachedRuleset") { throw { message: "Rulesets cannot be evaluated on a property.", index: this.index, filename: this.currentFileInfo.filename }; } return new(tree.Rule)(name, evaldValue, this.important, this.merge, this.index, this.currentFileInfo, this.inline); } catch(e) { if (typeof e.index !== 'number') { e.index = this.index; e.filename = this.currentFileInfo.filename; } throw e; } finally { if (strictMathBypass) { env.strictMath = false; } } }, makeImportant: function () { return new(tree.Rule)(this.name, this.value, "!important", this.merge, this.index, this.currentFileInfo, this.inline); } }; function evalName(env, name) { var value = "", i, n = name.length, output = {add: function (s) {value += s;}}; for (i = 0; i < n; i++) { name[i].eval(env).genCSS(env, output); } return value; } })(require('../tree')); (function (tree) { tree.RulesetCall = function (variable) { this.variable = variable; }; tree.RulesetCall.prototype = { type: "RulesetCall", accept: function (visitor) { }, eval: function (env) { var detachedRuleset = new(tree.Variable)(this.variable).eval(env); return detachedRuleset.callEval(env); } }; })(require('../tree')); (function (tree) { tree.Ruleset = function (selectors, rules, strictImports) { this.selectors = selectors; this.rules = rules; this._lookups = {}; this.strictImports = strictImports; }; tree.Ruleset.prototype = { type: "Ruleset", accept: function (visitor) { if (this.paths) { visitor.visitArray(this.paths, true); } else if (this.selectors) { this.selectors = visitor.visitArray(this.selectors); } if (this.rules && this.rules.length) { this.rules = visitor.visitArray(this.rules); } }, eval: function (env) { var thisSelectors = this.selectors, selectors, selCnt, selector, i, defaultFunc = tree.defaultFunc, hasOnePassingSelector = false; if (thisSelectors && (selCnt = thisSelectors.length)) { selectors = []; defaultFunc.error({ type: "Syntax", message: "it is currently only allowed in parametric mixin guards," }); for (i = 0; i < selCnt; i++) { selector = thisSelectors[i].eval(env); selectors.push(selector); if (selector.evaldCondition) { hasOnePassingSelector = true; } } defaultFunc.reset(); } else { hasOnePassingSelector = true; } var rules = this.rules ? this.rules.slice(0) : null, ruleset = new(tree.Ruleset)(selectors, rules, this.strictImports), rule, subRule; ruleset.originalRuleset = this; ruleset.root = this.root; ruleset.firstRoot = this.firstRoot; ruleset.allowImports = this.allowImports; if(this.debugInfo) { ruleset.debugInfo = this.debugInfo; } if (!hasOnePassingSelector) { rules.length = 0; } // push the current ruleset to the frames stack var envFrames = env.frames; envFrames.unshift(ruleset); // currrent selectors var envSelectors = env.selectors; if (!envSelectors) { env.selectors = envSelectors = []; } envSelectors.unshift(this.selectors); // Evaluate imports if (ruleset.root || ruleset.allowImports || !ruleset.strictImports) { ruleset.evalImports(env); } // Store the frames around mixin definitions, // so they can be evaluated like closures when the time comes. var rsRules = ruleset.rules, rsRuleCnt = rsRules ? rsRules.length : 0; for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Definition || rsRules[i] instanceof tree.DetachedRuleset) { rsRules[i] = rsRules[i].eval(env); } } var mediaBlockCount = (env.mediaBlocks && env.mediaBlocks.length) || 0; // Evaluate mixin calls. for (i = 0; i < rsRuleCnt; i++) { if (rsRules[i] instanceof tree.mixin.Call) { /*jshint loopfunc:true */ rules = rsRules[i].eval(env).filter(function(r) { if ((r instanceof tree.Rule) && r.variable) { // do not pollute the scope if the variable is // already there. consider returning false here // but we need a way to "return" variable from mixins return !(ruleset.variable(r.name)); } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); rsRuleCnt += rules.length - 1; i += rules.length-1; ruleset.resetCache(); } else if (rsRules[i] instanceof tree.RulesetCall) { /*jshint loopfunc:true */ rules = rsRules[i].eval(env).rules.filter(function(r) { if ((r instanceof tree.Rule) && r.variable) { // do not pollute the scope at all return false; } return true; }); rsRules.splice.apply(rsRules, [i, 1].concat(rules)); rsRuleCnt += rules.length - 1; i += rules.length-1; ruleset.resetCache(); } } // Evaluate everything else for (i = 0; i < rsRules.length; i++) { rule = rsRules[i]; if (! (rule instanceof tree.mixin.Definition || rule instanceof tree.DetachedRuleset)) { rsRules[i] = rule = rule.eval ? rule.eval(env) : rule; } } // Evaluate everything else for (i = 0; i < rsRules.length; i++) { rule = rsRules[i]; // for rulesets, check if it is a css guard and can be removed if (rule instanceof tree.Ruleset && rule.selectors && rule.selectors.length === 1) { // check if it can be folded in (e.g. & where) if (rule.selectors[0].isJustParentSelector()) { rsRules.splice(i--, 1); for(var j = 0; j < rule.rules.length; j++) { subRule = rule.rules[j]; if (!(subRule instanceof tree.Rule) || !subRule.variable) { rsRules.splice(++i, 0, subRule); } } } } } // Pop the stack envFrames.shift(); envSelectors.shift(); if (env.mediaBlocks) { for (i = mediaBlockCount; i < env.mediaBlocks.length; i++) { env.mediaBlocks[i].bubbleSelectors(selectors); } } return ruleset; }, evalImports: function(env) { var rules = this.rules, i, importRules; if (!rules) { return; } for (i = 0; i < rules.length; i++) { if (rules[i] instanceof tree.Import) { importRules = rules[i].eval(env); if (importRules && importRules.length) { rules.splice.apply(rules, [i, 1].concat(importRules)); i+= importRules.length-1; } else { rules.splice(i, 1, importRules); } this.resetCache(); } } }, makeImportant: function() { return new tree.Ruleset(this.selectors, this.rules.map(function (r) { if (r.makeImportant) { return r.makeImportant(); } else { return r; } }), this.strictImports); }, matchArgs: function (args) { return !args || args.length === 0; }, // lets you call a css selector with a guard matchCondition: function (args, env) { var lastSelector = this.selectors[this.selectors.length-1]; if (!lastSelector.evaldCondition) { return false; } if (lastSelector.condition && !lastSelector.condition.eval( new(tree.evalEnv)(env, env.frames))) { return false; } return true; }, resetCache: function () { this._rulesets = null; this._variables = null; this._lookups = {}; }, variables: function () { if (!this._variables) { this._variables = !this.rules ? {} : this.rules.reduce(function (hash, r) { if (r instanceof tree.Rule && r.variable === true) { hash[r.name] = r; } return hash; }, {}); } return this._variables; }, variable: function (name) { return this.variables()[name]; }, rulesets: function () { if (!this.rules) { return null; } var _Ruleset = tree.Ruleset, _MixinDefinition = tree.mixin.Definition, filtRules = [], rules = this.rules, cnt = rules.length, i, rule; for (i = 0; i < cnt; i++) { rule = rules[i]; if ((rule instanceof _Ruleset) || (rule instanceof _MixinDefinition)) { filtRules.push(rule); } } return filtRules; }, prependRule: function (rule) { var rules = this.rules; if (rules) { rules.unshift(rule); } else { this.rules = [ rule ]; } }, find: function (selector, self) { self = self || this; var rules = [], match, key = selector.toCSS(); if (key in this._lookups) { return this._lookups[key]; } this.rulesets().forEach(function (rule) { if (rule !== self) { for (var j = 0; j < rule.selectors.length; j++) { match = selector.match(rule.selectors[j]); if (match) { if (selector.elements.length > match) { Array.prototype.push.apply(rules, rule.find( new(tree.Selector)(selector.elements.slice(match)), self)); } else { rules.push(rule); } break; } } } }); this._lookups[key] = rules; return rules; }, genCSS: function (env, output) { var i, j, ruleNodes = [], rulesetNodes = [], rulesetNodeCnt, debugInfo, // Line number debugging rule, path; env.tabLevel = (env.tabLevel || 0); if (!this.root) { env.tabLevel++; } var tabRuleStr = env.compress ? '' : Array(env.tabLevel + 1).join(" "), tabSetStr = env.compress ? '' : Array(env.tabLevel).join(" "), sep; for (i = 0; i < this.rules.length; i++) { rule = this.rules[i]; if (rule.rules || (rule instanceof tree.Media) || rule instanceof tree.Directive || (this.root && rule instanceof tree.Comment)) { rulesetNodes.push(rule); } else { ruleNodes.push(rule); } } // If this is the root node, we don't render // a selector, or {}. if (!this.root) { debugInfo = tree.debugInfo(env, this, tabSetStr); if (debugInfo) { output.add(debugInfo); output.add(tabSetStr); } var paths = this.paths, pathCnt = paths.length, pathSubCnt; sep = env.compress ? ',' : (',\n' + tabSetStr); for (i = 0; i < pathCnt; i++) { path = paths[i]; if (!(pathSubCnt = path.length)) { continue; } if (i > 0) { output.add(sep); } env.firstSelector = true; path[0].genCSS(env, output); env.firstSelector = false; for (j = 1; j < pathSubCnt; j++) { path[j].genCSS(env, output); } } output.add((env.compress ? '{' : ' {\n') + tabRuleStr); } // Compile rules and rulesets for (i = 0; i < ruleNodes.length; i++) { rule = ruleNodes[i]; // @page{ directive ends up with root elements inside it, a mix of rules and rulesets // In this instance we do not know whether it is the last property if (i + 1 === ruleNodes.length && (!this.root || rulesetNodes.length === 0 || this.firstRoot)) { env.lastRule = true; } if (rule.genCSS) { rule.genCSS(env, output); } else if (rule.value) { output.add(rule.value.toString()); } if (!env.lastRule) { output.add(env.compress ? '' : ('\n' + tabRuleStr)); } else { env.lastRule = false; } } if (!this.root) { output.add((env.compress ? '}' : '\n' + tabSetStr + '}')); env.tabLevel--; } sep = (env.compress ? "" : "\n") + (this.root ? tabRuleStr : tabSetStr); rulesetNodeCnt = rulesetNodes.length; if (rulesetNodeCnt) { if (ruleNodes.length && sep) { output.add(sep); } rulesetNodes[0].genCSS(env, output); for (i = 1; i < rulesetNodeCnt; i++) { if (sep) { output.add(sep); } rulesetNodes[i].genCSS(env, output); } } if (!output.isEmpty() && !env.compress && this.firstRoot) { output.add('\n'); } }, toCSS: tree.toCSS, markReferenced: function () { if (!this.selectors) { return; } for (var s = 0; s < this.selectors.length; s++) { this.selectors[s].markReferenced(); } }, joinSelectors: function (paths, context, selectors) { for (var s = 0; s < selectors.length; s++) { this.joinSelector(paths, context, selectors[s]); } }, joinSelector: function (paths, context, selector) { var i, j, k, hasParentSelector, newSelectors, el, sel, parentSel, newSelectorPath, afterParentJoin, newJoinedSelector, newJoinedSelectorEmpty, lastSelector, currentElements, selectorsMultiplied; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; if (el.value === '&') { hasParentSelector = true; } } if (!hasParentSelector) { if (context.length > 0) { for (i = 0; i < context.length; i++) { paths.push(context[i].concat(selector)); } } else { paths.push([selector]); } return; } // The paths are [[Selector]] // The first list is a list of comma seperated selectors // The inner list is a list of inheritance seperated selectors // e.g. // .a, .b { // .c { // } // } // == [[.a] [.c]] [[.b] [.c]] // // the elements from the current selector so far currentElements = []; // the current list of new selectors to add to the path. // We will build it up. We initiate it with one empty selector as we "multiply" the new selectors // by the parents newSelectors = [[]]; for (i = 0; i < selector.elements.length; i++) { el = selector.elements[i]; // non parent reference elements just get added if (el.value !== "&") { currentElements.push(el); } else { // the new list of selectors to add selectorsMultiplied = []; // merge the current list of non parent selector elements // on to the current list of selectors to add if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } // loop through our current selectors for (j = 0; j < newSelectors.length; j++) { sel = newSelectors[j]; // if we don't have any parent paths, the & might be in a mixin so that it can be used // whether there are parents or not if (context.length === 0) { // the combinator used on el should now be applied to the next element instead so that // it is not lost if (sel.length > 0) { sel[0].elements = sel[0].elements.slice(0); sel[0].elements.push(new(tree.Element)(el.combinator, '', el.index, el.currentFileInfo)); } selectorsMultiplied.push(sel); } else { // and the parent selectors for (k = 0; k < context.length; k++) { parentSel = context[k]; // We need to put the current selectors // then join the last selector's elements on to the parents selectors // our new selector path newSelectorPath = []; // selectors from the parent after the join afterParentJoin = []; newJoinedSelectorEmpty = true; //construct the joined selector - if & is the first thing this will be empty, // if not newJoinedSelector will be the last set of elements in the selector if (sel.length > 0) { newSelectorPath = sel.slice(0); lastSelector = newSelectorPath.pop(); newJoinedSelector = selector.createDerived(lastSelector.elements.slice(0)); newJoinedSelectorEmpty = false; } else { newJoinedSelector = selector.createDerived([]); } //put together the parent selectors after the join if (parentSel.length > 1) { afterParentJoin = afterParentJoin.concat(parentSel.slice(1)); } if (parentSel.length > 0) { newJoinedSelectorEmpty = false; // join the elements so far with the first part of the parent newJoinedSelector.elements.push(new(tree.Element)(el.combinator, parentSel[0].elements[0].value, el.index, el.currentFileInfo)); newJoinedSelector.elements = newJoinedSelector.elements.concat(parentSel[0].elements.slice(1)); } if (!newJoinedSelectorEmpty) { // now add the joined selector newSelectorPath.push(newJoinedSelector); } // and the rest of the parent newSelectorPath = newSelectorPath.concat(afterParentJoin); // add that to our new set of selectors selectorsMultiplied.push(newSelectorPath); } } } // our new selectors has been multiplied, so reset the state newSelectors = selectorsMultiplied; currentElements = []; } } // if we have any elements left over (e.g. .a& .b == .b) // add them on to all the current selectors if (currentElements.length > 0) { this.mergeElementsOnToSelectors(currentElements, newSelectors); } for (i = 0; i < newSelectors.length; i++) { if (newSelectors[i].length > 0) { paths.push(newSelectors[i]); } } }, mergeElementsOnToSelectors: function(elements, selectors) { var i, sel; if (selectors.length === 0) { selectors.push([ new(tree.Selector)(elements) ]); return; } for (i = 0; i < selectors.length; i++) { sel = selectors[i]; // if the previous thing in sel is a parent this needs to join on to it if (sel.length > 0) { sel[sel.length - 1] = sel[sel.length - 1].createDerived(sel[sel.length - 1].elements.concat(elements)); } else { sel.push(new(tree.Selector)(elements)); } } } }; })(require('../tree')); (function (tree) { tree.Selector = function (elements, extendList, condition, index, currentFileInfo, isReferenced) { this.elements = elements; this.extendList = extendList; this.condition = condition; this.currentFileInfo = currentFileInfo || {}; this.isReferenced = isReferenced; if (!condition) { this.evaldCondition = true; } }; tree.Selector.prototype = { type: "Selector", accept: function (visitor) { if (this.elements) { this.elements = visitor.visitArray(this.elements); } if (this.extendList) { this.extendList = visitor.visitArray(this.extendList); } if (this.condition) { this.condition = visitor.visit(this.condition); } }, createDerived: function(elements, extendList, evaldCondition) { evaldCondition = (evaldCondition != null) ? evaldCondition : this.evaldCondition; var newSelector = new(tree.Selector)(elements, extendList || this.extendList, null, this.index, this.currentFileInfo, this.isReferenced); newSelector.evaldCondition = evaldCondition; newSelector.mediaEmpty = this.mediaEmpty; return newSelector; }, match: function (other) { var elements = this.elements, len = elements.length, olen, i; other.CacheElements(); olen = other._elements.length; if (olen === 0 || len < olen) { return 0; } else { for (i = 0; i < olen; i++) { if (elements[i].value !== other._elements[i]) { return 0; } } } return olen; // return number of matched elements }, CacheElements: function(){ var css = '', len, v, i; if( !this._elements ){ len = this.elements.length; for(i = 0; i < len; i++){ v = this.elements[i]; css += v.combinator.value; if( !v.value.value ){ css += v.value; continue; } if( typeof v.value.value !== "string" ){ css = ''; break; } css += v.value.value; } this._elements = css.match(/[,&#\.\w-]([\w-]|(\\.))*/g); if (this._elements) { if (this._elements[0] === "&") { this._elements.shift(); } } else { this._elements = []; } } }, isJustParentSelector: function() { return !this.mediaEmpty && this.elements.length === 1 && this.elements[0].value === '&' && (this.elements[0].combinator.value === ' ' || this.elements[0].combinator.value === ''); }, eval: function (env) { var evaldCondition = this.condition && this.condition.eval(env), elements = this.elements, extendList = this.extendList; elements = elements && elements.map(function (e) { return e.eval(env); }); extendList = extendList && extendList.map(function(extend) { return extend.eval(env); }); return this.createDerived(elements, extendList, evaldCondition); }, genCSS: function (env, output) { var i, element; if ((!env || !env.firstSelector) && this.elements[0].combinator.value === "") { output.add(' ', this.currentFileInfo, this.index); } if (!this._css) { //TODO caching? speed comparison? for(i = 0; i < this.elements.length; i++) { element = this.elements[i]; element.genCSS(env, output); } } }, toCSS: tree.toCSS, markReferenced: function () { this.isReferenced = true; }, getIsReferenced: function() { return !this.currentFileInfo.reference || this.isReferenced; }, getIsOutput: function() { return this.evaldCondition; } }; })(require('../tree')); (function (tree) { tree.UnicodeDescriptor = function (value) { this.value = value; }; tree.UnicodeDescriptor.prototype = { type: "UnicodeDescriptor", genCSS: function (env, output) { output.add(this.value); }, toCSS: tree.toCSS, eval: function () { return this; } }; })(require('../tree')); (function (tree) { tree.URL = function (val, currentFileInfo, isEvald) { this.value = val; this.currentFileInfo = currentFileInfo; this.isEvald = isEvald; }; tree.URL.prototype = { type: "Url", accept: function (visitor) { this.value = visitor.visit(this.value); }, genCSS: function (env, output) { output.add("url("); this.value.genCSS(env, output); output.add(")"); }, toCSS: tree.toCSS, eval: function (ctx) { var val = this.value.eval(ctx), rootpath; if (!this.isEvald) { // Add the base path if the URL is relative rootpath = this.currentFileInfo && this.currentFileInfo.rootpath; if (rootpath && typeof val.value === "string" && ctx.isPathRelative(val.value)) { if (!val.quote) { rootpath = rootpath.replace(/[\(\)'"\s]/g, function(match) { return "\\"+match; }); } val.value = rootpath + val.value; } val.value = ctx.normalizePath(val.value); // Add url args if enabled if (ctx.urlArgs) { if (!val.value.match(/^\s*data:/)) { var delimiter = val.value.indexOf('?') === -1 ? '?' : '&'; var urlArgs = delimiter + ctx.urlArgs; if (val.value.indexOf('#') !== -1) { val.value = val.value.replace('#', urlArgs + '#'); } else { val.value += urlArgs; } } } } return new(tree.URL)(val, this.currentFileInfo, true); } }; })(require('../tree')); (function (tree) { tree.Value = function (value) { this.value = value; }; tree.Value.prototype = { type: "Value", accept: function (visitor) { if (this.value) { this.value = visitor.visitArray(this.value); } }, eval: function (env) { if (this.value.length === 1) { return this.value[0].eval(env); } else { return new(tree.Value)(this.value.map(function (v) { return v.eval(env); })); } }, genCSS: function (env, output) { var i; for(i = 0; i < this.value.length; i++) { this.value[i].genCSS(env, output); if (i+1 < this.value.length) { output.add((env && env.compress) ? ',' : ', '); } } }, toCSS: tree.toCSS }; })(require('../tree')); (function (tree) { tree.Variable = function (name, index, currentFileInfo) { this.name = name; this.index = index; this.currentFileInfo = currentFileInfo || {}; }; tree.Variable.prototype = { type: "Variable", eval: function (env) { var variable, name = this.name; if (name.indexOf('@@') === 0) { name = '@' + new(tree.Variable)(name.slice(1)).eval(env).value; } if (this.evaluating) { throw { type: 'Name', message: "Recursive variable definition for " + name, filename: this.currentFileInfo.file, index: this.index }; } this.evaluating = true; variable = tree.find(env.frames, function (frame) { var v = frame.variable(name); if (v) { return v.value.eval(env); } }); if (variable) { this.evaluating = false; return variable; } else { throw { type: 'Name', message: "variable " + name + " is undefined", filename: this.currentFileInfo.filename, index: this.index }; } } }; })(require('../tree')); (function (tree) { var parseCopyProperties = [ 'paths', // option - unmodified - paths to search for imports on 'optimization', // option - optimization level (for the chunker) 'files', // list of files that have been imported, used for import-once 'contents', // map - filename to contents of all the files 'contentsIgnoredChars', // map - filename to lines at the begining of each file to ignore 'relativeUrls', // option - whether to adjust URL's to be relative 'rootpath', // option - rootpath to append to URL's 'strictImports', // option - 'insecure', // option - whether to allow imports from insecure ssl hosts 'dumpLineNumbers', // option - whether to dump line numbers 'compress', // option - whether to compress 'processImports', // option - whether to process imports. if false then imports will not be imported 'syncImport', // option - whether to import synchronously 'javascriptEnabled',// option - whether JavaScript is enabled. if undefined, defaults to true 'mime', // browser only - mime type for sheet import 'useFileCache', // browser only - whether to use the per file session cache 'currentFileInfo' // information about the current file - for error reporting and importing and making urls relative etc. ]; //currentFileInfo = { // 'relativeUrls' - option - whether to adjust URL's to be relative // 'filename' - full resolved filename of current file // 'rootpath' - path to append to normal URLs for this node // 'currentDirectory' - path to the current file, absolute // 'rootFilename' - filename of the base file // 'entryPath' - absolute path to the entry file // 'reference' - whether the file should not be output and only output parts that are referenced tree.parseEnv = function(options) { copyFromOriginal(options, this, parseCopyProperties); if (!this.contents) { this.contents = {}; } if (!this.contentsIgnoredChars) { this.contentsIgnoredChars = {}; } if (!this.files) { this.files = {}; } if (!this.currentFileInfo) { var filename = (options && options.filename) || "input"; var entryPath = filename.replace(/[^\/\\]*$/, ""); if (options) { options.filename = null; } this.currentFileInfo = { filename: filename, relativeUrls: this.relativeUrls, rootpath: (options && options.rootpath) || "", currentDirectory: entryPath, entryPath: entryPath, rootFilename: filename }; } }; var evalCopyProperties = [ 'silent', // whether to swallow errors and warnings 'verbose', // whether to log more activity 'compress', // whether to compress 'yuicompress', // whether to compress with the outside tool yui compressor 'ieCompat', // whether to enforce IE compatibility (IE8 data-uri) 'strictMath', // whether math has to be within parenthesis 'strictUnits', // whether units need to evaluate correctly 'cleancss', // whether to compress with clean-css 'sourceMap', // whether to output a source map 'importMultiple', // whether we are currently importing multiple copies 'urlArgs' // whether to add args into url tokens ]; tree.evalEnv = function(options, frames) { copyFromOriginal(options, this, evalCopyProperties); this.frames = frames || []; }; tree.evalEnv.prototype.inParenthesis = function () { if (!this.parensStack) { this.parensStack = []; } this.parensStack.push(true); }; tree.evalEnv.prototype.outOfParenthesis = function () { this.parensStack.pop(); }; tree.evalEnv.prototype.isMathOn = function () { return this.strictMath ? (this.parensStack && this.parensStack.length) : true; }; tree.evalEnv.prototype.isPathRelative = function (path) { return !/^(?:[a-z-]+:|\/)/.test(path); }; tree.evalEnv.prototype.normalizePath = function( path ) { var segments = path.split("/").reverse(), segment; path = []; while (segments.length !== 0 ) { segment = segments.pop(); switch( segment ) { case ".": break; case "..": if ((path.length === 0) || (path[path.length - 1] === "..")) { path.push( segment ); } else { path.pop(); } break; default: path.push( segment ); break; } } return path.join("/"); }; //todo - do the same for the toCSS env //tree.toCSSEnv = function (options) { //}; var copyFromOriginal = function(original, destination, propertiesToCopy) { if (!original) { return; } for(var i = 0; i < propertiesToCopy.length; i++) { if (original.hasOwnProperty(propertiesToCopy[i])) { destination[propertiesToCopy[i]] = original[propertiesToCopy[i]]; } } }; })(require('./tree')); (function (tree) { var _visitArgs = { visitDeeper: true }, _hasIndexed = false; function _noop(node) { return node; } function indexNodeTypes(parent, ticker) { // add .typeIndex to tree node types for lookup table var key, child; for (key in parent) { if (parent.hasOwnProperty(key)) { child = parent[key]; switch (typeof child) { case "function": // ignore bound functions directly on tree which do not have a prototype // or aren't nodes if (child.prototype && child.prototype.type) { child.prototype.typeIndex = ticker++; } break; case "object": ticker = indexNodeTypes(child, ticker); break; } } } return ticker; } tree.visitor = function(implementation) { this._implementation = implementation; this._visitFnCache = []; if (!_hasIndexed) { indexNodeTypes(tree, 1); _hasIndexed = true; } }; tree.visitor.prototype = { visit: function(node) { if (!node) { return node; } var nodeTypeIndex = node.typeIndex; if (!nodeTypeIndex) { return node; } var visitFnCache = this._visitFnCache, impl = this._implementation, aryIndx = nodeTypeIndex << 1, outAryIndex = aryIndx | 1, func = visitFnCache[aryIndx], funcOut = visitFnCache[outAryIndex], visitArgs = _visitArgs, fnName; visitArgs.visitDeeper = true; if (!func) { fnName = "visit" + node.type; func = impl[fnName] || _noop; funcOut = impl[fnName + "Out"] || _noop; visitFnCache[aryIndx] = func; visitFnCache[outAryIndex] = funcOut; } if (func !== _noop) { var newNode = func.call(impl, node, visitArgs); if (impl.isReplacing) { node = newNode; } } if (visitArgs.visitDeeper && node && node.accept) { node.accept(this); } if (funcOut != _noop) { funcOut.call(impl, node); } return node; }, visitArray: function(nodes, nonReplacing) { if (!nodes) { return nodes; } var cnt = nodes.length, i; // Non-replacing if (nonReplacing || !this._implementation.isReplacing) { for (i = 0; i < cnt; i++) { this.visit(nodes[i]); } return nodes; } // Replacing var out = []; for (i = 0; i < cnt; i++) { var evald = this.visit(nodes[i]); if (!evald.splice) { out.push(evald); } else if (evald.length) { this.flatten(evald, out); } } return out; }, flatten: function(arr, out) { if (!out) { out = []; } var cnt, i, item, nestedCnt, j, nestedItem; for (i = 0, cnt = arr.length; i < cnt; i++) { item = arr[i]; if (!item.splice) { out.push(item); continue; } for (j = 0, nestedCnt = item.length; j < nestedCnt; j++) { nestedItem = item[j]; if (!nestedItem.splice) { out.push(nestedItem); } else if (nestedItem.length) { this.flatten(nestedItem, out); } } } return out; } }; })(require('./tree')); (function (tree) { tree.importVisitor = function(importer, finish, evalEnv, onceFileDetectionMap, recursionDetector) { this._visitor = new tree.visitor(this); this._importer = importer; this._finish = finish; this.env = evalEnv || new tree.evalEnv(); this.importCount = 0; this.onceFileDetectionMap = onceFileDetectionMap || {}; this.recursionDetector = {}; if (recursionDetector) { for(var fullFilename in recursionDetector) { if (recursionDetector.hasOwnProperty(fullFilename)) { this.recursionDetector[fullFilename] = true; } } } }; tree.importVisitor.prototype = { isReplacing: true, run: function (root) { var error; try { // process the contents this._visitor.visit(root); } catch(e) { error = e; } this.isFinished = true; if (this.importCount === 0) { this._finish(error); } }, visitImport: function (importNode, visitArgs) { var importVisitor = this, evaldImportNode, inlineCSS = importNode.options.inline; if (!importNode.css || inlineCSS) { try { evaldImportNode = importNode.evalForImport(this.env); } catch(e){ if (!e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } // attempt to eval properly and treat as css importNode.css = true; // if that fails, this error will be thrown importNode.error = e; } if (evaldImportNode && (!evaldImportNode.css || inlineCSS)) { importNode = evaldImportNode; this.importCount++; var env = new tree.evalEnv(this.env, this.env.frames.slice(0)); if (importNode.options.multiple) { env.importMultiple = true; } this._importer.push(importNode.getPath(), importNode.currentFileInfo, importNode.options, function (e, root, importedAtRoot, fullPath) { if (e && !e.filename) { e.index = importNode.index; e.filename = importNode.currentFileInfo.filename; } if (!env.importMultiple) { if (importedAtRoot) { importNode.skip = true; } else { importNode.skip = function() { if (fullPath in importVisitor.onceFileDetectionMap) { return true; } importVisitor.onceFileDetectionMap[fullPath] = true; return false; }; } } var subFinish = function(e) { importVisitor.importCount--; if (importVisitor.importCount === 0 && importVisitor.isFinished) { importVisitor._finish(e); } }; if (root) { importNode.root = root; importNode.importedFilename = fullPath; var duplicateImport = importedAtRoot || fullPath in importVisitor.recursionDetector; if (!inlineCSS && (env.importMultiple || !duplicateImport)) { importVisitor.recursionDetector[fullPath] = true; new(tree.importVisitor)(importVisitor._importer, subFinish, env, importVisitor.onceFileDetectionMap, importVisitor.recursionDetector) .run(root); return; } } subFinish(); }); } } visitArgs.visitDeeper = false; return importNode; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; return ruleNode; }, visitDirective: function (directiveNode, visitArgs) { this.env.frames.unshift(directiveNode); return directiveNode; }, visitDirectiveOut: function (directiveNode) { this.env.frames.shift(); }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { this.env.frames.unshift(mixinDefinitionNode); return mixinDefinitionNode; }, visitMixinDefinitionOut: function (mixinDefinitionNode) { this.env.frames.shift(); }, visitRuleset: function (rulesetNode, visitArgs) { this.env.frames.unshift(rulesetNode); return rulesetNode; }, visitRulesetOut: function (rulesetNode) { this.env.frames.shift(); }, visitMedia: function (mediaNode, visitArgs) { this.env.frames.unshift(mediaNode.ruleset); return mediaNode; }, visitMediaOut: function (mediaNode) { this.env.frames.shift(); } }; })(require('./tree')); (function (tree) { tree.joinSelectorVisitor = function() { this.contexts = [[]]; this._visitor = new tree.visitor(this); }; tree.joinSelectorVisitor.prototype = { run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { var context = this.contexts[this.contexts.length - 1], paths = [], selectors; this.contexts.push(paths); if (! rulesetNode.root) { selectors = rulesetNode.selectors; if (selectors) { selectors = selectors.filter(function(selector) { return selector.getIsOutput(); }); rulesetNode.selectors = selectors.length ? selectors : (selectors = null); if (selectors) { rulesetNode.joinSelectors(paths, context, selectors); } } if (!selectors) { rulesetNode.rules = null; } rulesetNode.paths = paths; } }, visitRulesetOut: function (rulesetNode) { this.contexts.length = this.contexts.length - 1; }, visitMedia: function (mediaNode, visitArgs) { var context = this.contexts[this.contexts.length - 1]; mediaNode.rules[0].root = (context.length === 0 || context[0].multiMedia); } }; })(require('./tree')); (function (tree) { tree.toCSSVisitor = function(env) { this._visitor = new tree.visitor(this); this._env = env; }; tree.toCSSVisitor.prototype = { isReplacing: true, run: function (root) { return this._visitor.visit(root); }, visitRule: function (ruleNode, visitArgs) { if (ruleNode.variable) { return []; } return ruleNode; }, visitMixinDefinition: function (mixinNode, visitArgs) { // mixin definitions do not get eval'd - this means they keep state // so we have to clear that state here so it isn't used if toCSS is called twice mixinNode.frames = []; return []; }, visitExtend: function (extendNode, visitArgs) { return []; }, visitComment: function (commentNode, visitArgs) { if (commentNode.isSilent(this._env)) { return []; } return commentNode; }, visitMedia: function(mediaNode, visitArgs) { mediaNode.accept(this._visitor); visitArgs.visitDeeper = false; if (!mediaNode.rules.length) { return []; } return mediaNode; }, visitDirective: function(directiveNode, visitArgs) { if (directiveNode.currentFileInfo.reference && !directiveNode.isReferenced) { return []; } if (directiveNode.name === "@charset") { // Only output the debug info together with subsequent @charset definitions // a comment (or @media statement) before the actual @charset directive would // be considered illegal css as it has to be on the first line if (this.charset) { if (directiveNode.debugInfo) { var comment = new tree.Comment("/* " + directiveNode.toCSS(this._env).replace(/\n/g, "")+" */\n"); comment.debugInfo = directiveNode.debugInfo; return this._visitor.visit(comment); } return []; } this.charset = true; } return directiveNode; }, checkPropertiesInRoot: function(rules) { var ruleNode; for(var i = 0; i < rules.length; i++) { ruleNode = rules[i]; if (ruleNode instanceof tree.Rule && !ruleNode.variable) { throw { message: "properties must be inside selector blocks, they cannot be in the root.", index: ruleNode.index, filename: ruleNode.currentFileInfo ? ruleNode.currentFileInfo.filename : null}; } } }, visitRuleset: function (rulesetNode, visitArgs) { var rule, rulesets = []; if (rulesetNode.firstRoot) { this.checkPropertiesInRoot(rulesetNode.rules); } if (! rulesetNode.root) { if (rulesetNode.paths) { rulesetNode.paths = rulesetNode.paths .filter(function(p) { var i; if (p[0].elements[0].combinator.value === ' ') { p[0].elements[0].combinator = new(tree.Combinator)(''); } for(i = 0; i < p.length; i++) { if (p[i].getIsReferenced() && p[i].getIsOutput()) { return true; } } return false; }); } // Compile rules and rulesets var nodeRules = rulesetNode.rules, nodeRuleCnt = nodeRules ? nodeRules.length : 0; for (var i = 0; i < nodeRuleCnt; ) { rule = nodeRules[i]; if (rule && rule.rules) { // visit because we are moving them out from being a child rulesets.push(this._visitor.visit(rule)); nodeRules.splice(i, 1); nodeRuleCnt--; continue; } i++; } // accept the visitor to remove rules and refactor itself // then we can decide now whether we want it or not if (nodeRuleCnt > 0) { rulesetNode.accept(this._visitor); } else { rulesetNode.rules = null; } visitArgs.visitDeeper = false; nodeRules = rulesetNode.rules; if (nodeRules) { this._mergeRules(nodeRules); nodeRules = rulesetNode.rules; } if (nodeRules) { this._removeDuplicateRules(nodeRules); nodeRules = rulesetNode.rules; } // now decide whether we keep the ruleset if (nodeRules && nodeRules.length > 0 && rulesetNode.paths.length > 0) { rulesets.splice(0, 0, rulesetNode); } } else { rulesetNode.accept(this._visitor); visitArgs.visitDeeper = false; if (rulesetNode.firstRoot || (rulesetNode.rules && rulesetNode.rules.length > 0)) { rulesets.splice(0, 0, rulesetNode); } } if (rulesets.length === 1) { return rulesets[0]; } return rulesets; }, _removeDuplicateRules: function(rules) { if (!rules) { return; } // remove duplicates var ruleCache = {}, ruleList, rule, i; for(i = rules.length - 1; i >= 0 ; i--) { rule = rules[i]; if (rule instanceof tree.Rule) { if (!ruleCache[rule.name]) { ruleCache[rule.name] = rule; } else { ruleList = ruleCache[rule.name]; if (ruleList instanceof tree.Rule) { ruleList = ruleCache[rule.name] = [ruleCache[rule.name].toCSS(this._env)]; } var ruleCSS = rule.toCSS(this._env); if (ruleList.indexOf(ruleCSS) !== -1) { rules.splice(i, 1); } else { ruleList.push(ruleCSS); } } } } }, _mergeRules: function (rules) { if (!rules) { return; } var groups = {}, parts, rule, key; for (var i = 0; i < rules.length; i++) { rule = rules[i]; if ((rule instanceof tree.Rule) && rule.merge) { key = [rule.name, rule.important ? "!" : ""].join(","); if (!groups[key]) { groups[key] = []; } else { rules.splice(i--, 1); } groups[key].push(rule); } } Object.keys(groups).map(function (k) { function toExpression(values) { return new (tree.Expression)(values.map(function (p) { return p.value; })); } function toValue(values) { return new (tree.Value)(values.map(function (p) { return p; })); } parts = groups[k]; if (parts.length > 1) { rule = parts[0]; var spacedGroups = []; var lastSpacedGroup = []; parts.map(function (p) { if (p.merge==="+") { if (lastSpacedGroup.length > 0) { spacedGroups.push(toExpression(lastSpacedGroup)); } lastSpacedGroup = []; } lastSpacedGroup.push(p); }); spacedGroups.push(toExpression(lastSpacedGroup)); rule.value = toValue(spacedGroups); } }); } }; })(require('./tree')); (function (tree) { /*jshint loopfunc:true */ tree.extendFinderVisitor = function() { this._visitor = new tree.visitor(this); this.contexts = []; this.allExtendsStack = [[]]; }; tree.extendFinderVisitor.prototype = { run: function (root) { root = this._visitor.visit(root); root.allExtends = this.allExtendsStack[0]; return root; }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var i, j, extend, allSelectorsExtendList = [], extendList; // get &:extend(.a); rules which apply to all selectors in this ruleset var rules = rulesetNode.rules, ruleCnt = rules ? rules.length : 0; for(i = 0; i < ruleCnt; i++) { if (rulesetNode.rules[i] instanceof tree.Extend) { allSelectorsExtendList.push(rules[i]); rulesetNode.extendOnEveryPath = true; } } // now find every selector and apply the extends that apply to all extends // and the ones which apply to an individual extend var paths = rulesetNode.paths; for(i = 0; i < paths.length; i++) { var selectorPath = paths[i], selector = selectorPath[selectorPath.length - 1], selExtendList = selector.extendList; extendList = selExtendList ? selExtendList.slice(0).concat(allSelectorsExtendList) : allSelectorsExtendList; if (extendList) { extendList = extendList.map(function(allSelectorsExtend) { return allSelectorsExtend.clone(); }); } for(j = 0; j < extendList.length; j++) { this.foundExtends = true; extend = extendList[j]; extend.findSelfSelectors(selectorPath); extend.ruleset = rulesetNode; if (j === 0) { extend.firstExtendOnThisSelectorPath = true; } this.allExtendsStack[this.allExtendsStack.length-1].push(extend); } } this.contexts.push(rulesetNode.selectors); }, visitRulesetOut: function (rulesetNode) { if (!rulesetNode.root) { this.contexts.length = this.contexts.length - 1; } }, visitMedia: function (mediaNode, visitArgs) { mediaNode.allExtends = []; this.allExtendsStack.push(mediaNode.allExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { directiveNode.allExtends = []; this.allExtendsStack.push(directiveNode.allExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; tree.processExtendsVisitor = function() { this._visitor = new tree.visitor(this); }; tree.processExtendsVisitor.prototype = { run: function(root) { var extendFinder = new tree.extendFinderVisitor(); extendFinder.run(root); if (!extendFinder.foundExtends) { return root; } root.allExtends = root.allExtends.concat(this.doExtendChaining(root.allExtends, root.allExtends)); this.allExtendsStack = [root.allExtends]; return this._visitor.visit(root); }, doExtendChaining: function (extendsList, extendsListTarget, iterationCount) { // // chaining is different from normal extension.. if we extend an extend then we are not just copying, altering and pasting // the selector we would do normally, but we are also adding an extend with the same target selector // this means this new extend can then go and alter other extends // // this method deals with all the chaining work - without it, extend is flat and doesn't work on other extend selectors // this is also the most expensive.. and a match on one selector can cause an extension of a selector we had already processed if // we look at each selector at a time, as is done in visitRuleset var extendIndex, targetExtendIndex, matches, extendsToAdd = [], newSelector, extendVisitor = this, selectorPath, extend, targetExtend, newExtend; iterationCount = iterationCount || 0; //loop through comparing every extend with every target extend. // a target extend is the one on the ruleset we are looking at copy/edit/pasting in place // e.g. .a:extend(.b) {} and .b:extend(.c) {} then the first extend extends the second one // and the second is the target. // the seperation into two lists allows us to process a subset of chains with a bigger set, as is the // case when processing media queries for(extendIndex = 0; extendIndex < extendsList.length; extendIndex++){ for(targetExtendIndex = 0; targetExtendIndex < extendsListTarget.length; targetExtendIndex++){ extend = extendsList[extendIndex]; targetExtend = extendsListTarget[targetExtendIndex]; // look for circular references if( extend.parent_ids.indexOf( targetExtend.object_id ) >= 0 ){ continue; } // find a match in the target extends self selector (the bit before :extend) selectorPath = [targetExtend.selfSelectors[0]]; matches = extendVisitor.findMatch(extend, selectorPath); if (matches.length) { // we found a match, so for each self selector.. extend.selfSelectors.forEach(function(selfSelector) { // process the extend as usual newSelector = extendVisitor.extendSelector(matches, selectorPath, selfSelector); // but now we create a new extend from it newExtend = new(tree.Extend)(targetExtend.selector, targetExtend.option, 0); newExtend.selfSelectors = newSelector; // add the extend onto the list of extends for that selector newSelector[newSelector.length-1].extendList = [newExtend]; // record that we need to add it. extendsToAdd.push(newExtend); newExtend.ruleset = targetExtend.ruleset; //remember its parents for circular references newExtend.parent_ids = newExtend.parent_ids.concat(targetExtend.parent_ids, extend.parent_ids); // only process the selector once.. if we have :extend(.a,.b) then multiple // extends will look at the same selector path, so when extending // we know that any others will be duplicates in terms of what is added to the css if (targetExtend.firstExtendOnThisSelectorPath) { newExtend.firstExtendOnThisSelectorPath = true; targetExtend.ruleset.paths.push(newSelector); } }); } } } if (extendsToAdd.length) { // try to detect circular references to stop a stack overflow. // may no longer be needed. this.extendChainCount++; if (iterationCount > 100) { var selectorOne = "{unable to calculate}"; var selectorTwo = "{unable to calculate}"; try { selectorOne = extendsToAdd[0].selfSelectors[0].toCSS(); selectorTwo = extendsToAdd[0].selector.toCSS(); } catch(e) {} throw {message: "extend circular reference detected. One of the circular extends is currently:"+selectorOne+":extend(" + selectorTwo+")"}; } // now process the new extends on the existing rules so that we can handle a extending b extending c ectending d extending e... return extendsToAdd.concat(extendVisitor.doExtendChaining(extendsToAdd, extendsListTarget, iterationCount+1)); } else { return extendsToAdd; } }, visitRule: function (ruleNode, visitArgs) { visitArgs.visitDeeper = false; }, visitMixinDefinition: function (mixinDefinitionNode, visitArgs) { visitArgs.visitDeeper = false; }, visitSelector: function (selectorNode, visitArgs) { visitArgs.visitDeeper = false; }, visitRuleset: function (rulesetNode, visitArgs) { if (rulesetNode.root) { return; } var matches, pathIndex, extendIndex, allExtends = this.allExtendsStack[this.allExtendsStack.length-1], selectorsToAdd = [], extendVisitor = this, selectorPath; // look at each selector path in the ruleset, find any extend matches and then copy, find and replace for(extendIndex = 0; extendIndex < allExtends.length; extendIndex++) { for(pathIndex = 0; pathIndex < rulesetNode.paths.length; pathIndex++) { selectorPath = rulesetNode.paths[pathIndex]; // extending extends happens initially, before the main pass if (rulesetNode.extendOnEveryPath) { continue; } var extendList = selectorPath[selectorPath.length-1].extendList; if (extendList && extendList.length) { continue; } matches = this.findMatch(allExtends[extendIndex], selectorPath); if (matches.length) { allExtends[extendIndex].selfSelectors.forEach(function(selfSelector) { selectorsToAdd.push(extendVisitor.extendSelector(matches, selectorPath, selfSelector)); }); } } } rulesetNode.paths = rulesetNode.paths.concat(selectorsToAdd); }, findMatch: function (extend, haystackSelectorPath) { // // look through the haystack selector path to try and find the needle - extend.selector // returns an array of selector matches that can then be replaced // var haystackSelectorIndex, hackstackSelector, hackstackElementIndex, haystackElement, targetCombinator, i, extendVisitor = this, needleElements = extend.selector.elements, potentialMatches = [], potentialMatch, matches = []; // loop through the haystack elements for(haystackSelectorIndex = 0; haystackSelectorIndex < haystackSelectorPath.length; haystackSelectorIndex++) { hackstackSelector = haystackSelectorPath[haystackSelectorIndex]; for(hackstackElementIndex = 0; hackstackElementIndex < hackstackSelector.elements.length; hackstackElementIndex++) { haystackElement = hackstackSelector.elements[hackstackElementIndex]; // if we allow elements before our match we can add a potential match every time. otherwise only at the first element. if (extend.allowBefore || (haystackSelectorIndex === 0 && hackstackElementIndex === 0)) { potentialMatches.push({pathIndex: haystackSelectorIndex, index: hackstackElementIndex, matched: 0, initialCombinator: haystackElement.combinator}); } for(i = 0; i < potentialMatches.length; i++) { potentialMatch = potentialMatches[i]; // selectors add " " onto the first element. When we use & it joins the selectors together, but if we don't // then each selector in haystackSelectorPath has a space before it added in the toCSS phase. so we need to work out // what the resulting combinator will be targetCombinator = haystackElement.combinator.value; if (targetCombinator === '' && hackstackElementIndex === 0) { targetCombinator = ' '; } // if we don't match, null our match to indicate failure if (!extendVisitor.isElementValuesEqual(needleElements[potentialMatch.matched].value, haystackElement.value) || (potentialMatch.matched > 0 && needleElements[potentialMatch.matched].combinator.value !== targetCombinator)) { potentialMatch = null; } else { potentialMatch.matched++; } // if we are still valid and have finished, test whether we have elements after and whether these are allowed if (potentialMatch) { potentialMatch.finished = potentialMatch.matched === needleElements.length; if (potentialMatch.finished && (!extend.allowAfter && (hackstackElementIndex+1 < hackstackSelector.elements.length || haystackSelectorIndex+1 < haystackSelectorPath.length))) { potentialMatch = null; } } // if null we remove, if not, we are still valid, so either push as a valid match or continue if (potentialMatch) { if (potentialMatch.finished) { potentialMatch.length = needleElements.length; potentialMatch.endPathIndex = haystackSelectorIndex; potentialMatch.endPathElementIndex = hackstackElementIndex + 1; // index after end of match potentialMatches.length = 0; // we don't allow matches to overlap, so start matching again matches.push(potentialMatch); } } else { potentialMatches.splice(i, 1); i--; } } } } return matches; }, isElementValuesEqual: function(elementValue1, elementValue2) { if (typeof elementValue1 === "string" || typeof elementValue2 === "string") { return elementValue1 === elementValue2; } if (elementValue1 instanceof tree.Attribute) { if (elementValue1.op !== elementValue2.op || elementValue1.key !== elementValue2.key) { return false; } if (!elementValue1.value || !elementValue2.value) { if (elementValue1.value || elementValue2.value) { return false; } return true; } elementValue1 = elementValue1.value.value || elementValue1.value; elementValue2 = elementValue2.value.value || elementValue2.value; return elementValue1 === elementValue2; } elementValue1 = elementValue1.value; elementValue2 = elementValue2.value; if (elementValue1 instanceof tree.Selector) { if (!(elementValue2 instanceof tree.Selector) || elementValue1.elements.length !== elementValue2.elements.length) { return false; } for(var i = 0; i <elementValue1.elements.length; i++) { if (elementValue1.elements[i].combinator.value !== elementValue2.elements[i].combinator.value) { if (i !== 0 || (elementValue1.elements[i].combinator.value || ' ') !== (elementValue2.elements[i].combinator.value || ' ')) { return false; } } if (!this.isElementValuesEqual(elementValue1.elements[i].value, elementValue2.elements[i].value)) { return false; } } return true; } return false; }, extendSelector:function (matches, selectorPath, replacementSelector) { //for a set of matches, replace each match with the replacement selector var currentSelectorPathIndex = 0, currentSelectorPathElementIndex = 0, path = [], matchIndex, selector, firstElement, match, newElements; for (matchIndex = 0; matchIndex < matches.length; matchIndex++) { match = matches[matchIndex]; selector = selectorPath[match.pathIndex]; firstElement = new tree.Element( match.initialCombinator, replacementSelector.elements[0].value, replacementSelector.elements[0].index, replacementSelector.elements[0].currentFileInfo ); if (match.pathIndex > currentSelectorPathIndex && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } newElements = selector.elements .slice(currentSelectorPathElementIndex, match.index) .concat([firstElement]) .concat(replacementSelector.elements.slice(1)); if (currentSelectorPathIndex === match.pathIndex && matchIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(newElements); } else { path = path.concat(selectorPath.slice(currentSelectorPathIndex, match.pathIndex)); path.push(new tree.Selector( newElements )); } currentSelectorPathIndex = match.endPathIndex; currentSelectorPathElementIndex = match.endPathElementIndex; if (currentSelectorPathElementIndex >= selectorPath[currentSelectorPathIndex].elements.length) { currentSelectorPathElementIndex = 0; currentSelectorPathIndex++; } } if (currentSelectorPathIndex < selectorPath.length && currentSelectorPathElementIndex > 0) { path[path.length - 1].elements = path[path.length - 1].elements.concat(selectorPath[currentSelectorPathIndex].elements.slice(currentSelectorPathElementIndex)); currentSelectorPathIndex++; } path = path.concat(selectorPath.slice(currentSelectorPathIndex, selectorPath.length)); return path; }, visitRulesetOut: function (rulesetNode) { }, visitMedia: function (mediaNode, visitArgs) { var newAllExtends = mediaNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, mediaNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitMediaOut: function (mediaNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; }, visitDirective: function (directiveNode, visitArgs) { var newAllExtends = directiveNode.allExtends.concat(this.allExtendsStack[this.allExtendsStack.length-1]); newAllExtends = newAllExtends.concat(this.doExtendChaining(newAllExtends, directiveNode.allExtends)); this.allExtendsStack.push(newAllExtends); }, visitDirectiveOut: function (directiveNode) { this.allExtendsStack.length = this.allExtendsStack.length - 1; } }; })(require('./tree')); (function (tree) { tree.sourceMapOutput = function (options) { this._css = []; this._rootNode = options.rootNode; this._writeSourceMap = options.writeSourceMap; this._contentsMap = options.contentsMap; this._contentsIgnoredCharsMap = options.contentsIgnoredCharsMap; this._sourceMapFilename = options.sourceMapFilename; this._outputFilename = options.outputFilename; this._sourceMapURL = options.sourceMapURL; if (options.sourceMapBasepath) { this._sourceMapBasepath = options.sourceMapBasepath.replace(/\\/g, '/'); } this._sourceMapRootpath = options.sourceMapRootpath; this._outputSourceFiles = options.outputSourceFiles; this._sourceMapGeneratorConstructor = options.sourceMapGenerator || require("source-map").SourceMapGenerator; if (this._sourceMapRootpath && this._sourceMapRootpath.charAt(this._sourceMapRootpath.length-1) !== '/') { this._sourceMapRootpath += '/'; } this._lineNumber = 0; this._column = 0; }; tree.sourceMapOutput.prototype.normalizeFilename = function(filename) { filename = filename.replace(/\\/g, '/'); if (this._sourceMapBasepath && filename.indexOf(this._sourceMapBasepath) === 0) { filename = filename.substring(this._sourceMapBasepath.length); if (filename.charAt(0) === '\\' || filename.charAt(0) === '/') { filename = filename.substring(1); } } return (this._sourceMapRootpath || "") + filename; }; tree.sourceMapOutput.prototype.add = function(chunk, fileInfo, index, mapLines) { //ignore adding empty strings if (!chunk) { return; } var lines, sourceLines, columns, sourceColumns, i; if (fileInfo) { var inputSource = this._contentsMap[fileInfo.filename]; // remove vars/banner added to the top of the file if (this._contentsIgnoredCharsMap[fileInfo.filename]) { // adjust the index index -= this._contentsIgnoredCharsMap[fileInfo.filename]; if (index < 0) { index = 0; } // adjust the source inputSource = inputSource.slice(this._contentsIgnoredCharsMap[fileInfo.filename]); } inputSource = inputSource.substring(0, index); sourceLines = inputSource.split("\n"); sourceColumns = sourceLines[sourceLines.length-1]; } lines = chunk.split("\n"); columns = lines[lines.length-1]; if (fileInfo) { if (!mapLines) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + 1, column: this._column}, original: { line: sourceLines.length, column: sourceColumns.length}, source: this.normalizeFilename(fileInfo.filename)}); } else { for(i = 0; i < lines.length; i++) { this._sourceMapGenerator.addMapping({ generated: { line: this._lineNumber + i + 1, column: i === 0 ? this._column : 0}, original: { line: sourceLines.length + i, column: i === 0 ? sourceColumns.length : 0}, source: this.normalizeFilename(fileInfo.filename)}); } } } if (lines.length === 1) { this._column += columns.length; } else { this._lineNumber += lines.length - 1; this._column = columns.length; } this._css.push(chunk); }; tree.sourceMapOutput.prototype.isEmpty = function() { return this._css.length === 0; }; tree.sourceMapOutput.prototype.toCSS = function(env) { this._sourceMapGenerator = new this._sourceMapGeneratorConstructor({ file: this._outputFilename, sourceRoot: null }); if (this._outputSourceFiles) { for(var filename in this._contentsMap) { if (this._contentsMap.hasOwnProperty(filename)) { var source = this._contentsMap[filename]; if (this._contentsIgnoredCharsMap[filename]) { source = source.slice(this._contentsIgnoredCharsMap[filename]); } this._sourceMapGenerator.setSourceContent(this.normalizeFilename(filename), source); } } } this._rootNode.genCSS(env, this); if (this._css.length > 0) { var sourceMapURL, sourceMapContent = JSON.stringify(this._sourceMapGenerator.toJSON()); if (this._sourceMapURL) { sourceMapURL = this._sourceMapURL; } else if (this._sourceMapFilename) { sourceMapURL = this.normalizeFilename(this._sourceMapFilename); } if (this._writeSourceMap) { this._writeSourceMap(sourceMapContent); } else { sourceMapURL = "data:application/json," + encodeURIComponent(sourceMapContent); } if (sourceMapURL) { this._css.push("/*# sourceMappingURL=" + sourceMapURL + " */"); } } return this._css.join(''); }; })(require('./tree')); // // browser.js - client-side engine // /*global less, window, document, XMLHttpRequest, location */ var isFileProtocol = /^(file|chrome(-extension)?|resource|qrc|app):/.test(location.protocol); less.env = less.env || (location.hostname == '127.0.0.1' || location.hostname == '0.0.0.0' || location.hostname == 'localhost' || (location.port && location.port.length > 0) || isFileProtocol ? 'development' : 'production'); var logLevel = { debug: 3, info: 2, errors: 1, none: 0 }; // The amount of logging in the javascript console. // 3 - Debug, information and errors // 2 - Information and errors // 1 - Errors // 0 - None // Defaults to 2 less.logLevel = typeof(less.logLevel) != 'undefined' ? less.logLevel : (less.env === 'development' ? logLevel.debug : logLevel.errors); // Load styles asynchronously (default: false) // // This is set to `false` by default, so that the body // doesn't start loading before the stylesheets are parsed. // Setting this to `true` can result in flickering. // less.async = less.async || false; less.fileAsync = less.fileAsync || false; // Interval between watch polls less.poll = less.poll || (isFileProtocol ? 1000 : 1500); //Setup user functions if (less.functions) { for(var func in less.functions) { if (less.functions.hasOwnProperty(func)) { less.tree.functions[func] = less.functions[func]; } } } var dumpLineNumbers = /!dumpLineNumbers:(comments|mediaquery|all)/.exec(location.hash); if (dumpLineNumbers) { less.dumpLineNumbers = dumpLineNumbers[1]; } var typePattern = /^text\/(x-)?less$/; var cache = null; var fileCache = {}; function log(str, level) { if (typeof(console) !== 'undefined' && less.logLevel >= level) { console.log('less: ' + str); } } function extractId(href) { return href.replace(/^[a-z-]+:\/+?[^\/]+/, '' ) // Remove protocol & domain .replace(/^\//, '' ) // Remove root / .replace(/\.[a-zA-Z]+$/, '' ) // Remove simple extension .replace(/[^\.\w-]+/g, '-') // Replace illegal characters .replace(/\./g, ':'); // Replace dots with colons(for valid id) } function errorConsole(e, rootHref) { var template = '{line} {content}'; var filename = e.filename || rootHref; var errors = []; var content = (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + " in " + filename + " "; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.extract) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':\n' + errors.join('\n'); } else if (e.stack) { content += e.stack; } log(content, logLevel.errors); } function createCSS(styles, sheet, lastModified) { // Strip the query-string var href = sheet.href || ''; // If there is no title set, use the filename, minus the extension var id = 'less:' + (sheet.title || extractId(href)); // If this has already been inserted into the DOM, we may need to replace it var oldCss = document.getElementById(id); var keepOldCss = false; // Create a new stylesheet node for insertion or (if necessary) replacement var css = document.createElement('style'); css.setAttribute('type', 'text/css'); if (sheet.media) { css.setAttribute('media', sheet.media); } css.id = id; if (css.styleSheet) { // IE try { css.styleSheet.cssText = styles; } catch (e) { throw new(Error)("Couldn't reassign styleSheet.cssText."); } } else { css.appendChild(document.createTextNode(styles)); // If new contents match contents of oldCss, don't replace oldCss keepOldCss = (oldCss !== null && oldCss.childNodes.length > 0 && css.childNodes.length > 0 && oldCss.firstChild.nodeValue === css.firstChild.nodeValue); } var head = document.getElementsByTagName('head')[0]; // If there is no oldCss, just append; otherwise, only append if we need // to replace oldCss with an updated stylesheet if (oldCss === null || keepOldCss === false) { var nextEl = sheet && sheet.nextSibling || null; if (nextEl) { nextEl.parentNode.insertBefore(css, nextEl); } else { head.appendChild(css); } } if (oldCss && keepOldCss === false) { oldCss.parentNode.removeChild(oldCss); } // Don't update the local store if the file wasn't modified if (lastModified && cache) { log('saving ' + href + ' to cache.', logLevel.info); try { cache.setItem(href, styles); cache.setItem(href + ':timestamp', lastModified); } catch(e) { //TODO - could do with adding more robust error handling log('failed to save', logLevel.errors); } } } function postProcessCSS(styles) { if (less.postProcessor && typeof less.postProcessor === 'function') { styles = less.postProcessor.call(styles, styles) || styles; } return styles; } function errorHTML(e, rootHref) { var id = 'less-error-message:' + extractId(rootHref || ""); var template = '<li><label>{line}</label><pre class="{class}">{content}</pre></li>'; var elem = document.createElement('div'), timer, content, errors = []; var filename = e.filename || rootHref; var filenameNoPath = filename.match(/([^\/]+(\?.*)?)$/)[1]; elem.id = id; elem.className = "less-error-message"; content = '<h3>' + (e.type || "Syntax") + "Error: " + (e.message || 'There is an error in your .less file') + '</h3>' + '<p>in <a href="' + filename + '">' + filenameNoPath + "</a> "; var errorline = function (e, i, classname) { if (e.extract[i] !== undefined) { errors.push(template.replace(/\{line\}/, (parseInt(e.line, 10) || 0) + (i - 1)) .replace(/\{class\}/, classname) .replace(/\{content\}/, e.extract[i])); } }; if (e.extract) { errorline(e, 0, ''); errorline(e, 1, 'line'); errorline(e, 2, ''); content += 'on line ' + e.line + ', column ' + (e.column + 1) + ':</p>' + '<ul>' + errors.join('') + '</ul>'; } else if (e.stack) { content += '<br/>' + e.stack.split('\n').slice(1).join('<br/>'); } elem.innerHTML = content; // CSS for error messages createCSS([ '.less-error-message ul, .less-error-message li {', 'list-style-type: none;', 'margin-right: 15px;', 'padding: 4px 0;', 'margin: 0;', '}', '.less-error-message label {', 'font-size: 12px;', 'margin-right: 15px;', 'padding: 4px 0;', 'color: #cc7777;', '}', '.less-error-message pre {', 'color: #dd6666;', 'padding: 4px 0;', 'margin: 0;', 'display: inline-block;', '}', '.less-error-message pre.line {', 'color: #ff0000;', '}', '.less-error-message h3 {', 'font-size: 20px;', 'font-weight: bold;', 'padding: 15px 0 5px 0;', 'margin: 0;', '}', '.less-error-message a {', 'color: #10a', '}', '.less-error-message .error {', 'color: red;', 'font-weight: bold;', 'padding-bottom: 2px;', 'border-bottom: 1px dashed red;', '}' ].join('\n'), { title: 'error-message' }); elem.style.cssText = [ "font-family: Arial, sans-serif", "border: 1px solid #e00", "background-color: #eee", "border-radius: 5px", "-webkit-border-radius: 5px", "-moz-border-radius: 5px", "color: #e00", "padding: 15px", "margin-bottom: 15px" ].join(';'); if (less.env == 'development') { timer = setInterval(function () { if (document.body) { if (document.getElementById(id)) { document.body.replaceChild(elem, document.getElementById(id)); } else { document.body.insertBefore(elem, document.body.firstChild); } clearInterval(timer); } }, 10); } } function error(e, rootHref) { if (!less.errorReporting || less.errorReporting === "html") { errorHTML(e, rootHref); } else if (less.errorReporting === "console") { errorConsole(e, rootHref); } else if (typeof less.errorReporting === 'function') { less.errorReporting("add", e, rootHref); } } function removeErrorHTML(path) { var node = document.getElementById('less-error-message:' + extractId(path)); if (node) { node.parentNode.removeChild(node); } } function removeErrorConsole(path) { //no action } function removeError(path) { if (!less.errorReporting || less.errorReporting === "html") { removeErrorHTML(path); } else if (less.errorReporting === "console") { removeErrorConsole(path); } else if (typeof less.errorReporting === 'function') { less.errorReporting("remove", path); } } function loadStyles(modifyVars) { var styles = document.getElementsByTagName('style'), style; for (var i = 0; i < styles.length; i++) { style = styles[i]; if (style.type.match(typePattern)) { var env = new less.tree.parseEnv(less), lessText = style.innerHTML || ''; env.filename = document.location.href.replace(/#.*$/, ''); if (modifyVars || less.globalVars) { env.useFileCache = true; } /*jshint loopfunc:true */ // use closure to store current value of i var callback = (function(style) { return function (e, cssAST) { if (e) { return error(e, "inline"); } var css = cssAST.toCSS(less); style.type = 'text/css'; if (style.styleSheet) { style.styleSheet.cssText = css; } else { style.innerHTML = css; } }; })(style); new(less.Parser)(env).parse(lessText, callback, {globalVars: less.globalVars, modifyVars: modifyVars}); } } } function extractUrlParts(url, baseUrl) { // urlParts[1] = protocol&hostname || / // urlParts[2] = / if path relative to host base // urlParts[3] = directories // urlParts[4] = filename // urlParts[5] = parameters var urlPartsRegex = /^((?:[a-z-]+:)?\/+?(?:[^\/\?#]*\/)|([\/\\]))?((?:[^\/\\\?#]*[\/\\])*)([^\/\\\?#]*)([#\?].*)?$/i, urlParts = url.match(urlPartsRegex), returner = {}, directories = [], i, baseUrlParts; if (!urlParts) { throw new Error("Could not parse sheet href - '"+url+"'"); } // Stylesheets in IE don't always return the full path if (!urlParts[1] || urlParts[2]) { baseUrlParts = baseUrl.match(urlPartsRegex); if (!baseUrlParts) { throw new Error("Could not parse page url - '"+baseUrl+"'"); } urlParts[1] = urlParts[1] || baseUrlParts[1] || ""; if (!urlParts[2]) { urlParts[3] = baseUrlParts[3] + urlParts[3]; } } if (urlParts[3]) { directories = urlParts[3].replace(/\\/g, "/").split("/"); // extract out . before .. so .. doesn't absorb a non-directory for(i = 0; i < directories.length; i++) { if (directories[i] === ".") { directories.splice(i, 1); i -= 1; } } for(i = 0; i < directories.length; i++) { if (directories[i] === ".." && i > 0) { directories.splice(i-1, 2); i -= 2; } } } returner.hostPart = urlParts[1]; returner.directories = directories; returner.path = urlParts[1] + directories.join("/"); returner.fileUrl = returner.path + (urlParts[4] || ""); returner.url = returner.fileUrl + (urlParts[5] || ""); return returner; } function pathDiff(url, baseUrl) { // diff between two paths to create a relative path var urlParts = extractUrlParts(url), baseUrlParts = extractUrlParts(baseUrl), i, max, urlDirectories, baseUrlDirectories, diff = ""; if (urlParts.hostPart !== baseUrlParts.hostPart) { return ""; } max = Math.max(baseUrlParts.directories.length, urlParts.directories.length); for(i = 0; i < max; i++) { if (baseUrlParts.directories[i] !== urlParts.directories[i]) { break; } } baseUrlDirectories = baseUrlParts.directories.slice(i); urlDirectories = urlParts.directories.slice(i); for(i = 0; i < baseUrlDirectories.length-1; i++) { diff += "../"; } for(i = 0; i < urlDirectories.length-1; i++) { diff += urlDirectories[i] + "/"; } return diff; } function getXMLHttpRequest() { if (window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject)) { return new XMLHttpRequest(); } else { try { /*global ActiveXObject */ return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { log("browser doesn't support AJAX.", logLevel.errors); return null; } } } function doXHR(url, type, callback, errback) { var xhr = getXMLHttpRequest(); var async = isFileProtocol ? less.fileAsync : less.async; if (typeof(xhr.overrideMimeType) === 'function') { xhr.overrideMimeType('text/css'); } log("XHR: Getting '" + url + "'", logLevel.debug); xhr.open('GET', url+"?_nocache="+Math.random(), async); xhr.setRequestHeader('Accept', type || 'text/x-less, text/css; q=0.9, */*; q=0.5'); xhr.send(null); function handleResponse(xhr, callback, errback) { if (xhr.status >= 200 && xhr.status < 300) { callback(xhr.responseText, xhr.getResponseHeader("Last-Modified")); } else if (typeof(errback) === 'function') { errback(xhr.status, url); } } if (isFileProtocol && !less.fileAsync) { if (xhr.status === 0 || (xhr.status >= 200 && xhr.status < 300)) { callback(xhr.responseText); } else { errback(xhr.status, url); } } else if (async) { xhr.onreadystatechange = function () { if (xhr.readyState == 4) { handleResponse(xhr, callback, errback); } }; } else { handleResponse(xhr, callback, errback); } } function loadFile(originalHref, currentFileInfo, callback, env, modifyVars) { if (currentFileInfo && currentFileInfo.currentDirectory && !/^([a-z-]+:)?\//.test(originalHref)) { originalHref = currentFileInfo.currentDirectory + originalHref; } // sheet may be set to the stylesheet for the initial load or a collection of properties including // some env variables for imports var hrefParts = extractUrlParts(originalHref, window.location.href); var href = hrefParts.url; var newFileInfo = { currentDirectory: hrefParts.path, filename: href }; if (currentFileInfo) { newFileInfo.entryPath = currentFileInfo.entryPath; newFileInfo.rootpath = currentFileInfo.rootpath; newFileInfo.rootFilename = currentFileInfo.rootFilename; newFileInfo.relativeUrls = currentFileInfo.relativeUrls; } else { newFileInfo.entryPath = hrefParts.path; newFileInfo.rootpath = less.rootpath || hrefParts.path; newFileInfo.rootFilename = href; newFileInfo.relativeUrls = env.relativeUrls; } if (newFileInfo.relativeUrls) { if (env.rootpath) { newFileInfo.rootpath = extractUrlParts(env.rootpath + pathDiff(hrefParts.path, newFileInfo.entryPath)).path; } else { newFileInfo.rootpath = hrefParts.path; } } if (env.useFileCache && fileCache[href]) { try { var lessText = fileCache[href]; callback(null, lessText, href, newFileInfo, { lastModified: new Date() }); } catch (e) { callback(e, null, href); } return; } doXHR(href, env.mime, function (data, lastModified) { // per file cache fileCache[href] = data; // Use remote copy (re-parse) try { callback(null, data, href, newFileInfo, { lastModified: lastModified }); } catch (e) { callback(e, null, href); } }, function (status, url) { callback({ type: 'File', message: "'" + url + "' wasn't found (" + status + ")" }, null, href); }); } function loadStyleSheet(sheet, callback, reload, remaining, modifyVars) { var env = new less.tree.parseEnv(less); env.mime = sheet.type; if (modifyVars || less.globalVars) { env.useFileCache = true; } loadFile(sheet.href, null, function(e, data, path, newFileInfo, webInfo) { if (webInfo) { webInfo.remaining = remaining; var css = cache && cache.getItem(path), timestamp = cache && cache.getItem(path + ':timestamp'); if (!reload && timestamp && webInfo.lastModified && (new(Date)(webInfo.lastModified).valueOf() === new(Date)(timestamp).valueOf())) { // Use local copy createCSS(css, sheet); webInfo.local = true; callback(null, null, data, sheet, webInfo, path); return; } } //TODO add tests around how this behaves when reloading removeError(path); if (data) { env.currentFileInfo = newFileInfo; new(less.Parser)(env).parse(data, function (e, root) { if (e) { return callback(e, null, null, sheet); } try { callback(e, root, data, sheet, webInfo, path); } catch (e) { callback(e, null, null, sheet); } }, {modifyVars: modifyVars, globalVars: less.globalVars}); } else { callback(e, null, null, sheet, webInfo, path); } }, env, modifyVars); } function loadStyleSheets(callback, reload, modifyVars) { for (var i = 0; i < less.sheets.length; i++) { loadStyleSheet(less.sheets[i], callback, reload, less.sheets.length - (i + 1), modifyVars); } } function initRunningMode(){ if (less.env === 'development') { less.optimization = 0; less.watchTimer = setInterval(function () { if (less.watchMode) { loadStyleSheets(function (e, root, _, sheet, env) { if (e) { error(e, sheet.href); } else if (root) { var styles = root.toCSS(less); styles = postProcessCSS(styles); createCSS(styles, sheet, env.lastModified); } }); } }, less.poll); } else { less.optimization = 3; } } // // Watch mode // less.watch = function () { if (!less.watchMode ){ less.env = 'development'; initRunningMode(); } this.watchMode = true; return true; }; less.unwatch = function () {clearInterval(less.watchTimer); this.watchMode = false; return false; }; if (/!watch/.test(location.hash)) { less.watch(); } if (less.env != 'development') { try { cache = (typeof(window.localStorage) === 'undefined') ? null : window.localStorage; } catch (_) {} } // // Get all <link> tags with the 'rel' attribute set to "stylesheet/less" // var links = document.getElementsByTagName('link'); less.sheets = []; for (var i = 0; i < links.length; i++) { if (links[i].rel === 'stylesheet/less' || (links[i].rel.match(/stylesheet/) && (links[i].type.match(typePattern)))) { less.sheets.push(links[i]); } } // // With this function, it's possible to alter variables and re-render // CSS without reloading less-files // less.modifyVars = function(record) { less.refresh(false, record); }; less.refresh = function (reload, modifyVars) { var startTime, endTime; startTime = endTime = new Date(); loadStyleSheets(function (e, root, _, sheet, env) { if (e) { return error(e, sheet.href); } if (env.local) { log("loading " + sheet.href + " from cache.", logLevel.info); } else { log("parsed " + sheet.href + " successfully.", logLevel.debug); var styles = root.toCSS(less); styles = postProcessCSS(styles); createCSS(styles, sheet, env.lastModified); } log("css for " + sheet.href + " generated in " + (new Date() - endTime) + 'ms', logLevel.info); if (env.remaining === 0) { log("less has finished. css generated in " + (new Date() - startTime) + 'ms', logLevel.info); } endTime = new Date(); }, reload, modifyVars); loadStyles(modifyVars); }; less.refreshStyles = loadStyles; less.Parser.fileLoader = loadFile; less.refresh(less.env === 'development'); // amd.js // // Define Less as an AMD module. if (typeof define === "function" && define.amd) { define(function () { return less; } ); } })(window);
Java
#!/usr/bin/env bash # start ssh to be tested "running" by netstat service ssh start # run the tests - every test should result in "passed" cd /app && \ java -jar /app/dda-serverspec-standalone.jar -v /app/certificate-file.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/command.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/file.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar -v /app/package.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/http-cert.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/http-cert.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/netstat.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/netstat.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/netcat.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/netcat.edn && \ echo "----------" && \ java -jar /app/dda-serverspec-standalone.jar --install-dependencies /app/iproute.edn && \ java -jar /app/dda-serverspec-standalone.jar -v /app/iproute.edn -v
Java
package org.devspark.aws.tools; import java.lang.reflect.Method; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.ApiGateway; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.Resource; import org.devspark.aws.lambdasupport.endpoint.annotations.apigateway.ResourceMethod; import org.devspark.aws.tools.model.resources.EndpointResource; import org.devspark.aws.tools.model.resources.EndpointResourceMethod; import org.devspark.aws.tools.model.resources.EndpointResourceMethodParameter; import org.devspark.aws.tools.model.resources.EndpointResponse; import org.devspark.aws.tools.model.resources.EndpointResponseHeader; import org.devspark.aws.tools.model.resources.EndpointResponseSchema; import org.devspark.aws.tools.swagger.SwaggerFileWriter; import org.devspark.aws.tools.swagger.VelocitySwaggerFileWriter; import org.reflections.ReflectionUtils; import org.reflections.Reflections; import org.reflections.scanners.SubTypesScanner; import org.reflections.scanners.TypeAnnotationsScanner; import org.reflections.util.ClasspathHelper; import org.reflections.util.ConfigurationBuilder; @Mojo(name = "apigateway-deployer") public class AWSAPIGatewayDeployer extends AbstractMojo { @Parameter(property = "base-package") private String basePackage; private SwaggerFileWriter fileWriter = new VelocitySwaggerFileWriter(); @Override public void execute() throws MojoExecutionException, MojoFailureException { Reflections reflections = new Reflections(new ConfigurationBuilder() .setUrls(ClasspathHelper.forPackage(basePackage)).setScanners( new SubTypesScanner(), new TypeAnnotationsScanner())); Set<Class<?>> resources = reflections .getTypesAnnotatedWith(Resource.class); Set<Class<?>> apis = reflections .getTypesAnnotatedWith(ApiGateway.class); Map<String, EndpointResource> endpointResources = getEndpointResources(resources); String apiName = getApiName(apis); fileWriter.createSwaggerFile(new ArrayList<EndpointResource>(endpointResources.values()), apiName); } private String getApiName(Set<Class<?>> apis) { if (apis.size() != 1) { getLog().warn("Invalid number of @ApiGateway found."); } return apis.iterator().next().getAnnotationsByType(ApiGateway.class)[0].name(); } @SuppressWarnings("unchecked") private Map<String, EndpointResource> getEndpointResources(Set<Class<?>> resources) { Map<String, EndpointResource> endpointResources = new HashMap<String, EndpointResource>(); for (Class<?> type : resources) { Set<Method> resourceMethods = ReflectionUtils.getAllMethods(type, ReflectionUtils.withAnnotation(ResourceMethod.class)); if (resourceMethods.isEmpty()) { getLog().warn( "No methods annotated with @Resource found in type: " + type.getName()); continue; } for (Method method : resourceMethods) { Resource methodResource = method.getAnnotation(Resource.class); String resourceName = type.getAnnotationsByType(Resource.class)[0].name(); if(methodResource != null) { resourceName = resourceName + "/" + methodResource.name(); } EndpointResourceMethod endpointMethod = createMethodResource(method, resourceName); EndpointResource endpointResource = endpointResources.get(resourceName); if (endpointResource == null) { endpointResource = new EndpointResource(); endpointResource.setName(resourceName); endpointResource.setMethods(new ArrayList<EndpointResourceMethod>()); endpointResources.put(resourceName, endpointResource); } endpointResource.getMethods().add(endpointMethod); } } return endpointResources; } private EndpointResourceMethod createMethodResource(Method method, String resourceName) { EndpointResourceMethod endpointMethod = new EndpointResourceMethod(); ResourceMethod resourceMethod = method.getAnnotation(ResourceMethod.class); endpointMethod.setVerb(resourceMethod.httpMethod().name()); endpointMethod.setParameters(getParameters(resourceName)); endpointMethod.setProduces(Arrays.asList("application/json")); endpointMethod.setResponses(getMethodResponses()); return endpointMethod; } //TODO: Replace mocked list with the generation of the responses of the method. private List<EndpointResponse> getMethodResponses() { List<EndpointResponse> responses = new ArrayList<EndpointResponse>(); EndpointResponse sucessfulResponse = new EndpointResponse(); sucessfulResponse.setHttpStatus("200"); sucessfulResponse.setDescription("200 response"); sucessfulResponse.setHeaders(new EndpointResponseHeader()); EndpointResponseSchema schema = new EndpointResponseSchema(); schema.setRef("#/definitions/Empty"); sucessfulResponse.setSchema(schema); return responses; } private List<EndpointResourceMethodParameter> getParameters(String resourceName) { String pattern = "\\{[a-zA-A]*\\}"; Pattern r = Pattern.compile(pattern); List<EndpointResourceMethodParameter> parameters = new ArrayList<EndpointResourceMethodParameter>(); Matcher m = r.matcher(resourceName); while(m.find()){ EndpointResourceMethodParameter parameter = new EndpointResourceMethodParameter(); parameter.setName(m.group(0).replaceAll("\\{*\\}*", "")); //TODO: Review how to populate the parameter metadata. parameter.setRequired(true); parameter.setType("string"); parameter.setIn("path"); parameters.add(parameter); } return parameters; } }
Java
<?php //-------------------------------- //db_mysqli, db_pdo $var->db_driver = 'db_mysqli'; //$var->db_driver = 'db_pdo'; //for pdo: mysql, sqlite, ... //$var->db_engine = 'mysql'; $var->db_host = 'localhost'; $var->db_database = 'ada'; $var->db_user = 'ad'; $var->db_pass = 'dddd'; //$var->db_database = 'kargosha'; //$var->db_user = 'root'; //$var->db_pass = ''; $var->db_perfix = 'x_'; $var->db_set_utf8 = true; //-------------------------------- $var->session_unique = 'kargosha'; //-------------------------------- $var->auto_lang = false; $var->multi_domain = false; //------------ News letter { -------------------- $var->use_mailer_lite_api = true; $var->mailer_lite_api_key = ''; $var->mailer_lite_group_id = ''; //------------ } News letter -------------------- //-------------------------------- $var->cache_page = false; $var->cache_image = false; $var->cache_page_time = 1*24*60*60; // 1 day = 1 days * 24 hours * 60 mins * 60 secs $var->cache_image_time = 1*24*60*60; // 1 day = 1 days * 24 hours * 60 mins * 60 secs $var->cookie_expire_time = 30*24*60*60; // 30 day = 30 days * 24 hours * 60 mins * 60 secs //-------------------------------- $var->hit_counter = true; $var->hit_online = true; $var->hit_referers = false; $var->hit_requests = false; //-------------------------------- //--------------------------------bank: Beh Pardakht - Bank e Mellat $var->bank_mellat_terminal = 0; $var->bank_mellat_user = ''; $var->bank_mellat_pass = ''; $var->callBackUrl = "http://site.com/?a=transaction.callBack"; $var->bank_startpayUrl = "https://bpm.shaparak.ir/pgwchannel/startpay.mellat"; $var->bank_nusoap_client = "https://bpm.shaparak.ir/pgwchannel/services/pgw?wsdl"; $var->bank_namespace = "http://interfaces.core.sw.bps.com/"; //-------------------------------- $var->zarinpal_merchant_code = "AAAA-BBBB-CCCC-DDDD"; $var->zarinpal_callBackUrl = "http://site.com/?a=transaction_zarinpal.callBack"; //-------------------------------- ?>
Java
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.ide.actions; import com.intellij.CommonBundle; import com.intellij.history.LocalHistory; import com.intellij.history.LocalHistoryAction; import com.intellij.ide.IdeBundle; import com.intellij.openapi.application.WriteAction; import com.intellij.openapi.application.WriteActionAware; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.command.UndoConfirmationPolicy; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.Ref; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiElement; import com.intellij.psi.SmartPointerManager; import com.intellij.psi.SmartPsiElementPointer; import com.intellij.util.ThrowableRunnable; import com.intellij.util.containers.ContainerUtil; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.List; /** * @author peter */ public abstract class ElementCreator implements WriteActionAware { private static final Logger LOG = Logger.getInstance(ElementCreator.class); private final Project myProject; private final @NlsContexts.DialogTitle String myErrorTitle; protected ElementCreator(Project project, @NotNull @NlsContexts.DialogTitle String errorTitle) { myProject = project; myErrorTitle = errorTitle; } protected abstract PsiElement @NotNull [] create(@NotNull String newName) throws Exception; @NlsContexts.Command @NotNull protected abstract String getActionName(@NotNull String newName); public @NotNull PsiElement @NotNull [] tryCreate(@NotNull final String inputString) { if (inputString.isEmpty()) { Messages.showMessageDialog(myProject, IdeBundle.message("error.name.should.be.specified"), CommonBundle.getErrorTitle(), Messages.getErrorIcon()); return PsiElement.EMPTY_ARRAY; } Ref<List<SmartPsiElementPointer<?>>> createdElements = Ref.create(); Exception exception = executeCommand(getActionName(inputString), () -> { PsiElement[] psiElements = create(inputString); SmartPointerManager manager = SmartPointerManager.getInstance(myProject); createdElements.set(ContainerUtil.map(psiElements, manager::createSmartPsiElementPointer)); }); if (exception != null) { handleException(exception); return PsiElement.EMPTY_ARRAY; } return ContainerUtil.mapNotNull(createdElements.get(), SmartPsiElementPointer::getElement).toArray(PsiElement.EMPTY_ARRAY); } @Nullable private Exception executeCommand(@NotNull @NlsContexts.Command String commandName, @NotNull ThrowableRunnable<? extends Exception> invokeCreate) { final Exception[] exception = new Exception[1]; CommandProcessor.getInstance().executeCommand(myProject, () -> { LocalHistoryAction action = LocalHistory.getInstance().startAction(commandName); try { if (startInWriteAction()) { WriteAction.run(invokeCreate); } else { invokeCreate.run(); } } catch (Exception ex) { exception[0] = ex; } finally { action.finish(); } }, commandName, null, UndoConfirmationPolicy.REQUEST_CONFIRMATION); return exception[0]; } private void handleException(Exception t) { LOG.info(t); String errorMessage = getErrorMessage(t); Messages.showMessageDialog(myProject, errorMessage, myErrorTitle, Messages.getErrorIcon()); } public static @NlsContexts.DialogMessage String getErrorMessage(Throwable t) { String errorMessage = CreateElementActionBase.filterMessage(t.getMessage()); if (StringUtil.isEmpty(errorMessage)) { errorMessage = t.toString(); } return errorMessage; } }
Java
import tempfile from git import InvalidGitRepositoryError try: from unittest2 import TestCase from mock import patch, Mock except ImportError: from unittest import TestCase from mock import patch, Mock import textwrap from datetime import datetime from botocore.exceptions import ClientError from dateutil.tz import tzutc from cfn_sphere import util, CloudFormationStack from cfn_sphere.exceptions import CfnSphereException, CfnSphereBotoError from cfn_sphere.template import CloudFormationTemplate class UtilTests(TestCase): def test_convert_yaml_to_json_string_returns_valid_json_string(self): data = textwrap.dedent(""" foo: foo: baa """) self.assertEqual('{\n "foo": {\n "foo": "baa"\n }\n}', util.convert_yaml_to_json_string(data)) def test_convert_yaml_to_json_string_returns_valid_json_string_on_empty_string_input(self): data = "" self.assertEqual('{}', util.convert_yaml_to_json_string(data)) def test_convert_json_to_yaml_string_returns_valid_yaml_string(self): data = textwrap.dedent(""" { "foo": { "foo": "baa" } } """) self.assertEqual('foo:\n foo: baa\n', util.convert_json_to_yaml_string(data)) def test_convert_json_to_yaml_string_returns_empty_string_on_empty_json_input(self): data = {} self.assertEqual('', util.convert_json_to_yaml_string(data)) @patch("cfn_sphere.util.urllib2.urlopen") def test_get_cfn_api_server_time_returns_gmt_datetime(self, urlopen_mock): urlopen_mock.return_value.info.return_value.get.return_value = "Mon, 21 Sep 2015 17:17:26 GMT" expected_timestamp = datetime(year=2015, month=9, day=21, hour=17, minute=17, second=26, tzinfo=tzutc()) self.assertEqual(expected_timestamp, util.get_cfn_api_server_time()) @patch("cfn_sphere.util.urllib2.urlopen") def test_get_cfn_api_server_time_raises_exception_on_empty_date_header(self, urlopen_mock): urlopen_mock.return_value.info.return_value.get.return_value = "" with self.assertRaises(CfnSphereException): util.get_cfn_api_server_time() def test_with_boto_retry_retries_method_call_for_throttling_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() exception = CfnSphereBotoError( ClientError(error_response={"Error": {"Code": "Throttling", "Message": "Rate exceeded"}}, operation_name="DescribeStacks")) raise exception with self.assertRaises(CfnSphereBotoError): my_retried_method(count_func) self.assertEqual(2, count_func.call_count) def test_with_boto_retry_does_not_retry_for_simple_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() raise Exception with self.assertRaises(Exception): my_retried_method(count_func) self.assertEqual(1, count_func.call_count) def test_with_boto_retry_does_not_retry_for_another_boto_client_error(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() exception = ClientError(error_response={"Error": {"Code": "Another Error", "Message": "Foo"}}, operation_name="DescribeStacks") raise exception with self.assertRaises(ClientError): my_retried_method(count_func) self.assertEqual(1, count_func.call_count) def test_with_boto_retry_does_not_retry_without_exception(self): count_func = Mock() @util.with_boto_retry(max_retries=1, pause_time_multiplier=1) def my_retried_method(count_func): count_func() return "foo" self.assertEqual("foo", my_retried_method(count_func)) self.assertEqual(1, count_func.call_count) def test_get_pretty_parameters_string(self): template_body = { 'Parameters': { 'myParameter1': { 'Type': 'String', 'NoEcho': True }, 'myParameter2': { 'Type': 'String' }, 'myParameter3': { 'Type': 'Number', 'NoEcho': 'true' }, 'myParameter4': { 'Type': 'Number', 'NoEcho': 'false' }, 'myParameter5': { 'Type': 'Number', 'NoEcho': False } } } parameters = { 'myParameter1': 'super-secret', 'myParameter2': 'not-that-secret', 'myParameter3': 'also-super-secret', 'myParameter4': 'could-be-public', 'myParameter5': 'also-ok' } template = CloudFormationTemplate(template_body, 'just-another-template') stack = CloudFormationStack(template, parameters, 'just-another-stack', 'eu-west-1') expected_string = """+--------------+-----------------+ | Parameter | Value | +--------------+-----------------+ | myParameter1 | *** | | myParameter2 | not-that-secret | | myParameter3 | *** | | myParameter4 | could-be-public | | myParameter5 | also-ok | +--------------+-----------------+""" self.assertEqual(expected_string, util.get_pretty_parameters_string(stack)) def test_get_pretty_stack_outputs_returns_proper_table(self): outputs = [ { 'OutputKey': 'key1', 'OutputValue': 'value1', 'Description': 'desc1' }, { 'OutputKey': 'key2', 'OutputValue': 'value2', 'Description': 'desc2' }, { 'OutputKey': 'key3', 'OutputValue': 'value3', 'Description': 'desc3' } ] expected = """+--------+--------+ | Output | Value | +--------+--------+ | key1 | value1 | | key2 | value2 | | key3 | value3 | +--------+--------+""" result = util.get_pretty_stack_outputs(outputs) self.assertEqual(expected, result) def test_strip_string_strips_string(self): s = "sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwerA323" result = util.strip_string(s) self.assertEqual( "sfsdklgashgslkadghkafhgaknkbndkjfbnwurtqwhgsdnkshGLSAKGKLDJFHGSKDLGFLDFGKSDFLGKHAsdjdghskjdhsdcxbvwe...", result) def test_strip_string_doesnt_strip_short_strings(self): s = "my-short-string" result = util.strip_string(s) self.assertEqual("my-short-string...", result) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_none_if_no_repository_present(self, repo_mock): repo_mock.side_effect = InvalidGitRepositoryError self.assertEqual(None, util.get_git_repository_remote_url(tempfile.mkdtemp())) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_repo_url(self, repo_mock): url = "http://config.repo.git" repo_mock.return_value.remotes.origin.url = url self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp())) @patch("cfn_sphere.util.Repo") def test_get_git_repository_remote_url_returns_repo_url_from_parent_dir(self, repo_mock): url = "http://config.repo.git" repo_object_mock = Mock() repo_object_mock.remotes.origin.url = url repo_mock.side_effect = [InvalidGitRepositoryError, repo_object_mock] self.assertEqual(url, util.get_git_repository_remote_url(tempfile.mkdtemp())) def test_get_git_repository_remote_url_returns_none_for_none_working_dir(self): self.assertEqual(None, util.get_git_repository_remote_url(None)) def test_get_git_repository_remote_url_returns_none_for_empty_string_working_dir(self): self.assertEqual(None, util.get_git_repository_remote_url("")) def test_kv_list_to_dict_returns_empty_dict_for_empty_list(self): result = util.kv_list_to_dict([]) self.assertEqual({}, result) def test_kv_list_to_dict(self): result = util.kv_list_to_dict(["k1=v1", "k2=v2"]) self.assertEqual({"k1": "v1", "k2": "v2"}, result) def test_kv_list_to_dict_raises_exception_on_syntax_error(self): with self.assertRaises(CfnSphereException): util.kv_list_to_dict(["k1=v1", "k2:v2"])
Java
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Basic tests for TF-TensorRT integration.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test from tensorflow.python.framework import dtypes from tensorflow.python.ops import array_ops from tensorflow.python.ops import math_ops from tensorflow.python.platform import test class ReshapeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): outputs = [] # Here we test two types of reshapes, one changes the batch dimension and # the other does not. Note that we're not able to test reshaping to # scalar, since TRT requires input tensor to be of rank at least 2, so a # reshape with scalar input will be filtered out of the segment before # conversion. # # These reshapes happen at batch dimension, thus conversion should fail. for shape in [[2, 50, 24, 24, 2], [-1, 50, 24, 24, 2], [2, 50, -1, 24, 2]]: incompatible_reshape = array_ops.reshape(inp, shape) reshape_back = array_ops.reshape(incompatible_reshape, [-1, 24, 24, 2]) outputs.append(self.trt_incompatible_op(reshape_back)) # Add another block with many reshapes that don't change the batch # dimension. compatible_reshape = array_ops.reshape( inp, [-1, 24 * 24, 2], name="reshape-0") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24, -1], name="reshape-1") compatible_reshape = array_ops.reshape( compatible_reshape, [100, 24 * 2, 24], name="reshape-2") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24 * 2], name="reshape-3") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 24, 2], name="reshape-4") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 6, 4, 6, 4, 2, 1], name="reshape-5") compatible_reshape = array_ops.reshape( compatible_reshape, [-1, 24, 24, 2], name="reshape-6") outputs.append(self.trt_incompatible_op(compatible_reshape)) return math_ops.add_n(outputs, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[100, 24, 24, 2]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_0": ["reshape-%d" % i for i in range(7)] + ["reshape-%d/shape" % i for i in range(7)] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) class TransposeTest(trt_test.TfTrtIntegrationTestBase): def GraphFn(self, inp): # Add a block with compatible transposes. compatible_transpose = array_ops.transpose( inp, [0, 3, 1, 2], name="transpose-1") compatible_transpose = array_ops.transpose( compatible_transpose, [0, 2, 3, 1], name="transposeback") # Add an incompatible op so the first block will not be in the same # subgraph where the following block belongs. bridge = self.trt_incompatible_op(compatible_transpose) # Add a block with incompatible transposes. # # Note: by default Grappler will run the TRT optimizer twice. At the # first time it will group the two transpose ops below to same segment # then fail the conversion due to the expected batch dimension problem. # At the second time, since the input of bridge op is TRTEngineOp_0, it # will fail to do shape inference which then cause conversion to fail. # TODO(laigd): support shape inference, make TRT optimizer run only # once, and fix this. incompatible_transpose = array_ops.transpose( bridge, [2, 1, 0, 3], name="transpose-2") excluded_transpose = array_ops.transpose( incompatible_transpose, [0, 2, 3, 1], name="transpose-3") return array_ops.identity(excluded_transpose, name="output_0") def GetParams(self): return self.BuildParams(self.GraphFn, dtypes.float32, [[100, 24, 24, 2]], [[24, 100, 2, 24]]) def ExpectedEnginesToBuild(self, run_params): """Return the expected engines to build.""" return { "TRTEngineOp_0": [ "transpose-1", "transpose-1/perm", "transposeback", "transposeback/perm" ] } def ShouldRunTest(self, run_params): """Whether to run the test.""" return (not trt_test.IsQuantizationMode(run_params.precision_mode) and not run_params.dynamic_engine) if __name__ == "__main__": test.main()
Java
-- -- Copyright 2009-2012 the original author or authors. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- drop table if exists users; create table users ( id int, name varchar(20) ); insert into users (id, name) values(1, 'User1'); insert into users (id, name) values(2, 'User2'); insert into users (id, name) values(3, 'User3');
Java
// Copyright 2018-2020 Authors of Cilium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package datapath import ( "net" "github.com/cilium/cilium/pkg/cidr" ) // NodeAddressingFamily is the node addressing information for a particular // address family type NodeAddressingFamily interface { // Router is the address that will act as the router on each node where // an agent is running on. Endpoints have a default route that points // to this address. Router() net.IP // PrimaryExternal is the primary external address of the node. Nodes // must be able to reach each other via this address. PrimaryExternal() net.IP // AllocationCIDR is the CIDR used for IP allocation of all endpoints // on the node AllocationCIDR() *cidr.CIDR // LocalAddresses lists all local addresses LocalAddresses() ([]net.IP, error) // LoadBalancerNodeAddresses lists all addresses on which HostPort and // NodePort services should be responded to LoadBalancerNodeAddresses() []net.IP } // NodeAddressing implements addressing of a node type NodeAddressing interface { IPv6() NodeAddressingFamily IPv4() NodeAddressingFamily }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.camel.component.huaweicloud.smn; import java.util.HashMap; import com.huaweicloud.sdk.core.auth.BasicCredentials; import com.huaweicloud.sdk.core.http.HttpConfig; import com.huaweicloud.sdk.smn.v2.SmnClient; import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequest; import com.huaweicloud.sdk.smn.v2.model.PublishMessageRequestBody; import com.huaweicloud.sdk.smn.v2.model.PublishMessageResponse; import org.apache.camel.Exchange; import org.apache.camel.component.huaweicloud.smn.constants.SmnConstants; import org.apache.camel.component.huaweicloud.smn.constants.SmnOperations; import org.apache.camel.component.huaweicloud.smn.constants.SmnProperties; import org.apache.camel.component.huaweicloud.smn.constants.SmnServices; import org.apache.camel.component.huaweicloud.smn.models.ClientConfigurations; import org.apache.camel.support.DefaultProducer; import org.apache.camel.util.ObjectHelper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SimpleNotificationProducer extends DefaultProducer { private static final Logger LOG = LoggerFactory.getLogger(SimpleNotificationProducer.class); private SmnClient smnClient; private ClientConfigurations clientConfigurations; public SimpleNotificationProducer(SimpleNotificationEndpoint endpoint) { super(endpoint); } @Override protected void doStart() throws Exception { super.doStart(); validateAndInitializeSmnClient((SimpleNotificationEndpoint) super.getEndpoint()); } public void process(Exchange exchange) throws Exception { String service = ((SimpleNotificationEndpoint) super.getEndpoint()).getSmnService(); if (!ObjectHelper.isEmpty(service)) { switch (service) { case SmnServices.PUBLISH_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Using message publishing service"); } performPublishMessageServiceOperations((SimpleNotificationEndpoint) super.getEndpoint(), exchange); if (LOG.isDebugEnabled()) { LOG.debug("Completed publishing message"); } break; default: if (LOG.isErrorEnabled()) { LOG.error("Unsupported service name {}", service); } throw new UnsupportedOperationException(String.format("service %s is not a supported service", service)); } } else { if (LOG.isErrorEnabled()) { LOG.error("Service name is null/empty"); } throw new IllegalStateException("service name cannot be null/empty"); } } /** * Publish message service operations * * @param endpoint * @param exchange */ private void performPublishMessageServiceOperations(SimpleNotificationEndpoint endpoint, Exchange exchange) { PublishMessageResponse response; PublishMessageRequestBody apiBody; this.clientConfigurations = validateServiceConfigurations(endpoint, exchange); if (LOG.isDebugEnabled()) { LOG.debug("Checking operation name"); } switch (clientConfigurations.getOperation()) { case SmnOperations.PUBLISH_AS_TEXT_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Publishing as text message"); } apiBody = new PublishMessageRequestBody() .withMessage(exchange.getMessage().getBody(String.class)) .withSubject(clientConfigurations.getSubject()) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())); response = smnClient.publishMessage(new PublishMessageRequest() .withBody(apiBody) .withTopicUrn(clientConfigurations.getTopicUrn())); break; case SmnOperations.PUBLISH_AS_TEMPLATED_MESSAGE: if (LOG.isDebugEnabled()) { LOG.debug("Publishing as templated message"); } apiBody = new PublishMessageRequestBody() .withMessage(exchange.getMessage().getBody(String.class)) .withSubject(clientConfigurations.getSubject()) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())) .withMessageTemplateName((String) exchange.getProperty(SmnProperties.TEMPLATE_NAME)) .withTags((HashMap<String, String>) exchange.getProperty(SmnProperties.TEMPLATE_TAGS)) .withTimeToLive(String.valueOf(clientConfigurations.getMessageTtl())); response = smnClient.publishMessage(new PublishMessageRequest() .withBody(apiBody) .withTopicUrn(clientConfigurations.getTopicUrn())); break; default: throw new UnsupportedOperationException( String.format("operation %s not supported in publishMessage service", clientConfigurations.getOperation())); } setResponseParameters(exchange, response); } /** * maps api response parameters as exchange property * * @param exchange * @param response */ private void setResponseParameters(Exchange exchange, PublishMessageResponse response) { if (response == null) { return; // mapping is not required if response object is null } if (!ObjectHelper.isEmpty(response.getMessageId())) { exchange.setProperty(SmnProperties.SERVICE_MESSAGE_ID, response.getMessageId()); } if (!ObjectHelper.isEmpty(response.getRequestId())) { exchange.setProperty(SmnProperties.SERVICE_REQUEST_ID, response.getRequestId()); } } /** * validation and initialization of SmnClient object * * @param simpleNotificationEndpoint */ private void validateAndInitializeSmnClient(SimpleNotificationEndpoint simpleNotificationEndpoint) { if (simpleNotificationEndpoint.getSmnClient() != null) { if (LOG.isWarnEnabled()) { LOG.warn( "Instance of SmnClient was set on the endpoint. Skipping creation of SmnClient from endpoint parameters"); } this.smnClient = simpleNotificationEndpoint.getSmnClient(); return; } this.clientConfigurations = new ClientConfigurations(); //checking for cloud SK (secret key) if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getSecretKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) { if (LOG.isErrorEnabled()) { LOG.error("secret key (SK) not found"); } throw new IllegalArgumentException("authentication parameter 'secret key (SK)' not found"); } else { clientConfigurations.setSecretKey(simpleNotificationEndpoint.getSecretKey() != null ? simpleNotificationEndpoint.getSecretKey() : simpleNotificationEndpoint.getServiceKeys().getSecretKey()); } //checking for cloud AK (auth key) if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getAuthKey()) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getServiceKeys())) { if (LOG.isErrorEnabled()) { LOG.error("authentication key (AK) not found"); } throw new IllegalArgumentException("authentication parameter 'authentication key (AK)' not found"); } else { clientConfigurations.setAuthenticationkey(simpleNotificationEndpoint.getAuthKey() != null ? simpleNotificationEndpoint.getAuthKey() : simpleNotificationEndpoint.getServiceKeys().getAuthenticationKey()); } //checking for project ID if (ObjectHelper.isEmpty(simpleNotificationEndpoint.getProjectId())) { if (LOG.isErrorEnabled()) { LOG.error("Project ID not found"); } throw new IllegalArgumentException("project ID not found"); } else { clientConfigurations.setProjectId(simpleNotificationEndpoint.getProjectId()); } //checking for region String endpointUrl = SimpleNotificationUtils.resolveSmnServiceEndpoint(simpleNotificationEndpoint.getRegion()); if (endpointUrl == null) { if (LOG.isErrorEnabled()) { LOG.error("Valid region not found"); } throw new IllegalArgumentException("enter a valid region"); } else { clientConfigurations.setServiceEndpoint(endpointUrl); } //checking for ignore ssl verification boolean ignoreSslVerification = simpleNotificationEndpoint.isIgnoreSslVerification(); if (ignoreSslVerification) { if (LOG.isWarnEnabled()) { LOG.warn("SSL verification is ignored. This is unsafe in production environment"); } clientConfigurations.setIgnoreSslVerification(ignoreSslVerification); } //checking if http proxy authentication is used if (simpleNotificationEndpoint.getProxyHost() != null) { if (LOG.isDebugEnabled()) { LOG.debug("Reading http proxy configurations"); } clientConfigurations.setProxyHost(simpleNotificationEndpoint.getProxyHost()); clientConfigurations.setProxyPort(simpleNotificationEndpoint.getProxyPort()); clientConfigurations.setProxyUser(simpleNotificationEndpoint.getProxyUser()); clientConfigurations.setProxyPassword(simpleNotificationEndpoint.getProxyPassword()); } this.smnClient = initializeClient(clientConfigurations); } /** * initialization of smn client. this is lazily initialized on the first message * * @param clientConfigurations * @return */ private SmnClient initializeClient(ClientConfigurations clientConfigurations) { if (LOG.isDebugEnabled()) { LOG.debug("Initializing Smn client"); } HttpConfig httpConfig = null; if (clientConfigurations.getProxyHost() != null) { httpConfig = HttpConfig.getDefaultHttpConfig(); httpConfig.withProxyHost(clientConfigurations.getProxyHost()) .withProxyPort(clientConfigurations.getProxyPort()) .setIgnoreSSLVerification(clientConfigurations.isIgnoreSslVerification()); if (clientConfigurations.getProxyUser() != null) { httpConfig.withProxyUsername(clientConfigurations.getProxyUser()); httpConfig.withProxyPassword(clientConfigurations.getProxyPassword()); } } BasicCredentials credentials = new BasicCredentials() .withAk(clientConfigurations.getAuthenticationkey()) .withSk(clientConfigurations.getSecretKey()) .withProjectId(clientConfigurations.getProjectId()); if (LOG.isDebugEnabled()) { LOG.debug("Building Smn client"); } // building smn client object SmnClient smnClient = SmnClient.newBuilder() .withCredential(credentials) .withHttpConfig(httpConfig) .withEndpoint(clientConfigurations.getServiceEndpoint()) .build(); if (LOG.isDebugEnabled()) { LOG.debug("Successfully initialized Smn client"); } return smnClient; } /** * validation of all user inputs before attempting to invoke a service operation * * @param simpleNotificationEndpoint * @param exchange * @return */ private ClientConfigurations validateServiceConfigurations( SimpleNotificationEndpoint simpleNotificationEndpoint, Exchange exchange) { ClientConfigurations clientConfigurations = new ClientConfigurations(); if (LOG.isDebugEnabled()) { LOG.debug("Inspecting exchange body"); } // verifying if exchange has valid body content. this is mandatory for 'publish as text' operation if (ObjectHelper.isEmpty(exchange.getMessage().getBody())) { if (simpleNotificationEndpoint.getOperation().equals("publishAsTextMessage")) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty body. Cannot perform publish as text operation"); } throw new IllegalArgumentException("exchange body cannot be null / empty"); } } // checking for mandatory field 'operation name' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting operation name"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.SMN_OPERATION)) && ObjectHelper.isEmpty(simpleNotificationEndpoint.getOperation())) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty operation name. Cannot proceed with Smn operations"); } throw new IllegalArgumentException("operation name not found"); } else { clientConfigurations.setOperation(exchange.getProperty(SmnProperties.SMN_OPERATION) != null ? (String) exchange.getProperty(SmnProperties.SMN_OPERATION) : simpleNotificationEndpoint.getOperation()); } // checking for mandatory field 'topic name' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting topic name"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME))) { if (LOG.isErrorEnabled()) { LOG.error("Found null/empty topic name"); } throw new IllegalArgumentException("topic name not found"); } else { clientConfigurations.setTopicUrn(String.format(SmnConstants.TOPIC_URN_FORMAT, simpleNotificationEndpoint.getRegion(), simpleNotificationEndpoint.getProjectId(), exchange.getProperty(SmnProperties.NOTIFICATION_TOPIC_NAME))); } // checking for optional field 'message subject' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting notification subject value"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT))) { if (LOG.isWarnEnabled()) { LOG.warn("notification subject not found. defaulting to 'DEFAULT_SUBJECT'"); } clientConfigurations.setSubject("DEFAULT_SUBJECT"); } else { clientConfigurations.setSubject((String) exchange.getProperty(SmnProperties.NOTIFICATION_SUBJECT)); } // checking for optional field 'message ttl' if (LOG.isDebugEnabled()) { LOG.debug("Inspecting TTL"); } if (ObjectHelper.isEmpty(exchange.getProperty(SmnProperties.NOTIFICATION_TTL))) { if (LOG.isWarnEnabled()) { LOG.warn("TTL not found. defaulting to default value {}", simpleNotificationEndpoint.getMessageTtl()); } clientConfigurations.setMessageTtl(simpleNotificationEndpoint.getMessageTtl()); } else { clientConfigurations.setMessageTtl((int) exchange.getProperty(SmnProperties.NOTIFICATION_TTL)); } return clientConfigurations; } }
Java
package com.zswxsqxt.wf.dao; import java.util.ArrayList; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Repository; import cn.org.rapid_framework.page.Page; import com.opendata.common.base.BaseHibernateDao; import com.zswxsqxt.wf.model.WfActivity; import com.zswxsqxt.wf.model.WfProject; import com.zswxsqxt.wf.query.WfActivityQuery; /** describe:流程节点表Dao */ @Repository public class WfActivityDao extends BaseHibernateDao<WfActivity,String> { public Class getEntityClass() { return WfActivity.class; } /** 通过WfActivityQuery对象,查询流程节点表 */ public Page findPage(WfActivityQuery query,int pageSize,int pageNum) { StringBuilder hql=new StringBuilder(); hql.append(" from WfActivity ett where 1=1"); List param=new ArrayList(); if(query!=null) { if(!StringUtils.isEmpty(query.getId())) { hql.append(" and ett.id=?"); param.add(query.getId()); } if(!StringUtils.isEmpty(query.getName())) { hql.append(" and ett.name like ?"); param.add("%"+query.getName()+"%"); } if(query.getOrderNum()!=null) { hql.append(" and ett.orderNum=?"); param.add(query.getOrderNum()); } if(query.getActType()!=null) { hql.append(" and ett.actType=?"); param.add(query.getActType()); } if(query.getActFlag()!=null) { hql.append(" and ett.actFlag=?"); param.add(query.getActFlag()); } if(!StringUtils.isEmpty(query.getDescription())) { hql.append(" and ett.description=?"); param.add(query.getDescription()); } if(!StringUtils.isEmpty(query.getUrl())) { hql.append(" and ett.url=?"); param.add(query.getUrl()); } if(!StringUtils.isEmpty(query.getGroupFlag())) { hql.append(" and ett.groupFlag=?"); param.add(query.getGroupFlag()); } if(!StringUtils.isEmpty(query.getExtFiled3())) { hql.append(" and ett.extFiled3=?"); param.add(query.getExtFiled3()); } if(query.getTs()!=null) { hql.append(" and ett.ts=?"); param.add(query.getTs()); } if(query.getWfProject()!=null) { hql.append(" and ett.wfProject.id=?"); param.add(query.getWfProject().getId()); } if(query.getWfInstance()!=null) { hql.append(" and ett.wfInstance=?"); param.add(query.getWfInstance()); } } if(!StringUtils.isEmpty(query.getSortColumns())){ if(!query.getSortColumns().equals("ts")){ hql.append(" order by ett."+query.getSortColumns()+" , ett.ts desc "); }else{ hql.append(" order by ett.orderNum asc "); } }else{ hql.append(" order by ett.orderNum asc "); } return super.findByHql(hql.toString(), pageSize, pageNum, param.toArray()); } /** * 根据流程id得到流程下所有节点,并按照节点顺序排序 * @param proId * @return */ public List<WfActivity> getWfActivity(String proId){ String hql = "from WfActivity where wfProject.id = ? order by orderNum asc"; List<WfActivity> list = super.findFastByHql(hql, proId); if(list.size()>0){ return list; }else{ return null; } } }
Java
/** * Copyright 2015-2016 Red Hat, Inc, and individual contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.wildfly.swarm.plugin.maven; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.StringTokenizer; import java.util.concurrent.TimeUnit; import java.util.function.Predicate; import java.util.stream.Collectors; import org.apache.maven.artifact.Artifact; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import org.eclipse.aether.repository.RemoteRepository; import org.wildfly.swarm.bootstrap.util.BootstrapProperties; import org.wildfly.swarm.fractionlist.FractionList; import org.wildfly.swarm.spi.api.SwarmProperties; import org.wildfly.swarm.tools.ArtifactSpec; import org.wildfly.swarm.tools.BuildTool; import org.wildfly.swarm.tools.DependencyManager; import org.wildfly.swarm.tools.FractionDescriptor; import org.wildfly.swarm.tools.FractionUsageAnalyzer; import org.wildfly.swarm.tools.exec.SwarmExecutor; import org.wildfly.swarm.tools.exec.SwarmProcess; /** * @author Bob McWhirter * @author Ken Finnigan */ @Mojo(name = "start", requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME, requiresDependencyCollection = ResolutionScope.COMPILE_PLUS_RUNTIME) public class StartMojo extends AbstractSwarmMojo { @Parameter(alias = "stdoutFile", property = "swarm.stdout") public File stdoutFile; @Parameter(alias = "stderrFile", property = "swarm.stderr" ) public File stderrFile; @Parameter(alias = "useUberJar", defaultValue = "${wildfly-swarm.useUberJar}") public boolean useUberJar; @Parameter(alias = "debug", property = SwarmProperties.DEBUG_PORT) public Integer debugPort; @Parameter(alias = "jvmArguments", property = "swarm.jvmArguments") public List<String> jvmArguments = new ArrayList<>(); @Parameter(alias = "arguments" ) public List<String> arguments = new ArrayList<>(); @Parameter(property = "swarm.arguments", defaultValue = "") public String argumentsProp; boolean waitForProcess; @SuppressWarnings({"unchecked", "ThrowableResultOfMethodCallIgnored"}) @Override public void execute() throws MojoExecutionException, MojoFailureException { initProperties(true); initEnvironment(); final SwarmExecutor executor; if (this.useUberJar) { executor = uberJarExecutor(); } else if (this.project.getPackaging().equals("war")) { executor = warExecutor(); } else if (this.project.getPackaging().equals("jar")) { executor = jarExecutor(); } else { throw new MojoExecutionException("Unsupported packaging: " + this.project.getPackaging()); } executor.withJVMArguments( this.jvmArguments ); if ( this.argumentsProp != null ) { StringTokenizer args = new StringTokenizer(this.argumentsProp); while ( args.hasMoreTokens() ) { this.arguments.add( args.nextToken() ); } } executor.withArguments( this.arguments ); final SwarmProcess process; try { process = executor.withDebug(debugPort) .withProperties(this.properties) .withStdoutFile(this.stdoutFile != null ? this.stdoutFile.toPath() : null) .withStderrFile(this.stderrFile != null ? this.stderrFile.toPath() : null) .withEnvironment(this.environment) .withWorkingDirectory(this.project.getBasedir().toPath()) .withProperty("remote.maven.repo", String.join(",", this.project.getRemoteProjectRepositories().stream() .map(RemoteRepository::getUrl) .collect(Collectors.toList()))) .execute(); Runtime.getRuntime().addShutdownHook( new Thread(()->{ try { // Sleeping for a few millis will give time to shutdown gracefully Thread.sleep(100L); process.stop( 10, TimeUnit.SECONDS ); } catch (InterruptedException e) { } })); process.awaitReadiness(2, TimeUnit.MINUTES); if (!process.isAlive()) { throw new MojoFailureException("Process failed to start"); } if (process.getError() != null) { throw new MojoFailureException("Error starting process", process.getError()); } } catch (IOException e) { throw new MojoFailureException("unable to execute", e); } catch (InterruptedException e) { throw new MojoFailureException("Error waiting for deployment", e); } List<SwarmProcess> procs = (List<SwarmProcess>) getPluginContext().get("swarm-process"); if (procs == null) { procs = new ArrayList<>(); getPluginContext().put("swarm-process", procs); } procs.add(process); if (waitForProcess) { try { process.waitFor(); } catch (InterruptedException e) { try { process.stop( 10, TimeUnit.SECONDS ); } catch (InterruptedException ie) { // Do nothing } } finally { process.destroyForcibly(); } } } protected SwarmExecutor uberJarExecutor() throws MojoFailureException { getLog().info("Starting -swarm.jar"); String finalName = this.project.getBuild().getFinalName(); if (finalName.endsWith(".war") || finalName.endsWith(".jar")) { finalName = finalName.substring(0, finalName.length() - 4); } return new SwarmExecutor() .withExecutableJar(Paths.get(this.projectBuildDir, finalName + "-swarm.jar")); } protected SwarmExecutor warExecutor() throws MojoFailureException { getLog().info("Starting .war"); String finalName = this.project.getBuild().getFinalName(); if (!finalName.endsWith(".war")) { finalName = finalName + ".war"; } return executor(Paths.get(this.projectBuildDir, finalName), finalName, false); } protected SwarmExecutor jarExecutor() throws MojoFailureException { getLog().info("Starting .jar"); final String finalName = this.project.getBuild().getFinalName(); return executor(Paths.get(this.project.getBuild().getOutputDirectory()), finalName.endsWith(".jar") ? finalName : finalName + ".jar", true); } protected SwarmExecutor executor(final Path appPath, final String name, final boolean scanDependencies) throws MojoFailureException { final SwarmExecutor executor = new SwarmExecutor() .withModules(expandModules()) .withProperty(BootstrapProperties.APP_NAME, name) .withClassPathEntries(dependencies(appPath, scanDependencies)); if (this.mainClass != null) { executor.withMainClass(this.mainClass); } else { executor.withDefaultMainClass(); } return executor; } List<Path> findNeededFractions(final Set<Artifact> existingDeps, final Path source, final boolean scanDeps) throws MojoFailureException { getLog().info("Scanning for needed WildFly Swarm fractions with mode: " + fractionDetectMode); final Set<String> existingDepGASet = existingDeps.stream() .map(d -> String.format("%s:%s", d.getGroupId(), d.getArtifactId())) .collect(Collectors.toSet()); final Set<FractionDescriptor> fractions; final FractionUsageAnalyzer analyzer = new FractionUsageAnalyzer(FractionList.get()).source(source); if (scanDeps) { existingDeps.forEach(d -> analyzer.source(d.getFile())); } final Predicate<FractionDescriptor> notExistingDep = d -> !existingDepGASet.contains(String.format("%s:%s", d.getGroupId(), d.getArtifactId())); try { fractions = analyzer.detectNeededFractions().stream() .filter(notExistingDep) .collect(Collectors.toSet()); } catch (IOException e) { throw new MojoFailureException("failed to scan for fractions", e); } getLog().info("Detected fractions: " + String.join(", ", fractions.stream() .map(FractionDescriptor::av) .sorted() .collect(Collectors.toList()))); fractions.addAll(this.additionalFractions.stream() .map(f -> FractionDescriptor.fromGav(FractionList.get(), f)) .collect(Collectors.toSet())); final Set<FractionDescriptor> allFractions = new HashSet<>(fractions); allFractions.addAll(fractions.stream() .flatMap(f -> f.getDependencies().stream()) .filter(notExistingDep) .collect(Collectors.toSet())); getLog().info("Using fractions: " + String.join(", ", allFractions.stream() .map(FractionDescriptor::gavOrAv) .sorted() .collect(Collectors.toList()))); final Set<ArtifactSpec> specs = new HashSet<>(); specs.addAll(existingDeps.stream() .map(this::artifactToArtifactSpec) .collect(Collectors.toList())); specs.addAll(allFractions.stream() .map(FractionDescriptor::toArtifactSpec) .collect(Collectors.toList())); try { return mavenArtifactResolvingHelper().resolveAll(specs).stream() .map(s -> s.file.toPath()) .collect(Collectors.toList()); } catch (Exception e) { throw new MojoFailureException("failed to resolve fraction dependencies", e); } } List<Path> dependencies(final Path archiveContent, final boolean scanDependencies) throws MojoFailureException { final List<Path> elements = new ArrayList<>(); final Set<Artifact> artifacts = this.project.getArtifacts(); boolean hasSwarmDeps = false; for (Artifact each : artifacts) { if (each.getGroupId().equals(DependencyManager.WILDFLY_SWARM_GROUP_ID) && each.getArtifactId().equals(DependencyManager.WILDFLY_SWARM_BOOTSTRAP_ARTIFACT_ID)) { hasSwarmDeps = true; } if (each.getGroupId().equals("org.jboss.logmanager") && each.getArtifactId().equals("jboss-logmanager")) { continue; } if (each.getScope().equals("provided")) { continue; } elements.add(each.getFile().toPath()); } elements.add(Paths.get(this.project.getBuild().getOutputDirectory())); if (fractionDetectMode != BuildTool.FractionDetectionMode.never) { if (fractionDetectMode == BuildTool.FractionDetectionMode.force || !hasSwarmDeps) { List<Path> fractionDeps = findNeededFractions(artifacts, archiveContent, scanDependencies); for(Path p : fractionDeps) { if(!elements.contains(p)) elements.add(p); } } } else if (!hasSwarmDeps) { getLog().warn("No WildFly Swarm dependencies found and fraction detection disabled"); } return elements; } List<Path> expandModules() { return this.additionalModules.stream() .map(m -> Paths.get(this.project.getBuild().getOutputDirectory(), m)) .collect(Collectors.toList()); } }
Java
from O365 import attachment import unittest import json import base64 from random import randint att_rep = open('attachment.json','r').read() att_j = json.loads(att_rep) class TestAttachment (unittest.TestCase): def setUp(self): self.att = attachment.Attachment(att_j['value'][0]) def test_isType(self): self.assertTrue(self.att.isType('txt')) def test_getType(self): self.assertEqual(self.att.getType(),'.txt') def test_save(self): name = self.att.json['Name'] name1 = self.newFileName(name) self.att.json['Name'] = name1 self.assertTrue(self.att.save('/tmp')) with open('/tmp/'+name1,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) name2 = self.newFileName(name) self.att.json['Name'] = name2 self.assertTrue(self.att.save('/tmp/')) with open('/tmp/'+name2,'r') as ins: f = ins.read() self.assertEqual('testing w00t!',f) def newFileName(self,val): for i in range(4): val = str(randint(0,9)) + val return val def test_getByteString(self): self.assertEqual(self.att.getByteString(),b'testing w00t!') def test_getBase64(self): self.assertEqual(self.att.getBase64(),'dGVzdGluZyB3MDB0IQ==\n') def test_setByteString(self): test_string = b'testing testie test' self.att.setByteString(test_string) enc = base64.encodebytes(test_string) self.assertEqual(self.att.json['ContentBytes'],enc) def setBase64(self): wrong_test_string = 'I am sooooo not base64 encoded.' right_test_string = 'Base64 <3 all around!' enc = base64.encodestring(right_test_string) self.assertRaises(self.att.setBase64(wrong_test_string)) self.assertEqual(self.att.json['ContentBytes'],'dGVzdGluZyB3MDB0IQ==\n') self.att.setBase64(enc) self.assertEqual(self.att.json['ContentBytes'],enc) if __name__ == '__main__': unittest.main()
Java
/* * Copyright (C) 2007-2015 Peter Monks. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of an unsupported extension to Alfresco. * */ package org.alfresco.extension.bulkimport.source.fs; import java.io.File; import java.math.BigDecimal; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.SortedMap; import java.util.TreeMap; import java.util.TreeSet; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.alfresco.repo.content.ContentStore; import org.alfresco.service.ServiceRegistry; import org.alfresco.util.Pair; import org.alfresco.extension.bulkimport.source.BulkImportSourceStatus; import static org.alfresco.extension.bulkimport.util.LogUtils.*; import static org.alfresco.extension.bulkimport.source.fs.FilesystemSourceUtils.*; /** * This interface defines a directory analyser. This is the process by which * the contents of a source directory are grouped together into a list of * <code>FilesystemBulkImportItem</code>s. * * @author Peter Monks ([email protected]) */ public final class DirectoryAnalyser { private final static Log log = LogFactory.getLog(DirectoryAnalyser.class); // Status counters private final static String COUNTER_NAME_FILES_SCANNED = "Files scanned"; private final static String COUNTER_NAME_DIRECTORIES_SCANNED = "Directories scanned"; private final static String COUNTER_NAME_UNREADABLE_ENTRIES = "Unreadable entries"; private final static String[] COUNTER_NAMES = { COUNTER_NAME_FILES_SCANNED, COUNTER_NAME_DIRECTORIES_SCANNED, COUNTER_NAME_UNREADABLE_ENTRIES }; private final ServiceRegistry serviceRegistry; private final ContentStore configuredContentStore; private final MetadataLoader metadataLoader; private BulkImportSourceStatus importStatus; public DirectoryAnalyser(final ServiceRegistry serviceRegistry, final ContentStore configuredContentStore, final MetadataLoader metadataLoader) { // PRECONDITIONS assert serviceRegistry != null : "serviceRegistry must not be null."; assert configuredContentStore != null : "configuredContentStore must not be null."; assert metadataLoader != null : "metadataLoader must not be null."; assert importStatus != null : "importStatus must not be null."; // Body this.serviceRegistry = serviceRegistry; this.configuredContentStore = configuredContentStore; this.metadataLoader = metadataLoader; } public void init(final BulkImportSourceStatus importStatus) { this.importStatus = importStatus; importStatus.preregisterSourceCounters(COUNTER_NAMES); } /** * Analyses the given directory. * * @param sourceDirectory The source directory for the entire import (note: <u>must</u> be a directory) <i>(must not be null)</i>. * @param directory The directory to analyse (note: <u>must</u> be a directory) <i>(must not be null)</i>. * @return An <code>AnalysedDirectory</code> object <i>(will not be null)</i>. * @throws InterruptedException If the thread executing the method is interrupted. */ public Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> analyseDirectory(final File sourceDirectory, final File directory) throws InterruptedException { // PRECONDITIONS if (sourceDirectory == null) throw new IllegalArgumentException("sourceDirectory cannot be null."); if (directory == null) throw new IllegalArgumentException("directory cannot be null."); // Body if (debug(log)) debug(log, "Analysing directory " + getFileName(directory) + "..."); Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; File[] directoryListing = null; long analysisStart = 0L; long analysisEnd = 0L; long start = 0L; long end = 0L; String sourceRelativeParentDirectory = sourceDirectory.toPath().relativize(directory.toPath()).toString(); // Note: JDK 1.7 specific // List the directory start = System.nanoTime(); analysisStart = start; directoryListing = directory.listFiles(); end = System.nanoTime(); if (trace(log)) trace(log, "List directory (" + directoryListing.length + " entries) took: " + (float)(end - start) / (1000 * 1000 * 1000) + "s."); // Build up the list of items from the directory listing start = System.nanoTime(); result = analyseDirectory(sourceRelativeParentDirectory, directoryListing); end = System.nanoTime(); if (trace(log)) trace(log, "Convert directory listing to set of filesystem import items took: " + (float)(end - start) / (1000 * 1000 * 1000) + "s."); analysisEnd = end; if (debug(log)) debug(log, "Finished analysing directory " + getFileName(directory) + ", in " + (float)(analysisEnd - analysisStart) / (1000 * 1000 * 1000) + "s."); return(result); } private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> analyseDirectory(final String sourceRelativeParentDirectory, final File[] directoryListing) { Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; if (directoryListing != null) { // This needs some Clojure, desperately... Map<String, SortedMap<BigDecimal, Pair<File, File>>> categorisedFiles = categoriseFiles(directoryListing); if (debug(log)) debug(log, "Categorised files: " + String.valueOf(categorisedFiles)); result = constructImportItems(sourceRelativeParentDirectory, categorisedFiles); } return(result); } private Map<String, SortedMap<BigDecimal, Pair<File, File>>> categoriseFiles(final File[] directoryListing) { Map<String, SortedMap<BigDecimal, Pair<File, File>>> result = null; if (directoryListing != null) { result = new HashMap<String, SortedMap<BigDecimal, Pair<File, File>>>(); for (final File file : directoryListing) { categoriseFile(result, file); } } return(result); } /* * This method does the hard work of figuring out where the file belongs (which parent item, and where in that item's * version history). */ private void categoriseFile(final Map<String, SortedMap<BigDecimal, Pair<File, File>>> categorisedFiles, final File file) { if (file != null) { if (file.canRead()) { final String fileName = file.getName(); final String parentName = getParentName(metadataLoader, fileName); final boolean isMetadata = isMetadataFile(metadataLoader, fileName); final BigDecimal versionNumber = getVersionNumber(fileName); SortedMap<BigDecimal, Pair<File, File>> versions = categorisedFiles.get(parentName); // Find the item if (versions == null) { versions = new TreeMap<BigDecimal, Pair<File, File>>(); categorisedFiles.put(parentName, versions); } // Find the version within the item Pair<File, File> version = versions.get(versionNumber); if (version == null) { version = new Pair<File, File>(null, null); } // Categorise the incoming file in that version of the item if (isMetadata) { version = new Pair<File, File>(version.getFirst(), file); } else { version = new Pair<File, File>(file, version.getSecond()); } versions.put(versionNumber, version); if (file.isDirectory()) { importStatus.incrementSourceCounter(COUNTER_NAME_DIRECTORIES_SCANNED); } else { importStatus.incrementSourceCounter(COUNTER_NAME_FILES_SCANNED); } } else { if (warn(log)) warn(log, "Skipping '" + getFileName(file) + "' as Alfresco does not have permission to read it."); importStatus.incrementSourceCounter(COUNTER_NAME_UNREADABLE_ENTRIES); } } } private Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> constructImportItems(final String sourceRelativeParentDirectory, final Map<String, SortedMap<BigDecimal,Pair<File,File>>> categorisedFiles) { Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>> result = null; if (categorisedFiles != null) { final List<FilesystemBulkImportItem> directoryItems = new ArrayList<FilesystemBulkImportItem>(); final List<FilesystemBulkImportItem> fileItems = new ArrayList<FilesystemBulkImportItem>(); result = new Pair<List<FilesystemBulkImportItem>, List<FilesystemBulkImportItem>>(directoryItems, fileItems); for (final String parentName : categorisedFiles.keySet()) { final SortedMap<BigDecimal,Pair<File,File>> itemVersions = categorisedFiles.get(parentName); final NavigableSet<FilesystemBulkImportItemVersion> versions = constructImportItemVersions(itemVersions); final boolean isDirectory = versions.last().isDirectory(); final FilesystemBulkImportItem item = new FilesystemBulkImportItem(parentName, isDirectory, sourceRelativeParentDirectory, versions); if (isDirectory) { directoryItems.add(item); } else { fileItems.add(item); } } } return(result); } private final NavigableSet<FilesystemBulkImportItemVersion> constructImportItemVersions(final SortedMap<BigDecimal,Pair<File,File>> itemVersions) { // PRECONDITIONS if (itemVersions == null) throw new IllegalArgumentException("itemVersions cannot be null."); if (itemVersions.size() <= 0) throw new IllegalArgumentException("itemVersions cannot be empty."); // Body final NavigableSet<FilesystemBulkImportItemVersion> result = new TreeSet<FilesystemBulkImportItemVersion>(); for (final BigDecimal versionNumber : itemVersions.keySet()) { final Pair<File,File> contentAndMetadataFiles = itemVersions.get(versionNumber); final FilesystemBulkImportItemVersion version = new FilesystemBulkImportItemVersion(serviceRegistry, configuredContentStore, metadataLoader, versionNumber, contentAndMetadataFiles.getFirst(), contentAndMetadataFiles.getSecond()); result.add(version); } return(result); } }
Java
# Change Log All releases of the BOSH CPI for Google Cloud Platform will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/). ## [30.0.0] - 2019-01-04 ### Added - MULTI_IP_SUBNET support in GCE ### Changed - Go 1.12 - BOSH API v2 ## [29.0.0] - 2019-01-04 ### Fixed - VM IP address is cleared when dynamic network is used ### Added - Logs are returned in response to BOSH, making them viewable in task log - If a disk is already attached to a VM, it will only be attached via the BOSH agent ## [28.0.1] - 2018-10-02 ### Fixed - Avoid keeping old golang installation files in GOROOT ## [28.0.0] - 2018-09-18 ### Added - Support for scheme agnostic backend services. - Made it possible to inject a Google client when testing. - Implement a Find Service for accelerator types. - Implements creation of VM with accelerator. - Support for Accelerator in Cloud Properties. - Support for CPI Config. ### Changed - Use Debian 9 in test infrastructure. - Avoid Sandy Bridge CPUs. - Use Go 1.9. - Update types to pointer where is needed. ### Fixed - Fixes for integration tests modifying the CPI request to include context necessary for the 'cpi-config'-enabled CPI. - Fixes for unit tests. ## [25.10.0] - 2017-08-17 ### Added - Google Cloud Storage is a supported blobstore backend ### Changed - Improved documentation to include the new BOSH CLI ## [25.9.0] - 2017-05-23 ### Fixed - Address inconsistent stream error: stream ID 1; PROTOCOL_ERROR errors in CPI calls by updating to Go 1.8.1 CI: ### Changed - Tests use proper custom backend - Add publish light-stemcell 3421 jobs ## [25.8.0] - 2017-05-16 ### Changed - Tags no longer become labels on GCP - Support XPN VPC Networks via the `xpn_host_project_id` cloud property - Support for customizing user agent strings - Publish CentOS Lite 3363.x, 3312.x, Ubuntu Alpha Lite stemcells - Docs: update ubuntu image for bosh-bastion - Docs: simplify grabbing project ID - Docs: add backend_service docs for internal load balancers ## [25.7.1] - 2017-03-07 ### Fixed - Previously, requests to Google APIs that returned 5xx response codes were retried. This change adds retry support to transport errors (net.Error) that are known to be temporary. ## [25.7.0] - 2017-03-03 ### Fixed - Various docs changes ### Changed - Labels may be specified in cloud properties - CF docs include TCP router - Use lateset Docker image in CIA - Support internal load balancer ## [25.6.2] - 2016-12-19 ### Fixed - Improve tests - Corrects MTU on garden job ### Changed - Support `ImageURL` for specifying stemcellA - Concourse docs incude SSL support - Docs require setting a password instead of using default ## [25.6.1] - 2016-11-02 ### Fixed - Handles large disk sizes ### Changed - CF docs run under free-tier quota - Integration tests can use local stemcell ## [25.6.0] - 2016-10-27 ### Changed - Supports `has_disk` method - Improvements to stemcell pipelines ## [25.5.0] - 2016-10-17 ### Changed - Release uses Go 1.7.1 ### Fixed - A backend service previously could not have multiple instance groups with the same name. This release fixes that, and you may have instance groups with the same name associated to a backend service. ## [25.4.1] - 2016-09-14 ### Fixed - Tags that are applied by the director on VM create will be truncated to ensure they do not violate the 63-char max limit imposed by GCE. ## [25.4.0] - 2016-09-14 ### Changed - When using a custom service account, a default `cloud-platform` scope is used if no custom scopes are specified. ## [25.3.0] - 2016-09-02 ### Added - S3 is now a supported blobstore type. ## [25.2.1] - 2016-08-18 ### Fixed - Underscores are replaced with hyphens in metadata that is applied as labels to a VM. ### Added - Complete Concourse installation instructions, including cloud config and Terraform. ## [25.2.0] - 2016-08-18 ### Changed - Any metadata provided by bosh in the `set_vm_metadata` action will also be propagated to the VM as [labels](https://cloud.google.com/compute/docs/label-or-tag-resources), allowing sorting and filter in the web console based on job, deployment, etc. ## [25.1.0] - 2016-08-18 ### Added - The `service_account` cloud-config property may now use the e-mail address of a custom service account. ## [25.0.0] - 2016-07-25 ### Changed - The `default_zone` config property (in the `google` section of a manifest) is no longer supported. The `zone` property must be explicitly set in the `cloud_properties` section of `resource_pools` (or `azs` for a cloud-config director.) ## [24.4.0] - 2016-07-25 ### Fixed - An explicit region is used to locate a subnet, allowing subnets with the same name to be differentiated. ## [24.3.0] - 2016-07-25 ### Added - A `resource_pool`'s manifest can now specify `ephemeral_external_ip` and `ip_forwarding` properties, overriding those same properties in a manifest's `networks` section. ## [24.2.0] - 2016-07-25 ### Added - This changelog ### Changed - 3262.4 stemcell ### Fixed - All tests now use light stemcells ## [24.1.0] - 2016-07-25 ### Changed - Instance tags can be specified in any `cloud_properties` section of a BOSH manifest ### Removed - The dummy BOSH release is no longer part of the CI pipeline ### Fixed - Integration tests will use the CI pipeline stemcell rather than requiring an existing stemcell in a project [30.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v29.0.1...v30.0.0 [29.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v28.0.1...v29.0.0 [28.0.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v28.0.0...v28.0.1 [25.10.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.9.0...v25.10.0 [25.9.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.8.0...v25.9.0 [25.8.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.7.1...v25.8.0 [25.7.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.7.0...v25.7.1 [25.7.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.2...v25.7.0 [25.6.2]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.1...v25.6.2 [25.6.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.6.0...v25.6.1 [25.6.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.5.0...v25.6.0 [25.5.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.4.1...v25.5.0 [25.4.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.4.0...v25.4.1 [25.4.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.3.0...v25.4.0 [25.3.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.2.1...v25.3.0 [25.2.1]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.2.0...v25.2.1 [25.2.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.1.0...v25.2.0 [25.1.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v25.0.0...v25.1.0 [25.0.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.4.0...v25.0.0 [24.4.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.3.0...v24.4.0 [24.3.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.2.0...v24.3.0 [24.2.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24.1.0...v24.2.0 [24.1.0]: https://github.com/cloudfoundry-incubator/bosh-google-cpi-release/compare/v24...v24.1.0
Java
# Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS-IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Base model class.""" __author__ = 'Sean Lip' import feconf import utils from core.platform import models transaction_services = models.Registry.import_transaction_services() from google.appengine.ext import ndb class BaseModel(ndb.Model): """Base model for all persistent object storage classes.""" # When this entity was first created. created_on = ndb.DateTimeProperty(auto_now_add=True) # When this entity was last updated. last_updated = ndb.DateTimeProperty(auto_now=True) # Whether the current version of the file is deleted. deleted = ndb.BooleanProperty(indexed=True, default=False) @property def id(self): """A unique id for this model instance.""" return self.key.id() def _pre_put_hook(self): """This is run before model instances are saved to the datastore. Subclasses of BaseModel should override this method. """ pass class EntityNotFoundError(Exception): """Raised when no entity for a given id exists in the datastore.""" pass @classmethod def get(cls, entity_id, strict=True): """Gets an entity by id. Fails noisily if strict == True. Args: entity_id: str. The id of the entity. strict: bool. Whether to fail noisily if no entity with the given id exists in the datastore. Returns: None, if strict == False and no undeleted entity with the given id exists in the datastore. Otherwise, the entity instance that corresponds to the given id. Raises: - base_models.BaseModel.EntityNotFoundError: if strict == True and no undeleted entity with the given id exists in the datastore. """ entity = cls.get_by_id(entity_id) if entity and entity.deleted: entity = None if strict and entity is None: raise cls.EntityNotFoundError( 'Entity for class %s with id %s not found' % (cls.__name__, entity_id)) return entity def put(self): super(BaseModel, self).put() @classmethod def get_multi(cls, entity_ids): entity_keys = [ndb.Key(cls, entity_id) for entity_id in entity_ids] return ndb.get_multi(entity_keys) @classmethod def put_multi(cls, entities): return ndb.put_multi(entities) def delete(self): super(BaseModel, self).key.delete() @classmethod def get_all(cls, include_deleted_entities=False): """Returns a filterable iterable of all entities of this class. If include_deleted_entities is True then entities that have been marked deleted are returned as well. """ query = cls.query() if not include_deleted_entities: query = query.filter(cls.deleted == False) return query @classmethod def get_new_id(cls, entity_name): """Gets a new id for an entity, based on its name. The returned id is guaranteed to be unique among all instances of this entity. Args: entity_name: the name of the entity. Coerced to a utf-8 encoded string. Defaults to ''. Returns: str: a new unique id for this entity class. Raises: - Exception: if an id cannot be generated within a reasonable number of attempts. """ try: entity_name = unicode(entity_name).encode('utf-8') except Exception: entity_name = '' MAX_RETRIES = 10 RAND_RANGE = 127 * 127 ID_LENGTH = 12 for i in range(MAX_RETRIES): new_id = utils.convert_to_hash( '%s%s' % (entity_name, utils.get_random_int(RAND_RANGE)), ID_LENGTH) if not cls.get_by_id(new_id): return new_id raise Exception('New id generator is producing too many collisions.') class VersionedModel(BaseModel): """Model that handles storage of the version history of model instances. To use this class, you must declare a SNAPSHOT_METADATA_CLASS and a SNAPSHOT_CONTENT_CLASS. The former must contain the String fields 'committer_id', 'commit_type' and 'commit_message', and a JSON field for the Python list of dicts, 'commit_cmds'. The latter must contain the JSON field 'content'. The item that is being versioned must be serializable to a JSON blob. Note that commit() should be used for VersionedModels, as opposed to put() for direct subclasses of BaseModel. """ # The class designated as the snapshot model. This should be a subclass of # BaseSnapshotMetadataModel. SNAPSHOT_METADATA_CLASS = None # The class designated as the snapshot content model. This should be a # subclass of BaseSnapshotContentModel. SNAPSHOT_CONTENT_CLASS = None # Whether reverting is allowed. Default is False. ALLOW_REVERT = False ### IMPORTANT: Subclasses should only overwrite things above this line. ### # The possible commit types. _COMMIT_TYPE_CREATE = 'create' _COMMIT_TYPE_REVERT = 'revert' _COMMIT_TYPE_EDIT = 'edit' _COMMIT_TYPE_DELETE = 'delete' # A list containing the possible commit types. COMMIT_TYPE_CHOICES = [ _COMMIT_TYPE_CREATE, _COMMIT_TYPE_REVERT, _COMMIT_TYPE_EDIT, _COMMIT_TYPE_DELETE ] # The delimiter used to separate the version number from the model instance # id. To get the instance id from a snapshot id, use Python's rfind() # method to find the location of this delimiter. _VERSION_DELIMITER = '-' # The reserved prefix for keys that are automatically inserted into a # commit_cmd dict by this model. _AUTOGENERATED_PREFIX = 'AUTO' # The current version number of this instance. In each PUT operation, # this number is incremented and a snapshot of the modified instance is # stored in the snapshot metadata and content models. The snapshot # version number starts at 1 when the model instance is first created. # All data in this instance represents the version at HEAD; data about the # previous versions is stored in the snapshot models. version = ndb.IntegerProperty(default=0) def _require_not_marked_deleted(self): if self.deleted: raise Exception('This model instance has been deleted.') def _compute_snapshot(self): """Generates a snapshot (a Python dict) from the model fields.""" return self.to_dict(exclude=['created_on', 'last_updated']) def _reconstitute(self, snapshot_dict): """Makes this instance into a reconstitution of the given snapshot.""" self.populate(**snapshot_dict) return self def _reconstitute_from_snapshot_id(self, snapshot_id): """Makes this instance into a reconstitution of the given snapshot.""" snapshot_model = self.SNAPSHOT_CONTENT_CLASS.get(snapshot_id) snapshot_dict = snapshot_model.content return self._reconstitute(snapshot_dict) @classmethod def _get_snapshot_id(cls, instance_id, version_number): return '%s%s%s' % ( instance_id, cls._VERSION_DELIMITER, version_number) def _trusted_commit( self, committer_id, commit_type, commit_message, commit_cmds): if self.SNAPSHOT_METADATA_CLASS is None: raise Exception('No snapshot metadata class defined.') if self.SNAPSHOT_CONTENT_CLASS is None: raise Exception('No snapshot content class defined.') if not isinstance(commit_cmds, list): raise Exception( 'Expected commit_cmds to be a list of dicts, received %s' % commit_cmds) for item in commit_cmds: if not isinstance(item, dict): raise Exception( 'Expected commit_cmds to be a list of dicts, received %s' % commit_cmds) self.version += 1 snapshot = self._compute_snapshot() snapshot_id = self._get_snapshot_id(self.id, self.version) snapshot_metadata_instance = self.SNAPSHOT_METADATA_CLASS( id=snapshot_id, committer_id=committer_id, commit_type=commit_type, commit_message=commit_message, commit_cmds=commit_cmds) snapshot_content_instance = self.SNAPSHOT_CONTENT_CLASS( id=snapshot_id, content=snapshot) transaction_services.run_in_transaction( ndb.put_multi, [snapshot_metadata_instance, snapshot_content_instance, self]) def delete(self, committer_id, commit_message, force_deletion=False): if force_deletion: current_version = self.version version_numbers = [str(num + 1) for num in range(current_version)] snapshot_ids = [ self._get_snapshot_id(self.id, version_number) for version_number in version_numbers] metadata_keys = [ ndb.Key(self.SNAPSHOT_METADATA_CLASS, snapshot_id) for snapshot_id in snapshot_ids] ndb.delete_multi(metadata_keys) content_keys = [ ndb.Key(self.SNAPSHOT_CONTENT_CLASS, snapshot_id) for snapshot_id in snapshot_ids] ndb.delete_multi(content_keys) super(VersionedModel, self).delete() else: self._require_not_marked_deleted() self.deleted = True CMD_DELETE = '%s_mark_deleted' % self._AUTOGENERATED_PREFIX commit_cmds = [{ 'cmd': CMD_DELETE }] self._trusted_commit( committer_id, self._COMMIT_TYPE_DELETE, commit_message, commit_cmds) def put(self, *args, **kwargs): """For VersionedModels, this method is replaced with commit().""" raise NotImplementedError def commit(self, committer_id, commit_message, commit_cmds): """Saves a version snapshot and updates the model. commit_cmds should give sufficient information to reconstruct the commit. """ self._require_not_marked_deleted() for commit_cmd in commit_cmds: if 'cmd' not in commit_cmd: raise Exception( 'Invalid commit_cmd: %s. Expected a \'cmd\' key.' % commit_cmd) if commit_cmd['cmd'].startswith(self._AUTOGENERATED_PREFIX): raise Exception( 'Invalid change list command: ' % commit_cmd['cmd']) commit_type = ( self._COMMIT_TYPE_CREATE if self.version == 0 else self._COMMIT_TYPE_EDIT) self._trusted_commit( committer_id, commit_type, commit_message, commit_cmds) def revert(self, committer_id, commit_message, version_number): self._require_not_marked_deleted() if not self.ALLOW_REVERT: raise Exception( 'Reverting of objects of type %s is not allowed.' % self.__class__.__name__) CMD_REVERT = '%s_revert_version_number' % self._AUTOGENERATED_PREFIX commit_cmds = [{ 'cmd': CMD_REVERT, 'version_number': version_number }] # Do not overwrite the version number. current_version = self.version snapshot_id = self._get_snapshot_id(self.id, version_number) self._reconstitute_from_snapshot_id(snapshot_id) self.version = current_version self._trusted_commit( committer_id, self._COMMIT_TYPE_REVERT, commit_message, commit_cmds) @classmethod def get_version(cls, model_instance_id, version_number): """Returns a model instance representing the given version. The snapshot content is used to populate this model instance. The snapshot metadata is not used. """ cls.get(model_instance_id)._require_not_marked_deleted() snapshot_id = cls._get_snapshot_id(model_instance_id, version_number) return cls(id=model_instance_id)._reconstitute_from_snapshot_id( snapshot_id) @classmethod def get(cls, entity_id, strict=True, version=None): """Gets an entity by id. Fails noisily if strict == True.""" if version is None: return super(VersionedModel, cls).get(entity_id, strict=strict) else: return cls.get_version(entity_id, version) @classmethod def get_snapshots_metadata(cls, model_instance_id, version_numbers): """Returns a list of dicts, each representing a model snapshot. One dict is returned for each version number in the list of version numbers requested. If any of the version numbers does not exist, an error is raised. """ cls.get(model_instance_id)._require_not_marked_deleted() snapshot_ids = [ cls._get_snapshot_id(model_instance_id, version_number) for version_number in version_numbers] metadata_keys = [ ndb.Key(cls.SNAPSHOT_METADATA_CLASS, snapshot_id) for snapshot_id in snapshot_ids] returned_models = ndb.get_multi(metadata_keys) for ind, model in enumerate(returned_models): if model is None: raise Exception( 'Invalid version number %s for model %s with id %s' % (version_numbers[ind], cls.__name__, model_instance_id)) return [{ 'committer_id': model.committer_id, 'commit_message': model.commit_message, 'commit_cmds': model.commit_cmds, 'commit_type': model.commit_type, 'version_number': version_numbers[ind], 'created_on': model.created_on.strftime( feconf.HUMAN_READABLE_DATETIME_FORMAT), } for (ind, model) in enumerate(returned_models)] class BaseSnapshotMetadataModel(BaseModel): """Base class for snapshot metadata classes. The id of this model is computed using VersionedModel.get_snapshot_id(). """ # The id of the user who committed this revision. committer_id = ndb.StringProperty(required=True) # The type of the commit associated with this snapshot. commit_type = ndb.StringProperty( required=True, choices=VersionedModel.COMMIT_TYPE_CHOICES) # The commit message associated with this snapshot. commit_message = ndb.TextProperty(indexed=False) # A sequence of commands that can be used to describe this commit. # Represented as a list of dicts. commit_cmds = ndb.JsonProperty(indexed=False) class BaseSnapshotContentModel(BaseModel): """Base class for snapshot content classes. The id of this model is computed using VersionedModel.get_snapshot_id(). """ # The snapshot content, as a JSON blob. content = ndb.JsonProperty(indexed=False)
Java
using TestMonkeys.EntityTest.Framework; namespace UsageExample.PropertySetValidatorTests.TestObjects { public class TestObjectImproperGreaterThan { [ValidateActualGreaterThan(0)] public object GreaterThanValue { get; set; } } }
Java
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Tpu.V1.Snippets { // [START tpu_v1_generated_Tpu_CreateNode_async] using Google.Api.Gax.ResourceNames; using Google.Cloud.Tpu.V1; using Google.LongRunning; using System.Threading.Tasks; public sealed partial class GeneratedTpuClientSnippets { /// <summary>Snippet for CreateNodeAsync</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public async Task CreateNodeRequestObjectAsync() { // Create client TpuClient tpuClient = await TpuClient.CreateAsync(); // Initialize request argument(s) CreateNodeRequest request = new CreateNodeRequest { ParentAsLocationName = LocationName.FromProjectLocation("[PROJECT]", "[LOCATION]"), NodeId = "", Node = new Node(), }; // Make the request Operation<Node, OperationMetadata> response = await tpuClient.CreateNodeAsync(request); // Poll until the returned long-running operation is complete Operation<Node, OperationMetadata> completedResponse = await response.PollUntilCompletedAsync(); // Retrieve the operation result Node result = completedResponse.Result; // Or get the name of the operation string operationName = response.Name; // This name can be stored, then the long-running operation retrieved later by name Operation<Node, OperationMetadata> retrievedResponse = await tpuClient.PollOnceCreateNodeAsync(operationName); // Check if the retrieved long-running operation has completed if (retrievedResponse.IsCompleted) { // If it has completed, then access the result Node retrievedResult = retrievedResponse.Result; } } } // [END tpu_v1_generated_Tpu_CreateNode_async] }
Java
/* * Copyright 2015-2018 Jeeva Kandasamy ([email protected]) * and other contributors as indicated by the @author tags. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.mycontroller.standalone.api.jaxrs.mixins.deserializers; import java.io.IOException; import org.mycontroller.standalone.timer.TimerUtils.FREQUENCY_TYPE; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; /** * @author Jeeva Kandasamy (jkandasa) * @since 0.0.2 */ public class FrequencyTypeDeserializer extends JsonDeserializer<FREQUENCY_TYPE> { @Override public FREQUENCY_TYPE deserialize(JsonParser parser, DeserializationContext context) throws IOException, JsonProcessingException { final String nodeType = parser.getText(); if (nodeType != null) { return FREQUENCY_TYPE.fromString(nodeType); } else { return null; } } }
Java
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Linq; using System.Threading; using System.Threading.Tasks; using Roslyn.Test.Utilities; using Xunit; using LSP = Microsoft.VisualStudio.LanguageServer.Protocol; namespace Microsoft.CodeAnalysis.LanguageServer.UnitTests.Definitions { public class GoToDefinitionTests : AbstractLanguageServerProtocolTests { [Fact] public async Task TestGotoDefinitionAsync() { var markup = @"class A { string {|definition:aString|} = 'hello'; void M() { var len = {|caret:|}aString.Length; } }"; var (solution, locations) = CreateTestSolution(markup); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_DifferentDocument() { var markups = new string[] { @"namespace One { class A { public static int {|definition:aInt|} = 1; } }", @"namespace One { class B { int bInt = One.A.{|caret:|}aInt; } }" }; var (solution, locations) = CreateTestSolution(markups); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); AssertLocationsEqual(locations["definition"], results); } [Fact] public async Task TestGotoDefinitionAsync_InvalidLocation() { var markup = @"class A { void M() {{|caret:|} var len = aString.Length; } }"; var (solution, locations) = CreateTestSolution(markup); var results = await RunGotoDefinitionAsync(solution, locations["caret"].Single()); Assert.Empty(results); } private static async Task<LSP.Location[]> RunGotoDefinitionAsync(Solution solution, LSP.Location caret) => (LSP.Location[])await GetLanguageServer(solution).GoToDefinitionAsync(solution, CreateTextDocumentPositionParams(caret), new LSP.ClientCapabilities(), CancellationToken.None); } }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.mskcc.shenkers.data.interval; import htsjdk.tribble.Feature; import htsjdk.tribble.annotation.Strand; import htsjdk.tribble.bed.FullBEDFeature; import java.awt.Color; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * * @author sol */ public interface IntervalFeature<T> extends Feature { Strand getStrand(); T getValue(); }
Java
/* fixed page header & footer configuration */ .ui-header-fixed, .ui-footer-fixed { left: 0; right: 0; width: 100%; position: fixed; z-index: 1000; } .ui-header-fixed { top: -1px; padding-top: 1px; } .ui-header-fixed.ui-fixed-hidden { top: 0; padding-top: 0; } .ui-header-fixed .ui-btn-left, .ui-header-fixed .ui-btn-right { margin-top: 1px; } .ui-header-fixed.ui-fixed-hidden .ui-btn-left, .ui-header-fixed.ui-fixed-hidden .ui-btn-right { margin-top: 0; } .ui-footer-fixed { bottom: -1px; padding-bottom: 1px; } .ui-footer-fixed.ui-fixed-hidden { bottom: 0; padding-bottom: 0; } .ui-header-fullscreen, .ui-footer-fullscreen { filter: Alpha(Opacity=90); opacity: .9; } /* updatePagePadding() will update the padding to actual height of header and footer. */ .ui-page-header-fixed { padding-top: 2.8125em; } .ui-page-footer-fixed { padding-bottom: 2.8125em; } .ui-page-header-fullscreen > .ui-content, .ui-page-footer-fullscreen > .ui-content { padding: 0; } .ui-fixed-hidden { position: absolute; } .ui-page-header-fullscreen .ui-fixed-hidden, .ui-page-footer-fullscreen .ui-fixed-hidden { position: absolute !important; height: 1px; width: 1px; overflow: hidden; clip: rect(1px,1px,1px,1px); } .ui-header-fixed .ui-btn, .ui-footer-fixed .ui-btn { z-index: 10; } /* workarounds for other widgets */ .ui-android-2x-fixed .ui-li-has-thumb { -webkit-transform: translate3d(0,0,0); }
Java
/*! @license * Shaka Player * Copyright 2016 Google LLC * SPDX-License-Identifier: Apache-2.0 */ goog.provide('shaka.ui.FastForwardButton'); goog.require('shaka.ui.Controls'); goog.require('shaka.ui.Element'); goog.require('shaka.ui.Enums'); goog.require('shaka.ui.Locales'); goog.require('shaka.ui.Localization'); goog.require('shaka.util.Dom'); /** * @extends {shaka.ui.Element} * @final * @export */ shaka.ui.FastForwardButton = class extends shaka.ui.Element { /** * @param {!HTMLElement} parent * @param {!shaka.ui.Controls} controls */ constructor(parent, controls) { super(parent, controls); /** @private {!HTMLButtonElement} */ this.button_ = shaka.util.Dom.createButton(); this.button_.classList.add('material-icons-round'); this.button_.classList.add('shaka-fast-forward-button'); this.button_.classList.add('shaka-tooltip-status'); this.button_.setAttribute('shaka-status', '1x'); this.button_.textContent = shaka.ui.Enums.MaterialDesignIcons.FAST_FORWARD; this.parent.appendChild(this.button_); this.updateAriaLabel_(); /** @private {!Array.<number>} */ this.fastForwardRates_ = this.controls.getConfig().fastForwardRates; this.eventManager.listen( this.localization, shaka.ui.Localization.LOCALE_UPDATED, () => { this.updateAriaLabel_(); }); this.eventManager.listen( this.localization, shaka.ui.Localization.LOCALE_CHANGED, () => { this.updateAriaLabel_(); }); this.eventManager.listen(this.button_, 'click', () => { this.fastForward_(); }); } /** * @private */ updateAriaLabel_() { this.button_.ariaLabel = this.localization.resolve(shaka.ui.Locales.Ids.FAST_FORWARD); } /** * Cycles trick play rate between the selected fast forward rates. * @private */ fastForward_() { if (!this.video.duration) { return; } const trickPlayRate = this.player.getPlaybackRate(); const newRateIndex = this.fastForwardRates_.indexOf(trickPlayRate) + 1; // When the button is clicked, the next rate in this.fastForwardRates_ is // selected. If no more rates are available, the first one is set. const newRate = (newRateIndex != this.fastForwardRates_.length) ? this.fastForwardRates_[newRateIndex] : this.fastForwardRates_[0]; this.player.trickPlay(newRate); this.button_.setAttribute('shaka-status', newRate + 'x'); } }; /** * @implements {shaka.extern.IUIElement.Factory} * @final */ shaka.ui.FastForwardButton.Factory = class { /** @override */ create(rootElement, controls) { return new shaka.ui.FastForwardButton(rootElement, controls); } }; shaka.ui.Controls.registerElement( 'fast_forward', new shaka.ui.FastForwardButton.Factory());
Java
# General Information for Windows This file describes how to install, or build, and use Julia on Windows. For more general information about Julia, please see the [main README](https://github.com/JuliaLang/julia/blob/master/README.md) or the [documentation](http://docs.julialang.org/). # Unicode font support The built-in Windows fonts have rather poor coverage of the Unicode character space. The free [`DejaVu Sans Mono`](http://dejavu-fonts.org/) font can be used as a replacement font in the Windows console. Since Windows 2000, simply downloading the font and installing it is insufficient, since Windows keeps a list of approved fonts in the registry. Instructions for adding fonts to the terminal are available at: [http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815](http://support.microsoft.com/default.aspx?scid=kb;EN-US;Q247815) Additionally, rather than sticking with the default command prompt, you may want to use a different terminal emulator program, such as [`Conemu`](https://code.google.com/p/conemu-maximus5/) or [`Mintty`](https://code.google.com/p/mintty/) (note that running Julia on Mintty needs a copy of `stty.exe` in your `%PATH%` to work properly). Alternatively, you may prefer the features of a more full-function IDE, such as [`LightTable`](https://github.com/one-more-minute/Jupiter-LT), [`Sublime-IJulia`](https://github.com/quinnj/Sublime-IJulia), [`IJulia`](https://github.com/JuliaLang/IJulia.jl), or [`Julia Studio`](http://forio.com/labs/julia-studio/). # Binary distribution Julia runs on Windows XP-SP2 and later (including Windows Vista, Windows 7, and Windows 8). Both the 32-bit and 64-bit versions are supported. The 32-bit (i686) binary will run on either a 32-bit and 64-bit operating system. The 64-bit (x86_64) binary will only run on 64-bit Windows and will otherwise refuse to launch. 1. Download and install [7-Zip](http://www.7-zip.org/download.html). Install the full program, not just the command line version. 2. [Download](http://julialang.org/downloads) the latest version of Julia. Extract the binary to a reasonable destination folder, e.g. `C:\julia`. 3. Double-click the file `julia.bat` to launch Julia. # Line endings Julia uses binary-mode files exclusively. Unlike many other Window's programs, if you write '\n' to a file, you get a '\n' in the file, not some other bit pattern. This matches the behavior exhibited by other operating systems. If you have installed msysGit, it is suggested, but not required, that you configure your system msysGit to use the same convention: git config --global core.eol = lf git config --global core.autocrlf = input or edit `%USERPROFILE%\.gitconfig` and add/edit the lines: [core] eol = lf autocrlf = input # Source distribution ## Supported build platforms - Windows 8: supported (32 and 64 bits) - Windows 7: supported (32 and 64 bits) - Windows Vista: unknown - Windows XP: not supported (however, there have been some reports of success following the msys2 steps) ## Compiling with MinGW/MSYS2 ### MSYS2 provides a robust MSYS experience. ### The instructions in this section were tested with the latest versions of all packages specified as of 2014-02-28. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC, as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: `x32` or `x64` as appropriate and desired. - Threads: `win32` (not posix) - Exception: `sjlj` (for x32) or `seh` (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path, for example, - `C:\mingw-builds\x64-4.8.1-win32-seh-rev5` for 64 bits - `C:\mingw-builds\x32-4.8.1-win32-sjlj-rev5` for 32 bits 4. Install and configure [MSYS2](http://sourceforge.net/projects/msys2), a minimal POSIX-like environment for Windows. 1. Download the latest base [32-bit](http://sourceforge.net/projects/msys2/files/Base/i686/) or [64-bit](http://sourceforge.net/projects/msys2/files/Base/x86_64/) distribution, consistent with the architecture you chose for MinGW-builds. The archive will have a name like `msys2-base-x86_64-yyyymmdd.tar.xz` and these instructions were tested with `msys2-base-x86_64-20140216.tar.xz`. 2. Using [7-Zip](http://www.7-zip.org/download.html), extract the archive to any convenient directory. - *N.B.* Some versions of this archive contain zero-byte files that clash with existing files. If prompted, choose **not** to overwrite existing files. - You may need to extract the tarball in a separate step. This will create an `msys32` or `msys64` directory, according to the architecture you chose. - Move the `msys32` or `msys64` directory into your MinGW-builds directory, which is `C:\mingw-builds` if you followed the suggestions in step 3. We will omit the "32" or "64" in the steps below and refer to this as "the msys directory". 3. Double-click `msys2_shell.bat` in the msys directory. This will initialize MSYS2. The shell will tell you to `exit` and restart the shell. For now, ignore it. 4. Update MSYS2 and install packages required to build julia, using the `pacman` package manager included in MSYS2: ``` pacman-key --init #Download keys pacman -Syu #Update package database and full system upgrade ``` Now `exit` the MSYS2 shell and restart it, *even if you already restarted it above*. This is necessary in case the system upgrade updated the main MSYS2 libs. Reopen the MSYS2 shell and continue with: ``` pacman -S diffutils git m4 make patch tar msys/openssh ``` 5. Configure your MSYS2 shell for convenience: ``` echo "mount C:/Python27 /python" >> ~/.bashrc # uncomment ONE of the following two lines #echo "mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw" >> ~/.bashrc #echo "mount C:/mingw-builds/x32-4.8.1-win32-sjlj-rev5/mingw32 /mingw" >> ~/.bashrc echo "export PATH=/usr/local/bin:/usr/bin:/opt/bin:/mingw/bin:/python" >> ~/.bashrc ``` *N.B.* The `export` clobbers whatever `$PATH` is already defined. This is suggested to avoid path-masking. If you use MSYS2 for purposes other than building Julia, you may prefer to append rather than clobber. *N.B.* All of the path-separators in the mount commands are unix-style. 6. Configuration of the toolchain is complete. Now `exit` the MSYS2 shell. 5. Build Julia and its dependencies from source. 1. Relaunch the MSYS2 shell and type ``` . ~/.bashrc # Some versions of MSYS2 do not run this automatically ``` Ignore any warnings you see from `mount` about `/mingw` and `/python` not existing. 2. Get the Julia sources and start the build: ``` git clone https://github.com/JuliaLang/julia.git cd julia make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 3. The Julia build can (as of 2014-02-28) fail after building OpenBLAS. This appears (?) to be a result of the OpenBLAS build trying to run the Microsoft Visual C++ `lib.exe` tool -- which we don't need to do -- without checking for its existence. This uncaught error kills the Julia build. If this happens, follow the instructions in the helpful error message and continue the build, *viz.* ``` cd deps/openblas-v0.2.9.rc1 # This path will depend on the version of OpenBLAS. make install cd ../.. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 4. Some versions of PCRE (*e.g.* 8.31) will compile correctly but fail a test. This will cause the Julia build to fail. To circumvent testing for PCRE and allow the rest of the build to continue, ``` touch deps/pcre-8.31/checked # This path will depend on the version of PCRE. make -j 4 # Adjust the number of cores (4) to match your build environment. ``` 6. Setup Package Development Environment 1. The `Pkg` module in Base provides many convenient tools for [developing and publishing packages](http://docs.julialang.org/en/latest/manual/packages/). One of the packages added through pacman above was `openssh`, which will allow secure access to GitHub APIs. Follow GitHub's [guide](https://help.github.com/articles/generating-ssh-keys) to setting up SSH keys to ensure your local machine can communicate with GitHub effectively. 5. In case of the issues with building packages (i.e. ICU fails to build with the following error message ```error compiling xp_parse: error compiling xp_make_parser: could not load module libexpat-1: %```) run ```make win-extras``` and then copy everything from the ```dist-extras``` folder into ```usr/bin```. ## Building on Windows with MinGW-builds/MSYS ### The MSYS build of `make` is fragile and may not reliably support parallel builds. Use MSYS2 as described above, if you can. If you must use MSYS, take care to notice the special comments in this section. 1. Install [7-Zip](http://www.7-zip.org/download.html). 2. Install [Python 2.x](http://www.python.org/download/releases). Do **not** install Python 3. 3. Install [MinGW-builds](http://sourceforge.net/projects/mingwbuilds/), a Windows port of GCC. as follows. Do **not** use the regular MinGW distribution. 1. Download the [MinGW-builds installer](http://downloads.sourceforge.net/project/mingwbuilds/mingw-builds-install/mingw-builds-install.exe). 2. Run the installer. When prompted, choose: - Version: the most recent version (these instructions were tested with 4.8.1) - Architecture: x32 or x64 as appropriate and desired. - Threads: win32 (not posix) - Exception: sjlj (for x32) or seh (for x64). Do not choose dwarf2. - Build revision: most recent available (tested with 5) 3. Do **not** install to a directory with spaces in the name. You will have to change the default installation path. The following instructions will assume `C:\mingw-builds\x64-4.8.1-win32-seh-rev5\mingw64`. 4. Download and extract the [MSYS distribution for MinGW-builds](http://sourceforge.net/projects/mingwbuilds/files/external-binary-packages/) (e.g. msys+7za+wget+svn+git+mercurial+cvs-rev13.7z) to a directory *without* spaces in the name, e.g. `C:/mingw-builds/msys`. 5. Download the [MSYS distribution of make](http://sourceforge.net/projects/mingw/files/MSYS/Base/make) and use this `make.exe` to replace the one in the `mingw64\bin` subdirectory of the MinGW-builds installation. 6. Run the `msys.bat` installed in Step 4. Set up MSYS by running at the MSYS prompt: ``` mount C:/mingw-builds/x64-4.8.1-win32-seh-rev5/mingw64 /mingw mount C:/Python27 /python export PATH=$PATH:/mingw/bin:/python ``` Replace the directories as appropriate. 7. Download the Julia source repository and build it ``` git clone https://github.com/JuliaLang/julia.git cd julia make ``` *Tips:* - The MSYS build of `make` is fragile and will occasionally corrupt the build process. You can minimize the changes of this occurring by only running `make` in serial, i.e. avoid the `-j` argument. - When the build process fails for no apparent reason, try running `make` again. - Sometimes, `make` will appear to hang, consuming 100% cpu but without apparent progress. If this happens, kill `make` from the Task Manager and try again. - Expect this to take a very long time (dozens of hours is not uncommon). - If `make` fails complaining that `./flisp/flisp` is not found, force `make` to build FemtoLisp before Julia by running `make -C src/flisp && make`. 8. Run Julia with _either_ of: - Using `make` ``` make run-julia ``` (the full syntax is `make run-julia[-release|-debug]`) - Using the Julia executables directly ``` usr/bin/julia ``` ## Cross-compiling If you prefer to cross-compile, the following steps should get you started. ### Ubuntu and Mac Dependencies (these steps will work for almost any linux platform) First, you will need to ensure your system has the required dependencies. We need wine (>=1.7.5), a system compiler, and some downloaders. On Ubuntu: apt-add-repository ppa:ubuntu-wine/ppa apt-get upate apt-get install wine1.7 subversion cvs gcc wget p7zip-full On Mac: Install XCode, XCode command line tools, X11 (now [XQuartz](http://xquartz.macosforge.org/)), and [MacPorts](http://www.macports.org/install.php) or [Homebrew](http://mxcl.github.io/homebrew/). Then run ```port install wine wget``` or ```brew install wine wget```, as appropriate. On Both: Unfortunately, the version of gcc installed by Ubuntu is currently 4.6, which does not compile OpenBLAS correctly. On Mac, the situation is the same: the version in MacPorts is very old and Homebrew does not have it. So first we need to get a cross-compile version of gcc. Most binary packages appear to not include gfortran, so we will need to compile it from source (or ask @vtjnash to send you a tgz of his build). This is typically quite a bit of work, so we will use [this script](https://code.google.com/p/mingw-w64-dgn/) to make it easy. 1. `svn checkout http://mingw-w64-dgn.googlecode.com/svn/trunk/ mingw-w64-dgn` 2. `cd mingw-w64-dgn` 3. edit `rebuild_cross.sh` and make the following two changes: a. uncomment `export MAKE_OPT="-j 2"`, if appropriate for your machine b. add `fortran` to the end of `--enable-languages=c,c++,objc,obj-c++` 5. `bash update_source.sh` 4. `bash rebuild_cross.sh` 5. `mv cross ~/cross-w64` 6. `export PATH=$HOME/cross-w64/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Then we can essentially just repeat these steps for the 32-bit compiler, reusing some of the work: 7. `cd ..` 8. `cp -a mingw-w64-dgn mingw-w32-dgn` 9. `cd mingw-w32-dgn` 10. `rm -r cross build` 11. `bash rebuild_cross.sh 32r` 12. `mv cross ~/cross-w32` 13. `export PATH=$HOME/cross-w32/bin:$PATH` # NOTE: it is important that you remember to always do this before using make in the following steps!, you can put this line in your .profile to make it easy Note: for systems that support rpm-based package managers, the OpenSUSE build service appears to contain a fully up-to-date versions of the necessary dependencies. ### Arch Linux Dependencies 1. Install the following packages from the official Arch repository: `sudo pacman -S cloog gcc-ada libmpc p7zip ppl subversion zlib` 2. The rest of the prerequisites consist of the mingw-w64 packages, which are available in the AUR Arch repository. They must be installed exactly in the order they are given or else their installation will fail. The `yaourt` package manager is used for illustration purposes; you may instead follow the [Arch instructions for installing packages from AUR](https://wiki.archlinux.org/index.php/Arch_User_Repository#Installing_packages) or may use your preferred package manager. To start with, install `mingw-w64-binutils` via the command `yaourt -S mingw-w64-binutils` 3. `yaourt -S mingw-w64-headers-svn` 4. `yaourt -S mingw-w64-headers-bootstrap` 5. `yaourt -S mingw-w64-gcc-base` 6. `yaourt -S mingw-w64-crt-svn` 7. Remove `mingw-w64-headers-bootstrap` without removing its dependent mingw-w64 installed packages by using the command `yaourt -Rdd mingw-w64-headers-bootstrap` 8. `yaourt -S mingw-w64-winpthreads` 9. Remove `mingw-w64-gcc-base` without removing its installed mingw-w64 dependencies: `yaourt -Rdd mingw-w64-gcc-base` 10. Complete the installation of the required `mingw-w64` packages: `yaourt -S mingw-w64-gcc` ### Cross-building Julia Finally, the build and install process for Julia: 1. `git clone https://github.com/JuliaLang/julia.git julia-win32` 2. `echo override XC_HOST = i686-w64-mingw32 >> Make.user` 3. `make` 4. `make win-extras` (Necessary before running `make dist`p) 5. `make dist` 6. move the julia-* directory / zip file to the target machine If you are building for 64-bit windows, the steps are essentially the same. Just replace i686 in XC_HOST with x86_64. (note: on Mac, wine only runs in 32-bit mode) ## Windows Build Debugging ### Build process is slow/eats memory/hangs my computer - Disable the Windows [Superfetch](http://en.wikipedia.org/wiki/Windows_Vista_I/O_technologies#SuperFetch) and [Program Compatibility Assistant](http://blogs.msdn.com/b/cjacks/archive/2011/11/22/managing-the-windows-7-program-compatibility-assistant-pca.aspx) services, as they are known to have [spurious interactions]((https://cygwin.com/ml/cygwin/2011-12/msg00058.html)) with MinGW/Cygwin. As mentioned in the link above: excessive memory use by `svchost` specifically may be investigated in the Task Manager by clicking on the high-memory `svchost.exe` process and selecting `Go to Services`. Disable child services one-by-one until a culprit is found. - Beware of [BLODA](https://cygwin.com/faq/faq.html#faq.using.bloda) The [vmmap](http://technet.microsoft.com/en-us/sysinternals/dd535533.aspx) tool is indispensable for identifying such software conflicts. Use vmmap to inspect the list of loaded DLLs for bash, mintty, or another persistent process used to drive the build. Essentially *any* DLL outside of the Windows System directory is potential BLODA.
Java
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.geronimo.console.configcreator; import java.io.File; import javax.enterprise.deploy.shared.factories.DeploymentFactoryManager; import javax.enterprise.deploy.spi.DeploymentManager; import javax.enterprise.deploy.spi.Target; import javax.enterprise.deploy.spi.status.ProgressObject; import javax.naming.InitialContext; import javax.naming.NamingException; import javax.portlet.PortletException; import javax.portlet.PortletRequest; import org.apache.geronimo.deployment.plugin.jmx.CommandContext; import org.apache.geronimo.deployment.plugin.jmx.JMXDeploymentManager; import org.apache.geronimo.deployment.plugin.local.DistributeCommand; import org.apache.geronimo.j2ee.deployment.ApplicationInfo; import org.apache.geronimo.j2ee.deployment.EARConfigBuilder; import org.apache.geronimo.kernel.Kernel; import org.apache.geronimo.kernel.KernelRegistry; /** * Util class for JSR-88 related functions * * @version $Rev$ $Date$ */ public class JSR88_Util { /*private static List getEjbClassLoaders(PortletRequest request) { List deployedEjbs = JSR77_Util.getDeployedEJBs(request); List configurations = new ArrayList(); for (int i = 0; i < deployedEjbs.size(); i++) { String ejbPatternName = ((ReferredData) deployedEjbs.get(i)).getPatternName(); configurations.add(getDependencyString(ejbPatternName)); } return getConfigClassLoaders(configurations); } private static List getConfigClassLoaders(List configurationNames) { List classLoaders = new ArrayList(); ConfigurationManager configurationManager = PortletManager.getConfigurationManager(); for (int i = 0; i < configurationNames.size(); i++) { Artifact configurationId = Artifact.create((String) configurationNames.get(i)); classLoaders.add(configurationManager.getConfiguration(configurationId).getConfigurationClassLoader()); } return classLoaders; }*/ public static ApplicationInfo createApplicationInfo(PortletRequest actionRequest, File moduleFile) { ApplicationInfo applicationInfo = null; EARConfigBuilder.createPlanMode.set(Boolean.TRUE); try { DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance(); DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null); if (mgr instanceof JMXDeploymentManager) { ((JMXDeploymentManager) mgr).setLogConfiguration(false, true); } Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] { targets[0] }; DistributeCommand command = new DistributeCommand(getKernel(), targets, moduleFile, null); CommandContext commandContext = new CommandContext(true, true, null, null, false); commandContext.setUsername("system"); commandContext.setPassword("manager"); command.setCommandContext(commandContext); command.doDeploy(targets[0], true); } catch (Exception e) { // Any better ideas? if(EARConfigBuilder.appInfo.get() == null) throw new RuntimeException(e); } finally { EARConfigBuilder.createPlanMode.set(Boolean.FALSE); applicationInfo = EARConfigBuilder.appInfo.get(); EARConfigBuilder.appInfo.set(null); } return applicationInfo; } private static Kernel getKernel() { // todo: consider making this configurable; we could easily connect to a remote kernel if we wanted to Kernel kernel = null; try { kernel = (Kernel) new InitialContext().lookup("java:comp/GeronimoKernel"); } catch (NamingException e) { // log.error("Unable to look up kernel in JNDI", e); } if (kernel == null) { // log.debug("Unable to find kernel in JNDI; using KernelRegistry instead"); kernel = KernelRegistry.getSingleKernel(); } return kernel; } public static String[] deploy(PortletRequest actionRequest, File moduleFile, File planFile) throws PortletException { // TODO this is a duplicate of the code from // org.apache.geronimo.console.configmanager.DeploymentPortlet.processAction() // TODO need to eliminate this duplicate code DeploymentFactoryManager dfm = DeploymentFactoryManager.getInstance(); String[] statusMsgs = new String[2]; try { DeploymentManager mgr = dfm.getDeploymentManager("deployer:geronimo:inVM", null, null); try { if (mgr instanceof JMXDeploymentManager) { ((JMXDeploymentManager) mgr).setLogConfiguration(false, true); } Target[] targets = mgr.getTargets(); if (null == targets) { throw new IllegalStateException("No target to distribute to"); } targets = new Target[] { targets[0] }; ProgressObject progress = mgr.distribute(targets, moduleFile, planFile); while (progress.getDeploymentStatus().isRunning()) { Thread.sleep(100); } if (progress.getDeploymentStatus().isCompleted()) { progress = mgr.start(progress.getResultTargetModuleIDs()); while (progress.getDeploymentStatus().isRunning()) { Thread.sleep(100); } statusMsgs[0] = "infoMsg01"; } else { statusMsgs[0] = "errorMsg02"; statusMsgs[1] = progress.getDeploymentStatus().getMessage(); } } finally { mgr.release(); } } catch (Exception e) { throw new PortletException(e); } return statusMsgs; } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (1.8.0_191) on Fri Dec 21 13:21:36 PST 2018 --> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Constant Field Values (guacamole-ext 1.0.0 API)</title> <meta name="date" content="2018-12-21"> <link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style"> <script type="text/javascript" src="script.js"></script> </head> <body> <script type="text/javascript"><!-- try { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Constant Field Values (guacamole-ext 1.0.0 API)"; } } catch(err) { } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar.top"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.top.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 title="Constant Field Values" class="title">Constant Field Values</h1> <h2 title="Contents">Contents</h2> <ul> <li><a href="#org.apache">org.apache.*</a></li> </ul> </div> <div class="constantValuesContainer"><a name="org.apache"> <!-- --> </a> <h2 title="org.apache">org.apache.*</h2> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.form.<a href="org/apache/guacamole/form/DateField.html" title="class in org.apache.guacamole.form">DateField</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.form.DateField.FORMAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/form/DateField.html#FORMAT">FORMAT</a></code></td> <td class="colLast"><code>"yyyy-MM-dd"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.form.<a href="org/apache/guacamole/form/TimeField.html" title="class in org.apache.guacamole.form">TimeField</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.form.TimeField.FORMAT"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/form/TimeField.html#FORMAT">FORMAT</a></code></td> <td class="colLast"><code>"HH:mm:ss"</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.net.auth.<a href="org/apache/guacamole/net/auth/AbstractUserContext.html" title="class in org.apache.guacamole.net.auth">AbstractUserContext</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.net.auth.AbstractUserContext.DEFAULT_ROOT_CONNECTION_GROUP"> <!-- --> </a><code>protected&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/net/auth/AbstractUserContext.html#DEFAULT_ROOT_CONNECTION_GROUP">DEFAULT_ROOT_CONNECTION_GROUP</a></code></td> <td class="colLast"><code>"ROOT"</code></td> </tr> </tbody> </table> </li> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.net.auth.<a href="org/apache/guacamole/net/auth/AuthenticatedUser.html" title="interface in org.apache.guacamole.net.auth">AuthenticatedUser</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.net.auth.AuthenticatedUser.ANONYMOUS_IDENTIFIER"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/net/auth/AuthenticatedUser.html#ANONYMOUS_IDENTIFIER">ANONYMOUS_IDENTIFIER</a></code></td> <td class="colLast"><code>""</code></td> </tr> </tbody> </table> </li> </ul> <ul class="blockList"> <li class="blockList"> <table class="constantsSummary" border="0" cellpadding="3" cellspacing="0" summary="Constant Field Values table, listing constant fields, and values"> <caption><span>org.apache.guacamole.token.<a href="org/apache/guacamole/token/StandardTokens.html" title="class in org.apache.guacamole.token">StandardTokens</a></span><span class="tabEnd">&nbsp;</span></caption> <tr> <th class="colFirst" scope="col">Modifier and Type</th> <th scope="col">Constant Field</th> <th class="colLast" scope="col">Value</th> </tr> <tbody> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.CLIENT_ADDRESS_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#CLIENT_ADDRESS_TOKEN">CLIENT_ADDRESS_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_CLIENT_ADDRESS"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.CLIENT_HOSTNAME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#CLIENT_HOSTNAME_TOKEN">CLIENT_HOSTNAME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_CLIENT_HOSTNAME"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.DATE_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#DATE_TOKEN">DATE_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_DATE"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.PASSWORD_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#PASSWORD_TOKEN">PASSWORD_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_PASSWORD"</code></td> </tr> <tr class="altColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.TIME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#TIME_TOKEN">TIME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_TIME"</code></td> </tr> <tr class="rowColor"> <td class="colFirst"><a name="org.apache.guacamole.token.StandardTokens.USERNAME_TOKEN"> <!-- --> </a><code>public&nbsp;static&nbsp;final&nbsp;<a href="http://docs.oracle.com/javase/8/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a></code></td> <td><code><a href="org/apache/guacamole/token/StandardTokens.html#USERNAME_TOKEN">USERNAME_TOKEN</a></code></td> <td class="colLast"><code>"GUAC_USERNAME"</code></td> </tr> </tbody> </table> </li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar.bottom"> <!-- --> </a> <div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div> <a name="navbar.bottom.firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="overview-summary.html">Overview</a></li> <li>Package</li> <li>Class</li> <li>Use</li> <li><a href="overview-tree.html">Tree</a></li> <li><a href="deprecated-list.html">Deprecated</a></li> <li><a href="index-all.html">Index</a></li> <li><a href="help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="index.html?constant-values.html" target="_top">Frames</a></li> <li><a href="constant-values.html" target="_top">No&nbsp;Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="allclasses-noframe.html">All&nbsp;Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip.navbar.bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> <p class="legalCopy"><small>Copyright &#169; 2018. All rights reserved.</small></p> <!-- Google Analytics --> <script type="text/javascript"> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-75289145-1', 'auto'); ga('send', 'pageview'); </script> </body> </html>
Java
package cmdserver_test import ( "testing" . "github.com/onsi/ginkgo" . "github.com/onsi/gomega" ) func TestCmdServer(t *testing.T) { RegisterFailHandler(Fail) RunSpecs(t, "CmdServer Suite") }
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.eas.widgets.containers; import com.eas.core.XElement; import com.google.gwt.dom.client.Style; import com.google.gwt.user.client.ui.FlowPanel; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.Widget; /** * * @author mg */ public class FlowGapPanel extends FlowPanel implements RequiresResize { protected int hgap; protected int vgap; public FlowGapPanel() { super(); getElement().<XElement>cast().addResizingTransitionEnd(this); getElement().getStyle().setLineHeight(0, Style.Unit.PX); } public int getHgap() { return hgap; } public void setHgap(int aValue) { hgap = aValue; for (int i = 0; i < getWidgetCount(); i++) { Widget w = getWidget(i); w.getElement().getStyle().setMarginLeft(hgap, Style.Unit.PX); } } public int getVgap() { return vgap; } public void setVgap(int aValue) { vgap = aValue; for (int i = 0; i < getWidgetCount(); i++) { Widget w = getWidget(i); w.getElement().getStyle().setMarginTop(vgap, Style.Unit.PX); } } @Override public void add(Widget w) { w.getElement().getStyle().setMarginLeft(hgap, Style.Unit.PX); w.getElement().getStyle().setMarginTop(vgap, Style.Unit.PX); w.getElement().getStyle().setDisplay(Style.Display.INLINE_BLOCK); w.getElement().getStyle().setVerticalAlign(Style.VerticalAlign.BOTTOM); super.add(w); } @Override public void onResize() { // reserved for future use. } }
Java
package org.cohorte.herald.core.utils; import java.util.Iterator; import org.cohorte.herald.Message; import org.cohorte.herald.MessageReceived; import org.jabsorb.ng.JSONSerializer; import org.jabsorb.ng.serializer.MarshallException; import org.jabsorb.ng.serializer.UnmarshallException; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class MessageUtils { /** The Jabsorb serializer */ private static JSONSerializer pSerializer = new JSONSerializer(); static { try { pSerializer.registerDefaultSerializers(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } public static String toJSON(Message aMsg) throws MarshallException { JSONObject json = new JSONObject(); try { // headers JSONObject headers = new JSONObject(); for (String key : aMsg.getHeaders().keySet()) { headers.put(key, aMsg.getHeaders().get(key)); } json.put(Message.MESSAGE_HEADERS, headers); // subject json.put(Message.MESSAGE_SUBJECT, aMsg.getSubject()); // content if (aMsg.getContent() != null) { if (aMsg.getContent() instanceof String) { json.put(Message.MESSAGE_CONTENT, aMsg.getContent()); } else { JSONObject content = new JSONObject(pSerializer.toJSON(aMsg.getContent())); json.put(Message.MESSAGE_CONTENT, content); } } // metadata JSONObject metadata = new JSONObject(); for (String key : aMsg.getMetadata().keySet()) { metadata.put(key, aMsg.getMetadata().get(key)); } json.put(Message.MESSAGE_METADATA, metadata); } catch (JSONException e) { e.printStackTrace(); return null; } return json.toString(); } @SuppressWarnings("unchecked") public static MessageReceived fromJSON(String json) throws UnmarshallException { try { JSONObject wParsedMsg = new JSONObject(json); { try { // check if valid herald message (respects herald specification version) int heraldVersion = -1; JSONObject jHeader = wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS); if (jHeader != null) { if (jHeader.has(Message.MESSAGE_HERALD_VERSION)) { heraldVersion = jHeader.getInt(Message.MESSAGE_HERALD_VERSION); } } if (heraldVersion != Message.HERALD_SPECIFICATION_VERSION) { throw new JSONException("Herald specification of the received message is not supported!"); } MessageReceived wMsg = new MessageReceived( wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).getString(Message.MESSAGE_HEADER_UID), wParsedMsg.getString(Message.MESSAGE_SUBJECT), null, null, null, null, null, null); // content Object cont = wParsedMsg.opt(Message.MESSAGE_CONTENT); if (cont != null) { if (cont instanceof JSONObject || cont instanceof JSONArray) { wMsg.setContent(pSerializer.fromJSON(cont.toString())); } else wMsg.setContent(cont); } else { wMsg.setContent(null); } // headers Iterator<String> wKeys; if (wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS) != null) { wKeys = wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).keys(); while(wKeys.hasNext()) { String key = wKeys.next(); wMsg.addHeader(key, wParsedMsg.getJSONObject(Message.MESSAGE_HEADERS).get(key)); } } // metadata Iterator<String> wKeys2; if (wParsedMsg.getJSONObject(Message.MESSAGE_METADATA) != null) { wKeys2 = wParsedMsg.getJSONObject(Message.MESSAGE_METADATA).keys(); while(wKeys2.hasNext()) { String key = wKeys2.next(); wMsg.addMetadata(key, wParsedMsg.getJSONObject(Message.MESSAGE_METADATA).get(key)); } } return wMsg; } catch (JSONException e) { e.printStackTrace(); return null; } } } catch (Exception e) { e.printStackTrace(); return null; } } }
Java
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.cache.annotation; import java.util.Collection; import javax.annotation.PostConstruct; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.CacheManager; import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportAware; import org.springframework.core.annotation.AnnotationAttributes; import org.springframework.core.type.AnnotationMetadata; import org.springframework.util.Assert; import org.springframework.util.CollectionUtils; /** * Abstract base {@code @Configuration} class providing common structure for enabling * Spring's annotation-driven cache management capability. * * @author Chris Beams * @since 3.1 * @see EnableCaching */ @Configuration public abstract class AbstractCachingConfiguration implements ImportAware { protected AnnotationAttributes enableCaching; protected CacheManager cacheManager; protected KeyGenerator keyGenerator; @Autowired(required=false) private Collection<CacheManager> cacheManagerBeans; @Autowired(required=false) private Collection<CachingConfigurer> cachingConfigurers; @Override public void setImportMetadata(AnnotationMetadata importMetadata) { this.enableCaching = AnnotationAttributes.fromMap( importMetadata.getAnnotationAttributes(EnableCaching.class.getName(), false)); Assert.notNull(this.enableCaching, "@EnableCaching is not present on importing class " + importMetadata.getClassName()); } /** * Determine which {@code CacheManager} bean to use. Prefer the result of * {@link CachingConfigurer#cacheManager()} over any by-type matching. If none, fall * back to by-type matching on {@code CacheManager}. * @throws IllegalArgumentException if no CacheManager can be found; if more than one * CachingConfigurer implementation exists; if multiple CacheManager beans and no * CachingConfigurer exists to disambiguate. */ @PostConstruct protected void reconcileCacheManager() { if (!CollectionUtils.isEmpty(cachingConfigurers)) { int nConfigurers = cachingConfigurers.size(); if (nConfigurers > 1) { throw new IllegalStateException(nConfigurers + " implementations of " + "CachingConfigurer were found when only 1 was expected. " + "Refactor the configuration such that CachingConfigurer is " + "implemented only once or not at all."); } CachingConfigurer cachingConfigurer = cachingConfigurers.iterator().next(); this.cacheManager = cachingConfigurer.cacheManager(); this.keyGenerator = cachingConfigurer.keyGenerator(); } else if (!CollectionUtils.isEmpty(cacheManagerBeans)) { int nManagers = cacheManagerBeans.size(); if (nManagers > 1) { throw new IllegalStateException(nManagers + " beans of type CacheManager " + "were found when only 1 was expected. Remove all but one of the " + "CacheManager bean definitions, or implement CachingConfigurer " + "to make explicit which CacheManager should be used for " + "annotation-driven cache management."); } CacheManager cacheManager = cacheManagerBeans.iterator().next(); this.cacheManager = cacheManager; // keyGenerator remains null; will fall back to default within CacheInterceptor } else { throw new IllegalStateException("No bean of type CacheManager could be found. " + "Register a CacheManager bean or remove the @EnableCaching annotation " + "from your configuration."); } } }
Java
package org.apache.cocoon.transformation; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Map; import java.util.zip.ZipInputStream; import java.util.zip.ZipEntry; import org.apache.avalon.framework.parameters.Parameters; import org.apache.cocoon.ProcessingException; import org.apache.cocoon.environment.SourceResolver; import org.apache.commons.httpclient.HostConfiguration; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpMethod; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.commons.io.FilenameUtils; import org.apache.commons.io.IOUtils; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.AttributesImpl; /** * This transformer downloads a new file to disk. * <p> * It triggers for elements in the namespace "http://apache.org/cocoon/download/1.0". * Attributes: * @src : the file that should be downloaded * @target (optional): path where the file should be stored (includes filename) * @target-dir (optional): directory where the file should be stored * @unzip (optional): if "true" then unzip file after downloading. * If there is no @target or @target-dir attribute a temporary file is created. * <p> * Example XML input: * <pre> * {@code * <download:download src="http://some.server.com/zipfile.zip" * target="/tmp/zipfile.zip" unzip="true"/> * } * </pre> * The @src specifies the file that should be downloaded. The * @target specifies where the file should be stored. @unzip is true, so the * file will be unzipped immediately. * <p> * The result is * <pre> * {@code * <download:result unzipped="/path/to/unzipped/file/on/disk">/path/to/file/on/disk</download:result> * } * </pre> * (@unzipped is only present when @unzip="true") or * <pre> * {@code * <download:error>The error message</download:file> * } * </pre> * if an error (other than a HTTP error) occurs. * HTTP errors are thrown. * Define this transformer in the sitemap: * <pre> * {@code * <map:components> * <map:transformers> * <map:transformer name="download" logger="sitemap.transformer.download" * src="org.apache.cocoon.transformation.DownloadTransformer"/> * ... * } * </pre> * Use this transformer: * <pre> * {@code * <map:transform type="download"/> * } * </pre> * * * @author <a href="mailto:[email protected]">Maarten Kroon</a> * @author <a href="mailto:[email protected]">Huib Verweij</a> */ public class DownloadTransformer extends AbstractSAXTransformer { public static final String DOWNLOAD_NS = "http://apache.org/cocoon/download/1.0"; public static final String DOWNLOAD_ELEMENT = "download"; private static final String DOWNLOAD_PREFIX = "download"; public static final String RESULT_ELEMENT = "result"; public static final String ERROR_ELEMENT = "error"; public static final String SRC_ATTRIBUTE = "src"; public static final String TARGET_ATTRIBUTE = "target"; public static final String TARGETDIR_ATTRIBUTE = "target-dir"; public static final String UNZIP_ATTRIBUTE = "unzip"; public static final String RECURSIVE_UNZIP_ATTRIBUTE = "recursive-unzip"; public static final String UNZIPPED_ATTRIBUTE = "unzipped"; public DownloadTransformer() { this.defaultNamespaceURI = DOWNLOAD_NS; } @Override public void setup(SourceResolver resolver, Map objectModel, String src, Parameters params) throws ProcessingException, SAXException, IOException { super.setup(resolver, objectModel, src, params); } @Override public void startTransformingElement(String uri, String localName, String qName, Attributes attributes) throws SAXException, ProcessingException, IOException { if (DOWNLOAD_NS.equals(uri) && DOWNLOAD_ELEMENT.equals(localName)) { try { File[] downloadResult = download( attributes.getValue(SRC_ATTRIBUTE), attributes.getValue(TARGETDIR_ATTRIBUTE), attributes.getValue(TARGET_ATTRIBUTE), attributes.getValue(UNZIP_ATTRIBUTE), attributes.getValue(RECURSIVE_UNZIP_ATTRIBUTE) ); File downloadedFile = downloadResult[0]; File unzipDir = downloadResult[1]; String absPath = downloadedFile.getCanonicalPath(); AttributesImpl attrsImpl = new AttributesImpl(); if (unzipDir != null) { attrsImpl.addAttribute("", UNZIPPED_ATTRIBUTE, UNZIPPED_ATTRIBUTE, "CDATA", unzipDir.getAbsolutePath()); } xmlConsumer.startElement(uri, RESULT_ELEMENT, String.format("%s:%s", DOWNLOAD_PREFIX, RESULT_ELEMENT), attrsImpl); xmlConsumer.characters(absPath.toCharArray(), 0, absPath.length()); xmlConsumer.endElement(uri, RESULT_ELEMENT, String.format("%s:%s", DOWNLOAD_PREFIX, RESULT_ELEMENT)); } catch (Exception e) { // throw new SAXException("Error downloading file", e); xmlConsumer.startElement(uri, ERROR_ELEMENT, qName, attributes); String message = e.getMessage(); xmlConsumer.characters(message.toCharArray(), 0, message.length()); xmlConsumer.endElement(uri, ERROR_ELEMENT, qName); } } else { super.startTransformingElement(uri, localName, qName, attributes); } } @Override public void endTransformingElement(String uri, String localName, String qName) throws SAXException, ProcessingException, IOException { if (DOWNLOAD_NS.equals(namespaceURI) && DOWNLOAD_ELEMENT.equals(localName)) { return; } super.endTransformingElement(uri, localName, qName); } private File[] download(String sourceUri, String targetDir, String target, String unzip, String recursiveUnzip) throws ProcessingException, IOException, SAXException { File targetFile; File unZipped = null; if (null != target && !target.equals("")) { targetFile = new File(target); } else if (null != targetDir && !targetDir.equals("")) { targetFile = new File(targetDir); } else { String baseName = FilenameUtils.getBaseName(sourceUri); String extension = FilenameUtils.getExtension(sourceUri); targetFile = File.createTempFile(baseName, "." + extension); } if (!targetFile.getParentFile().exists()) { targetFile.getParentFile().mkdirs(); } boolean unzipFile = (null != unzip && unzip.equals("true")) || (null != recursiveUnzip && recursiveUnzip.equals("true")); String absPath = targetFile.getAbsolutePath(); String unzipDir = unzipFile ? FilenameUtils.removeExtension(absPath) : ""; HttpClient httpClient = new HttpClient(); httpClient.setConnectionTimeout(60000); httpClient.setTimeout(60000); if (System.getProperty("http.proxyHost") != null) { // getLogger().warn("PROXY: "+System.getProperty("http.proxyHost")); String nonProxyHostsRE = System.getProperty("http.nonProxyHosts", ""); if (nonProxyHostsRE.length() > 0) { String[] pHosts = nonProxyHostsRE.replaceAll("\\.", "\\\\.").replaceAll("\\*", ".*").split("\\|"); nonProxyHostsRE = ""; for (String pHost : pHosts) { nonProxyHostsRE += "|(^https?://" + pHost + ".*$)"; } nonProxyHostsRE = nonProxyHostsRE.substring(1); } if (nonProxyHostsRE.length() == 0 || !sourceUri.matches(nonProxyHostsRE)) { try { HostConfiguration hostConfiguration = httpClient.getHostConfiguration(); hostConfiguration.setProxy(System.getProperty("http.proxyHost"), Integer.parseInt(System.getProperty("http.proxyPort", "80"))); httpClient.setHostConfiguration(hostConfiguration); } catch (Exception e) { throw new ProcessingException("Cannot set proxy!", e); } } } HttpMethod httpMethod = new GetMethod(sourceUri); try { int responseCode = httpClient.executeMethod(httpMethod); if (responseCode < 200 || responseCode >= 300) { throw new ProcessingException(String.format("Received HTTP status code %d (%s)", responseCode, httpMethod.getStatusText())); } OutputStream os = new BufferedOutputStream(new FileOutputStream(targetFile)); try { IOUtils.copyLarge(httpMethod.getResponseBodyAsStream(), os); } finally { os.close(); } } finally { httpMethod.releaseConnection(); } if (!"".equals(unzipDir)) { unZipped = unZipIt(targetFile, unzipDir, recursiveUnzip); } return new File[] {targetFile, unZipped}; } /** * Unzip it * @param zipFile input zip file * @param outputFolder zip file output folder */ private File unZipIt(File zipFile, String outputFolder, String recursiveUnzip){ byte[] buffer = new byte[4096]; File folder = null; try{ //create output directory is not exists folder = new File(outputFolder); if (!folder.exists()){ folder.mkdir(); } //get the zipped file list entry try ( //get the zip file content ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) { //get the zipped file list entry ZipEntry ze = zis.getNextEntry(); while(ze != null){ String fileName = ze.getName(); File newFile = new File(outputFolder + File.separator + fileName); // System.out.println("file unzip : "+ newFile.getAbsoluteFile()); // create all non existing folders // else you will hit FileNotFoundException for compressed folder new File(newFile.getParent()).mkdirs(); try (FileOutputStream fos = new FileOutputStream(newFile)) { int len; while ((len = zis.read(buffer)) > 0) { fos.write(buffer, 0, len); } } if ((null != recursiveUnzip && "true".equals(recursiveUnzip)) && FilenameUtils.getExtension(fileName).equals("zip")) { unZipIt(newFile, FilenameUtils.concat(outputFolder, FilenameUtils.getBaseName(fileName)), recursiveUnzip); } ze = zis.getNextEntry(); } zis.closeEntry(); } // System.out.println("Done unzipping."); } catch(IOException ex){ ex.printStackTrace(); } return folder; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.hc.client5.testing.sync; import java.io.IOException; import org.apache.hc.client5.http.HttpRoute; import org.apache.hc.client5.http.UserTokenHandler; import org.apache.hc.client5.http.classic.methods.HttpGet; import org.apache.hc.client5.http.impl.classic.CloseableHttpClient; import org.apache.hc.client5.http.protocol.HttpClientContext; import org.apache.hc.core5.http.ClassicHttpRequest; import org.apache.hc.core5.http.ClassicHttpResponse; import org.apache.hc.core5.http.EndpointDetails; import org.apache.hc.core5.http.HttpException; import org.apache.hc.core5.http.HttpHost; import org.apache.hc.core5.http.HttpStatus; import org.apache.hc.core5.http.io.HttpRequestHandler; import org.apache.hc.core5.http.io.entity.EntityUtils; import org.apache.hc.core5.http.io.entity.StringEntity; import org.apache.hc.core5.http.protocol.BasicHttpContext; import org.apache.hc.core5.http.protocol.HttpContext; import org.junit.Assert; import org.junit.Test; /** * Test cases for state-ful connections. */ public class TestStatefulConnManagement extends LocalServerTestBase { private static class SimpleService implements HttpRequestHandler { public SimpleService() { super(); } @Override public void handle( final ClassicHttpRequest request, final ClassicHttpResponse response, final HttpContext context) throws HttpException, IOException { response.setCode(HttpStatus.SC_OK); final StringEntity entity = new StringEntity("Whatever"); response.setEntity(entity); } } @Test public void testStatefulConnections() throws Exception { final int workerCount = 5; final int requestCount = 5; this.server.registerHandler("*", new SimpleService()); this.connManager.setMaxTotal(workerCount); this.connManager.setDefaultMaxPerRoute(workerCount); final UserTokenHandler userTokenHandler = new UserTokenHandler() { @Override public Object getUserToken(final HttpRoute route, final HttpContext context) { final String id = (String) context.getAttribute("user"); return id; } }; this.clientBuilder.setUserTokenHandler(userTokenHandler); final HttpHost target = start(); final HttpClientContext[] contexts = new HttpClientContext[workerCount]; final HttpWorker[] workers = new HttpWorker[workerCount]; for (int i = 0; i < contexts.length; i++) { final HttpClientContext context = HttpClientContext.create(); contexts[i] = context; workers[i] = new HttpWorker( "user" + i, context, requestCount, target, this.httpclient); } for (final HttpWorker worker : workers) { worker.start(); } for (final HttpWorker worker : workers) { worker.join(LONG_TIMEOUT.toMillis()); } for (final HttpWorker worker : workers) { final Exception ex = worker.getException(); if (ex != null) { throw ex; } Assert.assertEquals(requestCount, worker.getCount()); } for (final HttpContext context : contexts) { final String state0 = (String) context.getAttribute("r0"); Assert.assertNotNull(state0); for (int r = 1; r < requestCount; r++) { Assert.assertEquals(state0, context.getAttribute("r" + r)); } } } static class HttpWorker extends Thread { private final String uid; private final HttpClientContext context; private final int requestCount; private final HttpHost target; private final CloseableHttpClient httpclient; private volatile Exception exception; private volatile int count; public HttpWorker( final String uid, final HttpClientContext context, final int requestCount, final HttpHost target, final CloseableHttpClient httpclient) { super(); this.uid = uid; this.context = context; this.requestCount = requestCount; this.target = target; this.httpclient = httpclient; this.count = 0; } public int getCount() { return this.count; } public Exception getException() { return this.exception; } @Override public void run() { try { this.context.setAttribute("user", this.uid); for (int r = 0; r < this.requestCount; r++) { final HttpGet httpget = new HttpGet("/"); final ClassicHttpResponse response = this.httpclient.execute( this.target, httpget, this.context); this.count++; final EndpointDetails endpointDetails = this.context.getEndpointDetails(); final String connuid = Integer.toHexString(System.identityHashCode(endpointDetails)); this.context.setAttribute("r" + r, connuid); EntityUtils.consume(response.getEntity()); } } catch (final Exception ex) { this.exception = ex; } } } @Test public void testRouteSpecificPoolRecylcing() throws Exception { // This tests what happens when a maxed connection pool needs // to kill the last idle connection to a route to build a new // one to the same route. final int maxConn = 2; this.server.registerHandler("*", new SimpleService()); this.connManager.setMaxTotal(maxConn); this.connManager.setDefaultMaxPerRoute(maxConn); final UserTokenHandler userTokenHandler = new UserTokenHandler() { @Override public Object getUserToken(final HttpRoute route, final HttpContext context) { return context.getAttribute("user"); } }; this.clientBuilder.setUserTokenHandler(userTokenHandler); final HttpHost target = start(); // Bottom of the pool : a *keep alive* connection to Route 1. final HttpContext context1 = new BasicHttpContext(); context1.setAttribute("user", "stuff"); final ClassicHttpResponse response1 = this.httpclient.execute( target, new HttpGet("/"), context1); EntityUtils.consume(response1.getEntity()); // The ConnPoolByRoute now has 1 free connection, out of 2 max // The ConnPoolByRoute has one RouteSpcfcPool, that has one free connection // for [localhost][stuff] Thread.sleep(100); // Send a very simple HTTP get (it MUST be simple, no auth, no proxy, no 302, no 401, ...) // Send it to another route. Must be a keepalive. final HttpContext context2 = new BasicHttpContext(); final ClassicHttpResponse response2 = this.httpclient.execute( new HttpHost("127.0.0.1", this.server.getPort()), new HttpGet("/"), context2); EntityUtils.consume(response2.getEntity()); // ConnPoolByRoute now has 2 free connexions, out of its 2 max. // The [localhost][stuff] RouteSpcfcPool is the same as earlier // And there is a [127.0.0.1][null] pool with 1 free connection Thread.sleep(100); // This will put the ConnPoolByRoute to the targeted state : // [localhost][stuff] will not get reused because this call is [localhost][null] // So the ConnPoolByRoute will need to kill one connection (it is maxed out globally). // The killed conn is the oldest, which means the first HTTPGet ([localhost][stuff]). // When this happens, the RouteSpecificPool becomes empty. final HttpContext context3 = new BasicHttpContext(); final ClassicHttpResponse response3 = this.httpclient.execute( target, new HttpGet("/"), context3); // If the ConnPoolByRoute did not behave coherently with the RouteSpecificPool // this may fail. Ex : if the ConnPool discared the route pool because it was empty, // but still used it to build the request3 connection. EntityUtils.consume(response3.getEntity()); } }
Java
package droidkit.app; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import java.util.Locale; /** * @author Daniel Serdyukov */ public final class MapsIntent { private static final String MAPS_URL = "https://maps.google.com/maps"; private MapsIntent() { } @NonNull public static Intent openMaps() { return new Intent(Intent.ACTION_VIEW, Uri.parse(MAPS_URL)); } @NonNull public static Intent openMaps(double lat, double lng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?q=%f,%f", lat, lng))); } @NonNull public static Intent route(double lat, double lng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?daddr=%f,%f", lat, lng))); } @NonNull public static Intent route(double fromLat, double fromLng, double toLat, double toLng) { return new Intent(Intent.ACTION_VIEW, Uri.parse(String.format(Locale.US, MAPS_URL + "?saddr=%f,%f&daddr=%f,%f", fromLat, fromLng, toLat, toLng))); } @NonNull public static Intent search(@NonNull String query) { return new Intent(Intent.ACTION_VIEW, Uri.parse(MAPS_URL + "?q=" + query)); } }
Java
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.test; import com.google.common.base.Joiner; import org.apache.commons.cli.CommandLine; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.conf.Configured; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.HRegionLocation; import org.apache.hadoop.hbase.IntegrationTestingUtility; import org.apache.hadoop.hbase.ServerName; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.HConstants; import org.apache.hadoop.hbase.client.Connection; import org.apache.hadoop.hbase.client.ConnectionFactory; import org.apache.hadoop.hbase.client.replication.ReplicationAdmin; import org.apache.hadoop.hbase.client.Admin; import org.apache.hadoop.hbase.replication.ReplicationPeerConfig; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import java.util.ArrayList; import java.util.HashMap; import java.util.Set; import java.util.TreeSet; import java.util.UUID; /** * This is an integration test for replication. It is derived off * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} that creates a large circular * linked list in one cluster and verifies that the data is correct in a sink cluster. The test * handles creating the tables and schema and setting up the replication. */ public class IntegrationTestReplication extends IntegrationTestBigLinkedList { protected String sourceClusterIdString; protected String sinkClusterIdString; protected int numIterations; protected int numMappers; protected long numNodes; protected String outputDir; protected int numReducers; protected int generateVerifyGap; protected Integer width; protected Integer wrapMultiplier; protected boolean noReplicationSetup = false; private final String SOURCE_CLUSTER_OPT = "sourceCluster"; private final String DEST_CLUSTER_OPT = "destCluster"; private final String ITERATIONS_OPT = "iterations"; private final String NUM_MAPPERS_OPT = "numMappers"; private final String OUTPUT_DIR_OPT = "outputDir"; private final String NUM_REDUCERS_OPT = "numReducers"; private final String NO_REPLICATION_SETUP_OPT = "noReplicationSetup"; /** * The gap (in seconds) from when data is finished being generated at the source * to when it can be verified. This is the replication lag we are willing to tolerate */ private final String GENERATE_VERIFY_GAP_OPT = "generateVerifyGap"; /** * The width of the linked list. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String WIDTH_OPT = "width"; /** * The number of rows after which the linked list points to the first row. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String WRAP_MULTIPLIER_OPT = "wrapMultiplier"; /** * The number of nodes in the test setup. This has to be a multiple of WRAP_MULTIPLIER * WIDTH * in order to ensure that the linked list can is complete. * See {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} for more details */ private final String NUM_NODES_OPT = "numNodes"; private final int DEFAULT_NUM_MAPPERS = 1; private final int DEFAULT_NUM_REDUCERS = 1; private final int DEFAULT_NUM_ITERATIONS = 1; private final int DEFAULT_GENERATE_VERIFY_GAP = 60; private final int DEFAULT_WIDTH = 1000000; private final int DEFAULT_WRAP_MULTIPLIER = 25; private final int DEFAULT_NUM_NODES = DEFAULT_WIDTH * DEFAULT_WRAP_MULTIPLIER; /** * Wrapper around an HBase ClusterID allowing us * to get admin connections and configurations for it */ protected class ClusterID { private final Configuration configuration; private Connection connection = null; /** * This creates a new ClusterID wrapper that will automatically build connections and * configurations to be able to talk to the specified cluster * * @param base the base configuration that this class will add to * @param key the cluster key in the form of zk_quorum:zk_port:zk_parent_node */ public ClusterID(Configuration base, String key) { configuration = new Configuration(base); String[] parts = key.split(":"); configuration.set(HConstants.ZOOKEEPER_QUORUM, parts[0]); configuration.set(HConstants.ZOOKEEPER_CLIENT_PORT, parts[1]); configuration.set(HConstants.ZOOKEEPER_ZNODE_PARENT, parts[2]); } @Override public String toString() { return Joiner.on(":").join(configuration.get(HConstants.ZOOKEEPER_QUORUM), configuration.get(HConstants.ZOOKEEPER_CLIENT_PORT), configuration.get(HConstants.ZOOKEEPER_ZNODE_PARENT)); } public Configuration getConfiguration() { return this.configuration; } public Connection getConnection() throws Exception { if (this.connection == null) { this.connection = ConnectionFactory.createConnection(this.configuration); } return this.connection; } public void closeConnection() throws Exception { this.connection.close(); this.connection = null; } public boolean equals(ClusterID other) { return this.toString().equalsIgnoreCase(other.toString()); } } /** * The main runner loop for the test. It uses * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList} * for the generation and verification of the linked list. It is heavily based on * {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Loop} */ protected class VerifyReplicationLoop extends Configured implements Tool { private final Log LOG = LogFactory.getLog(VerifyReplicationLoop.class); protected ClusterID source; protected ClusterID sink; IntegrationTestBigLinkedList integrationTestBigLinkedList; /** * This tears down any tables that existed from before and rebuilds the tables and schemas on * the source cluster. It then sets up replication from the source to the sink cluster by using * the {@link org.apache.hadoop.hbase.client.replication.ReplicationAdmin} * connection. * * @throws Exception */ protected void setupTablesAndReplication() throws Exception { TableName tableName = getTableName(source.getConfiguration()); ClusterID[] clusters = {source, sink}; // delete any old tables in the source and sink for (ClusterID cluster : clusters) { Admin admin = cluster.getConnection().getAdmin(); if (admin.tableExists(tableName)) { if (admin.isTableEnabled(tableName)) { admin.disableTable(tableName); } /** * TODO: This is a work around on a replication bug (HBASE-13416) * When we recreate a table against that has recently been * deleted, the contents of the logs are replayed even though * they should not. This ensures that we flush the logs * before the table gets deleted. Eventually the bug should be * fixed and this should be removed. */ Set<ServerName> regionServers = new TreeSet<>(); for (HRegionLocation rl : cluster.getConnection().getRegionLocator(tableName).getAllRegionLocations()) { regionServers.add(rl.getServerName()); } for (ServerName server : regionServers) { source.getConnection().getAdmin().rollWALWriter(server); } admin.deleteTable(tableName); } } // create the schema Generator generator = new Generator(); generator.setConf(source.getConfiguration()); generator.createSchema(); // setup the replication on the source if (!source.equals(sink)) { ReplicationAdmin replicationAdmin = new ReplicationAdmin(source.getConfiguration()); // remove any old replication peers for (String oldPeer : replicationAdmin.listPeerConfigs().keySet()) { replicationAdmin.removePeer(oldPeer); } // set the sink to be the target ReplicationPeerConfig peerConfig = new ReplicationPeerConfig(); peerConfig.setClusterKey(sink.toString()); // set the test table to be the table to replicate HashMap<TableName, ArrayList<String>> toReplicate = new HashMap<>(); toReplicate.put(tableName, new ArrayList<String>(0)); replicationAdmin.addPeer("TestPeer", peerConfig, toReplicate); replicationAdmin.enableTableRep(tableName); replicationAdmin.close(); } for (ClusterID cluster : clusters) { cluster.closeConnection(); } } protected void waitForReplication() throws Exception { // TODO: we shouldn't be sleeping here. It would be better to query the region servers // and wait for them to report 0 replication lag. Thread.sleep(generateVerifyGap * 1000); } /** * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Generator} in the * source cluster. This assumes that the tables have been setup via setupTablesAndReplication. * * @throws Exception */ protected void runGenerator() throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path generatorOutput = new Path(outputPath, uuid.toString()); Generator generator = new Generator(); generator.setConf(source.getConfiguration()); int retCode = generator.run(numMappers, numNodes, generatorOutput, width, wrapMultiplier); if (retCode > 0) { throw new RuntimeException("Generator failed with return code: " + retCode); } } /** * Run the {@link org.apache.hadoop.hbase.test.IntegrationTestBigLinkedList.Verify} * in the sink cluster. If replication is working properly the data written at the source * cluster should be available in the sink cluster after a reasonable gap * * @param expectedNumNodes the number of nodes we are expecting to see in the sink cluster * @throws Exception */ protected void runVerify(long expectedNumNodes) throws Exception { Path outputPath = new Path(outputDir); UUID uuid = UUID.randomUUID(); //create a random UUID. Path iterationOutput = new Path(outputPath, uuid.toString()); Verify verify = new Verify(); verify.setConf(sink.getConfiguration()); int retCode = verify.run(iterationOutput, numReducers); if (retCode > 0) { throw new RuntimeException("Verify.run failed with return code: " + retCode); } if (!verify.verify(expectedNumNodes)) { throw new RuntimeException("Verify.verify failed"); } LOG.info("Verify finished with success. Total nodes=" + expectedNumNodes); } /** * The main test runner * * This test has 4 steps: * 1: setupTablesAndReplication * 2: generate the data into the source cluster * 3: wait for replication to propagate * 4: verify that the data is available in the sink cluster * * @param args should be empty * @return 0 on success * @throws Exception on an error */ @Override public int run(String[] args) throws Exception { source = new ClusterID(getConf(), sourceClusterIdString); sink = new ClusterID(getConf(), sinkClusterIdString); if (!noReplicationSetup) { setupTablesAndReplication(); } int expectedNumNodes = 0; for (int i = 0; i < numIterations; i++) { LOG.info("Starting iteration = " + i); expectedNumNodes += numMappers * numNodes; runGenerator(); waitForReplication(); runVerify(expectedNumNodes); } /** * we are always returning 0 because exceptions are thrown when there is an error * in the verification step. */ return 0; } } @Override protected void addOptions() { super.addOptions(); addRequiredOptWithArg("s", SOURCE_CLUSTER_OPT, "Cluster ID of the source cluster (e.g. localhost:2181:/hbase)"); addRequiredOptWithArg("r", DEST_CLUSTER_OPT, "Cluster ID of the sink cluster (e.g. localhost:2182:/hbase)"); addRequiredOptWithArg("d", OUTPUT_DIR_OPT, "Temporary directory where to write keys for the test"); addOptWithArg("nm", NUM_MAPPERS_OPT, "Number of mappers (default: " + DEFAULT_NUM_MAPPERS + ")"); addOptWithArg("nr", NUM_REDUCERS_OPT, "Number of reducers (default: " + DEFAULT_NUM_MAPPERS + ")"); addOptNoArg("nrs", NO_REPLICATION_SETUP_OPT, "Don't setup tables or configure replication before starting test"); addOptWithArg("n", NUM_NODES_OPT, "Number of nodes. This should be a multiple of width * wrapMultiplier." + " (default: " + DEFAULT_NUM_NODES + ")"); addOptWithArg("i", ITERATIONS_OPT, "Number of iterations to run (default: " + DEFAULT_NUM_ITERATIONS + ")"); addOptWithArg("t", GENERATE_VERIFY_GAP_OPT, "Gap between generate and verify steps in seconds (default: " + DEFAULT_GENERATE_VERIFY_GAP + ")"); addOptWithArg("w", WIDTH_OPT, "Width of the linked list chain (default: " + DEFAULT_WIDTH + ")"); addOptWithArg("wm", WRAP_MULTIPLIER_OPT, "How many times to wrap around (default: " + DEFAULT_WRAP_MULTIPLIER + ")"); } @Override protected void processOptions(CommandLine cmd) { processBaseOptions(cmd); sourceClusterIdString = cmd.getOptionValue(SOURCE_CLUSTER_OPT); sinkClusterIdString = cmd.getOptionValue(DEST_CLUSTER_OPT); outputDir = cmd.getOptionValue(OUTPUT_DIR_OPT); /** This uses parseInt from {@link org.apache.hadoop.hbase.util.AbstractHBaseTool} */ numMappers = parseInt(cmd.getOptionValue(NUM_MAPPERS_OPT, Integer.toString(DEFAULT_NUM_MAPPERS)), 1, Integer.MAX_VALUE); numReducers = parseInt(cmd.getOptionValue(NUM_REDUCERS_OPT, Integer.toString(DEFAULT_NUM_REDUCERS)), 1, Integer.MAX_VALUE); numNodes = parseInt(cmd.getOptionValue(NUM_NODES_OPT, Integer.toString(DEFAULT_NUM_NODES)), 1, Integer.MAX_VALUE); generateVerifyGap = parseInt(cmd.getOptionValue(GENERATE_VERIFY_GAP_OPT, Integer.toString(DEFAULT_GENERATE_VERIFY_GAP)), 1, Integer.MAX_VALUE); numIterations = parseInt(cmd.getOptionValue(ITERATIONS_OPT, Integer.toString(DEFAULT_NUM_ITERATIONS)), 1, Integer.MAX_VALUE); width = parseInt(cmd.getOptionValue(WIDTH_OPT, Integer.toString(DEFAULT_WIDTH)), 1, Integer.MAX_VALUE); wrapMultiplier = parseInt(cmd.getOptionValue(WRAP_MULTIPLIER_OPT, Integer.toString(DEFAULT_WRAP_MULTIPLIER)), 1, Integer.MAX_VALUE); if (cmd.hasOption(NO_REPLICATION_SETUP_OPT)) { noReplicationSetup = true; } if (numNodes % (width * wrapMultiplier) != 0) { throw new RuntimeException("numNodes must be a multiple of width and wrap multiplier"); } } @Override public int runTestFromCommandLine() throws Exception { VerifyReplicationLoop tool = new VerifyReplicationLoop(); tool.integrationTestBigLinkedList = this; return ToolRunner.run(getConf(), tool, null); } public static void main(String[] args) throws Exception { Configuration conf = HBaseConfiguration.create(); IntegrationTestingUtility.setUseDistributedCluster(conf); int ret = ToolRunner.run(conf, new IntegrationTestReplication(), args); System.exit(ret); } }
Java
'use strict'; var nconf = require('nconf'); var path = require('path'); /** * Handle the configuration management. * * @constructor */ function Config() { nconf.argv().env("_"); var environment = nconf.get("NODE:ENV") || "development"; nconf.file(environment, {file: path.resolve(__dirname, '../config/' + environment + '.json')}); nconf.file('default', {file: path.resolve(__dirname, '../config/default.json')}); } /** * Return the value of the provided key from the configuration object. * * @param {string} key - Key from the configuration object. */ Config.prototype.get = function (key) { return nconf.get(key); }; module.exports = new Config();
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to you under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.calcite.test; import org.apache.calcite.sql.SqlNode; import org.apache.calcite.sql.parser.StringAndPos; import org.apache.calcite.sql.test.AbstractSqlTester; import org.apache.calcite.sql.test.SqlTestFactory; import org.apache.calcite.sql.test.SqlTests; import org.apache.calcite.sql.validate.SqlValidator; import org.checkerframework.checker.nullness.qual.Nullable; import static org.junit.jupiter.api.Assertions.assertNotNull; /** * Tester of {@link SqlValidator} and runtime execution of the input SQL. */ class SqlRuntimeTester extends AbstractSqlTester { SqlRuntimeTester() { } @Override public void checkFails(SqlTestFactory factory, StringAndPos sap, String expectedError, boolean runtime) { final StringAndPos sap2 = StringAndPos.of(runtime ? buildQuery2(factory, sap.addCarets()) : buildQuery(sap.addCarets())); assertExceptionIsThrown(factory, sap2, expectedError, runtime); } @Override public void checkAggFails(SqlTestFactory factory, String expr, String[] inputValues, String expectedError, boolean runtime) { String query = SqlTests.generateAggQuery(expr, inputValues); final StringAndPos sap = StringAndPos.of(query); assertExceptionIsThrown(factory, sap, expectedError, runtime); } @Override public void assertExceptionIsThrown(SqlTestFactory factory, StringAndPos sap, @Nullable String expectedMsgPattern) { assertExceptionIsThrown(factory, sap, expectedMsgPattern, false); } public void assertExceptionIsThrown(SqlTestFactory factory, StringAndPos sap, @Nullable String expectedMsgPattern, boolean runtime) { final SqlNode sqlNode; try { sqlNode = parseQuery(factory, sap.sql); } catch (Throwable e) { checkParseEx(e, expectedMsgPattern, sap); return; } Throwable thrown = null; final SqlTests.Stage stage; final SqlValidator validator = factory.createValidator(); if (runtime) { stage = SqlTests.Stage.RUNTIME; SqlNode validated = validator.validate(sqlNode); assertNotNull(validated); try { check(factory, sap.sql, SqlTests.ANY_TYPE_CHECKER, SqlTests.ANY_PARAMETER_CHECKER, SqlTests.ANY_RESULT_CHECKER); } catch (Throwable ex) { // get the real exception in runtime check thrown = ex; } } else { stage = SqlTests.Stage.VALIDATE; try { validator.validate(sqlNode); } catch (Throwable ex) { thrown = ex; } } SqlTests.checkEx(thrown, expectedMsgPattern, sap, stage); } }
Java
/* -*- mode: C++; c-basic-offset: 2; indent-tabs-mode: nil -*- */ /* * Main authors: * Christian Schulte <[email protected]> * * Copyright: * Christian Schulte, 2004 * * Last modified: * $Date: 2010-03-04 03:40:32 +1100 (Thu, 04 Mar 2010) $ by $Author: schulte $ * $Revision: 10365 $ * * This file is part of Gecode, the generic constraint * development environment: * http://www.gecode.org * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ #include <gecode/int/element.hh> namespace Gecode { using namespace Int; void element(Home home, IntSharedArray c, IntVar x0, IntVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); GECODE_ES_FAIL((Element::post_int<IntView,IntView>(home,c,x0,x1))); } void element(Home home, IntSharedArray c, IntVar x0, BoolVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); GECODE_ES_FAIL((Element::post_int<IntView,BoolView>(home,c,x0,x1))); } void element(Home home, IntSharedArray c, IntVar x0, int x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; for (int i = c.size(); i--; ) Limits::check(c[i],"Int::element"); ConstIntView cx1(x1); GECODE_ES_FAIL( (Element::post_int<IntView,ConstIntView>(home,c,x0,cx1))); } void element(Home home, const IntVarArgs& c, IntVar x0, IntVar x1, IntConLevel icl) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; Element::IdxViewArray<IntView> iv(home,c); if ((icl == ICL_DOM) || (icl == ICL_DEF)) { GECODE_ES_FAIL((Element::ViewDom<IntView,IntView,IntView> ::post(home,iv,x0,x1))); } else { GECODE_ES_FAIL((Element::ViewBnd<IntView,IntView,IntView> ::post(home,iv,x0,x1))); } } void element(Home home, const IntVarArgs& c, IntVar x0, int x1, IntConLevel icl) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; Element::IdxViewArray<IntView> iv(home,c); ConstIntView v1(x1); if ((icl == ICL_DOM) || (icl == ICL_DEF)) { GECODE_ES_FAIL((Element::ViewDom<IntView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } else { GECODE_ES_FAIL((Element::ViewBnd<IntView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } } void element(Home home, const BoolVarArgs& c, IntVar x0, BoolVar x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); if (home.failed()) return; Element::IdxViewArray<BoolView> iv(home,c); GECODE_ES_FAIL((Element::ViewBnd<BoolView,IntView,BoolView> ::post(home,iv,x0,x1))); } void element(Home home, const BoolVarArgs& c, IntVar x0, int x1, IntConLevel) { if (c.size() == 0) throw TooFewArguments("Int::element"); Limits::check(x1,"Int::element"); if (home.failed()) return; Element::IdxViewArray<BoolView> iv(home,c); ConstIntView v1(x1); GECODE_ES_FAIL((Element::ViewBnd<BoolView,IntView,ConstIntView> ::post(home,iv,x0,v1))); } namespace { IntVar pair(Home home, IntVar x, int w, IntVar y, int h) { IntVar xy(home,0,w*h-1); if (Element::Pair::post(home,x,y,xy,w,h) != ES_OK) home.fail(); return xy; } } void element(Home home, IntSharedArray a, IntVar x, int w, IntVar y, int h, IntVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, IntSharedArray a, IntVar x, int w, IntVar y, int h, BoolVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, const IntVarArgs& a, IntVar x, int w, IntVar y, int h, IntVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } void element(Home home, const BoolVarArgs& a, IntVar x, int w, IntVar y, int h, BoolVar z, IntConLevel icl) { if (a.size() != w*h) throw Int::ArgumentSizeMismatch("Int::element"); if (home.failed()) return; element(home, a, pair(home,x,w,y,h), z, icl); } } // STATISTICS: int-post
Java
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator.scalar; import com.facebook.presto.spi.type.ArrayType; import com.facebook.presto.spi.type.RowType; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.testng.annotations.Test; import java.util.Optional; import static com.facebook.presto.spi.type.BigintType.BIGINT; import static com.facebook.presto.spi.type.BooleanType.BOOLEAN; import static com.facebook.presto.spi.type.IntegerType.INTEGER; import static com.facebook.presto.spi.type.VarcharType.VARCHAR; import static com.facebook.presto.spi.type.VarcharType.createVarcharType; import static com.facebook.presto.type.UnknownType.UNKNOWN; import static com.facebook.presto.util.StructuralTestUtil.mapType; import static java.util.Arrays.asList; public class TestZipWithFunction extends AbstractTestFunctions { @Test public void testRetainedSizeBounded() { assertCachedInstanceHasBoundedRetainedSize("zip_with(ARRAY [25, 26, 27], ARRAY [1, 2, 3], (x, y) -> x + y)"); } @Test public void testSameLength() { assertFunction("zip_with(ARRAY[], ARRAY[], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), ImmutableList.of()); assertFunction("zip_with(ARRAY[1, 2], ARRAY['a', 'b'], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(createVarcharType(1), INTEGER), Optional.empty())), ImmutableList.of(ImmutableList.of("a", 1), ImmutableList.of("b", 2))); assertFunction("zip_with(ARRAY[1, 2], ARRAY[CAST('a' AS VARCHAR), CAST('b' AS VARCHAR)], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(VARCHAR, INTEGER), Optional.empty())), ImmutableList.of(ImmutableList.of("a", 1), ImmutableList.of("b", 2))); assertFunction("zip_with(ARRAY[1, 1], ARRAY[1, 2], (x, y) -> x + y)", new ArrayType(INTEGER), ImmutableList.of(2, 3)); assertFunction("zip_with(CAST(ARRAY[3, 5] AS ARRAY(BIGINT)), CAST(ARRAY[1, 2] AS ARRAY(BIGINT)), (x, y) -> x * y)", new ArrayType(BIGINT), ImmutableList.of(3L, 10L)); assertFunction("zip_with(ARRAY[true, false], ARRAY[false, true], (x, y) -> x OR y)", new ArrayType(BOOLEAN), ImmutableList.of(true, true)); assertFunction("zip_with(ARRAY['a', 'b'], ARRAY['c', 'd'], (x, y) -> concat(x, y))", new ArrayType(VARCHAR), ImmutableList.of("ac", "bd")); assertFunction("zip_with(ARRAY[MAP(ARRAY[CAST ('a' AS VARCHAR)], ARRAY[1]), MAP(ARRAY[CAST('b' AS VARCHAR)], ARRAY[2])], ARRAY[MAP(ARRAY['c'], ARRAY[3]), MAP()], (x, y) -> map_concat(x, y))", new ArrayType(mapType(VARCHAR, INTEGER)), ImmutableList.of(ImmutableMap.of("a", 1, "c", 3), ImmutableMap.of("b", 2))); } @Test public void testDifferentLength() { assertInvalidFunction("zip_with(ARRAY[1], ARRAY['a', 'b'], (x, y) -> (y, x))", "Arrays must have the same length"); assertInvalidFunction("zip_with(ARRAY[NULL, 2], ARRAY['a'], (x, y) -> (y, x))", "Arrays must have the same length"); assertInvalidFunction("zip_with(ARRAY[1, NULL], ARRAY[NULL, 2, 1], (x, y) -> x + y)", "Arrays must have the same length"); } @Test public void testWithNull() { assertFunction("zip_with(CAST(NULL AS ARRAY(UNKNOWN)), ARRAY[], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), null); assertFunction("zip_with(ARRAY[NULL], ARRAY[NULL], (x, y) -> (y, x))", new ArrayType(new RowType(ImmutableList.of(UNKNOWN, UNKNOWN), Optional.empty())), ImmutableList.of(asList(null, null))); assertFunction("zip_with(ARRAY[NULL], ARRAY[NULL], (x, y) -> x IS NULL AND y IS NULL)", new ArrayType(BOOLEAN), ImmutableList.of(true)); assertFunction("zip_with(ARRAY['a', NULL], ARRAY[NULL, 1], (x, y) -> x IS NULL OR y IS NULL)", new ArrayType(BOOLEAN), ImmutableList.of(true, true)); assertFunction("zip_with(ARRAY[1, NULL], ARRAY[3, 4], (x, y) -> x + y)", new ArrayType(INTEGER), asList(4, null)); assertFunction("zip_with(ARRAY['a', 'b'], ARRAY[1, 3], (x, y) -> NULL)", new ArrayType(UNKNOWN), asList(null, null)); } }
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.admin.jmx.internal; import javax.management.ObjectName; import javax.management.modelmbean.ModelMBean; import org.apache.geode.admin.internal.SystemMemberCacheImpl; import org.apache.geode.cache.Region; import org.apache.geode.internal.admin.GemFireVM; /** * MBean representation of {@link org.apache.geode.admin.SystemMemberRegion}. * * @since GemFire 3.5 */ public class SystemMemberRegionJmxImpl extends org.apache.geode.admin.internal.SystemMemberRegionImpl implements org.apache.geode.admin.jmx.internal.ManagedResource { /** The object name of this managed resource */ private ObjectName objectName; // ------------------------------------------------------------------------- // Constructor(s) // ------------------------------------------------------------------------- /** * Constructs an instance of SystemMemberRegionJmxImpl. * * @param cache the cache this region belongs to * @param region internal region to delegate real work to */ public SystemMemberRegionJmxImpl(SystemMemberCacheImpl cache, Region region) throws org.apache.geode.admin.AdminException { super(cache, region); initializeMBean(cache); } /** Create and register the MBean to manage this resource */ private void initializeMBean(SystemMemberCacheImpl cache) throws org.apache.geode.admin.AdminException { GemFireVM vm = cache.getVM(); mbeanName = "GemFire.Cache:" + "path=" + MBeanUtils.makeCompliantMBeanNameProperty(getFullPath()) + ",name=" + MBeanUtils.makeCompliantMBeanNameProperty(cache.getName()) + ",id=" + cache.getId() + ",owner=" + MBeanUtils.makeCompliantMBeanNameProperty(vm.getId().toString()) + ",type=Region"; objectName = MBeanUtils.createMBean(this); } // ------------------------------------------------------------------------- // ManagedResource implementation // ------------------------------------------------------------------------- /** The name of the MBean that will manage this resource */ private String mbeanName; /** The ModelMBean that is configured to manage this resource */ private ModelMBean modelMBean; @Override public String getMBeanName() { return mbeanName; } @Override public ModelMBean getModelMBean() { return modelMBean; } @Override public void setModelMBean(ModelMBean modelMBean) { this.modelMBean = modelMBean; } @Override public ObjectName getObjectName() { return objectName; } @Override public ManagedResourceType getManagedResourceType() { return ManagedResourceType.SYSTEM_MEMBER_REGION; } @Override public void cleanupResource() {} /** * Checks equality of the given object with <code>this</code> based on the type (Class) and the * MBean Name returned by <code>getMBeanName()</code> methods. * * @param obj object to check equality with * @return true if the given object is if the same type and its MBean Name is same as * <code>this</code> object's MBean Name, false otherwise */ @Override public boolean equals(Object obj) { if (!(obj instanceof SystemMemberRegionJmxImpl)) { return false; } SystemMemberRegionJmxImpl other = (SystemMemberRegionJmxImpl) obj; return getMBeanName().equals(other.getMBeanName()); } /** * Returns hash code for <code>this</code> object which is based on the MBean Name generated. * * @return hash code for <code>this</code> object */ @Override public int hashCode() { return getMBeanName().hashCode(); } }
Java
let hookTypes; const callStyles = { sync: 'applyPlugins', syncWaterfall: 'applyPluginsWaterfall', syncBail: 'applyPluginsBailResult', sync_map: 'applyPlugins', asyncWaterfall: 'applyPluginsAsyncWaterfall', asyncParallel: 'applyPluginsParallel', asyncSerial: 'applyPluginsAsync', }; const camelToDash = camel => camel.replace(/_/g, '--').replace(/[A-Z]/g, c => `-${c.toLowerCase()}`); const knownPluginRegistrations = { Compilation: { needAdditionalPass: ['sync', []], succeedModule: ['sync', ['module']], buildModule: ['sync', ['module']], seal: ['sync', []], }, Compiler: { afterCompile: ['asyncSerial', ['compilation']], afterEnvironment: ['sync', []], afterPlugins: ['sync', []], afterResolvers: ['sync', []], compilation: ['sync', ['compilation', 'params']], emit: ['asyncSerial', ['compilation']], make: ['asyncParallel', ['compilation']], watchRun: ['asyncSerial', ['watcher']], run: ['asyncSerial', ['compiler']], }, NormalModuleFactory: { createModule: ['syncBail', ['data']], parser: ['sync_map', ['parser', 'parserOptions']], resolver: ['syncWaterfall', ['nextResolver']], }, ContextModuleFactory: { afterResolve: ['asyncWaterfall', ['data']], }, }; exports.register = (tapable, name, style, args) => { if (tapable.hooks) { if (!hookTypes) { const Tapable = require('tapable'); hookTypes = { sync: Tapable.SyncHook, syncWaterfall: Tapable.SyncWaterfallHook, syncBail: Tapable.SyncBailHook, asyncWaterfall: Tapable.AsyncWaterfallHook, asyncParallel: Tapable.AsyncParallelHook, asyncSerial: Tapable.AsyncSeriesHook, asyncSeries: Tapable.AsyncSeriesHook, }; } if (!tapable.hooks[name]) { tapable.hooks[name] = new hookTypes[style](args); } } else { if (!tapable.__hardSource_hooks) { tapable.__hardSource_hooks = {}; } if (!tapable.__hardSource_hooks[name]) { tapable.__hardSource_hooks[name] = { name, dashName: camelToDash(name), style, args, async: style.startsWith('async'), map: style.endsWith('_map'), }; } if (!tapable.__hardSource_proxy) { tapable.__hardSource_proxy = {}; } if (!tapable.__hardSource_proxy[name]) { if (tapable.__hardSource_hooks[name].map) { const _forCache = {}; tapable.__hardSource_proxy[name] = { _forCache, for: key => { let hook = _forCache[key]; if (hook) { return hook; } _forCache[key] = { tap: (...args) => exports.tapFor(tapable, name, key, ...args), tapPromise: (...args) => exports.tapPromiseFor(tapable, name, key, ...args), call: (...args) => exports.callFor(tapable, name, key, ...args), promise: (...args) => exports.promiseFor(tapable, name, key, ...args), }; return _forCache[key]; }, tap: (...args) => exports.tapFor(tapable, name, ...args), tapPromise: (...args) => exports.tapPromiseFor(tapable, name, ...args), call: (...args) => exports.callFor(tapable, name, ...args), promise: (...args) => exports.promiseFor(tapable, name, ...args), }; } else { tapable.__hardSource_proxy[name] = { tap: (...args) => exports.tap(tapable, name, ...args), tapPromise: (...args) => exports.tapPromise(tapable, name, ...args), call: (...args) => exports.call(tapable, name, args), promise: (...args) => exports.promise(tapable, name, args), }; } } } }; exports.tap = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tap(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; if (tapable.__hardSource_hooks[name].async) { tapable.plugin(dashName, (...args) => { const cb = args.pop(); cb(null, callback(...args)); }); } else { tapable.plugin(dashName, callback); } } }; exports.tapPromise = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tapPromise(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; tapable.plugin(dashName, (...args) => { const cb = args.pop(); return callback(...args).then(value => cb(null, value), cb); }); } }; exports.tapAsync = (tapable, name, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].tapAsync(reason, callback); } else { if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) { const registration = knownPluginRegistrations[tapable.constructor.name][name]; exports.register(tapable, name, registration[0], registration[1]); } const dashName = tapable.__hardSource_hooks[name].dashName; tapable.plugin(dashName, callback); } }; exports.call = (tapable, name, args) => { if (tapable.hooks) { const hook = tapable.hooks[name]; return hook.call(...args); } else { const dashName = tapable.__hardSource_hooks[name].dashName; const style = tapable.__hardSource_hooks[name].style; return tapable[callStyles[style]](...[dashName].concat(args)); } }; exports.promise = (tapable, name, args) => { if (tapable.hooks) { const hook = tapable.hooks[name]; return hook.promise(...args); } else { const dashName = tapable.__hardSource_hooks[name].dashName; const style = tapable.__hardSource_hooks[name].style; return new Promise((resolve, reject) => { tapable[callStyles[style]]( ...[dashName].concat(args, (err, value) => { if (err) { reject(err); } else { resolve(value); } }), ); }); } }; exports.tapFor = (tapable, name, key, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].for(key).tap(reason, callback); } else { exports.tap(tapable, name, reason, callback); } }; exports.tapPromiseFor = (tapable, name, key, reason, callback) => { if (tapable.hooks) { tapable.hooks[name].for(key).tapPromise(reason, callback); } else { exports.tapPromise(tapable, name, reason, callback); } }; exports.callFor = (tapable, name, key, args) => { if (tapable.hooks) { tapable.hooks[name].for(key).call(...args); } else { exports.call(tapable, name, args); } }; exports.promiseFor = (tapable, name, key, args) => { if (tapable.hooks) { tapable.hooks[name].for(key).promise(...args); } else { exports.promise(tapable, name, args); } }; exports.hooks = tapable => { if (tapable.hooks) { return tapable.hooks; } if (!tapable.__hardSource_proxy) { tapable.__hardSource_proxy = {}; } const registrations = knownPluginRegistrations[tapable.constructor.name]; if (registrations) { for (const name in registrations) { const registration = registrations[name]; exports.register(tapable, name, registration[0], registration[1]); } } return tapable.__hardSource_proxy; };
Java
/* socket.c Created: Feb 2001 by Philip Homburg <[email protected]> Open a TCP connection */ #define _POSIX_C_SOURCE 2 #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include <signal.h> #include <string.h> #include <unistd.h> #include <sys/ioctl.h> #include <sys/wait.h> #include <net/hton.h> #include <net/netlib.h> #include <net/gen/in.h> #include <net/gen/inet.h> #include <netdb.h> #include <net/gen/socket.h> #include <net/gen/tcp.h> #include <net/gen/tcp_io.h> #define BUF_SIZE 10240 char *progname; int tcpfd= -1; char buf[BUF_SIZE]; static int bulk= 0; static int push= 0; static int stdout_issocket= 0; static int timeout; static void do_conn(char *hostname, char *portname); static void alrm_conn(int sig); static void alrm_io(int sig); static void fullduplex(void); static void fatal(char *msg, ...); static void usage(void); int main(int argc, char *argv[]) { int c; char *hostname; char *portname; char *check; int B_flag, P_flag, s_flag; char *t_arg; (progname=strrchr(argv[0],'/')) ? progname++ : (progname=argv[0]); B_flag= 0; P_flag= 0; s_flag= 0; t_arg= NULL; while (c= getopt(argc, argv, "BPst:?"), c != -1) { switch(c) { case 'B': B_flag= 1; break; case 'P': P_flag= 1; break; case 's': s_flag= 1; break; case 't': t_arg= optarg; break; case '?': usage(); default: fatal("getopt failed: '%c'", c); } } if (t_arg) { timeout= strtol(t_arg, &check, 0); if (check[0] != '\0') fatal("unable to parse timeout '%s'\n", t_arg); if (timeout <= 0) fatal("bad timeout '%d'\n", timeout); } else timeout= 0; if (optind+2 != argc) usage(); hostname= argv[optind++]; portname= argv[optind++]; bulk= B_flag; push= P_flag; stdout_issocket= s_flag; do_conn(hostname, portname); /* XXX */ if (timeout) { signal(SIGALRM, alrm_io); alarm(timeout); } fullduplex(); exit(0); } static void do_conn(char *hostname, char *portname) { ipaddr_t addr; tcpport_t port; struct hostent *he; struct servent *se; char *tcp_device, *check; nwio_tcpconf_t tcpconf; nwio_tcpcl_t tcpcl; nwio_tcpopt_t tcpopt; if (!inet_aton(hostname, &addr)) { he= gethostbyname(hostname); if (he == NULL) fatal("unknown hostname '%s'", hostname); if (he->h_addrtype != AF_INET || he->h_length != sizeof(addr)) fatal("bad address for '%s'", hostname); memcpy(&addr, he->h_addr, sizeof(addr)); } port= strtol(portname, &check, 0); if (check[0] != 0) { se= getservbyname(portname, "tcp"); if (se == NULL) fatal("unkown port '%s'", portname); port= ntohs(se->s_port); } tcp_device= getenv("TCP_DEVICE"); if (tcp_device == NULL) tcp_device= TCP_DEVICE; tcpfd= open(tcp_device, O_RDWR); if (tcpfd == -1) fatal("unable to open '%s': %s", tcp_device, strerror(errno)); tcpconf.nwtc_flags= NWTC_EXCL | NWTC_LP_SEL | NWTC_SET_RA | NWTC_SET_RP; tcpconf.nwtc_remaddr= addr; tcpconf.nwtc_remport= htons(port);; if (ioctl(tcpfd, NWIOSTCPCONF, &tcpconf) == -1) fatal("NWIOSTCPCONF failed: %s", strerror(errno)); if (timeout) { signal(SIGALRM, alrm_conn); alarm(timeout); } tcpcl.nwtcl_flags= 0; if (ioctl(tcpfd, NWIOTCPCONN, &tcpcl) == -1) { fatal("unable to connect to %s:%u: %s", inet_ntoa(addr), ntohs(tcpconf.nwtc_remport), strerror(errno)); } alarm(0); if (bulk) { tcpopt.nwto_flags= NWTO_BULK; if (ioctl(tcpfd, NWIOSTCPOPT, &tcpopt) == -1) fatal("NWIOSTCPOPT failed: %s", strerror(errno)); } } static void alrm_conn(int sig) { fatal("timeout during connect"); } static void alrm_io(int sig) { fatal("timeout during io"); } static void fullduplex(void) { pid_t cpid; int o, r, s, s_errno, loc; cpid= fork(); switch(cpid) { case -1: fatal("fork failed: %s", strerror(errno)); case 0: /* Read from TCP, write to stdout. */ for (;;) { r= read(tcpfd, buf, BUF_SIZE); if (r == 0) break; if (r == -1) { r= errno; if (stdout_issocket) ioctl(1, NWIOTCPSHUTDOWN, NULL); fatal("error reading from TCP conn.: %s", strerror(errno)); } s= r; for (o= 0; o<s; o += r) { r= write(1, buf+o, s-o); if (r <= 0) { fatal("error writing to stdout: %s", r == 0 ? "EOF" : strerror(errno)); } } } if (stdout_issocket) { r= ioctl(1, NWIOTCPSHUTDOWN, NULL); if (r == -1) { fatal("NWIOTCPSHUTDOWN failed on stdout: %s", strerror(errno)); } } exit(0); default: break; } /* Read from stdin, write to TCP. */ for (;;) { r= read(0, buf, BUF_SIZE); if (r == 0) break; if (r == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("error reading from stdin: %s", strerror(s_errno)); } s= r; for (o= 0; o<s; o += r) { r= write(tcpfd, buf+o, s-o); if (r <= 0) { s_errno= errno; kill(cpid, SIGTERM); fatal("error writing to TCP conn.: %s", r == 0 ? "EOF" : strerror(s_errno)); } } if (push) ioctl(tcpfd, NWIOTCPPUSH, NULL); } if (ioctl(tcpfd, NWIOTCPSHUTDOWN, NULL) == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("unable to shut down TCP conn.: %s", strerror(s_errno)); } r= waitpid(cpid, &loc, 0); if (r == -1) { s_errno= errno; kill(cpid, SIGTERM); fatal("waitpid failed: %s", strerror(s_errno)); } if (WIFEXITED(loc)) exit(WEXITSTATUS(loc)); kill(getpid(), WTERMSIG(loc)); exit(1); } static void fatal(char *fmt, ...) { va_list ap; va_start(ap, fmt); fprintf(stderr, "%s: ", progname); vfprintf(stderr, fmt, ap); fprintf(stderr, "\n"); va_end(ap); exit(1); } static void usage(void) { fprintf(stderr, "Usage: %s [-BPs] [-t timeout] hostname portname\n", progname); exit(1); } /* * $PchId: socket.c,v 1.3 2005/01/31 22:33:20 philip Exp $ */
Java
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. """Arm(R) Ethos(TM)-N integration relu tests""" import numpy as np import pytest import tvm from tvm import relay from tvm.testing import requires_ethosn from . import infrastructure as tei def _get_model(shape, dtype, a_min, a_max): assert a_min >= np.iinfo(dtype).min and a_max <= np.iinfo(dtype).max a = relay.var("a", shape=shape, dtype=dtype) relu = relay.clip(a, a_min=a_min, a_max=a_max) return relu @requires_ethosn @pytest.mark.parametrize("dtype", ["uint8", "int8"]) def test_relu(dtype): trials = [ ((1, 4, 4, 4), 65, 178, "uint8"), ((1, 8, 4, 2), 1, 254, "uint8"), ((1, 16), 12, 76, "uint8"), ((1, 4, 4, 4), 65, 125, "int8"), ((1, 8, 4, 2), -100, 100, "int8"), ((1, 16), -120, -20, "int8"), ] np.random.seed(0) for shape, a_min, a_max, trial_dtype in trials: if trial_dtype == dtype: inputs = { "a": tvm.nd.array( np.random.randint( low=np.iinfo(dtype).min, high=np.iinfo(dtype).max + 1, size=shape, dtype=dtype, ) ), } outputs = [] for npu in [False, True]: model = _get_model(inputs["a"].shape, dtype, a_min, a_max) mod = tei.make_module(model, {}) outputs.append(tei.build_and_run(mod, inputs, 1, {}, npu=npu)) tei.verify(outputs, dtype, 1) @requires_ethosn def test_relu_failure(): trials = [ ((1, 4, 4, 4, 4), "uint8", 65, 78, "dimensions=5, dimensions must be <= 4"), ((1, 8, 4, 2), "int16", 1, 254, "dtype='int16', dtype must be either uint8, int8 or int32"), ((1, 8, 4, 2), "uint8", 254, 1, "Relu has lower bound > upper bound"), ((2, 2, 2, 2), "uint8", 1, 63, "batch size=2, batch size must = 1; "), ] for shape, dtype, a_min, a_max, err_msg in trials: model = _get_model(shape, dtype, a_min, a_max) mod = tei.make_ethosn_partition(model) tei.test_error(mod, {}, err_msg)
Java
/* * Copyright (c) 2013 Houbrechts IT * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.github.houbie.lesscss.engine; import com.github.houbie.lesscss.LessParseException; import com.github.houbie.lesscss.resourcereader.ResourceReader; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.script.Invocable; import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.SequenceInputStream; import java.util.Map; import static com.github.houbie.lesscss.LessCompiler.CompilationDetails; /** * LessCompilationEngine implementation that uses a standard {@link javax.script.ScriptEngine} implementation. */ public class ScriptEngineLessCompilationEngine implements LessCompilationEngine { private static Logger logger = LoggerFactory.getLogger(ScriptEngineLessCompilationEngine.class); private static final String JS_ALL_MIN_JS = "js/all-min.js"; private static final String LESS_SCRIPT = "js/less-rhino-1.7.0-mod.js"; private static final String MINIFY_SCRIPT = "js/cssmin.js"; private static final String COMPILE_SCRIPT = "js/compile.js"; private static final boolean MINIFIED = true; private ScriptEngine scriptEngine; /** * @param scriptEngineName the name of the underlying ScriptEngine (e.g. "nashorn", "rhino", ...) */ public ScriptEngineLessCompilationEngine(String scriptEngineName) { logger.info("creating new NashornEngine"); ScriptEngineManager factory = new ScriptEngineManager(); scriptEngine = factory.getEngineByName(scriptEngineName); if (scriptEngine == null) { throw new RuntimeException("The ScriptEngine " + scriptEngineName + " could not be loaded"); } } /** * @param scriptEngine the underlying ScriptEngine */ public ScriptEngineLessCompilationEngine(ScriptEngine scriptEngine) { logger.info("creating new engine with {}", scriptEngine.getClass()); this.scriptEngine = scriptEngine; } @Override public void initialize(Reader customJavaScriptReader) { try { if (customJavaScriptReader != null) { scriptEngine.eval(customJavaScriptReader); } scriptEngine.eval(getLessScriptReader()); } catch (Exception e) { throw new RuntimeException(e); } } private Reader getLessScriptReader() { ClassLoader cl = getClass().getClassLoader(); InputStream concatenatedScripts; if (MINIFIED) { concatenatedScripts = cl.getResourceAsStream(JS_ALL_MIN_JS); } else { concatenatedScripts = new SequenceInputStream(cl.getResourceAsStream(LESS_SCRIPT), new SequenceInputStream(cl.getResourceAsStream(MINIFY_SCRIPT), cl.getResourceAsStream(COMPILE_SCRIPT))); } return new InputStreamReader(concatenatedScripts); } @Override public CompilationDetails compile(String less, CompilationOptions compilationOptions, ResourceReader resourceReader) { Map result; try { result = (Map) ((Invocable) scriptEngine).invokeFunction("compile", less, compilationOptions, resourceReader); } catch (Exception e) { throw new RuntimeException("Exception while compiling less", e); } if (result.get("parseException") != null) { throw new LessParseException((String) result.get("parseException")); } return new CompilationDetails((String) result.get("css"), (String) result.get("sourceMapContent")); } public ScriptEngine getScriptEngine() { return scriptEngine; } }
Java
/* * sbt * Copyright 2011 - 2018, Lightbend, Inc. * Copyright 2008 - 2010, Mark Harrah * Licensed under Apache License 2.0 (see LICENSE) */ package sbt package internal package parser import java.io.File import scala.io.Source object NewFormatSpec extends AbstractSpec { implicit val splitter: SplitExpressions.SplitExpression = EvaluateConfigurations.splitExpressions test("New Format should handle lines") { val rootPath = getClass.getResource("/new-format").getPath println(s"Reading files from: $rootPath") val allFiles = new File(rootPath).listFiles.toList allFiles foreach { path => println(s"$path") val lines = Source.fromFile(path).getLines().toList val (_, statements) = splitter(path, lines) assert(statements.nonEmpty, s""" |***should contains statements*** |$lines """.stripMargin) } } }
Java
package issues.issue130; public class Impl_0 { public int a = 0; protected void printMe(String s) { System.out.println(s); } }
Java
/** * Wraps the * * @param text * {string} haystack to search through * @param search * {string} needle to search for * @param [caseSensitive] * {boolean} optional boolean to use case-sensitive searching */ angular.module('ui.highlight', []).filter('highlight', function(highlight) { return function(text, search, caseSensitive) { if (search || angular.isNumber(search)) { var ltext = text.toString(); var lsearch = search.toString(); if (caseSensitive) { return ltext.split(lsearch).join('<span class="ui-match">' + lsearch + '</span>'); } else { return ltext.replace(new RegExp(lsearch, 'gi'), '<span class="ui-match">$&</span>'); } } else { return text; } }; });
Java
FROM ubuntu:18.04 LABEL maintainer="[email protected]" RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y build-essential clang git cmake \ qt5-default qttools5-dev qttools5-dev-tools libboost-system-dev libboost-filesystem-dev libboost-python-dev python-numpy \ libopencv-dev libpoco-dev libdlib-dev RUN cd / && git clone https://github.com/annotatorproject/annotatorlib RUN cd /annotatorlib && mkdir build && cd build \ && cmake -DCMAKE_BUILD_TYPE=Release .. \ && make -j3 && make install && ldconfig \ && ln -s /usr/local/lib/pyannotatorlib.so /usr/lib/python2.7/pyannotatorlib.so RUN cd /annotatorlib/source/imagesets && git clone https://github.com/annotatorproject/annotatorimageset_flickr \ && cd ../../build && cmake .. && make -j3 && make install && ldconfig
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.handler.export; import java.io.IOException; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.MultiDocValues; import org.apache.lucene.index.OrdinalMap; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.LongValues; class StringValue implements SortValue { private final SortedDocValues globalDocValues; private final OrdinalMap ordinalMap; private final String field; private final IntComp comp; protected LongValues toGlobal = LongValues.IDENTITY; // this segment to global ordinal. NN; protected SortedDocValues docValues; public int currentOrd; protected int lastDocID; private boolean present; private BytesRef lastBytes; private String lastString; private int lastOrd = -1; private int leafOrd = -1; public StringValue(SortedDocValues globalDocValues, String field, IntComp comp) { this.globalDocValues = globalDocValues; this.docValues = globalDocValues; if (globalDocValues instanceof MultiDocValues.MultiSortedDocValues) { this.ordinalMap = ((MultiDocValues.MultiSortedDocValues) globalDocValues).mapping; } else { this.ordinalMap = null; } this.field = field; this.comp = comp; this.currentOrd = comp.resetValue(); this.present = false; } public String getLastString() { return this.lastString; } public void setLastString(String lastString) { this.lastString = lastString; } public StringValue copy() { StringValue copy = new StringValue(globalDocValues, field, comp); return copy; } public void setCurrentValue(int docId) throws IOException { // System.out.println(docId +":"+lastDocID); /* if (docId < lastDocID) { throw new AssertionError("docs were sent out-of-order: lastDocID=" + lastDocID + " vs doc=" + docId); } lastDocID = docId; */ if (docId > docValues.docID()) { docValues.advance(docId); } if (docId == docValues.docID()) { present = true; currentOrd = docValues.ordValue(); } else { present = false; currentOrd = -1; } } @Override public boolean isPresent() { return present; } public void setCurrentValue(SortValue sv) { StringValue v = (StringValue) sv; this.currentOrd = v.currentOrd; this.present = v.present; this.leafOrd = v.leafOrd; this.lastOrd = v.lastOrd; this.toGlobal = v.toGlobal; } public Object getCurrentValue() throws IOException { assert present == true; if (currentOrd != lastOrd) { lastBytes = docValues.lookupOrd(currentOrd); lastOrd = currentOrd; lastString = null; } return lastBytes; } public void toGlobalValue(SortValue previousValue) { lastOrd = currentOrd; StringValue sv = (StringValue) previousValue; if (sv.lastOrd == currentOrd) { // Take the global ord from the previousValue unless we are a -1 which is the same in both // global and leaf ordinal if (this.currentOrd != -1) { this.currentOrd = sv.currentOrd; } } else { if (this.currentOrd > -1) { this.currentOrd = (int) toGlobal.get(this.currentOrd); } } } public String getField() { return field; } public void setNextReader(LeafReaderContext context) throws IOException { leafOrd = context.ord; if (ordinalMap != null) { toGlobal = ordinalMap.getGlobalOrds(context.ord); } docValues = DocValues.getSorted(context.reader(), field); lastDocID = 0; } public void reset() { this.currentOrd = comp.resetValue(); this.present = false; lastDocID = 0; } public int compareTo(SortValue o) { StringValue sv = (StringValue) o; return comp.compare(currentOrd, sv.currentOrd); } public String toString() { return Integer.toString(this.currentOrd); } }
Java
package at.jku.sea.cloud.rest.pojo.stream.provider; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeInfo.Id; import com.fasterxml.jackson.annotation.JsonTypeName; import at.jku.sea.cloud.rest.pojo.PojoCollectionArtifact; @JsonTypeInfo(use = Id.NAME, property = "__type") @JsonTypeName(value = "CollectionArtifactProvider") public class PojoCollectionArtifactProvider extends PojoProvider { private PojoCollectionArtifact collectionArtifact; public PojoCollectionArtifactProvider() { } public PojoCollectionArtifactProvider(PojoCollectionArtifact collectionArtifact) { this.collectionArtifact = collectionArtifact; } public PojoCollectionArtifact getCollectionArtifact() { return collectionArtifact; } public void setCollectionArtifact(PojoCollectionArtifact collectionArtifact) { this.collectionArtifact = collectionArtifact; } }
Java
package com.sebastian_daschner.scalable_coffee_shop.beans.boundary; import javax.inject.Inject; import javax.json.Json; import javax.json.JsonObject; import javax.json.JsonObjectBuilder; import javax.ws.rs.BadRequestException; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; @Path("beans") public class BeansResource { @Inject BeanCommandService commandService; @Inject BeanQueryService queryService; @GET public JsonObject getBeans() { final JsonObjectBuilder builder = Json.createObjectBuilder(); queryService.getStoredBeans() .entrySet().forEach(e -> builder.add(e.getKey(), e.getValue())); return builder.build(); } @POST public void storeBeans(JsonObject object) { final String beanOrigin = object.getString("beanOrigin", null); final int amount = object.getInt("amount", 0); if (beanOrigin == null || amount == 0) throw new BadRequestException(); commandService.storeBeans(beanOrigin, amount); } }
Java
#!/bin/bash -e # # # Shutdown script for Datafari # # if (( EUID != 0 )); then echo "You need to be root to run this script." 1>&2 exit 100 fi DIR=../../../macosx/bin source "set-datafari-env-devmode.sh" source "${DIR}/utils.sh" if is_running $SOLR_PID_FILE; then SOLR_INCLUDE=$SOLR_ENV $SOLR_INSTALL_DIR/bin/solr stop else echo "Warn : Solr does not seem to be running." fi if is_running $CASSANDRA_PID_FILE; then kill $(cat $CASSANDRA_PID_FILE) rm $CASSANDRA_PID_FILE else echo "Warn : Cassandra does not seem to be running." fi
Java
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package com.intellij.execution.configurations; import com.intellij.execution.ExecutionBundle; import com.intellij.openapi.options.ConfigurationException; import com.intellij.openapi.progress.ProcessCanceledException; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.NlsContexts.DialogMessage; import com.intellij.util.ThrowableRunnable; import javax.swing.*; import static com.intellij.openapi.util.NlsContexts.DialogTitle; public class RuntimeConfigurationException extends ConfigurationException { public RuntimeConfigurationException(@DialogMessage String message, @DialogTitle String title) { super(message, title); } public RuntimeConfigurationException(@DialogMessage String message) { super(message, ExecutionBundle.message("run.configuration.error.dialog.title")); } public RuntimeConfigurationException(@DialogMessage String message, Throwable cause) { super(message, cause, ExecutionBundle.message("run.configuration.error.dialog.title")); } public static <T extends Throwable> ValidationInfo validate(JComponent component, ThrowableRunnable<T> runnable) { try { runnable.run(); return new ValidationInfo("", component); } catch (ProcessCanceledException e) { throw e; } catch (Throwable t) { return new ValidationInfo(t.getMessage(), component); } } }
Java
package com.inmobi.messaging; /* * #%L * messaging-client-core * %% * Copyright (C) 2012 - 2014 InMobi * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.nio.ByteBuffer; /** * Message class holding the data. * */ public final class Message implements MessageBase { private ByteBuffer data; public Message() { } /** * Create new message with {@link ByteBuffer} * * @param data The {@link ByteBuffer} */ public Message(ByteBuffer data) { this.data = data; } /** * Create new message with byte array * * @param data The byte array. */ public Message(byte[] data) { this.data = ByteBuffer.wrap(data); } /** * Get the data associated with message. * * @return {@link ByteBuffer} holding the data. */ public ByteBuffer getData() { return data; } public synchronized void set(ByteBuffer data) { this.data = data; } public synchronized void clear() { data.clear(); } public long getSize() { return data.limit(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((data == null) ? 0 : data.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Message other = (Message) obj; if (data == null) { if (other.data != null) { return false; } } else if (!data.equals(other.data)) { return false; } return true; } @Override public Message clone() { Message m = new Message(data.duplicate()); return m; } }
Java
package org.jboss.resteasy.client.core; import org.jboss.resteasy.client.ClientExecutor; import org.jboss.resteasy.client.ClientRequest; import org.jboss.resteasy.client.ClientResponse; import org.jboss.resteasy.client.ProxyConfig; import org.jboss.resteasy.client.core.extractors.ClientErrorHandler; import org.jboss.resteasy.client.core.extractors.ClientRequestContext; import org.jboss.resteasy.client.core.extractors.EntityExtractor; import org.jboss.resteasy.client.core.extractors.EntityExtractorFactory; import org.jboss.resteasy.client.core.marshallers.ClientMarshallerFactory; import org.jboss.resteasy.client.core.marshallers.Marshaller; import org.jboss.resteasy.client.exception.mapper.ClientExceptionMapper; import org.jboss.resteasy.resteasy_jaxrs.i18n.Messages; import org.jboss.resteasy.specimpl.ResteasyUriBuilder; import org.jboss.resteasy.spi.ResteasyProviderFactory; import org.jboss.resteasy.util.MediaTypeHelper; import javax.ws.rs.Path; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.MediaType; import javax.ws.rs.ext.Providers; import java.lang.reflect.Method; import java.net.URI; import java.util.HashMap; import java.util.Map; /** * @author <a href="mailto:[email protected]">Bill Burke</a> * @version $Revision: 1 $ */ @SuppressWarnings("unchecked") public class ClientInvoker extends ClientInterceptorRepositoryImpl implements MethodInvoker { protected ResteasyProviderFactory providerFactory; protected String httpMethod; protected ResteasyUriBuilder uri; protected Method method; protected Class declaring; protected MediaType accepts; protected Marshaller[] marshallers; protected ClientExecutor executor; protected boolean followRedirects; protected EntityExtractor extractor; protected EntityExtractorFactory extractorFactory; protected URI baseUri; protected Map<String, Object> attributes = new HashMap<String, Object>(); public ClientInvoker(URI baseUri, Class declaring, Method method, ResteasyProviderFactory providerFactory, ClientExecutor executor, EntityExtractorFactory extractorFactory) { this(baseUri, declaring, method, new ProxyConfig(null, executor, providerFactory, extractorFactory, null, null, null)); } public ClientInvoker(URI baseUri, Class declaring, Method method, ProxyConfig config) { this.declaring = declaring; this.method = method; this.marshallers = ClientMarshallerFactory.createMarshallers(declaring, method, providerFactory, config.getServerConsumes()); this.providerFactory = config.getProviderFactory(); this.executor = config.getExecutor(); accepts = MediaTypeHelper.getProduces(declaring, method, config.getServerProduces()); this.uri = new ResteasyUriBuilder(); this.baseUri = baseUri; uri.uri(baseUri); if (declaring.isAnnotationPresent(Path.class)) uri.path(declaring); if (method.isAnnotationPresent(Path.class)) uri.path(method); this.extractorFactory = config.getExtractorFactory(); this.extractor = extractorFactory.createExtractor(method); } public Map<String, Object> getAttributes() { return attributes; } public MediaType getAccepts() { return accepts; } public Method getMethod() { return method; } public Class getDeclaring() { return declaring; } public ResteasyProviderFactory getProviderFactory() { return providerFactory; } public Object invoke(Object[] args) { boolean isProvidersSet = ResteasyProviderFactory.getContextData(Providers.class) != null; if (!isProvidersSet) ResteasyProviderFactory.pushContext(Providers.class, providerFactory); try { if (uri == null) throw new RuntimeException(Messages.MESSAGES.baseURINotSetForClientProxy()); ClientRequest request = createRequest(args); BaseClientResponse clientResponse = null; try { clientResponse = (BaseClientResponse) request.httpMethod(httpMethod); } catch (Exception e) { ClientExceptionMapper<Exception> mapper = providerFactory.getClientExceptionMapper(Exception.class); if (mapper != null) { throw mapper.toException(e); } throw new RuntimeException(e); } ClientErrorHandler errorHandler = new ClientErrorHandler(providerFactory.getClientErrorInterceptors()); clientResponse.setAttributeExceptionsTo(method.toString()); clientResponse.setAnnotations(method.getAnnotations()); ClientRequestContext clientRequestContext = new ClientRequestContext(request, clientResponse, errorHandler, extractorFactory, baseUri); return extractor.extractEntity(clientRequestContext); } finally { if (!isProvidersSet) ResteasyProviderFactory.popContextData(Providers.class); } } protected ClientRequest createRequest(Object[] args) { ClientRequest request = new ClientRequest(uri, executor, providerFactory); request.getAttributes().putAll(attributes); if (accepts != null) request.header(HttpHeaders.ACCEPT, accepts.toString()); this.copyClientInterceptorsTo(request); boolean isClientResponseResult = ClientResponse.class.isAssignableFrom(method.getReturnType()); request.followRedirects(!isClientResponseResult || this.followRedirects); for (int i = 0; i < marshallers.length; i++) { marshallers[i].build(request, args[i]); } return request; } public String getHttpMethod() { return httpMethod; } public void setHttpMethod(String httpMethod) { this.httpMethod = httpMethod; } public boolean isFollowRedirects() { return followRedirects; } public void setFollowRedirects(boolean followRedirects) { this.followRedirects = followRedirects; } public void followRedirects() { setFollowRedirects(true); } }
Java
module.exports = { "env": { "es6": true, "node": true }, "globals": { "expect": true, "it": true, "describe": true, }, "extends": "eslint:recommended", "parser": "babel-eslint", "parserOptions": { "ecmaFeatures": { "experimentalObjectRestSpread": true, "jsx": true }, "sourceType": "module" }, "plugins": [ "react" ], "rules": { "no-unused-vars": 2, "react/jsx-uses-vars": 2, "react/jsx-uses-react": 2, "indent": [ "error", 2 ], "linebreak-style": [ "error", "unix" ], "quotes": [ "error", "single" ], "semi": [ "error", "always" ] } };
Java
/* Public domain */ typedef struct vg_point { struct vg_node _inherit; float size; /* Size in pixels (0.0 = invisible) */ } VG_Point; #define VGPOINT(p) ((VG_Point *)(p)) /* Begin generated block */ __BEGIN_DECLS extern DECLSPEC VG_NodeOps vgPointOps; static __inline__ VG_Point * VG_PointNew(void *pNode, VG_Vector pos) { VG_Point *vp; vp = (VG_Point *)AG_Malloc(sizeof(VG_Point)); VG_NodeInit(vp, &vgPointOps); VG_Translate(vp, pos); VG_NodeAttach(pNode, vp); return (vp); } static __inline__ void VG_PointSize(VG_Point *vp, float r) { VG_Lock(VGNODE(vp)->vg); vp->size = r; VG_Unlock(VGNODE(vp)->vg); } __END_DECLS /* Close generated block */
Java
// Decompiled by Jad v1.5.8e. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: braces fieldsfirst space lnc package cn.com.smartdevices.bracelet.view; import android.animation.Animator; // Referenced classes of package cn.com.smartdevices.bracelet.view: // RoundProgressBar class s implements android.animation.Animator.AnimatorListener { final RoundProgressBar a; s(RoundProgressBar roundprogressbar) { a = roundprogressbar; super(); } public void onAnimationCancel(Animator animator) { } public void onAnimationEnd(Animator animator) { if (RoundProgressBar.a(a) < RoundProgressBar.b(a) && RoundProgressBar.c(a) < RoundProgressBar.b(a)) { RoundProgressBar.a(a, RoundProgressBar.b(a)); RoundProgressBar.a(a, RoundProgressBar.a(a) - RoundProgressBar.c(a), RoundProgressBar.c(a), RoundProgressBar.a(a)); } } public void onAnimationRepeat(Animator animator) { } public void onAnimationStart(Animator animator) { } }
Java
(function(window) { var DEFAULT_ERROR_ID = 'error-default'; /** * Very simple base class for views. * Provides functionality for active/inactive. * * The first time the view is activated * the onactive function/event will fire. * * The .seen property is added to each object * with view in its prototype. .seen can be used * to detect if the view has ever been activated. * * @param {String|Object} options options or a selector for element. */ function View(options) { if (typeof(options) === 'undefined') { options = {}; } if (typeof(options) === 'string') { this.selectors = { element: options }; } else { var key; if (typeof(options) === 'undefined') { options = {}; } for (key in options) { if (options.hasOwnProperty(key)) { this[key] = options[key]; } } } this.hideErrors = this.hideErrors.bind(this); } const INVALID_CSS = /([^a-zA-Z\-\_0-9])/g; View.ACTIVE = 'active'; View.prototype = { seen: false, activeClass: View.ACTIVE, errorVisible: false, get element() { return this._findElement('element'); }, get status() { return this._findElement('status'); }, get errors() { return this._findElement('errors'); }, /** * Creates a string id for a given model. * * view.idForModel('foo-', { _id: 1 }); // => foo-1 * view.idForModel('foo-', '2'); // => foo-2 * * @param {String} prefix of string. * @param {Object|String|Numeric} objectOrString representation of model. */ idForModel: function(prefix, objectOrString) { prefix += (typeof(objectOrString) === 'object') ? objectOrString._id : objectOrString; return prefix; }, calendarId: function(input) { if (typeof(input) !== 'string') { input = input.calendarId; } input = this.cssClean(input); return 'calendar-id-' + input; }, /** * Delegate pattern event listener. * * @param {HTMLElement} element parent element. * @param {String} type type of dom event. * @param {String} selector css selector element should match * _note_ there is no magic here this * is determined from the root of the document. * @param {Function|Object} handler event handler. * first argument is the raw * event second is the element * matching the pattern. */ delegate: function(element, type, selector, handler) { if (typeof(handler) === 'object') { var context = handler; handler = function() { context.handleEvent.apply(context, arguments); }; } element.addEventListener(type, function(e) { var target = e.target; while (target !== element) { if ('mozMatchesSelector' in target && target.mozMatchesSelector(selector)) { return handler(e, target); } target = target.parentNode; } }); }, /** * Clean a string for use with css. * Converts illegal chars to legal ones. */ cssClean: function(string) { if (typeof(string) !== 'string') return string; //TODO: I am worried about the performance //of using this all over the place =/ //consider sanitizing all keys to ensure //they don't blow up when used as a selector? return string.replace(INVALID_CSS, '-'); }, /** * Finds a caches a element defined * by selectors * * @param {String} selector name as defined in selectors. * @param {Boolean} all true when to find all elements. (default false). */ _findElement: function(name, all, element) { if (typeof(all) === 'object') { element = all; all = false; } element = element || document; var cacheName; var selector; if (typeof(all) === 'undefined') { all = false; } if (name in this.selectors) { cacheName = '_' + name + 'Element'; selector = this.selectors[name]; if (!this[cacheName]) { if (all) { this[cacheName] = element.querySelectorAll(selector); } else { this[cacheName] = element.querySelector(selector); } } return this[cacheName]; } return null; }, /** * Displays a list of errors * * @param {Array} list error list * (see Event.validaitonErrors) or Error object. */ showErrors: function(list) { var _ = navigator.mozL10n.get; var errors = ''; // We can pass Error objects or // Array of {name: foo} objects if (!Array.isArray(list)) { list = [list]; } var i = 0; var len = list.length; for (; i < len; i++) { var name = list[i].l10nID || list[i].name; errors += _('error-' + name) || _(DEFAULT_ERROR_ID); } // populate error and display it. this.errors.textContent = errors; this.errorVisible = true; this.status.classList.add(this.activeClass); this.status.addEventListener('animationend', this.hideErrors); }, hideErrors: function() { this.status.classList.remove(this.activeClass); this.status.removeEventListener('animationend', this.hideErrors); this.errorVisible = false; }, onactive: function() { if (this.errorVisible) { this.hideErrors(); } //seen can be set to anything other //then false to override this behaviour if (this.seen === false) { this.onfirstseen(); } // intentionally using 'in' if ('dispatch' in this) { this.dispatch.apply(this, arguments); } this.seen = true; if (this.element) { this.element.classList.add(this.activeClass); } }, oninactive: function() { if (this.element) { this.element.classList.remove(this.activeClass); } }, onfirstseen: function() {} }; Calendar.View = View; }(this));
Java
require_extension('D'); require_rv64; require_fp; softfloat_roundingMode = RM; WRITE_FRD(i64_to_f64(RS1)); set_fp_exceptions;
Java
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.support.design.widget; import android.graphics.drawable.Drawable; import android.graphics.drawable.DrawableContainer; import android.util.Log; import java.lang.reflect.Method; /** Caution. Gross hacks ahead. */ class DrawableUtils { private static final String LOG_TAG = "DrawableUtils"; private static Method sSetConstantStateMethod; private static boolean sSetConstantStateMethodFetched; private DrawableUtils() {} static boolean setContainerConstantState( DrawableContainer drawable, Drawable.ConstantState constantState) { // We can use getDeclaredMethod() on v9+ return setContainerConstantStateV9(drawable, constantState); } private static boolean setContainerConstantStateV9( DrawableContainer drawable, Drawable.ConstantState constantState) { if (!sSetConstantStateMethodFetched) { try { sSetConstantStateMethod = DrawableContainer.class.getDeclaredMethod( "setConstantState", DrawableContainer.DrawableContainerState.class); sSetConstantStateMethod.setAccessible(true); } catch (NoSuchMethodException e) { Log.e(LOG_TAG, "Could not fetch setConstantState(). Oh well."); } sSetConstantStateMethodFetched = true; } if (sSetConstantStateMethod != null) { try { sSetConstantStateMethod.invoke(drawable, constantState); return true; } catch (Exception e) { Log.e(LOG_TAG, "Could not invoke setConstantState(). Oh well."); } } return false; } }
Java
# This code was automatically generated using xdrgen # DO NOT EDIT or your changes may be overwritten require 'xdr' # === xdr source ============================================================ # # enum ManageOfferEffect # { # MANAGE_OFFER_CREATED = 0, # MANAGE_OFFER_UPDATED = 1, # MANAGE_OFFER_DELETED = 2 # }; # # =========================================================================== module Stellar class ManageOfferEffect < XDR::Enum member :manage_offer_created, 0 member :manage_offer_updated, 1 member :manage_offer_deleted, 2 seal end end
Java
package com.artemis; import static org.junit.Assert.assertEquals; import java.util.NoSuchElementException; import com.artemis.systems.EntityProcessingSystem; import com.artemis.utils.IntBag; import org.junit.Test; import com.artemis.utils.ImmutableBag; /** * Created by obartley on 6/9/14. */ public class EntitySystemTest { @SuppressWarnings("static-method") @Test(expected = NoSuchElementException.class) public void test_process_one_inactive() { World w = new World(new WorldConfiguration() .setSystem(new IteratorTestSystem(0))); Entity e = w.createEntity(); e.edit().add(new C()); e.disable(); w.process(); } @SuppressWarnings("static-method") @Test public void test_process_one_active() { World w = new World(new WorldConfiguration() .setSystem(new IteratorTestSystem(1))); Entity e = w.createEntity(); e.edit().add(new C()); w.process(); } @Test public void aspect_exclude_only() { ExcludingSystem es1 = new ExcludingSystem(); EmptySystem es2 = new EmptySystem(); World w = new World(new WorldConfiguration() .setSystem(es1) .setSystem(es2)); Entity e = w.createEntity(); w.process(); assertEquals(1, es1.getActives().size()); assertEquals(1, es2.getActives().size()); } public static class C extends Component {} public static class C2 extends Component {} public static class IteratorTestSystem extends EntitySystem { public int expectedSize; @SuppressWarnings("unchecked") public IteratorTestSystem(int expectedSize) { super(Aspect.all(C.class)); this.expectedSize = expectedSize; } @Override protected void processSystem() { assertEquals(expectedSize, subscription.getEntities().size()); getActives().iterator().next(); } @Override protected boolean checkProcessing() { return true; } } public static class ExcludingSystem extends EntityProcessingSystem { public ExcludingSystem() { super(Aspect.exclude(C.class)); } @Override protected void process(Entity e) {} } public static class EmptySystem extends EntityProcessingSystem { public EmptySystem() { super(Aspect.all()); } @Override protected void process(Entity e) {} } }
Java
package com.sqisland.gce2retrofit; import com.google.gson.Gson; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.stream.JsonReader; import com.squareup.javawriter.JavaWriter; import org.apache.commons.cli.BasicParser; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; import org.apache.commons.lang3.text.WordUtils; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import static javax.lang.model.element.Modifier.PUBLIC; public class Generator { private static final String OPTION_CLASS_MAP = "classmap"; private static final String OPTION_METHODS = "methods"; private static Gson gson = new Gson(); public enum MethodType { SYNC, ASYNC, REACTIVE } public static void main(String... args) throws IOException, URISyntaxException { Options options = getOptions(); CommandLine cmd = getCommandLine(options, args); if (cmd == null) { return; } String[] arguments = cmd.getArgs(); if (arguments.length != 2) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("java -jar gce2retrofit.jar discovery.json output_dir", options); System.exit(1); } String discoveryFile = arguments[0]; String outputDir = arguments[1]; Map<String, String> classMap = cmd.hasOption(OPTION_CLASS_MAP)? readClassMap(new FileReader(cmd.getOptionValue(OPTION_CLASS_MAP))) : null; EnumSet<MethodType> methodTypes = getMethods(cmd.getOptionValue(OPTION_METHODS)); generate(new FileReader(discoveryFile), new FileWriterFactory(new File(outputDir)), classMap, methodTypes); } private static Options getOptions() { Options options = new Options(); options.addOption( OPTION_CLASS_MAP, true, "Map fields to classes. Format: field_name\\tclass_name"); options.addOption( OPTION_METHODS, true, "Methods to generate, either sync, async or reactive. Default is to generate sync & async."); return options; } private static CommandLine getCommandLine(Options options, String... args) { CommandLineParser parser = new BasicParser(); try { CommandLine cmd = parser.parse(options, args); return cmd; } catch (ParseException e) { System.out.println("Unexpected exception:" + e.getMessage()); } return null; } public static void generate( Reader discoveryReader, WriterFactory writerFactory, Map<String, String> classMap, EnumSet<MethodType> methodTypes) throws IOException, URISyntaxException { JsonReader jsonReader = new JsonReader(discoveryReader); Discovery discovery = gson.fromJson(jsonReader, Discovery.class); String packageName = StringUtil.getPackageName(discovery.baseUrl); if (packageName == null || packageName.isEmpty()) { packageName = StringUtil.getPackageName(discovery.rootUrl); } String modelPackageName = packageName + ".model"; for (Entry<String, JsonElement> entry : discovery.schemas.entrySet()) { generateModel( writerFactory, modelPackageName, entry.getValue().getAsJsonObject(), classMap); } if (discovery.resources != null) { generateInterfaceFromResources( writerFactory, packageName, "", discovery.resources, methodTypes); } if (discovery.name != null && discovery.methods != null) { generateInterface( writerFactory, packageName, discovery.name, discovery.methods, methodTypes); } } public static Map<String, String> readClassMap(Reader reader) throws IOException { Map<String, String> classMap = new HashMap<String, String>(); String line; BufferedReader bufferedReader = new BufferedReader(reader); while ((line = bufferedReader.readLine()) != null) { String[] fields = line.split("\t"); if (fields.length == 2) { classMap.put(fields[0], fields[1]); } } return classMap; } public static EnumSet<MethodType> getMethods(String input) { EnumSet<MethodType> methodTypes = EnumSet.noneOf(MethodType.class); if (input != null) { String[] parts = input.split(","); for (String part : parts) { if ("sync".equals(part) || "both".equals(part)) { methodTypes.add(MethodType.SYNC); } if ("async".equals(part) || "both".equals(part)) { methodTypes.add(MethodType.ASYNC); } if ("reactive".equals(part)) { methodTypes.add(MethodType.REACTIVE); } } } if (methodTypes.isEmpty()) { methodTypes = EnumSet.of(Generator.MethodType.ASYNC, Generator.MethodType.SYNC); } return methodTypes; } private static void generateModel( WriterFactory writerFactory, String modelPackageName, JsonObject schema, Map<String, String> classMap) throws IOException { String id = schema.get("id").getAsString(); String path = StringUtil.getPath(modelPackageName, id + ".java"); Writer writer = writerFactory.getWriter(path); JavaWriter javaWriter = new JavaWriter(writer); javaWriter.emitPackage(modelPackageName) .emitImports("com.google.gson.annotations.SerializedName") .emitEmptyLine() .emitImports("java.util.List") .emitEmptyLine(); String type = schema.get("type").getAsString(); if (type.equals("object")) { javaWriter.beginType(modelPackageName + "." + id, "class", EnumSet.of(PUBLIC)); generateObject(javaWriter, schema, classMap); javaWriter.endType(); } else if (type.equals("string")) { javaWriter.beginType(modelPackageName + "." + id, "enum", EnumSet.of(PUBLIC)); generateEnum(javaWriter, schema); javaWriter.endType(); } writer.close(); } private static void generateObject( JavaWriter javaWriter, JsonObject schema, Map<String, String> classMap) throws IOException { JsonElement element = schema.get("properties"); if (element == null) { return; } JsonObject properties = element.getAsJsonObject(); for (Entry<String, JsonElement> entry : properties.entrySet()) { String key = entry.getKey(); String variableName = key; if (StringUtil.isReservedWord(key)) { javaWriter.emitAnnotation("SerializedName(\"" + key + "\")"); variableName += "_"; } PropertyType propertyType = gson.fromJson( entry.getValue(), PropertyType.class); String javaType = propertyType.toJavaType(); if (classMap != null && classMap.containsKey(key)) { javaType = classMap.get(key); } javaWriter.emitField(javaType, variableName, EnumSet.of(PUBLIC)); } } private static void generateEnum(JavaWriter javaWriter, JsonObject schema) throws IOException { JsonArray enums = schema.get("enum").getAsJsonArray(); for (int i = 0; i < enums.size(); ++i) { javaWriter.emitEnumValue(enums.get(i).getAsString()); } } private static void generateInterfaceFromResources( WriterFactory writerFactory, String packageName, String resourceName, JsonObject resources, EnumSet<MethodType> methodTypes) throws IOException { for (Entry<String, JsonElement> entry : resources.entrySet()) { JsonObject entryValue = entry.getValue().getAsJsonObject(); if (entryValue.has("methods")) { generateInterface(writerFactory, packageName, resourceName + "_" + entry.getKey(), entryValue.get("methods").getAsJsonObject(), methodTypes); } if (entryValue.has("resources")) { generateInterfaceFromResources(writerFactory, packageName, resourceName + "_" + entry.getKey(), entryValue.get("resources").getAsJsonObject(), methodTypes); } } } private static void generateInterface( WriterFactory writerFactory, String packageName, String resourceName, JsonObject methods, EnumSet<MethodType> methodTypes) throws IOException { String capitalizedName = WordUtils.capitalizeFully(resourceName, '_'); String className = capitalizedName.replaceAll("_", ""); String path = StringUtil.getPath(packageName, className + ".java"); Writer fileWriter = writerFactory.getWriter(path); JavaWriter javaWriter = new JavaWriter(fileWriter); javaWriter.emitPackage(packageName) .emitImports(packageName + ".model.*") .emitEmptyLine() .emitImports( "retrofit.Callback", "retrofit.client.Response", "retrofit.http.GET", "retrofit.http.POST", "retrofit.http.PATCH", "retrofit.http.DELETE", "retrofit.http.Body", "retrofit.http.Path", "retrofit.http.Query"); if (methodTypes.contains(MethodType.REACTIVE)) { javaWriter.emitImports("rx.Observable"); } javaWriter.emitEmptyLine(); javaWriter.beginType( packageName + "." + className, "interface", EnumSet.of(PUBLIC)); for (Entry<String, JsonElement> entry : methods.entrySet()) { String methodName = entry.getKey(); Method method = gson.fromJson(entry.getValue(), Method.class); for (MethodType methodType : methodTypes) { javaWriter.emitAnnotation(method.httpMethod, "\"/" + method.path + "\""); emitMethodSignature(fileWriter, methodName, method, methodType); } } javaWriter.endType(); fileWriter.close(); } // TODO: Use JavaWriter to emit method signature private static void emitMethodSignature( Writer writer, String methodName, Method method, MethodType methodType) throws IOException { ArrayList<String> params = new ArrayList<String>(); if (method.request != null) { params.add("@Body " + method.request.$ref + " " + (method.request.parameterName != null ? method.request.parameterName : "resource")); } for (Entry<String, JsonElement> param : getParams(method)) { params.add(param2String(param)); } String returnValue = "void"; if (methodType == MethodType.SYNC && "POST".equals(method.httpMethod)) { returnValue = "Response"; } if (method.response != null) { if (methodType == MethodType.SYNC) { returnValue = method.response.$ref; } else if (methodType == MethodType.REACTIVE) { returnValue = "Observable<" + method.response.$ref + ">"; } } if (methodType == MethodType.ASYNC) { if (method.response == null) { params.add("Callback<Void> cb"); } else { params.add("Callback<" + method.response.$ref + "> cb"); } } writer.append(" " + returnValue + " " + methodName + (methodType == MethodType.REACTIVE ? "Rx" : "") + "("); for (int i = 0; i < params.size(); ++i) { if (i != 0) { writer.append(", "); } writer.append(params.get(i)); } writer.append(");\n"); } /** * Assemble a list of parameters, with the first entries matching the ones * listed in parameterOrder * * @param method The method containing parameters and parameterOrder * @return Ordered parameters */ private static List<Entry<String, JsonElement>> getParams(Method method) { List<Entry<String, JsonElement>> params = new ArrayList<Entry<String, JsonElement>>(); if (method.parameters == null) { return params; } // Convert the entry set into a map, and extract the keys not listed in // parameterOrder HashMap<String, Entry<String, JsonElement>> map = new HashMap<String, Entry<String, JsonElement>>(); List<String> remaining = new ArrayList<String>(); for (Entry<String, JsonElement> entry : method.parameters.entrySet()) { String key = entry.getKey(); map.put(key, entry); if (method.parameterOrder == null || !method.parameterOrder.contains(key)) { remaining.add(key); } } // Add the keys in parameterOrder if (method.parameterOrder != null) { for (String key : method.parameterOrder) { params.add(map.get(key)); } } // Then add the keys not in parameterOrder for (String key : remaining) { params.add(map.get(key)); } return params; } private static String param2String(Entry<String, JsonElement> param) { StringBuffer buf = new StringBuffer(); String paramName = param.getKey(); ParameterType paramType = gson.fromJson( param.getValue(), ParameterType.class); if ("path".equals(paramType.location)) { buf.append("@Path(\"" + paramName + "\") "); } if ("query".equals(paramType.location)) { buf.append("@Query(\"" + paramName + "\") "); } String type = paramType.toJavaType(); if (!paramType.required) { type = StringUtil.primitiveToObject(type); } buf.append(type + " " + paramName); return buf.toString(); } }
Java
/* * Copyright 2017 Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include <type_traits> #include <assert.h> #include <errno.h> #include <stdint.h> #include <boost/noncopyable.hpp> #include <folly/AtomicStruct.h> #include <folly/detail/CacheLocality.h> #include <folly/portability/SysMman.h> #include <folly/portability/Unistd.h> // Ignore shadowing warnings within this file, so includers can use -Wshadow. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wshadow" namespace folly { namespace detail { template <typename Pool> struct IndexedMemPoolRecycler; } /// Instances of IndexedMemPool dynamically allocate and then pool their /// element type (T), returning 4-byte integer indices that can be passed /// to the pool's operator[] method to access or obtain pointers to the /// actual elements. The memory backing items returned from the pool /// will always be readable, even if items have been returned to the pool. /// These two features are useful for lock-free algorithms. The indexing /// behavior makes it easy to build tagged pointer-like-things, since /// a large number of elements can be managed using fewer bits than a /// full pointer. The access-after-free behavior makes it safe to read /// from T-s even after they have been recycled, since it is guaranteed /// that the memory won't have been returned to the OS and unmapped /// (the algorithm must still use a mechanism to validate that the read /// was correct, but it doesn't have to worry about page faults), and if /// the elements use internal sequence numbers it can be guaranteed that /// there won't be an ABA match due to the element being overwritten with /// a different type that has the same bit pattern. /// /// IndexedMemPool has two object lifecycle strategies. The first /// is to construct objects when they are allocated from the pool and /// destroy them when they are recycled. In this mode allocIndex and /// allocElem have emplace-like semantics. In the second mode, objects /// are default-constructed the first time they are removed from the pool, /// and deleted when the pool itself is deleted. By default the first /// mode is used for non-trivial T, and the second is used for trivial T. /// /// IMPORTANT: Space for extra elements is allocated to account for those /// that are inaccessible because they are in other local lists, so the /// actual number of items that can be allocated ranges from capacity to /// capacity + (NumLocalLists_-1)*LocalListLimit_. This is important if /// you are trying to maximize the capacity of the pool while constraining /// the bit size of the resulting pointers, because the pointers will /// actually range up to the boosted capacity. See maxIndexForCapacity /// and capacityForMaxIndex. /// /// To avoid contention, NumLocalLists_ free lists of limited (less than /// or equal to LocalListLimit_) size are maintained, and each thread /// retrieves and returns entries from its associated local list. If the /// local list becomes too large then elements are placed in bulk in a /// global free list. This allows items to be efficiently recirculated /// from consumers to producers. AccessSpreader is used to access the /// local lists, so there is no performance advantage to having more /// local lists than L1 caches. /// /// The pool mmap-s the entire necessary address space when the pool is /// constructed, but delays element construction. This means that only /// elements that are actually returned to the caller get paged into the /// process's resident set (RSS). template < typename T, uint32_t NumLocalLists_ = 32, uint32_t LocalListLimit_ = 200, template <typename> class Atom = std::atomic, bool EagerRecycleWhenTrivial = false, bool EagerRecycleWhenNotTrivial = true> struct IndexedMemPool : boost::noncopyable { typedef T value_type; typedef std::unique_ptr<T, detail::IndexedMemPoolRecycler<IndexedMemPool>> UniquePtr; static_assert(LocalListLimit_ <= 255, "LocalListLimit must fit in 8 bits"); enum { NumLocalLists = NumLocalLists_, LocalListLimit = LocalListLimit_ }; static constexpr bool eagerRecycle() { return std::is_trivial<T>::value ? EagerRecycleWhenTrivial : EagerRecycleWhenNotTrivial; } // these are public because clients may need to reason about the number // of bits required to hold indices from a pool, given its capacity static constexpr uint32_t maxIndexForCapacity(uint32_t capacity) { // index of std::numeric_limits<uint32_t>::max() is reserved for isAllocated // tracking return uint32_t(std::min( uint64_t(capacity) + (NumLocalLists - 1) * LocalListLimit, uint64_t(std::numeric_limits<uint32_t>::max() - 1))); } static constexpr uint32_t capacityForMaxIndex(uint32_t maxIndex) { return maxIndex - (NumLocalLists - 1) * LocalListLimit; } /// Constructs a pool that can allocate at least _capacity_ elements, /// even if all the local lists are full explicit IndexedMemPool(uint32_t capacity) : actualCapacity_(maxIndexForCapacity(capacity)) , size_(0) , globalHead_(TaggedPtr{}) { const size_t needed = sizeof(Slot) * (actualCapacity_ + 1); size_t pagesize = size_t(sysconf(_SC_PAGESIZE)); mmapLength_ = ((needed - 1) & ~(pagesize - 1)) + pagesize; assert(needed <= mmapLength_ && mmapLength_ < needed + pagesize); assert((mmapLength_ % pagesize) == 0); slots_ = static_cast<Slot*>(mmap(nullptr, mmapLength_, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0)); if (slots_ == MAP_FAILED) { assert(errno == ENOMEM); throw std::bad_alloc(); } } /// Destroys all of the contained elements ~IndexedMemPool() { if (!eagerRecycle()) { for (uint32_t i = size_; i > 0; --i) { slots_[i].~Slot(); } } munmap(slots_, mmapLength_); } /// Returns a lower bound on the number of elements that may be /// simultaneously allocated and not yet recycled. Because of the /// local lists it is possible that more elements than this are returned /// successfully uint32_t capacity() { return capacityForMaxIndex(actualCapacity_); } /// Finds a slot with a non-zero index, emplaces a T there if we're /// using the eager recycle lifecycle mode, and returns the index, /// or returns 0 if no elements are available. template <typename ...Args> uint32_t allocIndex(Args&&... args) { static_assert(sizeof...(Args) == 0 || eagerRecycle(), "emplace-style allocation requires eager recycle, " "which is defaulted only for non-trivial types"); auto idx = localPop(localHead()); if (idx != 0 && eagerRecycle()) { T* ptr = &slot(idx).elem; new (ptr) T(std::forward<Args>(args)...); } return idx; } /// If an element is available, returns a std::unique_ptr to it that will /// recycle the element to the pool when it is reclaimed, otherwise returns /// a null (falsy) std::unique_ptr template <typename ...Args> UniquePtr allocElem(Args&&... args) { auto idx = allocIndex(std::forward<Args>(args)...); T* ptr = idx == 0 ? nullptr : &slot(idx).elem; return UniquePtr(ptr, typename UniquePtr::deleter_type(this)); } /// Gives up ownership previously granted by alloc() void recycleIndex(uint32_t idx) { assert(isAllocated(idx)); if (eagerRecycle()) { slot(idx).elem.~T(); } localPush(localHead(), idx); } /// Provides access to the pooled element referenced by idx T& operator[](uint32_t idx) { return slot(idx).elem; } /// Provides access to the pooled element referenced by idx const T& operator[](uint32_t idx) const { return slot(idx).elem; } /// If elem == &pool[idx], then pool.locateElem(elem) == idx. Also, /// pool.locateElem(nullptr) == 0 uint32_t locateElem(const T* elem) const { if (!elem) { return 0; } static_assert(std::is_standard_layout<Slot>::value, "offsetof needs POD"); auto slot = reinterpret_cast<const Slot*>( reinterpret_cast<const char*>(elem) - offsetof(Slot, elem)); auto rv = uint32_t(slot - slots_); // this assert also tests that rv is in range assert(elem == &(*this)[rv]); return rv; } /// Returns true iff idx has been alloc()ed and not recycleIndex()ed bool isAllocated(uint32_t idx) const { return slot(idx).localNext == uint32_t(-1); } private: ///////////// types struct Slot { T elem; uint32_t localNext; uint32_t globalNext; Slot() : localNext{}, globalNext{} {} }; struct TaggedPtr { uint32_t idx; // size is bottom 8 bits, tag in top 24. g++'s code generation for // bitfields seems to depend on the phase of the moon, plus we can // do better because we can rely on other checks to avoid masking uint32_t tagAndSize; enum : uint32_t { SizeBits = 8, SizeMask = (1U << SizeBits) - 1, TagIncr = 1U << SizeBits, }; uint32_t size() const { return tagAndSize & SizeMask; } TaggedPtr withSize(uint32_t repl) const { assert(repl <= LocalListLimit); return TaggedPtr{ idx, (tagAndSize & ~SizeMask) | repl }; } TaggedPtr withSizeIncr() const { assert(size() < LocalListLimit); return TaggedPtr{ idx, tagAndSize + 1 }; } TaggedPtr withSizeDecr() const { assert(size() > 0); return TaggedPtr{ idx, tagAndSize - 1 }; } TaggedPtr withIdx(uint32_t repl) const { return TaggedPtr{ repl, tagAndSize + TagIncr }; } TaggedPtr withEmpty() const { return withIdx(0).withSize(0); } }; struct FOLLY_ALIGN_TO_AVOID_FALSE_SHARING LocalList { AtomicStruct<TaggedPtr,Atom> head; LocalList() : head(TaggedPtr{}) {} }; ////////// fields /// the number of bytes allocated from mmap, which is a multiple of /// the page size of the machine size_t mmapLength_; /// the actual number of slots that we will allocate, to guarantee /// that we will satisfy the capacity requested at construction time. /// They will be numbered 1..actualCapacity_ (note the 1-based counting), /// and occupy slots_[1..actualCapacity_]. uint32_t actualCapacity_; /// this records the number of slots that have actually been constructed. /// To allow use of atomic ++ instead of CAS, we let this overflow. /// The actual number of constructed elements is min(actualCapacity_, /// size_) Atom<uint32_t> size_; /// raw storage, only 1..min(size_,actualCapacity_) (inclusive) are /// actually constructed. Note that slots_[0] is not constructed or used FOLLY_ALIGN_TO_AVOID_FALSE_SHARING Slot* slots_; /// use AccessSpreader to find your list. We use stripes instead of /// thread-local to avoid the need to grow or shrink on thread start /// or join. These are heads of lists chained with localNext LocalList local_[NumLocalLists]; /// this is the head of a list of node chained by globalNext, that are /// themselves each the head of a list chained by localNext FOLLY_ALIGN_TO_AVOID_FALSE_SHARING AtomicStruct<TaggedPtr,Atom> globalHead_; ///////////// private methods uint32_t slotIndex(uint32_t idx) const { assert(0 < idx && idx <= actualCapacity_ && idx <= size_.load(std::memory_order_acquire)); return idx; } Slot& slot(uint32_t idx) { return slots_[slotIndex(idx)]; } const Slot& slot(uint32_t idx) const { return slots_[slotIndex(idx)]; } // localHead references a full list chained by localNext. s should // reference slot(localHead), it is passed as a micro-optimization void globalPush(Slot& s, uint32_t localHead) { while (true) { TaggedPtr gh = globalHead_.load(std::memory_order_acquire); s.globalNext = gh.idx; if (globalHead_.compare_exchange_strong(gh, gh.withIdx(localHead))) { // success return; } } } // idx references a single node void localPush(AtomicStruct<TaggedPtr,Atom>& head, uint32_t idx) { Slot& s = slot(idx); TaggedPtr h = head.load(std::memory_order_acquire); while (true) { s.localNext = h.idx; if (h.size() == LocalListLimit) { // push will overflow local list, steal it instead if (head.compare_exchange_strong(h, h.withEmpty())) { // steal was successful, put everything in the global list globalPush(s, idx); return; } } else { // local list has space if (head.compare_exchange_strong(h, h.withIdx(idx).withSizeIncr())) { // success return; } } // h was updated by failing CAS } } // returns 0 if empty uint32_t globalPop() { while (true) { TaggedPtr gh = globalHead_.load(std::memory_order_acquire); if (gh.idx == 0 || globalHead_.compare_exchange_strong( gh, gh.withIdx(slot(gh.idx).globalNext))) { // global list is empty, or pop was successful return gh.idx; } } } // returns 0 if allocation failed uint32_t localPop(AtomicStruct<TaggedPtr,Atom>& head) { while (true) { TaggedPtr h = head.load(std::memory_order_acquire); if (h.idx != 0) { // local list is non-empty, try to pop Slot& s = slot(h.idx); if (head.compare_exchange_strong( h, h.withIdx(s.localNext).withSizeDecr())) { // success s.localNext = uint32_t(-1); return h.idx; } continue; } uint32_t idx = globalPop(); if (idx == 0) { // global list is empty, allocate and construct new slot if (size_.load(std::memory_order_relaxed) >= actualCapacity_ || (idx = ++size_) > actualCapacity_) { // allocation failed return 0; } // default-construct it now if we aren't going to construct and // destroy on each allocation if (!eagerRecycle()) { T* ptr = &slot(idx).elem; new (ptr) T(); } slot(idx).localNext = uint32_t(-1); return idx; } Slot& s = slot(idx); if (head.compare_exchange_strong( h, h.withIdx(s.localNext).withSize(LocalListLimit))) { // global list moved to local list, keep head for us s.localNext = uint32_t(-1); return idx; } // local bulk push failed, return idx to the global list and try again globalPush(s, idx); } } AtomicStruct<TaggedPtr,Atom>& localHead() { auto stripe = detail::AccessSpreader<Atom>::current(NumLocalLists); return local_[stripe].head; } }; namespace detail { /// This is a stateful Deleter functor, which allows std::unique_ptr /// to track elements allocated from an IndexedMemPool by tracking the /// associated pool. See IndexedMemPool::allocElem. template <typename Pool> struct IndexedMemPoolRecycler { Pool* pool; explicit IndexedMemPoolRecycler(Pool* pool) : pool(pool) {} IndexedMemPoolRecycler(const IndexedMemPoolRecycler<Pool>& rhs) = default; IndexedMemPoolRecycler& operator= (const IndexedMemPoolRecycler<Pool>& rhs) = default; void operator()(typename Pool::value_type* elem) const { pool->recycleIndex(pool->locateElem(elem)); } }; } } // namespace folly # pragma GCC diagnostic pop
Java
#!/usr/bin/env ruby #-- # set.rb - defines the Set class #++ # Copyright (c) 2002 Akinori MUSHA <[email protected]> # # Documentation by Akinori MUSHA and Gavin Sinclair. # # All rights reserved. You can redistribute and/or modify it under the same # terms as Ruby. # # $Id: set.rb 8696 2009-01-10 21:17:58Z headius $ # # == Overview # # This library provides the Set class, which deals with a collection # of unordered values with no duplicates. It is a hybrid of Array's # intuitive inter-operation facilities and Hash's fast lookup. If you # need to keep values ordered, use the SortedSet class. # # The method +to_set+ is added to Enumerable for convenience. # # See the Set class for an example of usage. # # Set implements a collection of unordered values with no duplicates. # This is a hybrid of Array's intuitive inter-operation facilities and # Hash's fast lookup. # # Several methods accept any Enumerable object (implementing +each+) # for greater flexibility: new, replace, merge, subtract, |, &, -, ^. # # The equality of each couple of elements is determined according to # Object#eql? and Object#hash, since Set uses Hash as storage. # # Finally, if you are using class Set, you can also use Enumerable#to_set # for convenience. # # == Example # # require 'set' # s1 = Set.new [1, 2] # -> #<Set: {1, 2}> # s2 = [1, 2].to_set # -> #<Set: {1, 2}> # s1 == s2 # -> true # s1.add("foo") # -> #<Set: {1, 2, "foo"}> # s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}> # s1.subset? s2 # -> false # s2.subset? s1 # -> true # class Set include Enumerable # Creates a new set containing the given objects. def self.[](*ary) new(ary) end # Creates a new set containing the elements of the given enumerable # object. # # If a block is given, the elements of enum are preprocessed by the # given block. def initialize(enum = nil, &block) # :yields: o @hash ||= Hash.new enum.nil? and return if block enum.each { |o| add(block[o]) } else merge(enum) end end # Copy internal hash. def initialize_copy(orig) @hash = orig.instance_eval{@hash}.dup end # Returns the number of elements. def size @hash.size end alias length size # Returns true if the set contains no elements. def empty? @hash.empty? end # Removes all elements and returns self. def clear @hash.clear self end # Replaces the contents of the set with the contents of the given # enumerable object and returns self. def replace(enum) if enum.class == self.class @hash.replace(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" clear enum.each { |o| add(o) } end self end # Converts the set to an array. The order of elements is uncertain. def to_a @hash.keys end def flatten_merge(set, seen = Set.new) set.each { |e| if e.is_a?(Set) if seen.include?(e_id = e.object_id) raise ArgumentError, "tried to flatten recursive Set" end seen.add(e_id) flatten_merge(e, seen) seen.delete(e_id) else add(e) end } self end protected :flatten_merge # Returns a new set that is a copy of the set, flattening each # containing set recursively. def flatten self.class.new.flatten_merge(self) end # Equivalent to Set#flatten, but replaces the receiver with the # result in place. Returns nil if no modifications were made. def flatten! if detect { |e| e.is_a?(Set) } replace(flatten()) else nil end end # Returns true if the set contains the given object. def include?(o) @hash.include?(o) end alias member? include? # Returns true if the set is a superset of the given set. def superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size < set.size set.all? { |o| include?(o) } end # Returns true if the set is a proper superset of the given set. def proper_superset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if size <= set.size set.all? { |o| include?(o) } end # Returns true if the set is a subset of the given set. def subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size < size all? { |o| set.include?(o) } end # Returns true if the set is a proper subset of the given set. def proper_subset?(set) set.is_a?(Set) or raise ArgumentError, "value must be a set" return false if set.size <= size all? { |o| set.include?(o) } end # Calls the given block once for each element in the set, passing # the element as parameter. def each @hash.each_key { |o| yield(o) } self end # Adds the given object to the set and returns self. Use +merge+ to # add several elements at once. def add(o) @hash[o] = true self end alias << add # Adds the given object to the set and returns self. If the # object is already in the set, returns nil. def add?(o) if include?(o) nil else add(o) end end # Deletes the given object from the set and returns self. Use +subtract+ to # delete several items at once. def delete(o) @hash.delete(o) self end # Deletes the given object from the set and returns self. If the # object is not in the set, returns nil. def delete?(o) if include?(o) delete(o) else nil end end # Deletes every element of the set for which block evaluates to # true, and returns self. def delete_if to_a.each { |o| @hash.delete(o) if yield(o) } self end # Do collect() destructively. def collect! set = self.class.new each { |o| set << yield(o) } replace(set) end alias map! collect! # Equivalent to Set#delete_if, but returns nil if no changes were # made. def reject! n = size delete_if { |o| yield(o) } size == n ? nil : self end # Merges the elements of the given enumerable object to the set and # returns self. def merge(enum) if enum.is_a?(Set) @hash.update(enum.instance_eval { @hash }) else enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| add(o) } end self end # Deletes every element that appears in the given enumerable object # and returns self. def subtract(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" enum.each { |o| delete(o) } self end # Returns a new set built by merging the set and the elements of the # given enumerable object. def |(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.merge(enum) end alias + | ## alias union | ## # Returns a new set built by duplicating the set, removing every # element that appears in the given enumerable object. def -(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" dup.subtract(enum) end alias difference - ## # Returns a new set containing elements common to the set and the # given enumerable object. def &(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = self.class.new enum.each { |o| n.add(o) if include?(o) } n end alias intersection & ## # Returns a new set containing elements exclusive between the set # and the given enumerable object. (set ^ enum) is equivalent to # ((set | enum) - (set & enum)). def ^(enum) enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" n = Set.new(enum) each { |o| if n.include?(o) then n.delete(o) else n.add(o) end } n end # Returns true if two sets are equal. The equality of each couple # of elements is defined according to Object#eql?. def ==(set) equal?(set) and return true set.is_a?(Set) && size == set.size or return false hash = @hash.dup set.all? { |o| hash.include?(o) } end def hash # :nodoc: @hash.hash end def eql?(o) # :nodoc: return false unless o.is_a?(Set) @hash.eql?(o.instance_eval{@hash}) end # Classifies the set by the return value of the given block and # returns a hash of {value => set of elements} pairs. The block is # called once for each element of the set, passing the element as # parameter. # # e.g.: # # require 'set' # files = Set.new(Dir.glob("*.rb")) # hash = files.classify { |f| File.mtime(f).year } # p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>, # # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>, # # 2002=>#<Set: {"f.rb"}>} def classify # :yields: o h = {} each { |i| x = yield(i) (h[x] ||= self.class.new).add(i) } h end # Divides the set into a set of subsets according to the commonality # defined by the given block. # # If the arity of the block is 2, elements o1 and o2 are in common # if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are # in common if block.call(o1) == block.call(o2). # # e.g.: # # require 'set' # numbers = Set[1, 3, 4, 6, 9, 10, 11] # set = numbers.divide { |i,j| (i - j).abs == 1 } # p set # => #<Set: {#<Set: {1}>, # # #<Set: {11, 9, 10}>, # # #<Set: {3, 4}>, # # #<Set: {6}>}> def divide(&func) if func.arity == 2 require 'tsort' class << dig = {} # :nodoc: include TSort alias tsort_each_node each_key def tsort_each_child(node, &block) fetch(node).each(&block) end end each { |u| dig[u] = a = [] each{ |v| func.call(u, v) and a << v } } set = Set.new() dig.each_strongly_connected_component { |css| set.add(self.class.new(css)) } set else Set.new(classify(&func).values) end end InspectKey = :__inspect_key__ # :nodoc: # Returns a string containing a human-readable representation of the # set. ("#<Set: {element1, element2, ...}>") def inspect ids = (Thread.current[InspectKey] ||= []) if ids.include?(object_id) return sprintf('#<%s: {...}>', self.class.name) end begin ids << object_id return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2]) ensure ids.pop end end def pretty_print(pp) # :nodoc: pp.text sprintf('#<%s: {', self.class.name) pp.nest(1) { pp.seplist(self) { |o| pp.pp o } } pp.text "}>" end def pretty_print_cycle(pp) # :nodoc: pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...') end end # SortedSet implements a set which elements are sorted in order. See Set. class SortedSet < Set @@setup = false class << self def [](*ary) # :nodoc: new(ary) end def setup # :nodoc: @@setup and return module_eval { # a hack to shut up warning alias old_init initialize remove_method :old_init } begin require 'rbtree' module_eval %{ def initialize(*args, &block) @hash = RBTree.new super end } rescue LoadError module_eval %{ def initialize(*args, &block) @keys = nil super end def clear @keys = nil super end def replace(enum) @keys = nil super end def add(o) @keys = nil @hash[o] = true self end alias << add def delete(o) @keys = nil @hash.delete(o) self end def delete_if n = @hash.size super @keys = nil if @hash.size != n self end def merge(enum) @keys = nil super end def each to_a.each { |o| yield(o) } self end def to_a (@keys = @hash.keys).sort! unless @keys @keys end } end @@setup = true end end def initialize(*args, &block) # :nodoc: SortedSet.setup initialize(*args, &block) end end module Enumerable # Makes a set from the enumerable object with given arguments. # Needs to +require "set"+ to use this method. def to_set(klass = Set, *args, &block) klass.new(self, *args, &block) end end # =begin # == RestricedSet class # RestricedSet implements a set with restrictions defined by a given # block. # # === Super class # Set # # === Class Methods # --- RestricedSet::new(enum = nil) { |o| ... } # --- RestricedSet::new(enum = nil) { |rset, o| ... } # Creates a new restricted set containing the elements of the given # enumerable object. Restrictions are defined by the given block. # # If the block's arity is 2, it is called with the RestrictedSet # itself and an object to see if the object is allowed to be put in # the set. # # Otherwise, the block is called with an object to see if the object # is allowed to be put in the set. # # === Instance Methods # --- restriction_proc # Returns the restriction procedure of the set. # # =end # # class RestricedSet < Set # def initialize(*args, &block) # @proc = block or raise ArgumentError, "missing a block" # # if @proc.arity == 2 # instance_eval %{ # def add(o) # @hash[o] = true if @proc.call(self, o) # self # end # alias << add # # def add?(o) # if include?(o) || [email protected](self, o) # nil # else # @hash[o] = true # self # end # end # # def replace(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # clear # enum.each { |o| add(o) } # # self # end # # def merge(enum) # enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable" # enum.each { |o| add(o) } # # self # end # } # else # instance_eval %{ # def add(o) # if @proc.call(o) # @hash[o] = true # end # self # end # alias << add # # def add?(o) # if include?(o) || [email protected](o) # nil # else # @hash[o] = true # self # end # end # } # end # # super(*args) # end # # def restriction_proc # @proc # end # end if $0 == __FILE__ eval DATA.read, nil, $0, __LINE__+4 end __END__ require 'test/unit' class TC_Set < Test::Unit::TestCase def test_aref assert_nothing_raised { Set[] Set[nil] Set[1,2,3] } assert_equal(0, Set[].size) assert_equal(1, Set[nil].size) assert_equal(1, Set[[]].size) assert_equal(1, Set[[nil]].size) set = Set[2,4,6,4] assert_equal(Set.new([2,4,6]), set) end def test_s_new assert_nothing_raised { Set.new() Set.new(nil) Set.new([]) Set.new([1,2]) Set.new('a'..'c') Set.new('XYZ') } assert_raises(ArgumentError) { Set.new(false) } assert_raises(ArgumentError) { Set.new(1) } assert_raises(ArgumentError) { Set.new(1,2) } assert_equal(0, Set.new().size) assert_equal(0, Set.new(nil).size) assert_equal(0, Set.new([]).size) assert_equal(1, Set.new([nil]).size) ary = [2,4,6,4] set = Set.new(ary) ary.clear assert_equal(false, set.empty?) assert_equal(3, set.size) ary = [1,2,3] s = Set.new(ary) { |o| o * 2 } assert_equal([2,4,6], s.sort) end def test_clone set1 = Set.new set2 = set1.clone set1 << 'abc' assert_equal(Set.new, set2) end def test_dup set1 = Set[1,2] set2 = set1.dup assert_not_same(set1, set2) assert_equal(set1, set2) set1.add(3) assert_not_equal(set1, set2) end def test_size assert_equal(0, Set[].size) assert_equal(2, Set[1,2].size) assert_equal(2, Set[1,2,1].size) end def test_empty? assert_equal(true, Set[].empty?) assert_equal(false, Set[1, 2].empty?) end def test_clear set = Set[1,2] ret = set.clear assert_same(set, ret) assert_equal(true, set.empty?) end def test_replace set = Set[1,2] ret = set.replace('a'..'c') assert_same(set, ret) assert_equal(Set['a','b','c'], set) end def test_to_a set = Set[1,2,3,2] ary = set.to_a assert_equal([1,2,3], ary.sort) end def test_flatten # test1 set1 = Set[ 1, Set[ 5, Set[7, Set[0] ], Set[6,2], 1 ], 3, Set[3,4] ] set2 = set1.flatten set3 = Set.new(0..7) assert_not_same(set2, set1) assert_equal(set3, set2) # test2; destructive orig_set1 = set1 set1.flatten! assert_same(orig_set1, set1) assert_equal(set3, set1) # test3; multiple occurrences of a set in an set set1 = Set[1, 2] set2 = Set[set1, Set[set1, 4], 3] assert_nothing_raised { set2.flatten! } assert_equal(Set.new(1..4), set2) # test4; recursion set2 = Set[] set1 = Set[1, set2] set2.add(set1) assert_raises(ArgumentError) { set1.flatten! } # test5; miscellaneous empty = Set[] set = Set[Set[empty, "a"],Set[empty, "b"]] assert_nothing_raised { set.flatten } set1 = empty.merge(Set["no_more", set]) assert_nil(Set.new(0..31).flatten!) x = Set[Set[],Set[1,2]].flatten! y = Set[1,2] assert_equal(x, y) end def test_include? set = Set[1,2,3] assert_equal(true, set.include?(1)) assert_equal(true, set.include?(2)) assert_equal(true, set.include?(3)) assert_equal(false, set.include?(0)) assert_equal(false, set.include?(nil)) set = Set["1",nil,"2",nil,"0","1",false] assert_equal(true, set.include?(nil)) assert_equal(true, set.include?(false)) assert_equal(true, set.include?("1")) assert_equal(false, set.include?(0)) assert_equal(false, set.include?(true)) end def test_superset? set = Set[1,2,3] assert_raises(ArgumentError) { set.superset?() } assert_raises(ArgumentError) { set.superset?(2) } assert_raises(ArgumentError) { set.superset?([2]) } assert_equal(true, set.superset?(Set[])) assert_equal(true, set.superset?(Set[1,2])) assert_equal(true, set.superset?(Set[1,2,3])) assert_equal(false, set.superset?(Set[1,2,3,4])) assert_equal(false, set.superset?(Set[1,4])) assert_equal(true, Set[].superset?(Set[])) end def test_proper_superset? set = Set[1,2,3] assert_raises(ArgumentError) { set.proper_superset?() } assert_raises(ArgumentError) { set.proper_superset?(2) } assert_raises(ArgumentError) { set.proper_superset?([2]) } assert_equal(true, set.proper_superset?(Set[])) assert_equal(true, set.proper_superset?(Set[1,2])) assert_equal(false, set.proper_superset?(Set[1,2,3])) assert_equal(false, set.proper_superset?(Set[1,2,3,4])) assert_equal(false, set.proper_superset?(Set[1,4])) assert_equal(false, Set[].proper_superset?(Set[])) end def test_subset? set = Set[1,2,3] assert_raises(ArgumentError) { set.subset?() } assert_raises(ArgumentError) { set.subset?(2) } assert_raises(ArgumentError) { set.subset?([2]) } assert_equal(true, set.subset?(Set[1,2,3,4])) assert_equal(true, set.subset?(Set[1,2,3])) assert_equal(false, set.subset?(Set[1,2])) assert_equal(false, set.subset?(Set[])) assert_equal(true, Set[].subset?(Set[1])) assert_equal(true, Set[].subset?(Set[])) end def test_proper_subset? set = Set[1,2,3] assert_raises(ArgumentError) { set.proper_subset?() } assert_raises(ArgumentError) { set.proper_subset?(2) } assert_raises(ArgumentError) { set.proper_subset?([2]) } assert_equal(true, set.proper_subset?(Set[1,2,3,4])) assert_equal(false, set.proper_subset?(Set[1,2,3])) assert_equal(false, set.proper_subset?(Set[1,2])) assert_equal(false, set.proper_subset?(Set[])) assert_equal(false, Set[].proper_subset?(Set[])) end def test_each ary = [1,3,5,7,10,20] set = Set.new(ary) assert_raises(LocalJumpError) { set.each } assert_nothing_raised { set.each { |o| ary.delete(o) or raise "unexpected element: #{o}" } ary.empty? or raise "forgotten elements: #{ary.join(', ')}" } end def test_add set = Set[1,2,3] ret = set.add(2) assert_same(set, ret) assert_equal(Set[1,2,3], set) ret = set.add?(2) assert_nil(ret) assert_equal(Set[1,2,3], set) ret = set.add(4) assert_same(set, ret) assert_equal(Set[1,2,3,4], set) ret = set.add?(5) assert_same(set, ret) assert_equal(Set[1,2,3,4,5], set) end def test_delete set = Set[1,2,3] ret = set.delete(4) assert_same(set, ret) assert_equal(Set[1,2,3], set) ret = set.delete?(4) assert_nil(ret) assert_equal(Set[1,2,3], set) ret = set.delete(2) assert_equal(set, ret) assert_equal(Set[1,3], set) ret = set.delete?(1) assert_equal(set, ret) assert_equal(Set[3], set) end def test_delete_if set = Set.new(1..10) ret = set.delete_if { |i| i > 10 } assert_same(set, ret) assert_equal(Set.new(1..10), set) set = Set.new(1..10) ret = set.delete_if { |i| i % 3 == 0 } assert_same(set, ret) assert_equal(Set[1,2,4,5,7,8,10], set) end def test_collect! set = Set[1,2,3,'a','b','c',-1..1,2..4] ret = set.collect! { |i| case i when Numeric i * 2 when String i.upcase else nil end } assert_same(set, ret) assert_equal(Set[2,4,6,'A','B','C',nil], set) end def test_reject! set = Set.new(1..10) ret = set.reject! { |i| i > 10 } assert_nil(ret) assert_equal(Set.new(1..10), set) ret = set.reject! { |i| i % 3 == 0 } assert_same(set, ret) assert_equal(Set[1,2,4,5,7,8,10], set) end def test_merge set = Set[1,2,3] ret = set.merge([2,4,6]) assert_same(set, ret) assert_equal(Set[1,2,3,4,6], set) end def test_subtract set = Set[1,2,3] ret = set.subtract([2,4,6]) assert_same(set, ret) assert_equal(Set[1,3], set) end def test_plus set = Set[1,2,3] ret = set + [2,4,6] assert_not_same(set, ret) assert_equal(Set[1,2,3,4,6], ret) end def test_minus set = Set[1,2,3] ret = set - [2,4,6] assert_not_same(set, ret) assert_equal(Set[1,3], ret) end def test_and set = Set[1,2,3,4] ret = set & [2,4,6] assert_not_same(set, ret) assert_equal(Set[2,4], ret) end def test_xor set = Set[1,2,3,4] ret = set ^ [2,4,5,5] assert_not_same(set, ret) assert_equal(Set[1,3,5], ret) end def test_eq set1 = Set[2,3,1] set2 = Set[1,2,3] assert_equal(set1, set1) assert_equal(set1, set2) assert_not_equal(Set[1], [1]) set1 = Class.new(Set)["a", "b"] set2 = Set["a", "b", set1] set1 = set1.add(set1.clone) # assert_equal(set1, set2) # assert_equal(set2, set1) assert_equal(set2, set2.clone) assert_equal(set1.clone, set1) assert_not_equal(Set[Exception.new,nil], Set[Exception.new,Exception.new], "[ruby-dev:26127]") end # def test_hash # end # def test_eql? # end def test_classify set = Set.new(1..10) ret = set.classify { |i| i % 3 } assert_equal(3, ret.size) assert_instance_of(Hash, ret) ret.each_value { |value| assert_instance_of(Set, value) } assert_equal(Set[3,6,9], ret[0]) assert_equal(Set[1,4,7,10], ret[1]) assert_equal(Set[2,5,8], ret[2]) end def test_divide set = Set.new(1..10) ret = set.divide { |i| i % 3 } assert_equal(3, ret.size) n = 0 ret.each { |s| n += s.size } assert_equal(set.size, n) assert_equal(set, ret.flatten) set = Set[7,10,5,11,1,3,4,9,0] ret = set.divide { |a,b| (a - b).abs == 1 } assert_equal(4, ret.size) n = 0 ret.each { |s| n += s.size } assert_equal(set.size, n) assert_equal(set, ret.flatten) ret.each { |s| if s.include?(0) assert_equal(Set[0,1], s) elsif s.include?(3) assert_equal(Set[3,4,5], s) elsif s.include?(7) assert_equal(Set[7], s) elsif s.include?(9) assert_equal(Set[9,10,11], s) else raise "unexpected group: #{s.inspect}" end } end def test_inspect set1 = Set[1] assert_equal('#<Set: {1}>', set1.inspect) set2 = Set[Set[0], 1, 2, set1] assert_equal(false, set2.inspect.include?('#<Set: {...}>')) set1.add(set2) assert_equal(true, set1.inspect.include?('#<Set: {...}>')) end # def test_pretty_print # end # def test_pretty_print_cycle # end end class TC_SortedSet < Test::Unit::TestCase def test_sortedset s = SortedSet[4,5,3,1,2] assert_equal([1,2,3,4,5], s.to_a) prev = nil s.each { |o| assert(prev < o) if prev; prev = o } assert_not_nil(prev) s.map! { |o| -2 * o } assert_equal([-10,-8,-6,-4,-2], s.to_a) prev = nil ret = s.each { |o| assert(prev < o) if prev; prev = o } assert_not_nil(prev) assert_same(s, ret) s = SortedSet.new([2,1,3]) { |o| o * -2 } assert_equal([-6,-4,-2], s.to_a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.delete_if { |o| a << o; o[0] == ?t } assert_same(s, ret) assert_equal(['four', 'one'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.reject! { |o| a << o; o[0] == ?t } assert_same(s, ret) assert_equal(['four', 'one'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) s = SortedSet.new(['one', 'two', 'three', 'four']) a = [] ret = s.reject! { |o| a << o; false } assert_same(nil, ret) assert_equal(['four', 'one', 'three', 'two'], s.to_a) assert_equal(['four', 'one', 'three', 'two'], a) end end class TC_Enumerable < Test::Unit::TestCase def test_to_set ary = [2,5,4,3,2,1,3] set = ary.to_set assert_instance_of(Set, set) assert_equal([1,2,3,4,5], set.sort) set = ary.to_set { |o| o * -2 } assert_instance_of(Set, set) assert_equal([-10,-8,-6,-4,-2], set.sort) set = ary.to_set(SortedSet) assert_instance_of(SortedSet, set) assert_equal([1,2,3,4,5], set.to_a) set = ary.to_set(SortedSet) { |o| o * -2 } assert_instance_of(SortedSet, set) assert_equal([-10,-8,-6,-4,-2], set.sort) end end # class TC_RestricedSet < Test::Unit::TestCase # def test_s_new # assert_raises(ArgumentError) { RestricedSet.new } # # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } # assert_equal([2,3], s.sort) # end # # def test_restriction_proc # s = RestricedSet.new([-1,2,3]) { |o| o > 0 } # # f = s.restriction_proc # assert_instance_of(Proc, f) # assert(f[1]) # assert(!f[0]) # end # # def test_replace # s = RestricedSet.new(-3..3) { |o| o > 0 } # assert_equal([1,2,3], s.sort) # # s.replace([-2,0,3,4,5]) # assert_equal([3,4,5], s.sort) # end # # def test_merge # s = RestricedSet.new { |o| o > 0 } # s.merge(-5..5) # assert_equal([1,2,3,4,5], s.sort) # # s.merge([10,-10,-8,8]) # assert_equal([1,2,3,4,5,8,10], s.sort) # end # end
Java
# AUTOGENERATED FILE FROM balenalib/revpi-core-3-ubuntu:bionic-run # A few reasons for installing distribution-provided OpenJDK: # # 1. Oracle. Licensing prevents us from redistributing the official JDK. # # 2. Compiling OpenJDK also requires the JDK to be installed, and it gets # really hairy. # # For some sample build times, see Debian's buildd logs: # https://buildd.debian.org/status/logs.php?pkg=openjdk-7 # Default to UTF-8 file.encoding ENV LANG C.UTF-8 # add a simple script that can auto-detect the appropriate JAVA_HOME value # based on whether the JDK or only the JRE is installed RUN { \ echo '#!/bin/sh'; \ echo 'set -e'; \ echo; \ echo 'dirname "$(dirname "$(readlink -f "$(which javac || which java)")")"'; \ } > /usr/local/bin/docker-java-home \ && chmod +x /usr/local/bin/docker-java-home # do some fancy footwork to create a JAVA_HOME that's cross-architecture-safe RUN ln -svT "/usr/lib/jvm/java-8-openjdk-$(dpkg --print-architecture)" /docker-java-home ENV JAVA_HOME /docker-java-home RUN set -ex; \ \ # deal with slim variants not having man page directories (which causes "update-alternatives" to fail) if [ ! -d /usr/share/man/man1 ]; then \ mkdir -p /usr/share/man/man1; \ fi; \ \ apt-get update; \ apt-get install -y --no-install-recommends \ software-properties-common \ ; \ add-apt-repository ppa:openjdk-r/ppa; \ apt-get update; \ apt-get install -y --no-install-recommends \ openjdk-8-jre \ ; \ rm -rf /var/lib/apt/lists/*; \ \ # verify that "docker-java-home" returns what we expect [ "$(readlink -f "$JAVA_HOME")" = "$(docker-java-home)" ]; \ \ # update-alternatives so that future installs of other OpenJDK versions don't change /usr/bin/java update-alternatives --get-selections | awk -v home="$(readlink -f "$JAVA_HOME")" 'index($3, home) == 1 { $2 = "manual"; print | "update-alternatives --set-selections" }'; \ # ... and verify that it actually worked for one of the alternatives we care about update-alternatives --query java | grep -q 'Status: manual' CMD ["echo","'No CMD command was set in Dockerfile! Details about CMD command could be found in Dockerfile Guide section in our Docs. Here's the link: https://balena.io/docs"] RUN [ ! -d /.balena/messages ] && mkdir -p /.balena/messages; echo 'Here are a few details about this Docker image (For more information please visit https://www.balena.io/docs/reference/base-images/base-images/): \nArchitecture: ARM v7 \nOS: Ubuntu bionic \nVariant: run variant \nDefault variable(s): UDEV=off \nThe following software stack is preinstalled: \nOpenJDK v8-jre \nExtra features: \n- Easy way to install packages with `install_packages <package-name>` command \n- Run anywhere with cross-build feature (for ARM only) \n- Keep the container idling with `balena-idle` command \n- Show base image details with `balena-info` command' > /.balena/messages/image-info RUN echo '#!/bin/sh.real\nbalena-info\nrm -f /bin/sh\ncp /bin/sh.real /bin/sh\n/bin/sh "$@"' > /bin/sh-shim \ && chmod +x /bin/sh-shim \ && cp /bin/sh /bin/sh.real \ && mv /bin/sh-shim /bin/sh
Java
/* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ package org.apache.airavata.registry.core.app.catalog.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; import java.io.Serializable; import java.sql.Timestamp; @Entity @Table(name = "APPLICATION_INTERFACE") public class ApplicationInterface implements Serializable { @Id @Column(name = "INTERFACE_ID") private String interfaceID; @Column(name = "APPLICATION_NAME") private String appName; @Column(name = "APPLICATION_DESCRIPTION") private String appDescription; @Column(name = "CREATION_TIME") private Timestamp creationTime; @Column(name = "GATEWAY_ID") private String gatewayId; @Column(name = "ARCHIVE_WORKING_DIRECTORY") private boolean archiveWorkingDirectory; @Column(name = "HAS_OPTIONAL_FILE_INPUTS") private boolean hasOptionalFileInputs; @Column(name = "UPDATE_TIME") private Timestamp updateTime; public String getGatewayId() { return gatewayId; } public void setGatewayId(String gatewayId) { this.gatewayId = gatewayId; } public boolean isArchiveWorkingDirectory() { return archiveWorkingDirectory; } public void setArchiveWorkingDirectory(boolean archiveWorkingDirectory) { this.archiveWorkingDirectory = archiveWorkingDirectory; } public Timestamp getCreationTime() { return creationTime; } public void setCreationTime(Timestamp creationTime) { this.creationTime = creationTime; } public Timestamp getUpdateTime() { return updateTime; } public void setUpdateTime(Timestamp updateTime) { this.updateTime = updateTime; } public String getInterfaceID() { return interfaceID; } public void setInterfaceID(String interfaceID) { this.interfaceID = interfaceID; } public String getAppName() { return appName; } public void setAppName(String appName) { this.appName = appName; } public String getAppDescription() { return appDescription; } public void setAppDescription(String appDescription) { this.appDescription = appDescription; } public boolean isHasOptionalFileInputs() { return hasOptionalFileInputs; } public void setHasOptionalFileInputs(boolean hasOptionalFileInputs) { this.hasOptionalFileInputs = hasOptionalFileInputs; } }
Java
#!/bin/bash # This shell scripts generates the top-level Markdown structure of the # Snabb lwAFTR manual. # # The authors list is automatically generated from Git history, # ordered from most to least commits. # Script based on src/doc/genbook.sh lwaftr_app=../../../apps/lwaftr/ cat <<EOF % Snabb lwAFTR Manual % $(git log --pretty="%an" $lwaftr_app | \ grep -v -e '^root$' | \ sort | uniq -c | sort -nr | sed 's/^[0-9 ]*//' | \ awk 'BEGIN { first=1; } (NF >= 2) { if (first) { first=0 } else { printf("; ") }; printf("%s", $0) } END { print("") }') % Version $(git log -n1 --format="format:%h, %ad%n") $(cat README.welcome.md) $(cat README.build.md) $(cat README.running.md) $(cat README.testing.md) $(cat README.troubleshooting.md) $(cat README.bindingtable.md) $(cat README.configuration.md) $(cat README.rfccompliance.md) $(cat README.benchmarking.md) $(cat README.performance.md) $(cat README.virtualization.md) EOF
Java
from hazelcast.serialization.bits import * from hazelcast.protocol.client_message import ClientMessage from hazelcast.protocol.custom_codec import * from hazelcast.util import ImmutableLazyDataList from hazelcast.protocol.codec.map_message_type import * REQUEST_TYPE = MAP_REMOVEENTRYLISTENER RESPONSE_TYPE = 101 RETRYABLE = True def calculate_size(name, registration_id): """ Calculates the request payload size""" data_size = 0 data_size += calculate_size_str(name) data_size += calculate_size_str(registration_id) return data_size def encode_request(name, registration_id): """ Encode request into client_message""" client_message = ClientMessage(payload_size=calculate_size(name, registration_id)) client_message.set_message_type(REQUEST_TYPE) client_message.set_retryable(RETRYABLE) client_message.append_str(name) client_message.append_str(registration_id) client_message.update_frame_length() return client_message def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(response=None) parameters['response'] = client_message.read_bool() return parameters
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for checks.""" from grr.lib import flags from grr.lib import test_lib from grr.lib.checks import hints from grr.lib.rdfvalues import client as rdf_client from grr.lib.rdfvalues import config_file as rdf_config_file from grr.lib.rdfvalues import protodict as rdf_protodict class HintsTests(test_lib.GRRBaseTest): """Test hint operations.""" def testCheckOverlay(self): """Overlay(hint1, hint2) should populate hint2 with the values of hint1.""" # Fully populated hint. full = { "problem": "Terminator needs trousers.\n", "fix": "Give me your clothes.\n", "format": "{mission}, {target}\n", "summary": "I'll be back." } # Partial hint partial = { "problem": "Terminator needs to go shopping.", "fix": "Phased plasma rifle in the 40-watt range.", "format": "", "summary": "" } # Partial overlaid with full. overlay = { "problem": "Terminator needs to go shopping.", "fix": "Phased plasma rifle in the 40-watt range.", "format": "{mission}, {target}", "summary": "I'll be back." } # Empty hint. empty = {"problem": "", "fix": "", "format": "", "summary": ""} # Empty hint should not clobber populated hint. starts_full = full.copy() starts_empty = empty.copy() hints.Overlay(starts_full, starts_empty) self.assertDictEqual(full, starts_full) self.assertDictEqual(empty, starts_empty) # Populate empty hint from partially populated hint. starts_partial = partial.copy() starts_empty = empty.copy() hints.Overlay(starts_empty, starts_partial) self.assertDictEqual(partial, starts_partial) self.assertDictEqual(partial, starts_empty) # Overlay the full and partial hints to get the hybrid. starts_full = full.copy() starts_partial = partial.copy() hints.Overlay(starts_partial, starts_full) self.assertDictEqual(full, starts_full) self.assertDictEqual(overlay, starts_partial) def testRdfFormatter(self): """Hints format RDF values with arbitrary values and attributes.""" # Create a complex RDF value rdf = rdf_client.ClientSummary() rdf.system_info.system = "Linux" rdf.system_info.node = "coreai.skynet.com" # Users (repeated) rdf.users = [rdf_client.User(username=u) for u in ("root", "jconnor")] # Interface (nested, repeated) addresses = [ rdf_client.NetworkAddress(human_readable=a) for a in ("1.1.1.1", "2.2.2.2", "3.3.3.3") ] eth0 = rdf_client.Interface(ifname="eth0", addresses=addresses[:2]) ppp0 = rdf_client.Interface(ifname="ppp0", addresses=addresses[2]) rdf.interfaces = [eth0, ppp0] template = ("{system_info.system} {users.username} {interfaces.ifname} " "{interfaces.addresses.human_readable}\n") hinter = hints.Hinter(template=template) expected = "Linux root,jconnor eth0,ppp0 1.1.1.1,2.2.2.2,3.3.3.3" result = hinter.Render(rdf) self.assertEqual(expected, result) def testRdfFormatterHandlesKeyValuePair(self): """rdfvalue.KeyValue items need special handling to expand k and v.""" key = rdf_protodict.DataBlob().SetValue("skynet") value = rdf_protodict.DataBlob().SetValue([1997]) rdf = rdf_protodict.KeyValue(k=key, v=value) template = "{k}: {v}" hinter = hints.Hinter(template=template) expected = "skynet: 1997" result = hinter.Render(rdf) self.assertEqual(expected, result) def testRdfFormatterAttributedDict(self): sshd = rdf_config_file.SshdConfig() sshd.config = rdf_protodict.AttributedDict(skynet="operational") template = "{config.skynet}" hinter = hints.Hinter(template=template) expected = "operational" result = hinter.Render(sshd) self.assertEqual(expected, result) def testRdfFormatterFanOut(self): rdf = rdf_protodict.Dict() user1 = rdf_client.User(username="drexler") user2 = rdf_client.User(username="joy") rdf["cataclysm"] = "GreyGoo" rdf["thinkers"] = [user1, user2] rdf["reference"] = { "ecophage": ["bots", ["nanobots", ["picobots"]]], "doomsday": { "books": ["cats cradle", "prey"] } } template = ("{cataclysm}; {thinkers.username}; {reference.ecophage}; " "{reference.doomsday}\n") hinter = hints.Hinter(template=template) expected = ("GreyGoo; drexler,joy; bots,nanobots,picobots; " "books:cats cradle,prey") result = hinter.Render(rdf) self.assertEqual(expected, result) def testStatModeFormat(self): rdf = rdf_client.StatEntry(st_mode=33204) expected = "-rw-rw-r--" template = "{st_mode}" hinter = hints.Hinter(template=template) result = hinter.Render(rdf) self.assertEqual(expected, result) def main(argv): test_lib.main(argv) if __name__ == "__main__": flags.StartMain(main)
Java
// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * Extension ID of Files.app. * @type {string} * @const */ var FILE_MANAGER_EXTENSIONS_ID = 'hhaomjibdihmijegdhdafkllkbggdgoj'; /** * Calls a remote test util in Files.app's extension. See: test_util.js. * * @param {string} func Function name. * @param {?string} appId Target window's App ID or null for functions * not requiring a window. * @param {Array.<*>} args Array of arguments. * @param {function(*)} callback Callback handling the function's result. */ function callRemoteTestUtil(func, appId, args, callback) { chrome.runtime.sendMessage( FILE_MANAGER_EXTENSIONS_ID, { func: func, appId: appId, args: args }, callback); } chrome.test.runTests([ // Waits for the C++ code to send a string identifying a test, then runs that // test. function testRunner() { var command = chrome.extension.inIncognitoContext ? 'which test guest' : 'which test non-guest'; chrome.test.sendMessage(command, function(testCaseName) { // Run one of the test cases defined in the testcase namespace, in // test_cases.js. The test case name is passed via StartTest call in // file_manager_browsertest.cc. if (testcase[testCaseName]) testcase[testCaseName](); else chrome.test.fail('Bogus test name passed to testRunner()'); }); } ]);
Java
/* Copyright 2007-2009 WebDriver committers Copyright 2007-2009 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "stdafx.h" #include "webdriver.h" #include "finder.h" #include "interactions.h" #include "InternetExplorerDriver.h" #include "logging.h" #include "jsxpath.h" #include "cookies.h" #include "sizzle.h" #include "utils.h" #include "atoms.h" #include "IEReturnTypes.h" #include "windowHandling.h" #include <stdio.h> #include <iostream> #include <string> #include <vector> #define END_TRY catch(std::wstring& m) \ { \ if (m.find(L"TIME OUT") != std::wstring::npos) { return ETIMEOUT; } \ wcerr << m.c_str() << endl; \ LOG(WARN) << "Last error: " << GetLastError(); \ return EEXPECTEDERROR; \ } \ catch (...) \ { \ safeIO::CoutA("CException caught in dll", true); \ return EUNHANDLEDERROR; } struct WebDriver { InternetExplorerDriver *ie; long implicitWaitTimeout; }; struct WebElement { ElementWrapper *element; }; struct ScriptArgs { LONG currentIndex; int maxLength; SAFEARRAY* args; }; struct ScriptResult { CComVariant result; }; struct StringWrapper { wchar_t *text; }; struct ElementCollection { std::vector<ElementWrapper*>* elements; }; struct StringCollection { std::vector<std::wstring>* strings; }; InternetExplorerDriver* openIeInstance = NULL; clock_t endAt(WebDriver* driver) { clock_t end = clock() + (driver->implicitWaitTimeout / 1000 * CLOCKS_PER_SEC); if (driver->implicitWaitTimeout > 0 && driver->implicitWaitTimeout < 1000) { end += 1 * CLOCKS_PER_SEC; } return end; } int terminateIe() { std::vector<HWND> allWindows; getTopLevelWindows(&allWindows); // Wait until all open windows are gone. Common case, no worries while (allWindows.size() > 0) { allWindows.clear(); getTopLevelWindows(&allWindows); for (vector<HWND>::iterator curr = allWindows.begin(); curr != allWindows.end(); curr++) { SendMessage(*curr, WM_CLOSE, NULL, NULL); } // Pause to allow IE to process the message. If we don't do this and // we're using IE 8, and "Restore previous session" is enabled (an // increasingly common state) then a modal system dialog will be // displayed to the user. Not what we want. wait(500); } // If it's longer than this, we're on a very strange system wchar_t taskkillPath[256]; if (!ExpandEnvironmentStrings(L"%SystemRoot%\\system32\\taskkill.exe", taskkillPath, 256)) { cerr << "Unable to find taskkill application" << endl; return EUNHANDLEDERROR; } std::wstring args = L" /f /im iexplore.exe"; STARTUPINFO startup_info; memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(startup_info); PROCESS_INFORMATION process_info; if (!CreateProcessW(taskkillPath, &args[0], NULL, NULL, false, DETACHED_PROCESS, NULL, NULL, &startup_info, &process_info)) { cerr << "Could not execute taskkill. Bailing: " << GetLastError() << endl; return EUNHANDLEDERROR; } WaitForSingleObject(process_info.hProcess, INFINITE); CloseHandle(process_info.hThread); CloseHandle(process_info.hProcess); return SUCCESS; } extern "C" { // String manipulation functions int wdStringLength(StringWrapper* string, int* length) { if (!string) { cerr << "No string to get length of" << endl; *length = -1; return -1; } if (!string->text) { cerr << "No underlying string to get length of" << endl; *length = -1; return -2; } size_t len = wcslen(string->text); *length = (int) len + 1; return SUCCESS; } int wdFreeString(StringWrapper* string) { if (!string) { return ENOSTRING; } if (string->text) delete[] string->text; delete string; return SUCCESS; } int wdCopyString(StringWrapper* source, int size, wchar_t* dest) { if (!source) { cerr << "No source wrapper" << endl; return ENOSTRING; } if (!source->text) { cerr << "No source text" << endl; return ENOSTRING; } wcscpy_s(dest, size, source->text); return SUCCESS; } // Collection manipulation functions int wdcGetElementCollectionLength(ElementCollection* collection, int* length) { if (!collection || !collection->elements) return ENOCOLLECTION; *length = (int) collection->elements->size(); return SUCCESS; } int wdcGetElementAtIndex(ElementCollection* collection, int index, WebElement** result) { *result = NULL; if (!collection || !collection->elements) return ENOCOLLECTION; std::vector<ElementWrapper*>::const_iterator cur = collection->elements->begin(); cur += index; WebElement* element = new WebElement(); element->element = *cur; *result = element; return SUCCESS; } int wdcGetStringCollectionLength(StringCollection* collection, int* length) { if (!collection) return ENOCOLLECTION; *length = (int) collection->strings->size(); return SUCCESS; } int wdcGetStringAtIndex(StringCollection* collection, int index, StringWrapper** result) { *result = NULL; if (!collection) return ENOCOLLECTION; std::vector<std::wstring>::const_iterator cur = collection->strings->begin(); cur += index; StringWrapper* wrapper = new StringWrapper(); size_t size = (*cur).length() + 1; wrapper->text = new wchar_t[size]; wcscpy_s(wrapper->text, size, (*cur).c_str()); *result = wrapper; return SUCCESS; } // Element manipulation functions int wdeFreeElement(WebElement* element) { if (!element) return ENOSUCHDRIVER; if (element->element) delete element->element; delete element; return SUCCESS; } int wdFreeElementCollection(ElementCollection* collection, int alsoFreeElements) { if (!collection || !collection->elements) return ENOSUCHCOLLECTION; if (alsoFreeElements) { std::vector<ElementWrapper*>::const_iterator cur = collection->elements->begin(); std::vector<ElementWrapper*>::const_iterator end = collection->elements->end(); while (cur != end) { delete *cur; cur++; } } delete collection->elements; delete collection; return SUCCESS; } int wdFreeStringCollection(StringCollection* collection) { if (!collection || !collection->strings) return ENOSUCHCOLLECTION; delete collection->strings; delete collection; return SUCCESS; } int wdFreeScriptArgs(ScriptArgs* scriptArgs) { if (!scriptArgs || !scriptArgs->args) return ENOSUCHCOLLECTION; SafeArrayDestroy(scriptArgs->args); delete scriptArgs; return SUCCESS; } int wdFreeScriptResult(ScriptResult* scriptResult) { if (!scriptResult) return ENOCOLLECTION; VariantClear(&scriptResult->result); delete scriptResult; return SUCCESS; } // Driver manipulation functions int wdFreeDriver(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { terminateIe(); } catch (...) { // Fine. We're quitting anyway. } delete driver->ie; delete driver; driver = NULL; // Let the IE COM instance fade away wait(4000); return SUCCESS; } int wdNewDriverInstance(WebDriver** result) { *result = NULL; TRY { terminateIe(); /* wchar_t iePath[256]; if (!ExpandEnvironmentStrings(L"%ProgramFiles%\\Internet Explorer\\iexplore.exe", iePath, 256)) { cerr << "Unable to find IE" << endl; return EUNHANDLEDERROR; } memset(&startup_info, 0, sizeof(startup_info)); startup_info.cb = sizeof(startup_info); args = L"about:blank"; if (!CreateProcessW(iePath, &args[0], NULL, NULL, false, 0, NULL, NULL, &startup_info, &process_info)) { cerr << "Could not execute IE. Bailing: " << GetLastError() << endl; return EUNHANDLEDERROR; } */ WebDriver *driver = new WebDriver(); driver->ie = new InternetExplorerDriver(); driver->ie->setVisible(true); driver->implicitWaitTimeout = 0; openIeInstance = driver->ie; *result = driver; return SUCCESS; } END_TRY return ENOSUCHDRIVER; } int wdGet(WebDriver* driver, const wchar_t* url) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->get(url); driver->ie->waitForNavigateToFinish(); return SUCCESS; } END_TRY; } int wdGoBack(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->goBack(); return SUCCESS; } END_TRY; } int wdGoForward(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->goForward(); return SUCCESS; } END_TRY; } int wdRefresh(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; StringWrapper* wrapper; int result = wdGetCurrentUrl(driver, &wrapper); if (result != SUCCESS) { return result; } result = wdGet(driver, wrapper->text); wdFreeString(wrapper); return result; } int wdClose(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->close(); return SUCCESS; } END_TRY } int wdGetVisible(WebDriver* driver, int* value) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { *value = driver->ie->getVisible() ? 1 : 0; return SUCCESS; } END_TRY; } int wdSetVisible(WebDriver* driver, int value) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->setVisible(value != 0); } END_TRY; return SUCCESS; } int wdGetCurrentUrl(WebDriver* driver, StringWrapper** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->getCurrentUrl()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdGetTitle(WebDriver* driver, StringWrapper** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->getTitle()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdGetPageSource(WebDriver* driver, StringWrapper** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->getPageSource()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdGetCookies(WebDriver* driver, StringWrapper** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->getCookies()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdAddCookie(WebDriver* driver, const wchar_t* cookie) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { return driver->ie->addCookie(cookie); } END_TRY; } int wdDeleteCookie(WebDriver* driver, const wchar_t* cookieName) { if (!driver || !driver->ie) return ENOSUCHDRIVER; // Inject the XPath engine std::wstring script; for (int i = 0; DELETECOOKIES[i]; i++) { script += DELETECOOKIES[i]; } ScriptArgs* args; int result = wdNewScriptArgs(&args, 1); if (result != SUCCESS) { return result; } wdAddStringScriptArg(args, cookieName); ScriptResult* scriptResult = NULL; result = wdExecuteScript(driver, script.c_str(), args, &scriptResult); wdFreeScriptArgs(args); if (scriptResult) delete scriptResult; return result; } int wdSwitchToActiveElement(WebDriver* driver, WebElement** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { ElementWrapper* element = driver->ie->getActiveElement(); if (!element) return ENOSUCHELEMENT; WebElement* toReturn = new WebElement(); toReturn->element = element; *result = toReturn; return SUCCESS; } END_TRY; } int wdSwitchToWindow(WebDriver* driver, const wchar_t* name) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { int result; // It's entirely possible the window to switch to isn't here yet. // TODO(simon): Make this configurable for (int i = 0; i < 8; i++) { result = driver->ie->switchToWindow(name); if (result == SUCCESS) { break; } wait(500); } return result; } END_TRY; } int wdSwitchToFrame(WebDriver* driver, const wchar_t* path) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { // TODO(simon): Make this configurable for (int i = 0; i < 8; i++) { bool result = driver->ie->switchToFrame(path); if (result) { return SUCCESS; } wait(500); } return ENOSUCHFRAME; } END_TRY; } int wdWaitForLoadToComplete(WebDriver* driver) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { driver->ie->waitForNavigateToFinish(); return SUCCESS; } END_TRY; } int wdGetCurrentWindowHandle(WebDriver* driver, StringWrapper** handle) { if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->getHandle()); // TODO(simon): Check that the handle is in the map of known driver instances size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *handle = res; return SUCCESS; } END_TRY; } int wdGetAllWindowHandles(WebDriver* driver, StringCollection** handles) { if (!driver || !driver->ie) return ENOSUCHDRIVER; *handles = NULL; try { std::vector<std::wstring> rawHandles = driver->ie->getAllHandles(); StringCollection* collection = new StringCollection(); collection->strings = new std::vector<std::wstring>(); for (std::vector<std::wstring>::iterator curr = rawHandles.begin(); curr != rawHandles.end(); curr++) { collection->strings->push_back(std::wstring(*curr)); } *handles = collection; return SUCCESS; } END_TRY; } int verifyFresh(WebElement* element) { if (!element || !element->element) { return ENOSUCHELEMENT; } try { if (!element->element->isFresh()) { return EOBSOLETEELEMENT; } } END_TRY; return SUCCESS; } int wdeClick(WebElement* element) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { res = element->element->click(); return res; } END_TRY; } int wdeGetAttribute(WebDriver* driver, WebElement* element, const wchar_t* name, StringWrapper** result) { *result = NULL; int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { std::wstring script(L"(function() { return function(){ "); // Read in all the scripts for (int j = 0; GET_ATTRIBUTE[j]; j++) { script += GET_ATTRIBUTE[j]; script += L"\n"; } // Now for the magic script += L"var element = arguments[0];\n"; script += L"var attributeName = arguments[1];\n"; script += L"return getAttribute(element, attributeName);\n"; // Close things script += L"};})();"; ScriptArgs* args; res = wdNewScriptArgs(&args, 2); if (res != SUCCESS) { return res; } wdAddElementScriptArg(args, element); wdAddStringScriptArg(args, name); WebDriver* driver = new WebDriver(); driver->ie = element->element->getParent(); ScriptResult* scriptResult = NULL; res = wdExecuteScript(driver, script.c_str(), args, &scriptResult); wdFreeScriptArgs(args); driver->ie = NULL; delete driver; if (res != SUCCESS) { wdFreeScriptResult(scriptResult); return res; } int type; wdGetScriptResultType(driver, scriptResult, &type); if (type != TYPE_EMPTY && scriptResult->result.vt != VT_NULL) { const std::wstring originalString(comvariant2cw(scriptResult->result)); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); *result = new StringWrapper(); (*result)->text = toReturn; } wdFreeScriptResult(scriptResult); return SUCCESS; } END_TRY; } int wdeGetValueOfCssProperty(WebElement* element, const wchar_t* name, StringWrapper** result) { *result = NULL; int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { const std::wstring originalString(element->element->getValueOfCssProperty(name)); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdeGetText(WebElement* element, StringWrapper** result) { *result = NULL; int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { const std::wstring originalString(element->element->getText()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdeGetTagName(WebElement* element, StringWrapper** result) { *result = NULL; int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { const std::wstring originalString(element->element->getTagName()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdeIsSelected(WebElement* element, int* result) { *result = 0; try { StringWrapper* wrapper; WebDriver* driver = new WebDriver(); driver->ie = element->element->getParent(); int res = wdeGetAttribute(driver, element, L"selected", &wrapper); driver->ie = NULL; delete driver; if (res != SUCCESS) { return res; } *result = wrapper && wrapper->text && wcscmp(L"true", wrapper->text) == 0 ? 1 : 0; wdFreeString(wrapper); return SUCCESS; } END_TRY; } int wdeSetSelected(WebElement* element) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { return element->element->setSelected(); } END_TRY; } int wdeToggle(WebElement* element, int* result) { *result = 0; int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { int res = element->element->toggle(); if (res == SUCCESS) { return wdeIsSelected(element, result); } return res; } END_TRY; } int wdeIsEnabled(WebElement* element, int* result) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { *result = element->element->isEnabled() ? 1 : 0; return SUCCESS; } END_TRY; } int wdeIsDisplayed(WebElement* element, int* result) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { *result = element->element->isDisplayed() ? 1 : 0; return SUCCESS; } END_TRY; } int wdeSendKeys(WebElement* element, const wchar_t* text) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { return element->element->sendKeys(text); } END_TRY; } int wdeSendKeyPress(WebElement* element, const wchar_t* text) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { return element->element->sendKeyPress(text); } END_TRY; } int wdeSendKeyRelease(WebElement* element, const wchar_t* text) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { return element->element->sendKeyRelease(text); } END_TRY; } int wdeClear(WebElement* element) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { element->element->clear(); return SUCCESS; } END_TRY; } int wdeSubmit(WebElement* element) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { element->element->submit(); return SUCCESS; } END_TRY; } int wdeGetDetailsOnceScrolledOnToScreen(WebElement* element, HWND* hwnd, long* x, long* y, long* width, long* height) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { element->element->getLocationWhenScrolledIntoView(hwnd, x, y, width, height); return SUCCESS; } END_TRY; } int wdeGetLocation(WebElement* element, long* x, long* y) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { element->element->getLocation(x, y); return SUCCESS; } END_TRY; } int wdeGetSize(WebElement* element, long* width, long* height) { int res = verifyFresh(element); if (res != SUCCESS) { return res; } try { int result = element->element->getWidth(width); if (result != SUCCESS) { return result; } result = element->element->getHeight(height); return result; } END_TRY; } int wdFindElementById(WebDriver* driver, WebElement* element, const wchar_t* id, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; res = ie->selectElementById(elem, id, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsById(WebDriver* driver, WebElement* element, const wchar_t* id, ElementCollection** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } clock_t end = endAt(driver); ElementCollection* collection = new ElementCollection(); *result = collection; do { collection->elements = driver->ie->selectElementsById(elem, id); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int wdFindElementByName(WebDriver* driver, WebElement* element, const wchar_t* name, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } CComPtr<IHTMLDOMNode> res; InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; int res = ie->selectElementByName(elem, name, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsByName(WebDriver* driver, WebElement* element, const wchar_t* name, ElementCollection** result) { *result = NULL; try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } ElementCollection* collection = new ElementCollection(); *result = collection; clock_t end = endAt(driver); do { collection->elements = driver->ie->selectElementsByName(elem, name); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int wdFindElementByClassName(WebDriver* driver, WebElement* element, const wchar_t* className, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; int res = ie->selectElementByClassName(elem, className, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsByClassName(WebDriver* driver, WebElement* element, const wchar_t* className, ElementCollection** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } clock_t end = endAt(driver); ElementCollection* collection = new ElementCollection(); *result = collection; do { collection->elements = driver->ie->selectElementsByClassName(elem, className); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int wdFindElementByCss(WebDriver* driver, WebElement* element, const wchar_t* selector, WebElement** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = ENOSUCHELEMENT; do { std::wstring script(L"(function() { return function(){"); for (int i = 0; SIZZLE[i]; i++) { script += SIZZLE[i]; script += L"\n"; } script += L"var root = arguments[1] ? arguments[1] : document.documentElement;"; script += L"if (root['querySelector']) { return root.querySelector(arguments[0]); } "; script += L"var results = []; Sizzle(arguments[0], root, results);"; script += L"return results.length > 0 ? results[0] : null;"; script += L"};})();"; // Call it ScriptArgs* args; result = wdNewScriptArgs(&args, 2); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddStringScriptArg(args, selector); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } if (element) { result = wdAddElementScriptArg(args, element); } if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } ScriptResult* queryResult; result = wdExecuteScript(driver, script.c_str(), args, &queryResult); wdFreeScriptArgs(args); // And be done if (result == SUCCESS) { int type = 0; result = wdGetScriptResultType(driver, queryResult, &type); if (type != TYPE_EMPTY) { result = wdGetElementScriptResult(queryResult, driver, out); } else { result = ENOSUCHELEMENT; wdFreeScriptResult(queryResult); continue; } } wdFreeScriptResult(queryResult); return result; } while (clock() < end); return result; } END_TRY; } int wdFindElementsByCss(WebDriver* driver, WebElement* element, const wchar_t* selector, ElementCollection** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = EUNHANDLEDERROR; do { // Call it std::wstring script(L"(function() { return function(){"); for (int i = 0; SIZZLE[i]; i++) { script += SIZZLE[i]; script += L"\n"; } script += L"var root = arguments[1] ? arguments[1] : document.documentElement;"; script += L"if (root['querySelectorAll']) { return root.querySelectorAll(arguments[0]); } "; script += L"var results = []; Sizzle(arguments[0], root, results);"; script += L"return results;"; script += L"};})();"; // Call it ScriptArgs* args; result = wdNewScriptArgs(&args, 2); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddStringScriptArg(args, selector); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } result = wdAddElementScriptArg(args, element); if (result != SUCCESS) { wdFreeScriptArgs(args); continue; } ScriptResult* queryResult; result = wdExecuteScript(driver, script.c_str(), args, &queryResult); wdFreeScriptArgs(args); // And be done if (result != SUCCESS) { wdFreeScriptResult(queryResult); return result; } ElementCollection* elements = new ElementCollection(); elements->elements = new std::vector<ElementWrapper*>(); int length; result = wdGetArrayLengthScriptResult(driver, queryResult, &length); if (result != SUCCESS) { wdFreeScriptResult(queryResult); return result; } for (long i = 0; i < length; i++) { ScriptResult* getElemRes; wdGetArrayItemFromScriptResult(driver, queryResult, i, &getElemRes); WebElement* e; wdGetElementScriptResult(getElemRes, driver, &e); elements->elements->push_back(e->element); e->element = NULL; delete e; } wdFreeScriptResult(queryResult); *out = elements; return SUCCESS; } while (clock() < end); return result; } END_TRY; } int wdFindElementByLinkText(WebDriver* driver, WebElement* element, const wchar_t* linkText, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; int res = ie->selectElementByLink(elem, linkText, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsByLinkText(WebDriver* driver, WebElement* element, const wchar_t* linkText, ElementCollection** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } ElementCollection* collection = new ElementCollection(); *result = collection; clock_t end = endAt(driver); do { collection->elements = driver->ie->selectElementsByLink(elem, linkText); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int wdFindElementByPartialLinkText(WebDriver* driver, WebElement* element, const wchar_t* linkText, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; int res = ie->selectElementByPartialLink(elem, linkText, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsByPartialLinkText(WebDriver* driver, WebElement* element, const wchar_t* linkText, ElementCollection** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } ElementCollection* collection = new ElementCollection(); *result = collection; clock_t end = endAt(driver); do { collection->elements = driver->ie->selectElementsByPartialLink(elem, linkText); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int wdFindElementByTagName(WebDriver* driver, WebElement* element, const wchar_t* name, WebElement** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } try { clock_t end = endAt(driver); int res = ENOSUCHELEMENT; do { ElementWrapper* wrapper; int res = ie->selectElementByTagName(elem, name, &wrapper); if (res != SUCCESS) { continue; } WebElement* toReturn = new WebElement(); toReturn->element = wrapper; *result = toReturn; return SUCCESS; } while (clock() < end); return res; } END_TRY; } int wdFindElementsByTagName(WebDriver* driver, WebElement* element, const wchar_t* name, ElementCollection** result) { *result = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { InternetExplorerDriver* ie = driver->ie; CComPtr<IHTMLElement> elem; if (element && element->element) { elem = element->element->getWrappedElement(); } ElementCollection* collection = new ElementCollection(); *result = collection; clock_t end = endAt(driver); do { collection->elements = driver->ie->selectElementsByTagName(elem, name); if (collection->elements->size() > 0) { return SUCCESS; } } while (clock() < end); return SUCCESS; } END_TRY; } int injectXPathEngine(WebDriver* driver) { // Inject the XPath engine std::wstring script; for (int i = 0; XPATHJS[i]; i++) { script += XPATHJS[i]; } ScriptArgs* args; int result = wdNewScriptArgs(&args, 0); if (result != SUCCESS) { return result; } ScriptResult* scriptResult = NULL; result = wdExecuteScript(driver, script.c_str(), args, &scriptResult); wdFreeScriptArgs(args); if (scriptResult) delete scriptResult; return result; } int wdFindElementByXPath(WebDriver* driver, WebElement* element, const wchar_t* xpath, WebElement** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = ENOSUCHELEMENT; do { result = injectXPathEngine(driver); // TODO(simon): Why does the injecting sometimes fail? /* if (result != SUCCESS) { return result; } */ // Call it std::wstring query; if (element) { query += L"(function() { return function(){var res = document.__webdriver_evaluate(arguments[0], arguments[1], null, 7, null); return res.snapshotItem(0) ;};})();"; } else { query += L"(function() { return function(){var res = document.__webdriver_evaluate(arguments[0], document, null, 7, null); return res.snapshotLength != 0 ? res.snapshotItem(0) : undefined ;};})();"; } ScriptArgs* queryArgs; result = wdNewScriptArgs(&queryArgs, 2); if (result != SUCCESS) { wdFreeScriptArgs(queryArgs); continue; } result = wdAddStringScriptArg(queryArgs, xpath); if (result != SUCCESS) { wdFreeScriptArgs(queryArgs); continue; } if (element) { result = wdAddElementScriptArg(queryArgs, element); } if (result != SUCCESS) { wdFreeScriptArgs(queryArgs); continue; } ScriptResult* queryResult; result = wdExecuteScript(driver, query.c_str(), queryArgs, &queryResult); wdFreeScriptArgs(queryArgs); // And be done if (result == SUCCESS) { int type = 0; result = wdGetScriptResultType(driver, queryResult, &type); if (type != TYPE_EMPTY) { result = wdGetElementScriptResult(queryResult, driver, out); } else { result = ENOSUCHELEMENT; wdFreeScriptResult(queryResult); continue; } } wdFreeScriptResult(queryResult); return result; } while (clock() < end); return result; } END_TRY; } int wdFindElementsByXPath(WebDriver* driver, WebElement* element, const wchar_t* xpath, ElementCollection** out) { *out = NULL; if (!driver || !driver->ie) { return ENOSUCHDRIVER; } try { clock_t end = endAt(driver); int result = EUNHANDLEDERROR; do { result = injectXPathEngine(driver); if (result != SUCCESS) { continue; } // Call it std::wstring query; if (element) query += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], arguments[1], null, 7, null); return res;};})();"; else query += L"(function() { return function() {var res = document.__webdriver_evaluate(arguments[0], document, null, 7, null); return res;};})();"; // We need to use the raw functions because we don't allow random objects // to be returned from the executeScript method normally SAFEARRAYBOUND bounds; bounds.cElements = 2; bounds.lLbound = 0; SAFEARRAY* queryArgs = SafeArrayCreate(VT_VARIANT, 1, &bounds); CComVariant queryArg(xpath); LONG index = 0; SafeArrayPutElement(queryArgs, &index, &queryArg); if (element) { CComVariant elementArg(element->element->getWrappedElement()); LONG index = 1; SafeArrayPutElement(queryArgs, &index, &elementArg); } CComVariant snapshot; result = driver->ie->executeScript(query.c_str(), queryArgs, &snapshot); SafeArrayDestroy(queryArgs); if (result != SUCCESS) { continue; } bounds.cElements = 1; SAFEARRAY* lengthArgs = SafeArrayCreate(VT_VARIANT, 1, &bounds); index = 0; SafeArrayPutElement(lengthArgs, &index, &snapshot); CComVariant lengthVar; result = driver->ie->executeScript(L"(function(){return function() {return arguments[0].snapshotLength;}})();", lengthArgs, &lengthVar); SafeArrayDestroy(lengthArgs); if (result != SUCCESS) { continue; } if (lengthVar.vt != VT_I4) { result = EUNEXPECTEDJSERROR; continue; } long length = lengthVar.lVal; bounds.cElements = 2; SAFEARRAY* snapshotArgs = SafeArrayCreate(VT_VARIANT, 1, &bounds); index = 0; SafeArrayPutElement(snapshotArgs, &index, &snapshot); ElementCollection* elements = new ElementCollection(); elements->elements = new std::vector<ElementWrapper*>(); index = 1; for (long i = 0; i < length; i++) { ScriptArgs* getElemArgs; wdNewScriptArgs(&getElemArgs, 2); // Cheat index = 0; SafeArrayPutElement(getElemArgs->args, &index, &snapshot); getElemArgs->currentIndex++; wdAddNumberScriptArg(getElemArgs, i); ScriptResult* getElemRes; wdExecuteScript(driver, L"(function(){return function() {return arguments[0].iterateNext();}})();", getElemArgs, &getElemRes); WebElement* e; wdGetElementScriptResult(getElemRes, driver, &e); elements->elements->push_back(e->element); wdFreeScriptArgs(getElemArgs); } SafeArrayDestroy(queryArgs); *out = elements; return SUCCESS; } while (clock() < end); return result; } END_TRY; } int wdNewScriptArgs(ScriptArgs** scriptArgs, int maxLength) { *scriptArgs = NULL; ScriptArgs* args = new ScriptArgs(); args->currentIndex = 0; args->maxLength = maxLength; SAFEARRAYBOUND bounds; bounds.cElements = maxLength; bounds.lLbound = 0; args->args = SafeArrayCreate(VT_VARIANT, 1, &bounds); *scriptArgs = args; return SUCCESS; } int wdAddStringScriptArg(ScriptArgs* scriptArgs, const wchar_t* arg) { std::wstring value(arg); CComVariant dest(arg); LONG index = scriptArgs->currentIndex; SafeArrayPutElement(scriptArgs->args, &index, &dest); scriptArgs->currentIndex++; return SUCCESS; } int wdAddBooleanScriptArg(ScriptArgs* scriptArgs, int trueOrFalse) { VARIANT dest; dest.vt = VT_BOOL; dest.boolVal = trueOrFalse == 1; LONG index = scriptArgs->currentIndex; SafeArrayPutElement(scriptArgs->args, &index, &dest); scriptArgs->currentIndex++; return SUCCESS; } int wdAddNumberScriptArg(ScriptArgs* scriptArgs, long number) { VARIANT dest; dest.vt = VT_I4; dest.lVal = (LONG) number; LONG index = scriptArgs->currentIndex; SafeArrayPutElement(scriptArgs->args, &index, &dest); scriptArgs->currentIndex++; return SUCCESS; } int wdAddDoubleScriptArg(ScriptArgs* scriptArgs, double number) { VARIANT dest; dest.vt = VT_R8; dest.dblVal = (DOUBLE) number; LONG index = scriptArgs->currentIndex; SafeArrayPutElement(scriptArgs->args, &index, &dest); scriptArgs->currentIndex++; return SUCCESS; } int wdAddElementScriptArg(ScriptArgs* scriptArgs, WebElement* element) { VARIANT dest; VariantClear(&dest); if (!element || !element->element) { dest.vt = VT_EMPTY; } else { dest.vt = VT_DISPATCH; dest.pdispVal = element->element->getWrappedElement(); } LONG index = scriptArgs->currentIndex; SafeArrayPutElement(scriptArgs->args, &index, &dest); scriptArgs->currentIndex++; return SUCCESS; } int wdExecuteScript(WebDriver* driver, const wchar_t* script, ScriptArgs* scriptArgs, ScriptResult** scriptResultRef) { try { *scriptResultRef = NULL; CComVariant result; int res = driver->ie->executeScript(script, scriptArgs->args, &result); if (res != SUCCESS) { return res; } ScriptResult* toReturn = new ScriptResult(); HRESULT hr = VariantCopy(&(toReturn->result), &result); if (!SUCCEEDED(hr) && result.vt == VT_USERDEFINED) { // Special handling of the user defined path *sigh* toReturn->result.vt = VT_USERDEFINED; toReturn->result.bstrVal = CComBSTR(result.bstrVal); } *scriptResultRef = toReturn; return SUCCESS; } END_TRY; } int wdGetScriptResultType(WebDriver* driver, ScriptResult* result, int* type) { if (!result) { return ENOSCRIPTRESULT; } switch (result->result.vt) { case VT_BSTR: *type = TYPE_STRING; break; case VT_I4: case VT_I8: *type = TYPE_LONG; break; case VT_BOOL: *type = TYPE_BOOLEAN; break; case VT_DISPATCH: { LPCWSTR itemType = driver->ie->getScriptResultType(&(result->result)); std::string itemTypeStr; cw2string(itemType, itemTypeStr); LOG(DEBUG) << "Got type: " << itemTypeStr; // If it's a Javascript array or an HTML Collection - type 8 will // indicate the driver that this is ultimately an array. if ((itemTypeStr == "JavascriptArray") || (itemTypeStr == "HtmlCollection")) { *type = TYPE_ARRAY; } else { *type = TYPE_ELEMENT; } } break; case VT_EMPTY: *type = TYPE_EMPTY; break; case VT_USERDEFINED: *type = TYPE_EXCEPTION; break; case VT_R4: case VT_R8: *type = TYPE_DOUBLE; break; default: return EUNKNOWNSCRIPTRESULT; } return SUCCESS; } int wdGetStringScriptResult(ScriptResult* result, StringWrapper** wrapper) { *wrapper = NULL; if (!result) { return ENOSCRIPTRESULT; } StringWrapper* toReturn = new StringWrapper(); BSTR val = result->result.bstrVal; if (!val) { toReturn->text = new wchar_t[1]; wcscpy_s(toReturn->text, 1, L""); } else { UINT length = SysStringLen(val); toReturn->text = new wchar_t[length + 1]; wcscpy_s(toReturn->text, length + 1, val); } *wrapper = toReturn; return SUCCESS; } int wdGetNumberScriptResult(ScriptResult* result, long* value) { if (!result) { return ENOSCRIPTRESULT; } *value = result->result.lVal; return SUCCESS; } int wdGetDoubleScriptResult(ScriptResult* result, double* value) { if (!result) { return ENOSCRIPTRESULT; } *value = result->result.dblVal; return SUCCESS; } int wdGetBooleanScriptResult(ScriptResult* result, int* value) { if (!result) { return ENOSCRIPTRESULT; } *value = result->result.boolVal == VARIANT_TRUE ? 1 : 0; return SUCCESS; } int wdGetElementScriptResult(ScriptResult* result, WebDriver* driver, WebElement** element) { *element = NULL; if (!result) { return ENOSCRIPTRESULT; } IHTMLElement *node = (IHTMLElement*) result->result.pdispVal; WebElement* toReturn = new WebElement(); toReturn->element = new ElementWrapper(driver->ie, node); *element = toReturn; return SUCCESS; } int wdGetArrayLengthScriptResult(WebDriver* driver, ScriptResult* result, int* length) { // Prepare an array for the Javascript execution, containing only one // element - the original returned array from a JS execution. SAFEARRAYBOUND lengthQuery; lengthQuery.cElements = 1; lengthQuery.lLbound = 0; SAFEARRAY* lengthArgs = SafeArrayCreate(VT_VARIANT, 1, &lengthQuery); LONG index = 0; SafeArrayPutElement(lengthArgs, &index, &(result->result)); CComVariant lengthVar; int lengthResult = driver->ie->executeScript( L"(function(){return function() {return arguments[0].length;}})();", lengthArgs, &lengthVar); SafeArrayDestroy(lengthArgs); if (lengthResult != SUCCESS) { return lengthResult; } // Expect the return type to be an integer. A non-integer means this was // not an array after all. if (lengthVar.vt != VT_I4) { return EUNEXPECTEDJSERROR; } *length = lengthVar.lVal; return SUCCESS; } int wdGetArrayItemFromScriptResult(WebDriver* driver, ScriptResult* result, int index, ScriptResult** arrayItem) { // Prepare an array for Javascript execution. The array contains the original // array returned from a previous execution and the index of the item required // from that array. ScriptArgs* getItemArgs; wdNewScriptArgs(&getItemArgs, 2); LONG argIndex = 0; // Original array. SafeArrayPutElement(getItemArgs->args, &argIndex, &(result->result)); getItemArgs->currentIndex++; // Item index wdAddNumberScriptArg(getItemArgs, index); int execRes = wdExecuteScript( driver, L"(function(){return function() {return arguments[0][arguments[1]];}})();", getItemArgs, arrayItem); wdFreeScriptArgs(getItemArgs); getItemArgs = NULL; return execRes; } int wdeMouseDownAt(HWND hwnd, long windowX, long windowY) { mouseDownAt(hwnd, windowX, windowY, MOUSEBUTTON_LFET); return SUCCESS; } int wdeMouseUpAt(HWND hwnd, long windowX, long windowY) { mouseUpAt(hwnd, windowX, windowY, MOUSEBUTTON_LFET); return SUCCESS; } int wdeMouseMoveTo(HWND hwnd, long duration, long fromX, long fromY, long toX, long toY) { mouseMoveTo(hwnd, duration, fromX, fromY, toX, toY); return SUCCESS; } int wdCaptureScreenshotAsBase64(WebDriver* driver, StringWrapper** result) { *result = NULL; if (!driver || !driver->ie) return ENOSUCHDRIVER; try { const std::wstring originalString(driver->ie->captureScreenshotAsBase64()); size_t length = originalString.length() + 1; wchar_t* toReturn = new wchar_t[length]; wcscpy_s(toReturn, length, originalString.c_str()); StringWrapper* res = new StringWrapper(); res->text = toReturn; *result = res; return SUCCESS; } END_TRY; } int wdSetImplicitWaitTimeout(WebDriver* driver, long timeoutInMillis) { if (!driver || !driver->ie) return ENOSUCHDRIVER; driver->implicitWaitTimeout = timeoutInMillis; return SUCCESS; } }
Java
/** * Copyright 2014 Nortal AS * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.nortal.petit.orm.statement; import java.util.List; import org.springframework.util.CollectionUtils; /** * @author Lauri Lättemäe ([email protected]) * @created 29.04.2013 */ public abstract class ExecutableStatement<B> extends SimpleStatement<B> { /** * Returns statements sql with parameter values * * @return */ @Override public String getSqlWithParams() { prepare(); StringBuffer sb = new StringBuffer(); if (!CollectionUtils.isEmpty(getBeans())) { for (B bean : getBeans()) { prepare(bean); sb.append(super.getSqlWithParams()).append("\n"); } } else { sb.append(super.getSqlWithParams()).append("\n"); } return sb.toString(); } protected abstract List<B> getBeans(); protected abstract void prepare(B bean); public abstract void exec(); }
Java
/* * Copyright 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.javascript.jscomp; import com.google.common.base.Preconditions; import com.google.javascript.jscomp.ControlFlowGraph.Branch; import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback; import com.google.javascript.jscomp.NodeTraversal.ScopedCallback; import com.google.javascript.jscomp.graph.GraphReachability; import com.google.javascript.jscomp.graph.DiGraph.DiGraphEdge; import com.google.javascript.jscomp.graph.DiGraph.DiGraphNode; import com.google.javascript.rhino.Node; import com.google.javascript.rhino.Token; import java.util.Deque; import java.util.LinkedList; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; /** * Removes dead code from a parse tree. The kinds of dead code that this pass * removes are: * - Any code following a return statement, such as the <code>alert</code> * call in: <code>if (x) { return; alert('unreachable'); }</code>. * - Statements that have no side effects, such as: * <code>a.b.MyClass.prototype.propertyName;</code> or <code>true;</code>. * That first kind of statement sometimes appears intentionally, so that * prototype properties can be annotated using JSDoc without actually * being initialized. * */ class UnreachableCodeElimination extends AbstractPostOrderCallback implements CompilerPass, ScopedCallback { private static final Logger logger = Logger.getLogger(UnreachableCodeElimination.class.getName()); private final AbstractCompiler compiler; private final boolean removeNoOpStatements; Deque<ControlFlowGraph<Node>> cfgStack = new LinkedList<ControlFlowGraph<Node>>(); ControlFlowGraph<Node> curCfg = null; UnreachableCodeElimination(AbstractCompiler compiler, boolean removeNoOpStatements) { this.compiler = compiler; this.removeNoOpStatements = removeNoOpStatements; } @Override public void enterScope(NodeTraversal t) { Scope scope = t.getScope(); // Computes the control flow graph. ControlFlowAnalysis cfa = new ControlFlowAnalysis(compiler, false); cfa.process(null, scope.getRootNode()); cfgStack.push(curCfg); curCfg = cfa.getCfg(); new GraphReachability<Node, ControlFlowGraph.Branch>(curCfg) .compute(curCfg.getEntry().getValue()); } @Override public void exitScope(NodeTraversal t) { curCfg = cfgStack.pop(); } @Override public void process(Node externs, Node root) { NodeTraversal.traverse(compiler, root, this); } @Override public void visit(NodeTraversal t, Node n, Node parent) { if (parent == null) { return; } if (n.getType() == Token.FUNCTION || n.getType() == Token.SCRIPT) { return; } // Removes TRYs that had its CATCH removed and/or empty FINALLY. // TODO(dcc): Move the parts of this that don't require a control flow // graph to PeepholeRemoveDeadCode if (n.getType() == Token.TRY) { Node body = n.getFirstChild(); Node catchOrFinallyBlock = body.getNext(); Node finallyBlock = catchOrFinallyBlock.getNext(); if (!catchOrFinallyBlock.hasChildren() && (finallyBlock == null || !finallyBlock.hasChildren())) { n.removeChild(body); parent.replaceChild(n, body); compiler.reportCodeChange(); n = body; } } DiGraphNode<Node, Branch> gNode = curCfg.getDirectedGraphNode(n); if (gNode == null) { // Not in CFG. return; } if (gNode.getAnnotation() != GraphReachability.REACHABLE || (removeNoOpStatements && !NodeUtil.mayHaveSideEffects(n))) { removeDeadExprStatementSafely(n); return; } tryRemoveUnconditionalBranching(n); } /** * Tries to remove n if an unconditional branch node (break, continue or * return) if the target of n is the same as the the follow of n. That is, if * we remove n, the control flow remains the same. Also if n targets to * another unconditional branch, this function will recursively try to remove * the target branch as well. The reason why we want to cascade this removal * is because we only run this pass once. If we have code such as * * break -> break -> break * * where all 3 break's are useless. The order of removal matters. When we * first look at the first break, we see that it branches to the 2nd break. * However, if we remove the last break, the 2nd break becomes useless and * finally the first break becomes useless as well. * * @return The target of this jump. If the target is also useless jump, * the target of that useless jump recursively. */ @SuppressWarnings("fallthrough") private Node tryRemoveUnconditionalBranching(Node n) { /* * For each of the unconditional branching control flow node, check to see * if the ControlFlowAnalysis.computeFollowNode of that node is same as * the branching target. If it is, the branch node is safe to be removed. * * This is not as clever as MinimizeExitPoints because it doesn't do any * if-else conversion but it handles more complicated switch statements * much nicer. */ // If n is null the target is the end of the function, nothing to do. if (n == null) { return n; } DiGraphNode<Node, Branch> gNode = curCfg.getDirectedGraphNode(n); if (gNode == null) { return n; } // If the parent is null, this mean whatever node it was there is now // useless and it has been removed by other logics in this pass. That node // while no longer exists in the AST, is still in the CFG because we // never update the graph as nodes are removed. if (n.getParent() == null) { List<DiGraphEdge<Node,Branch>> outEdges = gNode.getOutEdges(); if (outEdges.size() == 1) { return tryRemoveUnconditionalBranching( outEdges.get(0).getDestination().getValue()); } } switch (n.getType()) { case Token.BLOCK: if (n.hasChildren()) { Node first = n.getFirstChild(); return tryRemoveUnconditionalBranching(first); } else { return tryRemoveUnconditionalBranching( ControlFlowAnalysis.computeFollowNode(n)); } case Token.RETURN: if (n.hasChildren()) { break; } case Token.BREAK: case Token.CONTINUE: // We are looking for a control flow changing statement that always // branches to the same node. If removing it the control flow still // branches to that same node. It is safe to remove it. List<DiGraphEdge<Node,Branch>> outEdges = gNode.getOutEdges(); if (outEdges.size() == 1 && // If there is a next node, there is no chance this jump is useless. (n.getNext() == null || n.getNext().getType() == Token.FUNCTION)) { Preconditions.checkState(outEdges.get(0).getValue() == Branch.UNCOND); Node fallThrough = tryRemoveUnconditionalBranching( ControlFlowAnalysis.computeFollowNode(n)); Node nextCfgNode = outEdges.get(0).getDestination().getValue(); if (nextCfgNode == fallThrough) { removeDeadExprStatementSafely(n); return fallThrough; } } } return n; } private void removeDeadExprStatementSafely(Node n) { if (n.getType() == Token.EMPTY || (n.getType() == Token.BLOCK && !n.hasChildren())) { // Not always trivial to remove, let FoldContants work its magic later. return; } // Removing an unreachable DO node is messy because it means we still have // to execute one iteration. If the DO's body has breaks in the middle, it // can get even more trickier and code size might actually increase. switch (n.getType()) { case Token.DO: case Token.TRY: case Token.CATCH: case Token.FINALLY: return; } NodeUtil.redeclareVarsInsideBranch(n); compiler.reportCodeChange(); if (logger.isLoggable(Level.FINE)) { logger.fine("Removing " + n.toString()); } NodeUtil.removeChild(n.getParent(), n); } }
Java
package theinternet.pages; import com.frameworkium.core.ui.annotations.Visible; import com.frameworkium.core.ui.pages.BasePage; import com.frameworkium.core.ui.pages.PageFactory; import io.qameta.allure.Step; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import ru.yandex.qatools.htmlelements.annotations.Name; import ru.yandex.qatools.htmlelements.element.FileInput; public class FileUploadPage extends BasePage<FileUploadPage> { @Visible @Name("Choose Files button") @FindBy(css = "input#file-upload") private FileInput chooseFileInput; @Visible @Name("Upload button") @FindBy(css = "input#file-submit") private WebElement uploadButton; @Step("Upload a file by choosing file and then clicking upload") public FileUploadSuccessPage uploadFile(String filePath) { chooseFileInput.setFileToUpload(filePath); uploadButton.click(); return PageFactory.newInstance(FileUploadSuccessPage.class); } }
Java
/* * Copyright (C) 2014 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "OpenGLRenderer" #include "jni.h" #include "GraphicsJNI.h" #include <nativehelper/JNIHelp.h> #include "core_jni_helpers.h" #include <android_runtime/android_graphics_SurfaceTexture.h> #include <gui/GLConsumer.h> #include <Paint.h> #include <SkBitmap.h> #include <SkCanvas.h> #include <SkMatrix.h> #include <SkXfermode.h> #include <DeferredLayerUpdater.h> #include <LayerRenderer.h> #include <SkiaShader.h> #include <Rect.h> #include <RenderNode.h> namespace android { using namespace uirenderer; static jboolean android_view_HardwareLayer_prepare(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr, jint width, jint height, jboolean isOpaque) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); bool changed = false; changed |= layer->setSize(width, height); changed |= layer->setBlend(!isOpaque); return changed; } static void android_view_HardwareLayer_setLayerPaint(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr, jlong paintPtr) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); if (layer) { Paint* paint = reinterpret_cast<Paint*>(paintPtr); layer->setPaint(paint); } } static void android_view_HardwareLayer_setTransform(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr, jlong matrixPtr) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); SkMatrix* matrix = reinterpret_cast<SkMatrix*>(matrixPtr); layer->setTransform(matrix); } static void android_view_HardwareLayer_setSurfaceTexture(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr, jobject surface, jboolean isAlreadyAttached) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); sp<GLConsumer> surfaceTexture(SurfaceTexture_getSurfaceTexture(env, surface)); layer->setSurfaceTexture(surfaceTexture, !isAlreadyAttached); } static void android_view_HardwareLayer_updateSurfaceTexture(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); layer->updateTexImage(); } static jint android_view_HardwareLayer_getTexName(JNIEnv* env, jobject clazz, jlong layerUpdaterPtr) { DeferredLayerUpdater* layer = reinterpret_cast<DeferredLayerUpdater*>(layerUpdaterPtr); return layer->backingLayer()->getTextureId(); } // ---------------------------------------------------------------------------- // JNI Glue // ---------------------------------------------------------------------------- const char* const kClassPathName = "android/view/HardwareLayer"; static JNINativeMethod gMethods[] = { { "nPrepare", "(JIIZ)Z", (void*) android_view_HardwareLayer_prepare }, { "nSetLayerPaint", "(JJ)V", (void*) android_view_HardwareLayer_setLayerPaint }, { "nSetTransform", "(JJ)V", (void*) android_view_HardwareLayer_setTransform }, { "nSetSurfaceTexture", "(JLandroid/graphics/SurfaceTexture;Z)V", (void*) android_view_HardwareLayer_setSurfaceTexture }, { "nUpdateSurfaceTexture", "(J)V", (void*) android_view_HardwareLayer_updateSurfaceTexture }, { "nGetTexName", "(J)I", (void*) android_view_HardwareLayer_getTexName }, }; int register_android_view_HardwareLayer(JNIEnv* env) { return RegisterMethodsOrDie(env, kClassPathName, gMethods, NELEM(gMethods)); } };
Java
import { Type } from 'angular2/src/facade/lang'; import { CanActivate } from './lifecycle_annotations_impl'; import { reflector } from 'angular2/src/core/reflection/reflection'; export function hasLifecycleHook(e, type) { if (!(type instanceof Type)) return false; return e.name in type.prototype; } export function getCanActivateHook(type) { var annotations = reflector.annotations(type); for (let i = 0; i < annotations.length; i += 1) { let annotation = annotations[i]; if (annotation instanceof CanActivate) { return annotation.fn; } } return null; } //# sourceMappingURL=route_lifecycle_reflector.js.map
Java
/** * Copyright (c) 2016-present, RxJava Contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See * the License for the specific language governing permissions and limitations under the License. */ package io.reactivex.internal.operators.flowable; import java.util.concurrent.atomic.AtomicReference; import org.reactivestreams.*; import io.reactivex.*; import io.reactivex.annotations.Nullable; import io.reactivex.disposables.*; import io.reactivex.exceptions.Exceptions; import io.reactivex.functions.Function; import io.reactivex.internal.disposables.DisposableHelper; import io.reactivex.internal.functions.ObjectHelper; import io.reactivex.internal.subscriptions.*; import io.reactivex.internal.util.AtomicThrowable; import io.reactivex.plugins.RxJavaPlugins; /** * Maps a sequence of values into CompletableSources and awaits their termination. * @param <T> the value type */ public final class FlowableFlatMapCompletable<T> extends AbstractFlowableWithUpstream<T, T> { final Function<? super T, ? extends CompletableSource> mapper; final int maxConcurrency; final boolean delayErrors; public FlowableFlatMapCompletable(Flowable<T> source, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { super(source); this.mapper = mapper; this.delayErrors = delayErrors; this.maxConcurrency = maxConcurrency; } @Override protected void subscribeActual(Subscriber<? super T> subscriber) { source.subscribe(new FlatMapCompletableMainSubscriber<T>(subscriber, mapper, delayErrors, maxConcurrency)); } static final class FlatMapCompletableMainSubscriber<T> extends BasicIntQueueSubscription<T> implements FlowableSubscriber<T> { private static final long serialVersionUID = 8443155186132538303L; final Subscriber<? super T> downstream; final AtomicThrowable errors; final Function<? super T, ? extends CompletableSource> mapper; final boolean delayErrors; final CompositeDisposable set; final int maxConcurrency; Subscription upstream; volatile boolean cancelled; FlatMapCompletableMainSubscriber(Subscriber<? super T> subscriber, Function<? super T, ? extends CompletableSource> mapper, boolean delayErrors, int maxConcurrency) { this.downstream = subscriber; this.mapper = mapper; this.delayErrors = delayErrors; this.errors = new AtomicThrowable(); this.set = new CompositeDisposable(); this.maxConcurrency = maxConcurrency; this.lazySet(1); } @Override public void onSubscribe(Subscription s) { if (SubscriptionHelper.validate(this.upstream, s)) { this.upstream = s; downstream.onSubscribe(this); int m = maxConcurrency; if (m == Integer.MAX_VALUE) { s.request(Long.MAX_VALUE); } else { s.request(m); } } } @Override public void onNext(T value) { CompletableSource cs; try { cs = ObjectHelper.requireNonNull(mapper.apply(value), "The mapper returned a null CompletableSource"); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); upstream.cancel(); onError(ex); return; } getAndIncrement(); InnerConsumer inner = new InnerConsumer(); if (!cancelled && set.add(inner)) { cs.subscribe(inner); } } @Override public void onError(Throwable e) { if (errors.addThrowable(e)) { if (delayErrors) { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); downstream.onError(ex); } else { if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } } else { cancel(); if (getAndSet(0) > 0) { Throwable ex = errors.terminate(); downstream.onError(ex); } } } else { RxJavaPlugins.onError(e); } } @Override public void onComplete() { if (decrementAndGet() == 0) { Throwable ex = errors.terminate(); if (ex != null) { downstream.onError(ex); } else { downstream.onComplete(); } } else { if (maxConcurrency != Integer.MAX_VALUE) { upstream.request(1); } } } @Override public void cancel() { cancelled = true; upstream.cancel(); set.dispose(); } @Override public void request(long n) { // ignored, no values emitted } @Nullable @Override public T poll() throws Exception { return null; // always empty } @Override public boolean isEmpty() { return true; // always empty } @Override public void clear() { // nothing to clear } @Override public int requestFusion(int mode) { return mode & ASYNC; } void innerComplete(InnerConsumer inner) { set.delete(inner); onComplete(); } void innerError(InnerConsumer inner, Throwable e) { set.delete(inner); onError(e); } final class InnerConsumer extends AtomicReference<Disposable> implements CompletableObserver, Disposable { private static final long serialVersionUID = 8606673141535671828L; @Override public void onSubscribe(Disposable d) { DisposableHelper.setOnce(this, d); } @Override public void onComplete() { innerComplete(this); } @Override public void onError(Throwable e) { innerError(this, e); } @Override public void dispose() { DisposableHelper.dispose(this); } @Override public boolean isDisposed() { return DisposableHelper.isDisposed(get()); } } } }
Java
/* * Copyright 2017 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.dmn.core.compiler; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Optional; import org.kie.dmn.api.core.DMNType; import org.kie.dmn.api.core.ast.BusinessKnowledgeModelNode; import org.kie.dmn.api.core.ast.DMNNode; import org.kie.dmn.api.core.ast.DecisionNode; import org.kie.dmn.api.core.ast.DecisionServiceNode; import org.kie.dmn.api.core.ast.InputDataNode; import org.kie.dmn.core.api.DMNExpressionEvaluator; import org.kie.dmn.core.ast.DecisionNodeImpl; import org.kie.dmn.core.impl.CompositeTypeImpl; import org.kie.dmn.core.impl.DMNModelImpl; import org.kie.dmn.core.util.Msg; import org.kie.dmn.model.api.DRGElement; import org.kie.dmn.model.api.Decision; public class DecisionCompiler implements DRGElementCompiler { @Override public boolean accept(DRGElement de) { return de instanceof Decision; } @Override public void compileNode(DRGElement de, DMNCompilerImpl compiler, DMNModelImpl model) { Decision decision = (Decision) de; DecisionNodeImpl dn = new DecisionNodeImpl( decision ); DMNType type = null; if ( decision.getVariable() == null ) { DMNCompilerHelper.reportMissingVariable( model, de, decision, Msg.MISSING_VARIABLE_FOR_DECISION ); return; } DMNCompilerHelper.checkVariableName( model, decision, decision.getName() ); if ( decision.getVariable() != null && decision.getVariable().getTypeRef() != null ) { type = compiler.resolveTypeRef(model, decision, decision.getVariable(), decision.getVariable().getTypeRef()); } else { type = compiler.resolveTypeRef(model, decision, decision, null); } dn.setResultType( type ); model.addDecision( dn ); } @Override public boolean accept(DMNNode node) { return node instanceof DecisionNodeImpl; } @Override public void compileEvaluator(DMNNode node, DMNCompilerImpl compiler, DMNCompilerContext ctx, DMNModelImpl model) { DecisionNodeImpl di = (DecisionNodeImpl) node; compiler.linkRequirements( model, di ); ctx.enterFrame(); try { Map<String, DMNType> importedTypes = new HashMap<>(); for( DMNNode dep : di.getDependencies().values() ) { if( dep instanceof DecisionNode ) { if (dep.getModelNamespace().equals(model.getNamespace())) { ctx.setVariable(dep.getName(), ((DecisionNode) dep).getResultType()); } else { // then the Decision dependency is an imported Decision. Optional<String> alias = model.getImportAliasFor(dep.getModelNamespace(), dep.getModelName()); if (alias.isPresent()) { CompositeTypeImpl importedComposite = (CompositeTypeImpl) importedTypes.computeIfAbsent(alias.get(), a -> new CompositeTypeImpl()); importedComposite.addField(dep.getName(), ((DecisionNode) dep).getResultType()); } } } else if( dep instanceof InputDataNode ) { if (dep.getModelNamespace().equals(model.getNamespace())) { ctx.setVariable(dep.getName(), ((InputDataNode) dep).getType()); } else { // then the InputData dependency is an imported InputData. Optional<String> alias = model.getImportAliasFor(dep.getModelNamespace(), dep.getModelName()); if (alias.isPresent()) { CompositeTypeImpl importedComposite = (CompositeTypeImpl) importedTypes.computeIfAbsent(alias.get(), a -> new CompositeTypeImpl()); importedComposite.addField(dep.getName(), ((InputDataNode) dep).getType()); } } } else if( dep instanceof BusinessKnowledgeModelNode ) { if (dep.getModelNamespace().equals(model.getNamespace())) { // might need to create a DMNType for "functions" and replace the type here by that ctx.setVariable(dep.getName(), ((BusinessKnowledgeModelNode) dep).getResultType()); } else { // then the BKM dependency is an imported BKM. Optional<String> alias = model.getImportAliasFor(dep.getModelNamespace(), dep.getModelName()); if (alias.isPresent()) { CompositeTypeImpl importedComposite = (CompositeTypeImpl) importedTypes.computeIfAbsent(alias.get(), a -> new CompositeTypeImpl()); importedComposite.addField(dep.getName(), ((BusinessKnowledgeModelNode) dep).getResultType()); } } } else if (dep instanceof DecisionServiceNode) { if (dep.getModelNamespace().equals(model.getNamespace())) { // might need to create a DMNType for "functions" and replace the type here by that ctx.setVariable(dep.getName(), ((DecisionServiceNode) dep).getResultType()); } else { // then the BKM dependency is an imported BKM. Optional<String> alias = model.getImportAliasFor(dep.getModelNamespace(), dep.getModelName()); if (alias.isPresent()) { CompositeTypeImpl importedComposite = (CompositeTypeImpl) importedTypes.computeIfAbsent(alias.get(), a -> new CompositeTypeImpl()); importedComposite.addField(dep.getName(), ((DecisionServiceNode) dep).getResultType()); } } } } for (Entry<String, DMNType> importedType : importedTypes.entrySet()) { ctx.setVariable(importedType.getKey(), importedType.getValue()); } DMNExpressionEvaluator evaluator = compiler.getEvaluatorCompiler().compileExpression( ctx, model, di, di.getName(), di.getDecision().getExpression() ); di.setEvaluator( evaluator ); } finally { ctx.exitFrame(); } } }
Java
var msg = require('./locale'); var api = require('./apiJavascript.js'); var paramLists = require('./paramLists.js'); module.exports.blocks = [ {func: 'setDroid', parent: api, category: '', params: ['"R2-D2"'], dropdown: { 0: ['"random"', '"R2-D2"', '"C-3PO"'] } }, {func: 'setDroidSpeed', parent: api, category: '', params: ['"fast"'], dropdown: { 0: ['"random"', '"slow"', '"normal"', '"fast"'] } }, {func: 'setBackground', parent: api, category: '', params: ['"Hoth"'], dropdown: { 0: ['"random"', '"Endor"', '"Hoth"', '"Starship"'] } }, {func: 'setMap', parent: api, category: '', params: ['"blank"'], dropdown: { 0: ['"random"', '"blank"', '"circle"', '"horizontal"', '"grid"', '"blobs"'] } }, {func: 'moveRight', parent: api, category: '', }, {func: 'moveLeft', parent: api, category: '', }, {func: 'moveUp', parent: api, category: '', }, {func: 'moveDown', parent: api, category: '', }, {func: 'goRight', parent: api, category: '', }, {func: 'goLeft', parent: api, category: '', }, {func: 'goUp', parent: api, category: '', }, {func: 'goDown', parent: api, category: '', }, {func: 'playSound', parent: api, category: '', params: ['"R2-D2sound1"'], dropdown: { 0: paramLists.playSoundDropdown } }, {func: 'endGame', parent: api, category: '', params: ['"win"'], dropdown: { 0: ['"win"', '"lose"'] } }, {func: 'addPoints', parent: api, category: '', params: ["100"] }, {func: 'removePoints', parent: api, category: '', params: ["100"] }, {func: 'addCharacter', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } }, {func: 'moveFast', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } }, {func: 'moveNormal', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } }, {func: 'moveSlow', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] } }, {func: 'whenLeft', block: 'function whenLeft() {}', expansion: 'function whenLeft() {\n __;\n}', category: '' }, {func: 'whenRight', block: 'function whenRight() {}', expansion: 'function whenRight() {\n __;\n}', category: '' }, {func: 'whenUp', block: 'function whenUp() {}', expansion: 'function whenUp() {\n __;\n}', category: '' }, {func: 'whenDown', block: 'function whenDown() {}', expansion: 'function whenDown() {\n __;\n}', category: '' }, {func: 'whenTouchObstacle', block: 'function whenTouchObstacle() {}', expansion: 'function whenTouchObstacle() {\n __;\n}', category: '' }, {func: 'whenGetCharacter', block: 'function whenGetCharacter() {}', expansion: 'function whenGetCharacter() {\n __;\n}', category: '' }, {func: 'whenGetStormtrooper', block: 'function whenGetStormtrooper() {}', expansion: 'function whenGetStormtrooper() {\n __;\n}', category: '' }, {func: 'whenGetRebelPilot', block: 'function whenGetRebelPilot() {}', expansion: 'function whenGetRebelPilot() {\n __;\n}', category: '' }, {func: 'whenGetPufferPig', block: 'function whenGetPufferPig() {}', expansion: 'function whenGetPufferPig() {\n __;\n}', category: '' }, {func: 'whenGetMynock', block: 'function whenGetMynock() {}', expansion: 'function whenGetMynock() {\n __;\n}', category: '' }, {func: 'whenGetMouseDroid', block: 'function whenGetMouseDroid() {}', expansion: 'function whenGetMouseDroid() {\n __;\n}', category: '' }, {func: 'whenGetTauntaun', block: 'function whenGetTauntaun() {}', expansion: 'function whenGetTauntaun() {\n __;\n}', category: '' }, {func: 'whenGetProbot', block: 'function whenGetProbot() {}', expansion: 'function whenGetProbot() {\n __;\n}', category: '' }, {func: 'whenGetAllCharacters', block: 'function whenGetAllCharacters() {}', expansion: 'function whenGetAllCharacters() {\n __;\n}', category: '' }, {func: 'whenGetAllStormtroopers', block: 'function whenGetAllStormtroopers() {}', expansion: 'function whenGetAllStormtroopers() {\n __;\n}', category: '' }, {func: 'whenGetAllRebelPilots', block: 'function whenGetAllRebelPilots() {}', expansion: 'function whenGetAllRebelPilots() {\n __;\n}', category: '' }, {func: 'whenGetAllPufferPigs', block: 'function whenGetAllPufferPigs() {}', expansion: 'function whenGetAllPufferPigs() {\n __;\n}', category: '' }, {func: 'whenGetAllMynocks', block: 'function whenGetAllMynocks() {}', expansion: 'function whenGetAllMynocks() {\n __;\n}', category: '' }, {func: 'whenGetAllMouseDroids', block: 'function whenGetAllMouseDroids() {}', expansion: 'function whenGetAllMouseDroids() {\n __;\n}', category: '' }, {func: 'whenGetAllTauntauns', block: 'function whenGetAllTauntauns() {}', expansion: 'function whenGetAllTauntauns() {\n __;\n}', category: '' }, {func: 'whenGetAllProbots', block: 'function whenGetAllProbots() {}', expansion: 'function whenGetAllProbots() {\n __;\n}', category: '' }, // Functions hidden from autocomplete - not used in hoc2015: {func: 'whenTouchStormtrooper', block: 'function whenTouchStormtrooper() {}', expansion: 'function whenTouchStormtrooper() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchRebelPilot', block: 'function whenTouchRebelPilot() {}', expansion: 'function whenTouchRebelPilot() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchPufferPig', block: 'function whenTouchPufferPig() {}', expansion: 'function whenTouchPufferPig() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchMynock', block: 'function whenTouchMynock() {}', expansion: 'function whenTouchMynock() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchMouseDroid', block: 'function whenTouchMouseDroid() {}', expansion: 'function whenTouchMouseDroid() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchTauntaun', block: 'function whenTouchTauntaun() {}', expansion: 'function whenTouchTauntaun() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchProbot', block: 'function whenTouchProbot() {}', expansion: 'function whenTouchProbot() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchCharacter', block: 'function whenTouchCharacter() {}', expansion: 'function whenTouchCharacter() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'changeScore', parent: api, category: '', params: ["1"], noAutocomplete: true }, {func: 'whenTouchGoal', block: 'function whenTouchGoal() {}', expansion: 'function whenTouchGoal() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenTouchAllGoals', block: 'function whenTouchAllGoals() {}', expansion: 'function whenTouchAllGoals() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'whenScore1000', block: 'function whenScore1000() {}', expansion: 'function whenScore1000() {\n __;\n}', category: '', noAutocomplete: true }, {func: 'setToChase', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true }, {func: 'setToFlee', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true }, {func: 'setToRoam', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true }, {func: 'setToStop', parent: api, category: '', params: ['"PufferPig"'], dropdown: { 0: ['"random"', '"Stormtrooper"', '"RebelPilot"', '"PufferPig"', '"Mynock"', '"MouseDroid"', '"Tauntaun"', '"Probot"'] }, noAutocomplete: true }, {func: 'setSprite', parent: api, category: '', params: ['0', '"R2-D2"'], dropdown: { 1: ['"random"', '"R2-D2"', '"C-3PO"'] }, noAutocomplete: true }, {func: 'setSpritePosition', parent: api, category: '', params: ["0", "7"], noAutocomplete: true }, {func: 'setSpriteSpeed', parent: api, category: '', params: ["0", "8"], noAutocomplete: true }, {func: 'setSpriteEmotion', parent: api, category: '', params: ["0", "1"], noAutocomplete: true }, {func: 'setSpriteSize', parent: api, category: '', params: ["0", "1.0"], noAutocomplete: true }, {func: 'throwProjectile', parent: api, category: '', params: ["0", "1", '"blue_fireball"'], noAutocomplete: true }, {func: 'vanish', parent: api, category: '', params: ["0"], noAutocomplete: true }, {func: 'move', parent: api, category: '', params: ["0", "1"], noAutocomplete: true }, {func: 'showDebugInfo', parent: api, category: '', params: ["false"], noAutocomplete: true }, {func: 'onEvent', parent: api, category: '', params: ["'when-left'", "function() {\n \n}"], noAutocomplete: true }, ]; module.exports.categories = { '': { color: 'red', blocks: [] }, 'Play Lab': { color: 'red', blocks: [] }, Commands: { color: 'red', blocks: [] }, Events: { color: 'green', blocks: [] }, }; module.exports.autocompleteFunctionsWithParens = true; module.exports.showParamDropdowns = true;
Java
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\Classroom; class CloudPubsubTopic extends \Google\Model { /** * @var string */ public $topicName; /** * @param string */ public function setTopicName($topicName) { $this->topicName = $topicName; } /** * @return string */ public function getTopicName() { return $this->topicName; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(CloudPubsubTopic::class, 'Google_Service_Classroom_CloudPubsubTopic');
Java
/** * libjass * * https://github.com/Arnavion/libjass * * Copyright 2013 Arnav Singh * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ define(["intern!tdd", "require", "tests/support/test-page"], function (tdd, require, TestPage) { tdd.suite("Outlines", function () { tdd.test("Basic", function () { var testPage = new TestPage(this.remote, require.toUrl("tests/support/browser-test-page.html"), "/tests/functional/outlines/outlines.ass", 1280, 720); return testPage .prepare() .then(function (testPage) { return testPage.seekAndCompareScreenshot(0.5, require.toUrl("./outlines-1.png")); }) .then(function (testPage) { return testPage.seekAndCompareScreenshot(1.5, require.toUrl("./outlines-2.png")); }) .then(function (testPage) { return testPage.seekAndCompareScreenshot(2.5, require.toUrl("./outlines-3.png")); }) .then(function (testPage) { return testPage.seekAndCompareScreenshot(3.5, require.toUrl("./outlines-4.png")); }) .then(function (testPage) { return testPage.done(); }); }); }); });
Java
<?php /* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ namespace Google\Service\ToolResults; class NonSdkApiUsageViolation extends \Google\Collection { protected $collection_key = 'apiSignatures'; /** * @var string[] */ public $apiSignatures; /** * @var int */ public $uniqueApis; /** * @param string[] */ public function setApiSignatures($apiSignatures) { $this->apiSignatures = $apiSignatures; } /** * @return string[] */ public function getApiSignatures() { return $this->apiSignatures; } /** * @param int */ public function setUniqueApis($uniqueApis) { $this->uniqueApis = $uniqueApis; } /** * @return int */ public function getUniqueApis() { return $this->uniqueApis; } } // Adding a class alias for backwards compatibility with the previous class name. class_alias(NonSdkApiUsageViolation::class, 'Google_Service_ToolResults_NonSdkApiUsageViolation');
Java
#!/usr/bin/env python # encoding=utf-8 # Copyright 2014 Cloudera Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import pexpect import pytest import shlex import shutil import socket import signal from impala_shell_results import get_shell_cmd_result, cancellation_helper from subprocess import Popen, PIPE from tests.common.impala_service import ImpaladService from tests.verifiers.metric_verifier import MetricVerifier from time import sleep SHELL_CMD = "%s/bin/impala-shell.sh" % os.environ['IMPALA_HOME'] SHELL_HISTORY_FILE = os.path.expanduser("~/.impalahistory") TMP_HISTORY_FILE = os.path.expanduser("~/.impalahistorytmp") class TestImpalaShellInteractive(object): """Test the impala shell interactively""" def _send_cmd_to_shell(self, p, cmd): """Given an open shell process, write a cmd to stdin This method takes care of adding the delimiter and EOL, callers should send the raw command. """ p.stdin.write("%s;\n" % cmd) p.stdin.flush() def _start_new_shell_process(self, args=None): """Starts a shell process and returns the process handle""" cmd = "%s %s" % (SHELL_CMD, args) if args else SHELL_CMD return Popen(shlex.split(SHELL_CMD), shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE) @classmethod def setup_class(cls): if os.path.exists(SHELL_HISTORY_FILE): shutil.move(SHELL_HISTORY_FILE, TMP_HISTORY_FILE) @classmethod def teardown_class(cls): if os.path.exists(TMP_HISTORY_FILE): shutil.move(TMP_HISTORY_FILE, SHELL_HISTORY_FILE) @pytest.mark.execute_serially def test_escaped_quotes(self): """Test escaping quotes""" # test escaped quotes outside of quotes result = run_impala_shell_interactive("select \\'bc';") assert "could not match input" in result.stderr result = run_impala_shell_interactive("select \\\"bc\";") assert "could not match input" in result.stderr # test escaped quotes within quotes result = run_impala_shell_interactive("select 'ab\\'c';") assert "Fetched 1 row(s)" in result.stderr result = run_impala_shell_interactive("select \"ab\\\"c\";") assert "Fetched 1 row(s)" in result.stderr @pytest.mark.execute_serially def test_cancellation(self): impalad = ImpaladService(socket.getfqdn()) impalad.wait_for_num_in_flight_queries(0) command = "select sleep(10000);" p = self._start_new_shell_process() self._send_cmd_to_shell(p, command) sleep(1) # iterate through all processes with psutil shell_pid = cancellation_helper() sleep(2) os.kill(shell_pid, signal.SIGINT) result = get_shell_cmd_result(p) assert impalad.wait_for_num_in_flight_queries(0) @pytest.mark.execute_serially def test_unicode_input(self): "Test queries containing non-ascii input" # test a unicode query spanning multiple lines unicode_text = u'\ufffd' args = "select '%s'\n;" % unicode_text.encode('utf-8') result = run_impala_shell_interactive(args) assert "Fetched 1 row(s)" in result.stderr @pytest.mark.execute_serially def test_welcome_string(self): """Test that the shell's welcome message is only printed once when the shell is started. Ensure it is not reprinted on errors. Regression test for IMPALA-1153 """ result = run_impala_shell_interactive('asdf;') assert result.stdout.count("Welcome to the Impala shell") == 1 result = run_impala_shell_interactive('select * from non_existent_table;') assert result.stdout.count("Welcome to the Impala shell") == 1 @pytest.mark.execute_serially def test_bash_cmd_timing(self): """Test existence of time output in bash commands run from shell""" args = "! ls;" result = run_impala_shell_interactive(args) assert "Executed in" in result.stderr @pytest.mark.execute_serially def test_reconnect(self): """Regression Test for IMPALA-1235 Verifies that a connect command by the user is honoured. """ def get_num_open_sessions(impala_service): """Helper method to retrieve the number of open sessions""" return impala_service.get_metric_value('impala-server.num-open-beeswax-sessions') hostname = socket.getfqdn() initial_impala_service = ImpaladService(hostname) target_impala_service = ImpaladService(hostname, webserver_port=25001, beeswax_port=21001, be_port=22001) # Get the initial state for the number of sessions. num_sessions_initial = get_num_open_sessions(initial_impala_service) num_sessions_target = get_num_open_sessions(target_impala_service) # Connect to localhost:21000 (default) p = self._start_new_shell_process() sleep(2) # Make sure we're connected <hostname>:21000 assert get_num_open_sessions(initial_impala_service) == num_sessions_initial + 1, \ "Not connected to %s:21000" % hostname self._send_cmd_to_shell(p, "connect %s:21001" % hostname) # Wait for a little while sleep(2) # The number of sessions on the target impalad should have been incremented. assert get_num_open_sessions(target_impala_service) == num_sessions_target + 1, \ "Not connected to %s:21001" % hostname # The number of sessions on the initial impalad should have been decremented. assert get_num_open_sessions(initial_impala_service) == num_sessions_initial, \ "Connection to %s:21000 should have been closed" % hostname @pytest.mark.execute_serially def test_ddl_queries_are_closed(self): """Regression test for IMPALA-1317 The shell does not call close() for alter, use and drop queries, leaving them in flight. This test issues those queries in interactive mode, and checks the debug webpage to confirm that they've been closed. TODO: Add every statement type. """ TMP_DB = 'inflight_test_db' TMP_TBL = 'tmp_tbl' MSG = '%s query should be closed' NUM_QUERIES = 'impala-server.num-queries' impalad = ImpaladService(socket.getfqdn()) p = self._start_new_shell_process() try: start_num_queries = impalad.get_metric_value(NUM_QUERIES) self._send_cmd_to_shell(p, 'create database if not exists %s' % TMP_DB) self._send_cmd_to_shell(p, 'use %s' % TMP_DB) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 2) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'use' self._send_cmd_to_shell(p, 'create table %s(i int)' % TMP_TBL) self._send_cmd_to_shell(p, 'alter table %s add columns (j int)' % TMP_TBL) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 4) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'alter' self._send_cmd_to_shell(p, 'drop table %s' % TMP_TBL) impalad.wait_for_metric_value(NUM_QUERIES, start_num_queries + 5) assert impalad.wait_for_num_in_flight_queries(0), MSG % 'drop' finally: run_impala_shell_interactive("drop table if exists %s.%s;" % (TMP_DB, TMP_TBL)) run_impala_shell_interactive("drop database if exists foo;") @pytest.mark.execute_serially def test_multiline_queries_in_history(self): """Test to ensure that multiline queries with comments are preserved in history Ensure that multiline queries are preserved when they're read back from history. Additionally, also test that comments are preserved. """ # regex for pexpect, a shell prompt is expected after each command.. prompt_regex = '.*%s:2100.*' % socket.getfqdn() # readline gets its input from tty, so using stdin does not work. child_proc = pexpect.spawn(SHELL_CMD) queries = ["select\n1--comment;", "select /*comment*/\n1;", "select\n/*comm\nent*/\n1;"] for query in queries: child_proc.expect(prompt_regex) child_proc.sendline(query) child_proc.expect(prompt_regex) child_proc.sendline('quit;') p = self._start_new_shell_process() self._send_cmd_to_shell(p, 'history') result = get_shell_cmd_result(p) for query in queries: assert query in result.stderr, "'%s' not in '%s'" % (query, result.stderr) def run_impala_shell_interactive(command, shell_args=''): """Runs a command in the Impala shell interactively.""" cmd = "%s %s" % (SHELL_CMD, shell_args) # workaround to make Popen environment 'utf-8' compatible # since piping defaults to ascii my_env = os.environ my_env['PYTHONIOENCODING'] = 'utf-8' p = Popen(shlex.split(cmd), shell=True, stdout=PIPE, stdin=PIPE, stderr=PIPE, env=my_env) p.stdin.write(command + "\n") p.stdin.flush() return get_shell_cmd_result(p)
Java
/* * Copyright (c) 2001-2007, TIBCO Software Inc. * Use, modification, and distribution subject to terms of license. */ jsx3.require("jsx3.chart.Axis");jsx3.Class.defineClass("jsx3.chart.CategoryAxis",jsx3.chart.Axis,null,function(c,p){var ub={d:"h6",a:"aligned",c:"av",f:"gn",b:"between",e:"tickAlignment"};c.TICKS_ALIGNED=ub.a;c.TICKS_BETWEEN=ub.b;c.MAX_TICKS=200;c.BG={aligned:1,between:1};p.init=function(i,r,q){this.jsxsuper(i,r,q);this.tickAlignment=ub.b;this.categoryField=null;this.paddingLow=null;this.paddingHigh=null;this.Ho(ub.c,0);this.Ho(ub.d,0);};p.getTickAlignment=function(){return this.tickAlignment;};p.setTickAlignment=function(l){if(c.BG[l]){this.tickAlignment=l;}else throw new jsx3.IllegalArgumentException(ub.e,l);};p.getCategoryField=function(){return this.categoryField;};p.setCategoryField=function(m){this.categoryField=m;};p.getPaddingLow=function(){return this.paddingLow!=null?this.paddingLow:0;};p.setPaddingLow=function(h){this.paddingLow=h;};p.getPaddingHigh=function(){return this.paddingHigh!=null?this.paddingHigh:0;};p.setPaddingHigh=function(r){this.paddingHigh=r;};p.fl=function(){this.Ll(ub.f);var da=this.getChart();if(da==null){this.Ho(ub.c,0);this.Ho(ub.d,0);}else{var tb=da.pe(this,true);var ib=da.bh();this.Ho(ub.d,tb.length);this.Ho(ub.c,ib!=null?ib.length:0);}};p.Hf=function(){var nb=this.pj(ub.f);if(nb!=null)return nb;var B=this.pj(ub.c);nb=[];if(B<1)return nb;var ga=this.getPaddingLow();var Va=this.getPaddingHigh();var x=this.tickAlignment==ub.b?B+1:B;var La=x-1;var fb=La+ga+Va;var pb=this.length/fb;var C=ga*pb;for(var Qa=0;Qa<x&&Qa<c.MAX_TICKS;Qa++)nb.push(Math.round(C+Qa*pb));this.Ho(ub.f,nb);return nb;};p.se=function(){var B=this.pj(ub.c);if(this.tickAlignment==ub.b){var Ab=this.Hf();var Xa=[];for(var va=0;va<B;va++)Xa[va]=Math.round((Ab[va]+Ab[va+1])/2);return Xa;}else return this.Hf();};p.Xj=function(b){var Pa=b;var z=this.getChart();if(this.categoryField&&z!=null){var ab=z.bh();if(ab!=null){var ga=ab[b];if(ga!=null)Pa=ga.getAttribute([this.categoryField]);}}return Pa;};p.mo=function(){return false;};p.getRangeForCategory=function(j){var _=this.Hf();if(this.tickAlignment==ub.b){if(j<0||j>=_.length-1)return null;else return [_[j],_[j+1]];}else{if(j<0||j>=_.length||_.length<2)return null;var Xa=j==0?_[1]-_[0]:_[j]-_[j-1];return [Math.round(_[j]-Xa/2),Math.round(_[j]+Xa/2)];}};p.getPointForCategory=function(n){var Aa=this.Hf();if(this.tickAlignment==ub.b){if(n<0||n>=Aa.length-1)return null;else return Math.round((Aa[n]+Aa[n+1])/2);}else return Aa[n];};c.getVersion=function(){return jsx3.chart.si;};});
Java
/* * Copyright 2012-2013 eBay Software Foundation and ios-driver committers * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.uiautomation.ios; import com.google.common.collect.ImmutableList; import org.libimobiledevice.ios.driver.binding.exceptions.SDKException; import org.libimobiledevice.ios.driver.binding.model.ApplicationInfo; import org.libimobiledevice.ios.driver.binding.model.DeviceInfo; import org.libimobiledevice.ios.driver.binding.services.DeviceCallBack; import org.libimobiledevice.ios.driver.binding.services.DeviceService; import org.libimobiledevice.ios.driver.binding.services.IOSDevice; import org.libimobiledevice.ios.driver.binding.services.ImageMountingService; import org.libimobiledevice.ios.driver.binding.services.InformationService; import org.libimobiledevice.ios.driver.binding.services.InstallerService; import org.openqa.selenium.WebDriverException; import org.uiautomation.ios.application.IPAShellApplication; import org.uiautomation.ios.utils.DDILocator; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Set; import java.util.concurrent.CopyOnWriteArrayList; import java.util.logging.Logger; public class DeviceStore extends DeviceCallBack { private static final Logger log = Logger.getLogger(DeviceStore.class.getName()); private final List<RealDevice> reals = new CopyOnWriteArrayList<RealDevice>(); private final List<SimulatorDevice> sims = new CopyOnWriteArrayList<SimulatorDevice>(); private final ApplicationStore apps; private final Set<String> uuidWhitelist; public DeviceStore(ApplicationStore apps, Set<String> uuidWhitelist) { super(); this.apps = apps; this.uuidWhitelist = uuidWhitelist; } /** * @return immutable copy of the currently available devices. */ public List<Device> getDevices() { List<Device> all = new ArrayList<Device>(); all.addAll(reals); all.addAll(sims); return ImmutableList.copyOf(all); } public List<RealDevice> getRealDevices() { return reals; } public List<SimulatorDevice> getSimulatorDevices() { return sims; } public void add(SimulatorDevice simulatorDevice) { sims.add(simulatorDevice); } @Override protected void onDeviceAdded(String uuid) { if (!uuidWhitelist.isEmpty() && !uuidWhitelist.contains(uuid)) { log.info("device detected but not whitelisted"); return; } RealDevice d = null; try { IOSDevice device = DeviceService.get(uuid); DeviceInfo info = new DeviceInfo(uuid); d = new RealDevice(info); log.info("new device detected (" + uuid + ") " + info.getDeviceName()); reals.add(d); InstallerService s = new InstallerService(device); String id = "com.apple.mobilesafari"; ApplicationInfo safari = s.getApplication(id); String v = (String) safari.getProperty("CFBundleVersion"); log.info("device " + info.getDeviceName() + " = safari " + v); IPAShellApplication ipa = new IPAShellApplication(id, v, safari); apps.add(ipa); InformationService i = new InformationService(device); if (!i.isDevModeEnabled()) { log.warning( "The device " + uuid + " is not set to dev mode. It can't be used for testing."); File ddi = DDILocator.locateDDI(device); mount(device, ddi); log.info("DDI mounted.Device now in dev mode."); } } catch (SDKException | WebDriverException e) { if (d != null) { reals.remove(d); } } } private void mount(IOSDevice device, File ddi) throws SDKException { ImageMountingService service = null; try { service = new ImageMountingService(device); service.mount(ddi); } finally { if (service != null) { service.free(); } } } @Override protected void onDeviceRemoved(String uuid) { if (!uuidWhitelist.isEmpty() && !uuidWhitelist.contains(uuid)) { log.info("device removed but not whitelisted"); return; } for (RealDevice d : reals) { if (d.getUuid().equals(uuid)) { log.info("Removing " + uuid + " for the devices pool"); boolean ok = reals.remove(d); if (!ok) { log.warning("device " + uuid + " has been unplugged, but was never there ?"); } } } } }
Java