code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
/* Copyright (C) 2016 Red Hat, 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 config import ( "io/ioutil" "os" "path/filepath" "testing" "github.com/minishift/minishift/cmd/minishift/state" "github.com/minishift/minishift/pkg/minikube/constants" "github.com/stretchr/testify/assert" ) func TestNotFound(t *testing.T) { err := Set("nonexistant", "10", true) assert.Error(t, err, "Set did not return error for unknown property") } func TestModifyData(t *testing.T) { testDir, err := ioutil.TempDir("", "minishift-config-") assert.NoError(t, err, "Error creating temp directory") state.InstanceDirs = state.GetMinishiftDirsStructure(testDir) constants.ConfigFile = filepath.Join(testDir, "config.json") defer os.RemoveAll(testDir) verifyValueUnset(t, "cpus") persistValue(t, "cpus", "4") verifyStoredValue(t, "cpus", "4") // override existing value and check if that persistent persistValue(t, "cpus", "10") verifyStoredValue(t, "cpus", "10") } func verifyStoredValue(t *testing.T, key string, expectedValue string) { actualValue, err := get(key) assert.NoError(t, err, "Unexpexted value in config") assert.Equal(t, expectedValue, actualValue) } func verifyValueUnset(t *testing.T, key string) { actualValue, err := get(key) assert.NoError(t, err, "Error getting value") assert.Equal(t, "<nil>", actualValue) } func persistValue(t *testing.T, key string, value string) { err := Set(key, value, true) assert.NoError(t, err, "Error setting value") }
LalatenduMohanty/minishift
cmd/minishift/cmd/config/set_test.go
GO
apache-2.0
1,979
/* Copyright 2011-2016 Google Inc. 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. */ package com.google.security.zynamics.reil.translators; import java.util.ArrayList; import com.google.security.zynamics.reil.OperandSize; import com.google.security.zynamics.reil.ReilInstruction; public class TranslationResultInternal { private final int nextVariable; private final OperandSize resultSize; private final TranslationResultType resultType; private final ArrayList<ReilInstruction> instructions; public TranslationResultInternal(final int nextVariable, final TranslationResultType resultType, final OperandSize resultSize, final ArrayList<ReilInstruction> instructions) { this.nextVariable = nextVariable; this.resultType = resultType; this.resultSize = resultSize; this.instructions = instructions; } public ArrayList<ReilInstruction> getInstructions() { return instructions; } public int getNextVariable() { return nextVariable; } public OperandSize getResultSize() { return resultSize; } public TranslationResultType getResultType() { return resultType; } }
chubbymaggie/binnavi
src/main/java/com/google/security/zynamics/reil/translators/TranslationResultInternal.java
Java
apache-2.0
1,634
/** * 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.hdfs.server.datanode.fsdataset.impl; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.FilenameFilter; import java.io.IOException; import java.nio.channels.ClosedChannelException; import java.io.OutputStreamWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardCopyOption; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Executor; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Preconditions; import org.apache.hadoop.classification.InterfaceAudience; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.DF; import org.apache.hadoop.fs.FileUtil; import org.apache.hadoop.fs.StorageType; import org.apache.hadoop.hdfs.DFSConfigKeys; import org.apache.hadoop.hdfs.protocol.Block; import org.apache.hadoop.hdfs.protocol.BlockListAsLongs; import org.apache.hadoop.hdfs.protocol.ExtendedBlock; import org.apache.hadoop.hdfs.server.datanode.DataStorage; import org.apache.hadoop.hdfs.server.datanode.DatanodeUtil; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeReference; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsDatasetSpi; import org.apache.hadoop.hdfs.server.datanode.fsdataset.FsVolumeSpi; import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage; import org.apache.hadoop.util.CloseableReferenceCount; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.DiskChecker.DiskErrorException; import com.google.common.util.concurrent.ThreadFactoryBuilder; import org.apache.hadoop.util.Time; import org.codehaus.jackson.annotate.JsonProperty; import org.codehaus.jackson.map.ObjectMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The underlying volume used to store replica. * * It uses the {@link FsDatasetImpl} object for synchronization. */ @InterfaceAudience.Private @VisibleForTesting public class FsVolumeImpl implements FsVolumeSpi { public static final Logger LOG = LoggerFactory.getLogger(FsVolumeImpl.class); private final FsDatasetImpl dataset; private final String storageID; private final StorageType storageType; private final Map<String, BlockPoolSlice> bpSlices = new ConcurrentHashMap<String, BlockPoolSlice>(); private final File currentDir; // <StorageDirectory>/current private final DF usage; private final long reserved; private CloseableReferenceCount reference = new CloseableReferenceCount(); // Disk space reserved for open blocks. private AtomicLong reservedForRbw; // Capacity configured. This is useful when we want to // limit the visible capacity for tests. If negative, then we just // query from the filesystem. protected volatile long configuredCapacity; /** * Per-volume worker pool that processes new blocks to cache. * The maximum number of workers per volume is bounded (configurable via * dfs.datanode.fsdatasetcache.max.threads.per.volume) to limit resource * contention. */ protected ThreadPoolExecutor cacheExecutor; FsVolumeImpl(FsDatasetImpl dataset, String storageID, File currentDir, Configuration conf, StorageType storageType) throws IOException { this.dataset = dataset; this.storageID = storageID; this.reserved = conf.getLong( DFSConfigKeys.DFS_DATANODE_DU_RESERVED_KEY, DFSConfigKeys.DFS_DATANODE_DU_RESERVED_DEFAULT); this.reservedForRbw = new AtomicLong(0L); this.currentDir = currentDir; File parent = currentDir.getParentFile(); this.usage = new DF(parent, conf); this.storageType = storageType; this.configuredCapacity = -1; cacheExecutor = initializeCacheExecutor(parent); } protected ThreadPoolExecutor initializeCacheExecutor(File parent) { if (storageType.isTransient()) { return null; } if (dataset.datanode == null) { // FsVolumeImpl is used in test. return null; } final int maxNumThreads = dataset.datanode.getConf().getInt( DFSConfigKeys.DFS_DATANODE_FSDATASETCACHE_MAX_THREADS_PER_VOLUME_KEY, DFSConfigKeys.DFS_DATANODE_FSDATASETCACHE_MAX_THREADS_PER_VOLUME_DEFAULT); ThreadFactory workerFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("FsVolumeImplWorker-" + parent.toString() + "-%d") .build(); ThreadPoolExecutor executor = new ThreadPoolExecutor( 1, maxNumThreads, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), workerFactory); executor.allowCoreThreadTimeOut(true); return executor; } private void printReferenceTraceInfo(String op) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); for (StackTraceElement ste : stack) { switch (ste.getMethodName()) { case "getDfsUsed": case "getBlockPoolUsed": case "getAvailable": case "getVolumeMap": return; default: break; } } FsDatasetImpl.LOG.trace("Reference count: " + op + " " + this + ": " + this.reference.getReferenceCount()); FsDatasetImpl.LOG.trace( Joiner.on("\n").join(Thread.currentThread().getStackTrace())); } /** * Increase the reference count. The caller must increase the reference count * before issuing IOs. * * @throws IOException if the volume is already closed. */ private void reference() throws ClosedChannelException { this.reference.reference(); if (FsDatasetImpl.LOG.isTraceEnabled()) { printReferenceTraceInfo("incr"); } } /** * Decrease the reference count. */ private void unreference() { if (FsDatasetImpl.LOG.isTraceEnabled()) { printReferenceTraceInfo("desc"); } if (FsDatasetImpl.LOG.isDebugEnabled()) { if (reference.getReferenceCount() <= 0) { FsDatasetImpl.LOG.debug("Decrease reference count <= 0 on " + this + Joiner.on("\n").join(Thread.currentThread().getStackTrace())); } } checkReference(); this.reference.unreference(); } private static class FsVolumeReferenceImpl implements FsVolumeReference { private final FsVolumeImpl volume; FsVolumeReferenceImpl(FsVolumeImpl volume) throws ClosedChannelException { this.volume = volume; volume.reference(); } /** * Decreases the reference count. * @throws IOException it never throws IOException. */ @Override public void close() throws IOException { volume.unreference(); } @Override public FsVolumeSpi getVolume() { return this.volume; } } @Override public FsVolumeReference obtainReference() throws ClosedChannelException { return new FsVolumeReferenceImpl(this); } private void checkReference() { Preconditions.checkState(reference.getReferenceCount() > 0); } /** * Close this volume and wait all other threads to release the reference count * on this volume. * @throws IOException if the volume is closed or the waiting is interrupted. */ void closeAndWait() throws IOException { try { this.reference.setClosed(); } catch (ClosedChannelException e) { throw new IOException("The volume has already closed.", e); } final int SLEEP_MILLIS = 500; while (this.reference.getReferenceCount() > 0) { if (FsDatasetImpl.LOG.isDebugEnabled()) { FsDatasetImpl.LOG.debug(String.format( "The reference count for %s is %d, wait to be 0.", this, reference.getReferenceCount())); } try { Thread.sleep(SLEEP_MILLIS); } catch (InterruptedException e) { throw new IOException(e); } } } File getCurrentDir() { return currentDir; } File getRbwDir(String bpid) throws IOException { return getBlockPoolSlice(bpid).getRbwDir(); } File getLazyPersistDir(String bpid) throws IOException { return getBlockPoolSlice(bpid).getLazypersistDir(); } File getTmpDir(String bpid) throws IOException { return getBlockPoolSlice(bpid).getTmpDir(); } void decDfsUsed(String bpid, long value) { synchronized(dataset) { BlockPoolSlice bp = bpSlices.get(bpid); if (bp != null) { bp.decDfsUsed(value); } } } void incDfsUsed(String bpid, long value) { synchronized(dataset) { BlockPoolSlice bp = bpSlices.get(bpid); if (bp != null) { bp.incDfsUsed(value); } } } @VisibleForTesting public long getDfsUsed() throws IOException { long dfsUsed = 0; synchronized(dataset) { for(BlockPoolSlice s : bpSlices.values()) { dfsUsed += s.getDfsUsed(); } } return dfsUsed; } long getBlockPoolUsed(String bpid) throws IOException { return getBlockPoolSlice(bpid).getDfsUsed(); } /** * Return either the configured capacity of the file system if configured; or * the capacity of the file system excluding space reserved for non-HDFS. * * @return the unreserved number of bytes left in this filesystem. May be * zero. */ @VisibleForTesting public long getCapacity() { if (configuredCapacity < 0) { long remaining = usage.getCapacity() - reserved; return remaining > 0 ? remaining : 0; } return configuredCapacity; } /** * This function MUST NOT be used outside of tests. * * @param capacity */ @VisibleForTesting public void setCapacityForTesting(long capacity) { this.configuredCapacity = capacity; } /* * Calculate the available space of the filesystem, excluding space reserved * for non-HDFS and space reserved for RBW * * @return the available number of bytes left in this filesystem. May be zero. */ @Override public long getAvailable() throws IOException { long remaining = getCapacity() - getDfsUsed() - reservedForRbw.get(); long available = usage.getAvailable() - reserved - reservedForRbw.get(); if (remaining > available) { remaining = available; } return (remaining > 0) ? remaining : 0; } @VisibleForTesting public long getReservedForRbw() { return reservedForRbw.get(); } long getReserved(){ return reserved; } BlockPoolSlice getBlockPoolSlice(String bpid) throws IOException { BlockPoolSlice bp = bpSlices.get(bpid); if (bp == null) { throw new IOException("block pool " + bpid + " is not found"); } return bp; } @Override public String getBasePath() { return currentDir.getParent(); } @Override public boolean isTransientStorage() { return storageType.isTransient(); } @Override public String getPath(String bpid) throws IOException { return getBlockPoolSlice(bpid).getDirectory().getAbsolutePath(); } @Override public File getFinalizedDir(String bpid) throws IOException { return getBlockPoolSlice(bpid).getFinalizedDir(); } /** * Make a deep copy of the list of currently active BPIDs */ @Override public String[] getBlockPoolList() { return bpSlices.keySet().toArray(new String[bpSlices.keySet().size()]); } /** * Temporary files. They get moved to the finalized block directory when * the block is finalized. */ File createTmpFile(String bpid, Block b) throws IOException { checkReference(); return getBlockPoolSlice(bpid).createTmpFile(b); } @Override public void reserveSpaceForRbw(long bytesToReserve) { if (bytesToReserve != 0) { reservedForRbw.addAndGet(bytesToReserve); } } @Override public void releaseReservedSpace(long bytesToRelease) { if (bytesToRelease != 0) { long oldReservation, newReservation; do { oldReservation = reservedForRbw.get(); newReservation = oldReservation - bytesToRelease; if (newReservation < 0) { // Failsafe, this should never occur in practice, but if it does we don't // want to start advertising more space than we have available. newReservation = 0; } } while (!reservedForRbw.compareAndSet(oldReservation, newReservation)); } } private enum SubdirFilter implements FilenameFilter { INSTANCE; @Override public boolean accept(File dir, String name) { return name.startsWith("subdir"); } } private enum BlockFileFilter implements FilenameFilter { INSTANCE; @Override public boolean accept(File dir, String name) { return !name.endsWith(".meta") && name.startsWith(Block.BLOCK_FILE_PREFIX); } } @VisibleForTesting public static String nextSorted(List<String> arr, String prev) { int res = 0; if (prev != null) { res = Collections.binarySearch(arr, prev); if (res < 0) { res = -1 - res; } else { res++; } } if (res >= arr.size()) { return null; } return arr.get(res); } private static class BlockIteratorState { BlockIteratorState() { lastSavedMs = iterStartMs = Time.now(); curFinalizedDir = null; curFinalizedSubDir = null; curEntry = null; atEnd = false; } // The wall-clock ms since the epoch at which this iterator was last saved. @JsonProperty private long lastSavedMs; // The wall-clock ms since the epoch at which this iterator was created. @JsonProperty private long iterStartMs; @JsonProperty private String curFinalizedDir; @JsonProperty private String curFinalizedSubDir; @JsonProperty private String curEntry; @JsonProperty private boolean atEnd; } /** * A BlockIterator implementation for FsVolumeImpl. */ private class BlockIteratorImpl implements FsVolumeSpi.BlockIterator { private final File bpidDir; private final String name; private final String bpid; private long maxStalenessMs = 0; private List<String> cache; private long cacheMs; private BlockIteratorState state; BlockIteratorImpl(String bpid, String name) { this.bpidDir = new File(currentDir, bpid); this.name = name; this.bpid = bpid; rewind(); } /** * Get the next subdirectory within the block pool slice. * * @return The next subdirectory within the block pool slice, or * null if there are no more. */ private String getNextSubDir(String prev, File dir) throws IOException { List<String> children = IOUtils.listDirectory(dir, SubdirFilter.INSTANCE); cache = null; cacheMs = 0; if (children.size() == 0) { LOG.trace("getNextSubDir({}, {}): no subdirectories found in {}", storageID, bpid, dir.getAbsolutePath()); return null; } Collections.sort(children); String nextSubDir = nextSorted(children, prev); if (nextSubDir == null) { LOG.trace("getNextSubDir({}, {}): no more subdirectories found in {}", storageID, bpid, dir.getAbsolutePath()); } else { LOG.trace("getNextSubDir({}, {}): picking next subdirectory {} " + "within {}", storageID, bpid, nextSubDir, dir.getAbsolutePath()); } return nextSubDir; } private String getNextFinalizedDir() throws IOException { File dir = Paths.get( bpidDir.getAbsolutePath(), "current", "finalized").toFile(); return getNextSubDir(state.curFinalizedDir, dir); } private String getNextFinalizedSubDir() throws IOException { if (state.curFinalizedDir == null) { return null; } File dir = Paths.get( bpidDir.getAbsolutePath(), "current", "finalized", state.curFinalizedDir).toFile(); return getNextSubDir(state.curFinalizedSubDir, dir); } private List<String> getSubdirEntries() throws IOException { if (state.curFinalizedSubDir == null) { return null; // There are no entries in the null subdir. } long now = Time.monotonicNow(); if (cache != null) { long delta = now - cacheMs; if (delta < maxStalenessMs) { return cache; } else { LOG.trace("getSubdirEntries({}, {}): purging entries cache for {} " + "after {} ms.", storageID, bpid, state.curFinalizedSubDir, delta); cache = null; } } File dir = Paths.get(bpidDir.getAbsolutePath(), "current", "finalized", state.curFinalizedDir, state.curFinalizedSubDir).toFile(); List<String> entries = IOUtils.listDirectory(dir, BlockFileFilter.INSTANCE); if (entries.size() == 0) { entries = null; } else { Collections.sort(entries); } if (entries == null) { LOG.trace("getSubdirEntries({}, {}): no entries found in {}", storageID, bpid, dir.getAbsolutePath()); } else { LOG.trace("getSubdirEntries({}, {}): listed {} entries in {}", storageID, bpid, entries.size(), dir.getAbsolutePath()); } cache = entries; cacheMs = now; return cache; } /** * Get the next block.<p/> * * Each volume has a hierarchical structure.<p/> * * <code> * BPID B0 * finalized/ * subdir0 * subdir0 * blk_000 * blk_001 * ... * subdir1 * subdir0 * ... * rbw/ * </code> * * When we run out of entries at one level of the structure, we search * progressively higher levels. For example, when we run out of blk_ * entries in a subdirectory, we search for the next subdirectory. * And so on. */ @Override public ExtendedBlock nextBlock() throws IOException { if (state.atEnd) { return null; } try { while (true) { List<String> entries = getSubdirEntries(); if (entries != null) { state.curEntry = nextSorted(entries, state.curEntry); if (state.curEntry == null) { LOG.trace("nextBlock({}, {}): advancing from {} to next " + "subdirectory.", storageID, bpid, state.curFinalizedSubDir); } else { ExtendedBlock block = new ExtendedBlock(bpid, Block.filename2id(state.curEntry)); LOG.trace("nextBlock({}, {}): advancing to {}", storageID, bpid, block); return block; } } state.curFinalizedSubDir = getNextFinalizedSubDir(); if (state.curFinalizedSubDir == null) { state.curFinalizedDir = getNextFinalizedDir(); if (state.curFinalizedDir == null) { state.atEnd = true; return null; } } } } catch (IOException e) { state.atEnd = true; LOG.error("nextBlock({}, {}): I/O error", storageID, bpid, e); throw e; } } @Override public boolean atEnd() { return state.atEnd; } @Override public void rewind() { cache = null; cacheMs = 0; state = new BlockIteratorState(); } @Override public void save() throws IOException { state.lastSavedMs = Time.now(); boolean success = false; ObjectMapper mapper = new ObjectMapper(); try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter( new FileOutputStream(getTempSaveFile(), false), "UTF-8"))) { mapper.writerWithDefaultPrettyPrinter().writeValue(writer, state); success = true; } finally { if (!success) { if (getTempSaveFile().delete()) { LOG.debug("save({}, {}): error deleting temporary file.", storageID, bpid); } } } Files.move(getTempSaveFile().toPath(), getSaveFile().toPath(), StandardCopyOption.ATOMIC_MOVE); if (LOG.isTraceEnabled()) { LOG.trace("save({}, {}): saved {}", storageID, bpid, mapper.writerWithDefaultPrettyPrinter().writeValueAsString(state)); } } public void load() throws IOException { ObjectMapper mapper = new ObjectMapper(); File file = getSaveFile(); this.state = mapper.reader(BlockIteratorState.class).readValue(file); LOG.trace("load({}, {}): loaded iterator {} from {}: {}", storageID, bpid, name, file.getAbsoluteFile(), mapper.writerWithDefaultPrettyPrinter().writeValueAsString(state)); } File getSaveFile() { return new File(bpidDir, name + ".cursor"); } File getTempSaveFile() { return new File(bpidDir, name + ".cursor.tmp"); } @Override public void setMaxStalenessMs(long maxStalenessMs) { this.maxStalenessMs = maxStalenessMs; } @Override public void close() throws IOException { // No action needed for this volume implementation. } @Override public long getIterStartMs() { return state.iterStartMs; } @Override public long getLastSavedMs() { return state.lastSavedMs; } @Override public String getBlockPoolId() { return bpid; } } @Override public BlockIterator newBlockIterator(String bpid, String name) { return new BlockIteratorImpl(bpid, name); } @Override public BlockIterator loadBlockIterator(String bpid, String name) throws IOException { BlockIteratorImpl iter = new BlockIteratorImpl(bpid, name); iter.load(); return iter; } @Override public FsDatasetSpi getDataset() { return dataset; } /** * RBW files. They get moved to the finalized block directory when * the block is finalized. */ File createRbwFile(String bpid, Block b) throws IOException { checkReference(); reserveSpaceForRbw(b.getNumBytes()); return getBlockPoolSlice(bpid).createRbwFile(b); } /** * * @param bytesReservedForRbw Space that was reserved during * block creation. Now that the block is being finalized we * can free up this space. * @return * @throws IOException */ File addFinalizedBlock(String bpid, Block b, File f, long bytesReservedForRbw) throws IOException { releaseReservedSpace(bytesReservedForRbw); return getBlockPoolSlice(bpid).addFinalizedBlock(b, f); } Executor getCacheExecutor() { return cacheExecutor; } void checkDirs() throws DiskErrorException { // TODO:FEDERATION valid synchronization for(BlockPoolSlice s : bpSlices.values()) { s.checkDirs(); } } void getVolumeMap(ReplicaMap volumeMap, final RamDiskReplicaTracker ramDiskReplicaMap) throws IOException { for(BlockPoolSlice s : bpSlices.values()) { s.getVolumeMap(volumeMap, ramDiskReplicaMap); } } void getVolumeMap(String bpid, ReplicaMap volumeMap, final RamDiskReplicaTracker ramDiskReplicaMap) throws IOException { getBlockPoolSlice(bpid).getVolumeMap(volumeMap, ramDiskReplicaMap); } @Override public String toString() { return currentDir.getAbsolutePath(); } void shutdown() { if (cacheExecutor != null) { cacheExecutor.shutdown(); } Set<Entry<String, BlockPoolSlice>> set = bpSlices.entrySet(); for (Entry<String, BlockPoolSlice> entry : set) { entry.getValue().shutdown(null); } } void addBlockPool(String bpid, Configuration conf) throws IOException { File bpdir = new File(currentDir, bpid); BlockPoolSlice bp = new BlockPoolSlice(bpid, this, bpdir, conf); bpSlices.put(bpid, bp); } void shutdownBlockPool(String bpid, BlockListAsLongs blocksListsAsLongs) { BlockPoolSlice bp = bpSlices.get(bpid); if (bp != null) { bp.shutdown(blocksListsAsLongs); } bpSlices.remove(bpid); } boolean isBPDirEmpty(String bpid) throws IOException { File volumeCurrentDir = this.getCurrentDir(); File bpDir = new File(volumeCurrentDir, bpid); File bpCurrentDir = new File(bpDir, DataStorage.STORAGE_DIR_CURRENT); File finalizedDir = new File(bpCurrentDir, DataStorage.STORAGE_DIR_FINALIZED); File rbwDir = new File(bpCurrentDir, DataStorage.STORAGE_DIR_RBW); if (finalizedDir.exists() && !DatanodeUtil.dirNoFilesRecursive( finalizedDir)) { return false; } if (rbwDir.exists() && FileUtil.list(rbwDir).length != 0) { return false; } return true; } void deleteBPDirectories(String bpid, boolean force) throws IOException { File volumeCurrentDir = this.getCurrentDir(); File bpDir = new File(volumeCurrentDir, bpid); if (!bpDir.isDirectory()) { // nothing to be deleted return; } File tmpDir = new File(bpDir, DataStorage.STORAGE_DIR_TMP); File bpCurrentDir = new File(bpDir, DataStorage.STORAGE_DIR_CURRENT); File finalizedDir = new File(bpCurrentDir, DataStorage.STORAGE_DIR_FINALIZED); File lazypersistDir = new File(bpCurrentDir, DataStorage.STORAGE_DIR_LAZY_PERSIST); File rbwDir = new File(bpCurrentDir, DataStorage.STORAGE_DIR_RBW); if (force) { FileUtil.fullyDelete(bpDir); } else { if (!rbwDir.delete()) { throw new IOException("Failed to delete " + rbwDir); } if (!DatanodeUtil.dirNoFilesRecursive(finalizedDir) || !FileUtil.fullyDelete(finalizedDir)) { throw new IOException("Failed to delete " + finalizedDir); } if (lazypersistDir.exists() && ((!DatanodeUtil.dirNoFilesRecursive(lazypersistDir) || !FileUtil.fullyDelete(lazypersistDir)))) { throw new IOException("Failed to delete " + lazypersistDir); } FileUtil.fullyDelete(tmpDir); for (File f : FileUtil.listFiles(bpCurrentDir)) { if (!f.delete()) { throw new IOException("Failed to delete " + f); } } if (!bpCurrentDir.delete()) { throw new IOException("Failed to delete " + bpCurrentDir); } for (File f : FileUtil.listFiles(bpDir)) { if (!f.delete()) { throw new IOException("Failed to delete " + f); } } if (!bpDir.delete()) { throw new IOException("Failed to delete " + bpDir); } } } @Override public String getStorageID() { return storageID; } @Override public StorageType getStorageType() { return storageType; } DatanodeStorage toDatanodeStorage() { return new DatanodeStorage(storageID, DatanodeStorage.State.NORMAL, storageType); } }
messi49/hadoop
hadoop-hdfs-project/hadoop-hdfs/src/main/java/org/apache/hadoop/hdfs/server/datanode/fsdataset/impl/FsVolumeImpl.java
Java
apache-2.0
27,858
// Copyright 2016 Husky Team // // 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 "base/serialization.hpp" #include <string> #include <vector> namespace csci5570 { BinStream::BinStream() : front_(0) {} BinStream::BinStream(size_t sz) : front_(0) { buffer_.resize(sz); } BinStream::BinStream(const char* src, size_t sz) : front_(0) { push_back_bytes(src, sz); } BinStream::BinStream(const std::vector<char>& v) : front_(0), buffer_(v) {} BinStream::BinStream(std::vector<char>&& v) : front_(0), buffer_(std::move(v)) {} BinStream::BinStream(const BinStream& stream) { front_ = stream.front_; buffer_ = stream.buffer_; } BinStream::BinStream(BinStream&& stream) : front_(stream.front_), buffer_(std::move(stream.buffer_)) { stream.front_ = 0; } BinStream& BinStream::operator=(BinStream&& stream) { front_ = stream.front_; buffer_ = std::move(stream.buffer_); stream.front_ = 0; return *this; } size_t BinStream::hash() { size_t ret = 0; for (auto& i : buffer_) ret += i; return ret; } void BinStream::clear() { buffer_.clear(); front_ = 0; } void BinStream::purge() { std::vector<char> tmp; buffer_.swap(tmp); front_ = 0; } void BinStream::resize(size_t size) { buffer_.resize(size); front_ = 0; } void BinStream::seek(size_t pos) { front_ = pos; } void BinStream::push_back_bytes(const char* src, size_t sz) { buffer_.insert(buffer_.end(), (const char*) src, (const char*) src + sz); } void* BinStream::pop_front_bytes(size_t sz) { assert(front_ <= buffer_.size()); void* ret = &buffer_[front_]; front_ += sz; return ret; } void BinStream::append(const BinStream& stream) { push_back_bytes(stream.get_remained_buffer(), stream.size()); } BinStream& operator<<(BinStream& stream, const BinStream& bin) { stream << bin.size(); stream.push_back_bytes(bin.get_remained_buffer(), bin.size()); return stream; } BinStream& operator>>(BinStream& stream, BinStream& bin) { size_t len; stream >> len; bin.resize(len); for (char* i = bin.get_buffer(); len--; i++) stream >> *i; return stream; } BinStream& operator<<(BinStream& stream, const std::string& x) { stream << x.size(); stream.push_back_bytes(x.data(), x.length()); return stream; } BinStream& operator>>(BinStream& stream, std::string& x) { size_t len; stream >> len; std::string s(reinterpret_cast<char*>(stream.pop_front_bytes(len)), len); x.swap(s); return stream; } BinStream& operator<<(BinStream& stream, const std::vector<bool>& v) { size_t len = v.size(); stream << len; for (int i = 0; i < v.size(); ++i) stream << static_cast<bool>(v[i]); return stream; } BinStream& operator>>(BinStream& stream, std::vector<bool>& v) { size_t len; stream >> len; v.clear(); v.resize(len); bool bool_tmp; for (int i = 0; i < v.size(); ++i) { stream >> bool_tmp; v[i] = bool_tmp; } return stream; } BinStream::~BinStream() {} } // namespace csci5570
TatianaJin/csci5570
base/serialization.cpp
C++
apache-2.0
3,451
/* * 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.sis.referencing.factory; import org.opengis.util.FactoryException; import org.opengis.referencing.IdentifiedObject; import org.opengis.referencing.AuthorityFactory; import org.opengis.referencing.datum.GeodeticDatum; import org.opengis.referencing.crs.*; import org.opengis.referencing.cs.CoordinateSystem; import org.opengis.referencing.cs.CoordinateSystemAxis; import org.opengis.referencing.datum.PrimeMeridian; import org.opengis.referencing.datum.Ellipsoid; import org.opengis.referencing.datum.Datum; import org.apache.sis.referencing.datum.DefaultGeodeticDatum; import org.apache.sis.referencing.crs.DefaultGeographicCRS; import org.apache.sis.referencing.crs.DefaultProjectedCRS; import org.apache.sis.referencing.crs.DefaultDerivedCRS; import org.apache.sis.referencing.crs.AbstractCRS; import org.apache.sis.test.DependsOn; import org.apache.sis.test.TestCase; import org.junit.Test; import static org.junit.Assert.*; /** * Tests the {@link AuthorityFactoryProxy} implementation. * This test uses {@link CommonAuthorityFactory} as a simple factory implementation. * * @author Martin Desruisseaux (Geomatys) * @version 0.7 * @since 0.7 * @module */ @DependsOn(CommonAuthorityFactoryTest.class) public final strictfp class AuthorityFactoryProxyTest extends TestCase { /** * Ensures that the most specific interfaces appear first in the list of proxies. */ @Test public void testProxies() { for (int i=1; i<AuthorityFactoryProxy.PROXIES.length; i++) { final Class<?> generic = AuthorityFactoryProxy.PROXIES[i].type; for (int j=0; j<i; j++) { assertFalse(AuthorityFactoryProxy.PROXIES[j].type.isAssignableFrom(generic)); } } } /** * Tests {@link AuthorityFactoryProxy#getInstance(Class)}. */ @Test public void testGetInstance() { assertEquals(ProjectedCRS.class, AuthorityFactoryProxy.getInstance(ProjectedCRS.class) .type); assertEquals(ProjectedCRS.class, AuthorityFactoryProxy.getInstance(DefaultProjectedCRS.class) .type); assertEquals(GeographicCRS.class, AuthorityFactoryProxy.getInstance(GeographicCRS.class) .type); assertEquals(GeographicCRS.class, AuthorityFactoryProxy.getInstance(DefaultGeographicCRS.class).type); assertEquals(DerivedCRS.class, AuthorityFactoryProxy.getInstance(DefaultDerivedCRS.class) .type); assertEquals(GeodeticDatum.class, AuthorityFactoryProxy.getInstance(DefaultGeodeticDatum.class).type); assertEquals(CoordinateReferenceSystem.class, AuthorityFactoryProxy.getInstance(AbstractCRS.class) .type); assertEquals(CoordinateSystem.class, AuthorityFactoryProxy.getInstance(CoordinateSystem.class) .type); assertEquals(CoordinateSystemAxis.class, AuthorityFactoryProxy.getInstance(CoordinateSystemAxis.class).type); assertEquals(PrimeMeridian.class, AuthorityFactoryProxy.getInstance(PrimeMeridian.class) .type); assertEquals(Ellipsoid.class, AuthorityFactoryProxy.getInstance(Ellipsoid.class) .type); assertEquals(Datum.class, AuthorityFactoryProxy.getInstance(Datum.class) .type); } /** * Tests {@link AuthorityFactoryProxy#specialize(String)}. */ @Test public void testSpecialize() { final AuthorityFactoryProxy<IdentifiedObject> base = AuthorityFactoryProxy.OBJECT; assertEquals(CoordinateReferenceSystem.class, base.specialize("CRS") .type); assertEquals(CoordinateSystem.class, base.specialize("CS") .type); assertEquals(CoordinateSystemAxis.class, base.specialize("aXis") .type); assertEquals(PrimeMeridian.class, base.specialize("Meridian") .type); assertEquals(Ellipsoid.class, base.specialize("ellipsoid").type); assertEquals(Datum.class, base.specialize("datum") .type); assertEquals(GeodeticDatum.class, AuthorityFactoryProxy.GEODETIC_DATUM.specialize("datum").type); assertNull(AuthorityFactoryProxy.COORDINATE_SYSTEM.specialize("datum")); } /** * Tests {@link AuthorityFactoryProxy#createFromAPI(AuthorityFactory, String)}. * We use the {@link CommonAuthorityFactory} for testing purpose. * * @throws FactoryException if an error occurred while creating a CRS. */ @Test public void testCreateFromAPI() throws FactoryException { final CRSAuthorityFactory factory = new CommonAuthorityFactory(); final CoordinateReferenceSystem expected = factory.createCoordinateReferenceSystem("83"); AuthorityFactoryProxy<?> proxy; /* * Try the proxy using the 'createGeographicCRS', 'createCoordinateReferenceSystem' * and 'createObject' methods. The later uses a generic implementation, while the * first two should use specialized implementations. */ proxy = AuthorityFactoryProxy.getInstance(GeographicCRS.class); assertSame(AuthorityFactoryProxy.GEOGRAPHIC_CRS, proxy); assertSame(expected, proxy.createFromAPI(factory, "83")); assertSame(expected, proxy.createFromAPI(factory, "CRS:83")); proxy = AuthorityFactoryProxy.getInstance(CoordinateReferenceSystem.class); assertSame(AuthorityFactoryProxy.CRS, proxy); assertSame(expected, proxy.createFromAPI(factory, "83")); assertSame(expected, proxy.createFromAPI(factory, "CRS:83")); proxy = AuthorityFactoryProxy.getInstance(IdentifiedObject.class); assertSame(AuthorityFactoryProxy.OBJECT, proxy); assertSame(expected, proxy.createFromAPI(factory, "83")); assertSame(expected, proxy.createFromAPI(factory, "CRS:83")); /* * Try using the 'createProjectedCRS' method, which should not * be supported for the CRS factory (at least not for code "83"). */ proxy = AuthorityFactoryProxy.getInstance(ProjectedCRS.class); assertSame(AuthorityFactoryProxy.PROJECTED_CRS, proxy); try { assertSame(expected, proxy.createFromAPI(factory, "83")); fail("Should not have created a CRS of the wrong type."); } catch (FactoryException e) { // This is the expected exception. final String message = e.getMessage(); assertTrue(message.contains("83")); assertTrue(message.contains("GeographicCRS")); assertTrue(message.contains("ProjectedCRS")); } } }
Geomatys/sis
core/sis-referencing/src/test/java/org/apache/sis/referencing/factory/AuthorityFactoryProxyTest.java
Java
apache-2.0
7,519
package visualizers.KeepAway; import generalGameCode.Utilities; import generalGameCode.Vector2D; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Polygon; import java.awt.geom.AffineTransform; import java.awt.geom.Rectangle2D; import java.util.Vector; import KeepAway.SoccerPitch; import KeepAway.Wall2D; import kaMessages.KAStateRequest; import kaMessages.KAStateResponse; import kaMessages.PlayerFacadeInterface; import kaMessages.SoccerTeamFacadeInterface; import rlVizLib.visualization.VizComponent; import org.rlcommunity.rlglue.codec.types.Observation; public class KeepAwayVizComponent implements VizComponent{ KeepAwayVisualizer myVisualizer=null; int lastUpdateStep=-1; public KeepAwayVizComponent(KeepAwayVisualizer keepAwayVisualizer) { myVisualizer=keepAwayVisualizer; } public void render(Graphics2D g) { final boolean debugThis=false; double ballDiam=1.0d; double halfBD=ballDiam/2.0d; double widthDivider=.001d; double heightDivider=.001d; double Width=1.0d/widthDivider; double Height=1.0d/heightDivider; double fieldWidth=100.0d; double fieldHeight=50.0d; double wM=Width/fieldWidth; double hM=Width/fieldWidth; //Make it 100 x 100 AffineTransform saveAT = g.getTransform(); g.scale(widthDivider, heightDivider); //Draw the ball //Should only do this when new info available KAStateResponse R=KAStateRequest.Execute(); if(R==null)return; Vector<Wall2D> theWalls=R.getTheWalls(); for (Wall2D thisWall : theWalls) { g.drawLine((int)(thisWall.From().x*wM),(int)(thisWall.From().y*hM),(int)(thisWall.To().x*wM),(int)(thisWall.To().y*hM)); // System.out.println("Drawing a line from: "+(int)thisWall.From().x+","+(int)thisWall.From().y+" to "+(int)thisWall.To().x+","+(int)thisWall.To().y); } SoccerTeamFacadeInterface theKeepers=R.getKeepers(); g.setColor(Color.blue); drawTeam(g,theKeepers,wM,hM); SoccerTeamFacadeInterface theTakers=R.getTakers(); g.setColor(Color.red); drawTeam(g,theTakers,wM,hM); Vector2D BallPosition=R.getBallPosition(); g.setColor(Color.white); g.fillOval((int)((BallPosition.x-halfBD)*wM),(int)((BallPosition.y-halfBD)*hM), (int)(ballDiam*wM), (int)(ballDiam*hM)); g.setTransform(saveAT); } public void drawTeam(Graphics2D g,SoccerTeamFacadeInterface theTeam,double wM,double hM){ boolean debugThis=false; int playerCount=theTeam.getPlayerCount(); for(int i=0;i<playerCount;i++){ PlayerFacadeInterface thisPlayer=theTeam.getPlayer(i); Vector<Vector2D> vertices=thisPlayer.getVertices(); Vector<Vector2D> transformedVertices=Utilities.WorldTransform(vertices, thisPlayer.Pos(), thisPlayer.Heading(), thisPlayer.Side(), thisPlayer.Scale()); if(debugThis) System.out.println("Player Details: \n"+thisPlayer); int numPoints=transformedVertices.size(); int xPoints[]=new int[numPoints]; int yPoints[]=new int[numPoints]; for(int j=0;j<numPoints;j++){ xPoints[j]=(int)(wM*transformedVertices.get(j).x); yPoints[j]=(int)(hM*transformedVertices.get(j).y); } g.fillPolygon(xPoints, yPoints, numPoints); Vector2D steering=thisPlayer.SteeringForce(); Vector2D position=thisPlayer.Pos(); Vector2D endPosOfSteering=position.addToCopy(steering.multiplyToCopy(2.0)); g.drawLine((int)(wM*position.x), (int)(hM*position.y), (int)(wM*endPosOfSteering.x),(int) (hM*endPosOfSteering.y)); g.fillOval((int)(wM*position.x), (int)(hM*position.y),5,5); } } public boolean update() { int currentTimeStep=myVisualizer.theGlueState.getTotalSteps(); if(currentTimeStep>lastUpdateStep){ lastUpdateStep=currentTimeStep; return true; } return false; } }
chaostrigger/rl-library
projects/environments/experimental/KeepAway/src/visualizers/KeepAway/KeepAwayVizComponent.java
Java
apache-2.0
3,748
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- Fav and touch icons --> <link rel="apple-touch-icon-precomposed" sizes="144x144" href="assets/ico/apple-touch-icon-144-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="114x114" href="assets/ico/apple-touch-icon-114-precomposed.png"> <link rel="apple-touch-icon-precomposed" sizes="72x72" href="assets/ico/apple-touch-icon-72-precomposed.png"> <link rel="apple-touch-icon-precomposed" href="ico/apple-touch-icon-57-precomposed.png"> <link rel="shortcut icon" href="assets/ico/favicon.png"> <title>TSHOP - Bootstrap E-Commerce Parallax Theme</title> <!-- Bootstrap core CSS --> <link href="assets/bootstrap/css/bootstrap.css" rel="stylesheet"> <!-- Custom styles for this template --> <link href="assets/css/style.css" rel="stylesheet"> <!-- css3 animation effect for this template --> <link href="assets/css/animate.min.css" rel="stylesheet"> <!-- styles needed by carousel slider --> <link href="assets/css/owl.carousel.css" rel="stylesheet"> <link href="assets/css/owl.theme.css" rel="stylesheet"> <!-- styles needed by checkRadio --> <link href="assets/css/ion.checkRadio.css" rel="stylesheet"> <link href="assets/css/ion.checkRadio.cloudy.css" rel="stylesheet"> <!-- styles needed by mCustomScrollbar --> <link href="assets/css/jquery.mCustomScrollbar.css" rel="stylesheet"> <!-- Just for debugging purposes. --> <!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script> <![endif]--> <!-- include pace script for automatic web page progress bar --> <script> paceOptions = { elements: true }; </script> <script src="assets/js/pace.min.js"></script> </head> <body> <!-- Modal Login start --> <div class="modal signUpContent fade" id="ModalLogin" tabindex="-1" role="dialog" > <div class="modal-dialog "> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h3 class="modal-title-site text-center" > Login to TSHOP </h3> </div> <div class="modal-body"> <div class="form-group login-username"> <div > <input name="log" id="login-user" class="form-control input" size="20" placeholder="Enter Username" type="text"> </div> </div> <div class="form-group login-password"> <div > <input name="Password" id="login-password" class="form-control input" size="20" placeholder="Password" type="password"> </div> </div> <div class="form-group"> <div > <div class="checkbox login-remember"> <label> <input name="rememberme" value="forever" checked="checked" type="checkbox"> Remember Me </label> </div> </div> </div> <div > <div > <input name="submit" class="btn btn-block btn-lg btn-primary" value="LOGIN" type="submit"> </div> </div> <!--userForm--> </div> <div class="modal-footer"> <p class="text-center"> Not here before? <a data-toggle="modal" data-dismiss="modal" href="#ModalSignup"> Sign Up. </a> <br> <a href="forgot-password.html" > Lost your password? </a> </p> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.Modal Login --> <!-- Modal Signup start --> <div class="modal signUpContent fade" id="ModalSignup" tabindex="-1" role="dialog" > <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> &times; </button> <h3 class="modal-title-site text-center" > REGISTER </h3> </div> <div class="modal-body"> <div class="control-group"> <a class="fb_button btn btn-block btn-lg " href="#"> SIGNUP WITH FACEBOOK </a> </div> <h5 style="padding:10px 0 10px 0;" class="text-center"> OR </h5> <div class="form-group reg-username"> <div > <input name="login" class="form-control input" size="20" placeholder="Enter Username" type="text"> </div> </div> <div class="form-group reg-email"> <div > <input name="reg" class="form-control input" size="20" placeholder="Enter Email" type="text"> </div> </div> <div class="form-group reg-password"> <div > <input name="password" class="form-control input" size="20" placeholder="Password" type="password"> </div> </div> <div class="form-group"> <div > <div class="checkbox login-remember"> <label> <input name="rememberme" id="rememberme" value="forever" checked="checked" type="checkbox"> Remember Me </label> </div> </div> </div> <div > <div > <input name="submit" class="btn btn-block btn-lg btn-primary" value="REGISTER" type="submit"> </div> </div> <!--userForm--> </div> <div class="modal-footer"> <p class="text-center"> Already member? <a data-toggle="modal" data-dismiss="modal" href="#ModalLogin"> Sign in </a> </p> </div> </div> <!-- /.modal-content --> </div> <!-- /.modal-dialog --> </div> <!-- /.ModalSignup End --> <!-- Fixed navbar start --> <div class="navbar navbar-tshop navbar-fixed-top megamenu" role="navigation"> <div class="navbar-top"> <div class="container"> <div class="row"> <div class="col-lg-6 col-sm-6 col-xs-6 col-md-6"> <div class="pull-left "> <ul class="userMenu "> <li> <a href="#"> <span class="hidden-xs">HELP</span><i class="glyphicon glyphicon-info-sign hide visible-xs "></i> </a> </li> <li class="phone-number"> <a href="callto:+8801680531352"> <span> <i class="glyphicon glyphicon-phone-alt "></i></span> <span class="hidden-xs" style="margin-left:5px"> 88 01680 53 1352 </span> </a> </li> </ul> </div> </div> <div class="col-lg-6 col-sm-6 col-xs-6 col-md-6 no-margin no-padding"> <div class="pull-right"> <ul class="userMenu"> <li> <a href="account-1.html"><span class="hidden-xs"> My Account</span> <i class="glyphicon glyphicon-user hide visible-xs "></i></a> </li> <li> <a href="#" data-toggle="modal" data-target="#ModalLogin"> <span class="hidden-xs">Sign In</span> <i class="glyphicon glyphicon-log-in hide visible-xs "></i> </a> </li> <li class="hidden-xs"> <a href="#" data-toggle="modal" data-target="#ModalSignup"> Create Account </a> </li> </ul> </div> </div> </div> </div> </div> <!--/.navbar-top--> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> <span class="sr-only"> Toggle navigation </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> <span class="icon-bar"> </span> </button> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-cart"> <i class="fa fa-shopping-cart colorWhite"> </i> <span class="cartRespons colorWhite"> Cart ($210.00) </span> </button> <a class="navbar-brand " href="index.html"> <img src="images/logo.png" alt="TSHOP"> </a> <!-- this part for mobile --> <div class="search-box pull-right hidden-lg hidden-md hidden-sm"> <div class="input-group"> <button class="btn btn-nobg getFullSearch" type="button"> <i class="fa fa-search"> </i> </button> </div> <!-- /input-group --> </div> </div> <!-- this part is duplicate from cartMenu keep it for mobile --> <div class="navbar-cart collapse"> <div class="cartMenu col-lg-4 col-xs-12 col-md-4 "> <div class="w100 miniCartTable scroll-pane"> <table > <tbody> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/3.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/2.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/5.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/3.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/3.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/4.jpg" alt="img"> </a> </div></td> <td style="40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $8.80 </span> </div> </div></td> <td style="10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="5%" class="delete"><a > x </a></td> </tr> </tbody> </table> </div> <!--/.miniCartTable--> <div class="miniCartFooter miniCartFooterInMobile text-right"> <h3 class="text-right subtotal"> Subtotal: $210 </h3> <a class="btn btn-sm btn-danger"> <i class="fa fa-shopping-cart"> </i> VIEW CART </a> <a class="btn btn-sm btn-primary"> CHECKOUT </a> </div> <!--/.miniCartFooter--> </div> <!--/.cartMenu--> </div> <!--/.navbar-cart--> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li class="active"> <a href="#"> Home </a> </li> <li class="dropdown megamenu-fullwidth"> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> New Products <b class="caret"> </b> </a> <ul class="dropdown-menu"> <li class="megamenu-content "> <ul class="col-lg-3 col-sm-3 col-md-3 unstyled noMarginLeft newCollectionUl"> <li class="no-border"> <p class="promo-1"> <strong> NEW COLLECTION </strong> </p> </li> <li> <a href="category.html"> ALL NEW PRODUCTS </a> </li> <li> <a href="category.html"> NEW TOPS </a> </li> <li> <a href="category.html"> NEW SHOES </a> </li> <li> <a href="category.html"> NEW TSHIRT </a> </li> <li> <a href="category.html"> NEW TSHOP </a> </li> </ul> <ul class="col-lg-3 col-sm-3 col-md-3 col-xs-4"> <li> <a class="newProductMenuBlock" href="product-details.html"> <img class="img-responsive" src="images/site/promo1.jpg" alt="product"> <span class="ProductMenuCaption"> <i class="fa fa-caret-right"> </i> JEANS </span> </a> </li> </ul> <ul class="col-lg-3 col-sm-3 col-md-3 col-xs-4"> <li> <a class="newProductMenuBlock" href="product-details.html"> <img class="img-responsive" src="images/site/promo2.jpg" alt="product"> <span class="ProductMenuCaption"> <i class="fa fa-caret-right"> </i> PARTY DRESS </span> </a> </li> </ul> <ul class="col-lg-3 col-sm-3 col-md-3 col-xs-4"> <li> <a class="newProductMenuBlock" href="product-details.html"> <img class="img-responsive" src="images/site/promo3.jpg" alt="product"> <span class="ProductMenuCaption"> <i class="fa fa-caret-right"> </i> SHOES </span> </a> </li> </ul> </li> </ul> </li> <!-- change width of megamenu = use class > megamenu-fullwidth, megamenu-60width, megamenu-40width --> <li class="dropdown megamenu-80width "> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> SHOP <b class="caret"> </b> </a> <ul class="dropdown-menu"> <li class="megamenu-content"> <!-- megamenu-content --> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled noMarginLeft"> <li> <p> <strong> Women Collection </strong> </p> </li> <li> <a href="#"> Kameez </a> </li> <li> <a href="#"> Tops </a> </li> <li> <a href="#"> Shoes </a> </li> <li> <a href="#"> T shirt </a> </li> <li> <a href="#"> TSHOP </a> </li> <li> <a href="#"> Party Dress </a> </li> <li> <a href="#"> Women Fragrances </a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li> <p> <strong> Men Collection </strong> </p> </li> <li> <a href="#"> Panjabi </a> </li> <li> <a href="#"> Male Fragrances </a> </li> <li> <a href="#"> Scarf </a> </li> <li> <a href="#"> Sandal </a> </li> <li> <a href="#"> Underwear </a> </li> <li> <a href="#"> Winter Collection </a> </li> <li> <a href="#"> Men Accessories </a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li> <p> <strong> Top Brands </strong> </p> </li> <li> <a href="#"> Diesel </a> </li> <li> <a href="#"> Farah </a> </li> <li> <a href="#"> G-Star RAW </a> </li> <li> <a href="#"> Lyle & Scott </a> </li> <li> <a href="#"> Pretty Green </a> </li> <li> <a href="#"> TSHOP </a> </li> <li> <a href="#"> TANJIM </a> </li> </ul> <ul class="col-lg-3 col-sm-3 col-md-3 col-xs-6"> <li class="no-margin productPopItem "> <a href="product-details.html"> <img class="img-responsive" src="images/site/g4.jpg" alt="img"> </a> <a class="text-center productInfo alpha90" href="product-details.html"> Eodem modo typi <br> <span> $60 </span> </a> </li> </ul> <ul class="col-lg-3 col-sm-3 col-md-3 col-xs-6"> <li class="no-margin productPopItem relative"> <a href="product-details.html"> <img class="img-responsive" src="images/site/g5.jpg" alt="img"> </a> <a class="text-center productInfo alpha90" href="product-details.html"> Eodem modo typi <br> <span> $60 </span> </a> </li> </ul> </li> </ul> </li> <li class="dropdown megamenu-fullwidth"> <a data-toggle="dropdown" class="dropdown-toggle" href="#"> PAGES <b class="caret"> </b> </a> <ul class="dropdown-menu"> <li class="megamenu-content"> <!-- megamenu-content --> <h3 class="promo-1 no-margin hidden-xs"> 28+ HTML PAGES ONLY $8 || AVAILABLE ONLY AT WRAP BOOTSTRAP </h3> <h3 class="promo-1sub hidden-xs"> Complete Parallax E-Commerce Boostrap Template, Responsive on any Device, 10+ color Theme + Parallax Effect </h3> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> Home Pages </strong> </p> </li> <li> <a href="index.html"> Home Version 1 </a> </li> <li> <a href="index2.html"> Home Version 2 </a> </li> <li> <a href="index3.html"> Home Version 3 (BOXES) </a> </li> <li> <a href="index4.html"> Home Version 4 (LOOK 2)</a> </li> <li> <a href="index5.html"> Home Version 5 (LOOK 3)</a> </li> <li> <a href="index-header2.html"> Header Version 2 </a> </li> <li> <a href="index-header3.html"> Header Version 3 </a> </li> <li> <a href="index-static-search.html">Header Version 4<br> ( Static Search Form)</a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> Featured Pages </strong> </p> </li> <li> <a href="category.html"> Category </a> </li> <li> <a href="sub-category.html"> Sub Category </a> </li> <li> <a href="category-list.html"> Category List View </a> </li> <li> <a href="product-details.html"> Product Details Version 1 </a> </li> <li> <a href="product-details-style2.html"> Product Details Version 2 </a> </li> <li> <a href="product-details-style3.html"> Product Details Version 3 (Custom Thumbnail Position)</a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> &nbsp; </strong> </p> </li> <li> <a href="cart.html"> Cart </a> </li> <li> <a href="about-us.html"> About us </a> </li> <li> <a href="about-us-2.html"> About us 2 (no parallax) </a> </li> <li> <a href="contact-us.html"> Contact us </a> </li> <li> <a href="contact-us-2.html"> Contact us 2 (No Fixed Map) </a> </li> <li> <a href="terms-conditions.html"> Terms &amp; Conditions </a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> Checkout </strong> </p> </li> <li> <a href="checkout-0.html"> Checkout Before </a> </li> <li> <a href="checkout-1.html"> checkout step 1 </a> </li> <li> <a href="checkout-2.html"> checkout step 2 </a> </li> <li> <a href="checkout-3.html"> checkout step 3 </a> </li> <li> <a href="checkout-4.html"> checkout step 4 </a> </li> <li> <a href="checkout-5.html"> checkout step 5 </a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> User Account </strong> </p> </li> <li> <a href="account-1.html"> Account Login </a> </li> <li> <a href="account.html"> My Account </a> </li> <li> <a href="my-address.html"> My Address </a> </li> <li> <a href="user-information.html"> User information </a> </li> <li> <a href="wishlist.html"> Wisth list </a> </li> <li> <a href="order-list.html"> Order list </a> </li> <li> <a href="forgot-password.html"> Forgot Password </a> </li> </ul> <ul class="col-lg-2 col-sm-2 col-md-2 unstyled"> <li class="no-border"> <p> <strong> &nbsp; </strong> </p> </li> <li> <a href="error-page.html"> Error Page </a> </li> <li> <a href="blank-page.html"> Blank Page </a> </li> <li> <a href="form.html"> Basic Form Element </a> </li> </ul> </li> </ul> </li> </ul> <!--- this part will be hidden for mobile version --> <div class="nav navbar-nav navbar-right hidden-xs"> <div class="dropdown cartMenu "> <a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fa fa-shopping-cart"> </i> <span class="cartRespons"> Cart ($210.00) </span> <b class="caret"> </b> </a> <div class="dropdown-menu col-lg-4 col-xs-12 col-md-4 "> <div class="w100 miniCartTable scroll-pane"> <table> <tbody> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/3.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP Tshirt DO9 </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $22 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $33 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/2.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TShir TSHOP 09 </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $15 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $120 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/5.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> Tshir 2014 </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $30 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $80 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/3.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> TSHOP T shirt DO20 </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $15 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $55 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/product/4.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> T shirt Black </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $44 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $40 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> <tr class="miniCartProduct"> <td style="width:20%" class="miniCartProductThumb"><div> <a href="product-details.html"> <img src="images/site/winter.jpg" alt="img"> </a> </div></td> <td style="width:40%"><div class="miniCartDescription"> <h4> <a href="product-details.html"> G Star T shirt </a> </h4> <span class="size"> 12 x 1.5 L </span> <div class="price"> <span> $80 </span> </div> </div></td> <td style="width:10%" class="miniCartQuantity"><a > X 1 </a></td> <td style="width:15%" class="miniCartSubtotal"><span> $8.80 </span></td> <td style="width:5%" class="delete"><a > x </a></td> </tr> </tbody> </table> </div> <!--/.miniCartTable--> <div class="miniCartFooter text-right"> <h3 class="text-right subtotal"> Subtotal: $210 </h3> <a class="btn btn-sm btn-danger"> <i class="fa fa-shopping-cart"> </i> VIEW CART </a> <a class="btn btn-sm btn-primary"> CHECKOUT </a> </div> <!--/.miniCartFooter--> </div> <!--/.dropdown-menu--> </div> <!--/.cartMenu--> <div class="search-box"> <div class="input-group"> <button class="btn btn-nobg getFullSearch" type="button"> <i class="fa fa-search"> </i> </button> </div> <!-- /input-group --> </div> <!--/.search-box --> </div> <!--/.navbar-nav hidden-xs--> </div> <!--/.nav-collapse --> </div> <!--/.container --> <div class="search-full text-right"> <a class="pull-right search-close"> <i class=" fa fa-times-circle"> </i> </a> <div class="searchInputBox pull-right"> <input type="search" data-searchurl="search?=" name="q" placeholder="start typing and hit enter to search" class="search-input"> <button class="btn-nobg search-btn" type="submit"> <i class="fa fa-search"> </i> </button> </div> </div> <!--/.search-full--> </div> <!-- /.Fixed navbar --> <div class="banner"> <div class="full-container"> <div class="slider-content"> <ul id="pager2" class="container"> </ul> <!-- prev/next links --> <span class="prevControl sliderControl"> <i class="fa fa-angle-left fa-3x "></i></span> <span class="nextControl sliderControl"> <i class="fa fa-angle-right fa-3x "></i></span> <div class="slider slider-v1" data-cycle-swipe=true data-cycle-prev=".prevControl" data-cycle-next=".nextControl" data-cycle-loader="wait"> <div class="slider-item slider-item-img1"> <img src="images/slider/slider0.jpg" class="img-responsive parallaximg sliderImg" alt="img"> </div> <div class="slider-item slider-item-img1"> <div class="sliderInfo"> <div class="container"> <div class="col-lg-12 col-md-12 col-sm-12 sliderTextFull "> <div class="inner text-center"> <div class="topAnima animated"> <h1 class="uppercase xlarge">FREE SHIPPING</h1> <h3 class="hidden-xs"> Free Standard Shipping on Orders Over $100 </h3> </div> <a class="btn btn-danger btn-lg bottomAnima animated opacity0">SHOP NOW ON TSHOP <span class="arrowUnicode">►</span></a> </div> </div> </div> </div> <img src="images/slider/slider1.jpg" class="img-responsive parallaximg sliderImg" alt="img"> </div> <!--/.slider-item--> <div class="slider-item slider-item-img2 "> <div class="sliderInfo"> <div class="container"> <div class="col-lg-12 col-md-12 col-sm-12 sliderTextFull "> <div class="inner dark maxwidth500 text-center animated topAnima"> <div class=" "> <h1 class="uppercase xlarge"> CUSTOM HTML BLOCK</h1> <h3 class="hidden-xs"> Custom Slides to Your Slider </h3> </div> <a class="btn btn-danger btn-lg">SHOP NOW ON TSHOP <span class="arrowUnicode">►</span></a> </div> </div> </div> </div> <img src="images/slider/slider3.jpg" class="img-responsive parallaximg sliderImg" alt="img"> </div> <!--/.slider-item--> <div class="slider-item slider-item-img3 "> <div class="sliderInfo"> <div class="container"> <div class="col-lg-5 col-md-4 col-sm-6 col-xs-8 pull-left sliderText white hidden-xs"> <div class="inner"> <h1>TSHOP JEANS</h1> <h3 class="price "> Free Shipping on $100</h3> <p class="hidden-xs">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. </p> <a href="category.html" class="btn btn-primary">SHOP NOW <span class="arrowUnicode">►</span></a> </div> </div> </div> </div> <img src="images/slider/slider4.jpg" class="img-responsive parallaximg sliderImg" alt="img"> </div> <!--/.slider-item--> <div class="slider-item slider-item-img3"> <div class="sliderInfo"> <div class="container"> <div class="col-lg-5 col-md-6 col-sm-5 col-xs-5 pull-left sliderText blankstyle transformRight"> <div class="inner text-right"> <img src="images/slider/color.png" class="img-responsive" alt="img"> </div> </div> <div class="col-lg-4 col-md-4 col-sm-5 col-xs-7 pull-left sliderText blankstyle color-white"> <div class="inner"> <h1 class="uppercase topAnima animated ">10+ Amazing Color Theme</h1> <p class="bot tomAnima animated opacity0 hidden-xs"> Fully responsive bootstrap Ecommerce Template. Available in 10+ color schemes and easy to set. </p> </div> </div> </div> </div> <img src="images/slider/6.jpg" class="img-responsive parallaximg sliderImg" alt="img"> </div> </div> <!--/.slider slider-v1--> </div> <!--/.slider-content--> </div> <!--/.full-container--> </div> <!--/.banner style1--> <div class="container main-container"> <!-- Main component call to action --> <div class="row featuredPostContainer globalPadding style2"> <h3 class="section-title style2 text-center"><span>NEW ARRIVALS</span></h3> <div id="productslider" class="owl-carousel owl-theme"> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/34.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">consectetuer adipiscing </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/30.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">luptatum zzril delenit</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/36.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> </div> </div> <div class="description"> <h4><a href="product-details.html">eleifend option </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/9.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">mutationem consuetudium </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/12.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">sequitur mutationem </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/13.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">consuetudium lectorum.</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/21.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">parum claram</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/24.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">duis dolore </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <div class="item"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/15.jpg" alt="img" class="img-responsive"></a></div> <div class="description"> <h4><a href="product-details.html">feugait nulla facilisi</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> </div> <!--/.productslider--> </div> <!--/.featuredPostContainer--> </div> <!-- /main container --> <div class="parallax-section parallax-image-1"> <div class="container"> <div class="row "> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div class="parallax-content clearfix"> <h1 class="parallaxPrce"> $200 </h1> <h2 class="uppercase">FREE INTERNATIONAL SHIPPING! Get Free Shipping Coupons</h2> <h3 > Energistically develop parallel mindshare rather than premier deliverables. </h3> <div style="clear:both"></div> <a class="btn btn-discover "> <i class="fa fa-shopping-cart"></i> SHOP NOW </a> </div> </div> </div> <!--/.row--> </div> <!--/.container--> </div> <!--/.parallax-image-1--> <div class="container main-container"> <!-- Main component call to action --> <div class="morePost row featuredPostContainer style2 globalPaddingTop " > <h3 class="section-title style2 text-center"><span>FEATURES PRODUCT</span></h3> <div class="container"> <div class="row xsResponse"> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/30.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">aliquam erat volutpat</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> <span class="old-price">$75</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/31.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">ullamcorper suscipit lobortis </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/34.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> </div> </div> <div class="description"> <h4><a href="product-details.html">demonstraverunt lectores </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/12.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">humanitatis per</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/33.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">Eodem modo typi</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/10.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">sequitur mutationem </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/37.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">consuetudium lectorum.</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/35.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">parum claram</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> <span class="old-price">$75</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/13.jpg" alt="img" class="img-responsive"></a> </div> <div class="description"> <h4><a href="product-details.html">duis dolore </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/21.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">aliquam erat volutpat</a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/14.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="discount">15% OFF</span> </div> </div> <div class="description"> <h4><a href="product-details.html">ullamcorper suscipit lobortis </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> <div class="item col-lg-3 col-md-3 col-sm-4 col-xs-6"> <div class="product"> <a class="add-fav tooltipHere" data-toggle="tooltip" data-original-title="Add to Wishlist" data-placement="left"> <i class="glyphicon glyphicon-heart"></i> </a> <div class="image"> <a href="product-details.html"><img src="images/product/17.jpg" alt="img" class="img-responsive"></a> <div class="promotion"> <span class="new-product"> NEW</span> </div> </div> <div class="description"> <h4><a href="product-details.html">demonstraverunt lectores </a></h4> <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p> <span class="size">XL / XXL / S </span> </div> <div class="price"> <span>$25</span> </div> <div class="action-control"> <a class="btn btn-primary"> <span class="add2cart"><i class="glyphicon glyphicon-shopping-cart"> </i> Add to cart </span> </a> </div> </div> </div> <!--/.item--> </div> <!-- /.row --> <div class="row"> <div class="load-more-block text-center"> <a class="btn btn-thin" href="#"> <i class="fa fa-plus-sign">+</i> load more products</a> </div> </div> </div> <!--/.container--> </div> <!--/.featuredPostContainer--> <hr class="no-margin-top"> <div class="width100 section-block "> <div class="row featureImg"> <div class="col-md-3 col-sm-3 col-xs-6"> <a href="category.html"><img src="images/site/new-collection-1.jpg" class="img-responsive" alt="img" ></a> </div> <div class="col-md-3 col-sm-3 col-xs-6"> <a href="category.html"><img src="images/site/new-collection-2.jpg" class="img-responsive" alt="img" ></a> </div> <div class="col-md-3 col-sm-3 col-xs-6"> <a href="category.html"><img src="images/site/new-collection-3.jpg" class="img-responsive" alt="img" ></a> </div> <div class="col-md-3 col-sm-3 col-xs-6"> <a href="category.html"><img src="images/site/new-collection-4.jpg" class="img-responsive" alt="img"></a> </div> </div> <!--/.row--> </div> <!--/.section-block--> <div class="width100 section-block"> <h3 class="section-title"><span> BRAND</span> <a id="nextBrand" class="link pull-right carousel-nav"> <i class="fa fa-angle-right"></i></a> <a id="prevBrand" class="link pull-right carousel-nav"> <i class="fa fa-angle-left"></i> </a> </h3> <div class="row"> <div class="col-lg-12"> <ul class="no-margin brand-carousel owl-carousel owl-theme"> <li> <a ><img src="images/brand/1.gif" alt="img" ></a></li> <li><img src="images/brand/2.png" alt="img" ></li> <li><img src="images/brand/3.png" alt="img" ></li> <li><img src="images/brand/4.png" alt="img" ></li> <li><img src="images/brand/5.png" alt="img" ></li> <li><img src="images/brand/6.png" alt="img" ></li> <li><img src="images/brand/7.png" alt="img" ></li> <li><img src="images/brand/8.png" alt="img" ></li> <li><img src="images/brand/1.gif" alt="img" ></li> <li><img src="images/brand/2.png" alt="img" ></li> <li><img src="images/brand/3.png" alt="img" ></li> <li><img src="images/brand/4.png" alt="img" ></li> <li><img src="images/brand/5.png" alt="img" ></li> <li><img src="images/brand/6.png" alt="img" ></li> <li><img src="images/brand/7.png" alt="img" ></li> <li><img src="images/brand/8.png" alt="img" ></li> </ul> </div> </div> <!--/.row--> </div> <!--/.section-block--> </div> <!--main-container--> <div class="parallax-section parallax-image-2"> <div class="w100 parallax-section-overley"> <div class="container"> <div class="row"> <div class="col-xs-12 col-sm-12 col-md-12 col-lg-12"> <div class="parallax-content clearfix"> <h1 class="xlarge"> Trusted Seller 500+ </h1> <h5 class="parallaxSubtitle"> Lorem ipsum dolor sit amet consectetuer </h5> </div> </div> </div> </div> </div> </div> <!--/.parallax-section--> <footer> <div class="footer" id="footer"> <div class="container"> <div class="row"> <div class="col-lg-3 col-md-3 col-sm-4 col-xs-6"> <h3> Support </h3> <ul> <li class="supportLi"> <p> Lorem ipsum dolor sit amet, consectetur </p> <h4> <a class="inline" href="callto:+8801680531352"> <strong> <i class="fa fa-phone"> </i> 88 01680 531352 </strong> </a> </h4> <h4> <a class="inline" href="mailto:[email protected]"> <i class="fa fa-envelope-o"> </i> [email protected] </a> </h4> </li> </ul> </div> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6"> <h3> Shop </h3> <ul> <li> <a href="index.html"> Home </a> </li> <li> <a href="category.html"> Category </a> </li> <li> <a href="sub-category.html"> Sub Category </a> </li> </ul> </div> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6"> <h3> Information </h3> <ul> <li> <a href="product-details.html"> Product Details </a> </li> <li> <a href="product-details-style2.html"> Product Details Version 2 </a> </li> <li> <a href="cart.html"> Cart </a> </li> <li> <a href="about-us.html"> About us </a> </li> <li> <a href="about-us-2.html"> About us 2 </a> </li> <li> <a href="contact-us.html"> Contact us </a> </li> <li> <a href="contact-us-2.html"> Contact us 2 </a> </li> <li> <a href="terms-conditions.html"> Terms &amp; Conditions </a> </li> </ul> </div> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-6"> <h3> My Account </h3> <ul> <li> <a href="account-1.html"> Account Login </a> </li> <li> <a href="account.html"> My Account </a> </li> <li> <a href="my-address.html"> My Address </a> </li> <li> <a href="wishlist.html"> Wisth list </a> </li> <li> <a href="order-list.html"> Order list </a> </li> </ul> </div> <div class="col-lg-3 col-md-3 col-sm-6 col-xs-12 "> <h3> Stay in touch </h3> <ul> <li> <div class="input-append newsLatterBox text-center"> <input type="text" class="full text-center" placeholder="Email "> <button class="btn bg-gray" type="button"> Subscribe <i class="fa fa-long-arrow-right"> </i> </button> </div> </li> </ul> <ul class="social"> <li> <a href="http://facebook.com"> <i class=" fa fa-facebook"> &nbsp; </i> </a> </li> <li> <a href="http://twitter.com"> <i class="fa fa-twitter"> &nbsp; </i> </a> </li> <li> <a href="https://plus.google.com"> <i class="fa fa-google-plus"> &nbsp; </i> </a> </li> <li> <a href="http://youtube.com"> <i class="fa fa-pinterest"> &nbsp; </i> </a> </li> <li> <a href="http://youtube.com"> <i class="fa fa-youtube"> &nbsp; </i> </a> </li> </ul> </div> </div> <!--/.row--> </div> <!--/.container--> </div> <!--/.footer--> <div class="footer-bottom"> <div class="container"> <p class="pull-left"> &copy; TSHOP 2014. All right reserved. </p> <div class="pull-right paymentMethodImg"> <img height="30" class="pull-right" src="images/site/payment/master_card.png" alt="img" > <img height="30" class="pull-right" src="images/site/payment/paypal.png" alt="img" > <img height="30" class="pull-right" src="images/site/payment/american_express_card.png" alt="img" > <img height="30" class="pull-right" src="images/site/payment/discover_network_card.png" alt="img" > <img height="30" class="pull-right" src="images/site/payment/google_wallet.png" alt="img" > </div> </div> </div> <!--/.footer-bottom--> </footer> <!-- Le javascript ================================================== --> <!-- Placed at the end of the document so the pages load faster --> <script type="text/javascript" src="assets/js/jquery/1.8.3/jquery.js"></script> <script src="assets/bootstrap/js/bootstrap.min.js"></script> <!-- include jqueryCycle plugin --> <script src="assets/js/jquery.cycle2.min.js"></script> <!-- include easing plugin --> <script src="assets/js/jquery.easing.1.3.js"></script> <!-- include parallax plugin --> <script type="text/javascript" src="assets/js/jquery.parallax-1.1.js"></script> <!-- optionally include helper plugins --> <script type="text/javascript" src="assets/js/helper-plugins/jquery.mousewheel.min.js"></script> <!-- include mCustomScrollbar plugin //Custom Scrollbar --> <script type="text/javascript" src="assets/js/jquery.mCustomScrollbar.js"></script> <!-- include checkRadio plugin //Custom check & Radio --> <script type="text/javascript" src="assets/js/ion-checkRadio/ion.checkRadio.min.js"></script> <!-- include grid.js // for equal Div height --> <script src="assets/js/grids.js"></script> <!-- include carousel slider plugin --> <script src="assets/js/owl.carousel.min.js"></script> <!-- jQuery minimalect // custom select --> <script src="assets/js/jquery.minimalect.min.js"></script> <!-- include touchspin.js // touch friendly input spinner component --> <script src="assets/js/bootstrap.touchspin.js"></script> <!-- include custom script for only homepage --> <script src="assets/js/home.js"></script> <!-- include custom script for site --> <script src="assets/js/script.js"></script> <script> </script> </body> </html>
networksoft/erp.gsuperclub
cart/HTML/index.html
HTML
apache-2.0
65,481
/* * Copyright (c) 2008-2021, Hazelcast, Inc. 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. */ package com.hazelcast.jet.impl.exception; import com.hazelcast.jet.JetException; import static com.hazelcast.jet.Util.idToString; /** * Thrown in response to operations sent from the coordinator, if the * target doesn't know the execution. */ public class ExecutionNotFoundException extends JetException { private static final long serialVersionUID = 1L; public ExecutionNotFoundException() { } public ExecutionNotFoundException(long executionId) { this("Execution " + idToString(executionId) + " not found"); } public ExecutionNotFoundException(String message) { super(message); } public ExecutionNotFoundException(String message, Throwable cause) { super(message, cause); } public ExecutionNotFoundException(Throwable cause) { super(cause); } }
jerrinot/hazelcast
hazelcast/src/main/java/com/hazelcast/jet/impl/exception/ExecutionNotFoundException.java
Java
apache-2.0
1,462
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/apigateway/model/GetStageRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::APIGateway::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; GetStageRequest::GetStageRequest() : m_restApiIdHasBeenSet(false), m_stageNameHasBeenSet(false) { } Aws::String GetStageRequest::SerializePayload() const { return ""; }
chiaming0914/awe-cpp-sdk
aws-cpp-sdk-apigateway/source/model/GetStageRequest.cpp
C++
apache-2.0
983
package org.apache.lucene.analysis.core; /* * 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. */ import java.io.IOException; import java.io.Reader; import java.io.StringReader; import java.util.Random; import org.apache.lucene.analysis.*; import org.apache.lucene.analysis.standard.StandardTokenizer; import org.apache.lucene.analysis.tokenattributes.CharTermAttribute; import org.apache.lucene.analysis.tokenattributes.PayloadAttribute; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.Version; public class TestAnalyzers extends BaseTokenStreamTestCase { public void testSimple() throws Exception { Analyzer a = new SimpleAnalyzer(TEST_VERSION_CURRENT); assertAnalyzesTo(a, "foo bar FOO BAR", new String[] { "foo", "bar", "foo", "bar" }); assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[] { "foo", "bar", "foo", "bar" }); assertAnalyzesTo(a, "foo.bar.FOO.BAR", new String[] { "foo", "bar", "foo", "bar" }); assertAnalyzesTo(a, "U.S.A.", new String[] { "u", "s", "a" }); assertAnalyzesTo(a, "C++", new String[] { "c" }); assertAnalyzesTo(a, "B2B", new String[] { "b", "b" }); assertAnalyzesTo(a, "2B", new String[] { "b" }); assertAnalyzesTo(a, "\"QUOTED\" word", new String[] { "quoted", "word" }); } public void testNull() throws Exception { Analyzer a = new WhitespaceAnalyzer(TEST_VERSION_CURRENT); assertAnalyzesTo(a, "foo bar FOO BAR", new String[] { "foo", "bar", "FOO", "BAR" }); assertAnalyzesTo(a, "foo bar . FOO <> BAR", new String[] { "foo", "bar", ".", "FOO", "<>", "BAR" }); assertAnalyzesTo(a, "foo.bar.FOO.BAR", new String[] { "foo.bar.FOO.BAR" }); assertAnalyzesTo(a, "U.S.A.", new String[] { "U.S.A." }); assertAnalyzesTo(a, "C++", new String[] { "C++" }); assertAnalyzesTo(a, "B2B", new String[] { "B2B" }); assertAnalyzesTo(a, "2B", new String[] { "2B" }); assertAnalyzesTo(a, "\"QUOTED\" word", new String[] { "\"QUOTED\"", "word" }); } public void testStop() throws Exception { Analyzer a = new StopAnalyzer(TEST_VERSION_CURRENT); assertAnalyzesTo(a, "foo bar FOO BAR", new String[] { "foo", "bar", "foo", "bar" }); assertAnalyzesTo(a, "foo a bar such FOO THESE BAR", new String[] { "foo", "bar", "foo", "bar" }); } void verifyPayload(TokenStream ts) throws IOException { PayloadAttribute payloadAtt = ts.getAttribute(PayloadAttribute.class); ts.reset(); for(byte b=1;;b++) { boolean hasNext = ts.incrementToken(); if (!hasNext) break; // System.out.println("id="+System.identityHashCode(nextToken) + " " + t); // System.out.println("payload=" + (int)nextToken.getPayload().toByteArray()[0]); assertEquals(b, payloadAtt.getPayload().bytes[0]); } } // Make sure old style next() calls result in a new copy of payloads public void testPayloadCopy() throws IOException { String s = "how now brown cow"; TokenStream ts; ts = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(s)); ts = new PayloadSetter(ts); verifyPayload(ts); ts = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader(s)); ts = new PayloadSetter(ts); verifyPayload(ts); } // LUCENE-1150: Just a compile time test, to ensure the // StandardAnalyzer constants remain publicly accessible @SuppressWarnings("unused") public void _testStandardConstants() { int x = StandardTokenizer.ALPHANUM; x = StandardTokenizer.APOSTROPHE; x = StandardTokenizer.ACRONYM; x = StandardTokenizer.COMPANY; x = StandardTokenizer.EMAIL; x = StandardTokenizer.HOST; x = StandardTokenizer.NUM; x = StandardTokenizer.CJ; String[] y = StandardTokenizer.TOKEN_TYPES; } private static class LowerCaseWhitespaceAnalyzer extends Analyzer { @Override public TokenStreamComponents createComponents(String fieldName, Reader reader) { Tokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader); return new TokenStreamComponents(tokenizer, new LowerCaseFilter(TEST_VERSION_CURRENT, tokenizer)); } } /** * Test that LowercaseFilter handles entire unicode range correctly */ public void testLowerCaseFilter() throws IOException { Analyzer a = new LowerCaseWhitespaceAnalyzer(); // BMP assertAnalyzesTo(a, "AbaCaDabA", new String[] { "abacadaba" }); // supplementary assertAnalyzesTo(a, "\ud801\udc16\ud801\udc16\ud801\udc16\ud801\udc16", new String[] {"\ud801\udc3e\ud801\udc3e\ud801\udc3e\ud801\udc3e"}); assertAnalyzesTo(a, "AbaCa\ud801\udc16DabA", new String[] { "abaca\ud801\udc3edaba" }); // unpaired lead surrogate assertAnalyzesTo(a, "AbaC\uD801AdaBa", new String [] { "abac\uD801adaba" }); // unpaired trail surrogate assertAnalyzesTo(a, "AbaC\uDC16AdaBa", new String [] { "abac\uDC16adaba" }); } /** * Test that LowercaseFilter handles the lowercasing correctly if the term * buffer has a trailing surrogate character leftover and the current term in * the buffer ends with a corresponding leading surrogate. */ public void testLowerCaseFilterLowSurrogateLeftover() throws IOException { // test if the limit of the termbuffer is correctly used with supplementary // chars WhitespaceTokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, new StringReader("BogustermBogusterm\udc16")); LowerCaseFilter filter = new LowerCaseFilter(TEST_VERSION_CURRENT, tokenizer); assertTokenStreamContents(filter, new String[] {"bogustermbogusterm\udc16"}); filter.reset(); String highSurEndingUpper = "BogustermBoguster\ud801"; String highSurEndingLower = "bogustermboguster\ud801"; tokenizer.setReader(new StringReader(highSurEndingUpper)); assertTokenStreamContents(filter, new String[] {highSurEndingLower}); assertTrue(filter.hasAttribute(CharTermAttribute.class)); char[] termBuffer = filter.getAttribute(CharTermAttribute.class).buffer(); int length = highSurEndingLower.length(); assertEquals('\ud801', termBuffer[length - 1]); assertEquals('\udc3e', termBuffer[length]); } public void testLowerCaseTokenizer() throws IOException { StringReader reader = new StringReader("Tokenizer \ud801\udc1ctest"); LowerCaseTokenizer tokenizer = new LowerCaseTokenizer(TEST_VERSION_CURRENT, reader); assertTokenStreamContents(tokenizer, new String[] { "tokenizer", "\ud801\udc44test" }); } /** @deprecated (3.1) */ @Deprecated public void testLowerCaseTokenizerBWCompat() throws IOException { StringReader reader = new StringReader("Tokenizer \ud801\udc1ctest"); LowerCaseTokenizer tokenizer = new LowerCaseTokenizer(Version.LUCENE_30, reader); assertTokenStreamContents(tokenizer, new String[] { "tokenizer", "test" }); } public void testWhitespaceTokenizer() throws IOException { StringReader reader = new StringReader("Tokenizer \ud801\udc1ctest"); WhitespaceTokenizer tokenizer = new WhitespaceTokenizer(TEST_VERSION_CURRENT, reader); assertTokenStreamContents(tokenizer, new String[] { "Tokenizer", "\ud801\udc1ctest" }); } /** @deprecated (3.1) */ @Deprecated public void testWhitespaceTokenizerBWCompat() throws IOException { StringReader reader = new StringReader("Tokenizer \ud801\udc1ctest"); WhitespaceTokenizer tokenizer = new WhitespaceTokenizer(Version.LUCENE_30, reader); assertTokenStreamContents(tokenizer, new String[] { "Tokenizer", "\ud801\udc1ctest" }); } /** blast some random strings through the analyzer */ public void testRandomStrings() throws Exception { checkRandomData(random(), new WhitespaceAnalyzer(TEST_VERSION_CURRENT), 1000*RANDOM_MULTIPLIER); checkRandomData(random(), new SimpleAnalyzer(TEST_VERSION_CURRENT), 1000*RANDOM_MULTIPLIER); checkRandomData(random(), new StopAnalyzer(TEST_VERSION_CURRENT), 1000*RANDOM_MULTIPLIER); } /** blast some random large strings through the analyzer */ public void testRandomHugeStrings() throws Exception { Random random = random(); checkRandomData(random, new WhitespaceAnalyzer(TEST_VERSION_CURRENT), 100*RANDOM_MULTIPLIER, 8192); checkRandomData(random, new SimpleAnalyzer(TEST_VERSION_CURRENT), 100*RANDOM_MULTIPLIER, 8192); checkRandomData(random, new StopAnalyzer(TEST_VERSION_CURRENT), 100*RANDOM_MULTIPLIER, 8192); } } final class PayloadSetter extends TokenFilter { PayloadAttribute payloadAtt; public PayloadSetter(TokenStream input) { super(input); payloadAtt = addAttribute(PayloadAttribute.class); } byte[] data = new byte[1]; BytesRef p = new BytesRef(data,0,1); @Override public boolean incrementToken() throws IOException { boolean hasNext = input.incrementToken(); if (!hasNext) return false; payloadAtt.setPayload(p); // reuse the payload / byte[] data[0]++; return true; } }
pkarmstr/NYBC
solr-4.2.1/lucene/analysis/common/src/test/org/apache/lucene/analysis/core/TestAnalyzers.java
Java
apache-2.0
10,135
/* * #%L * SparkCommerce Common Libraries * %% * Copyright (C) 2015 Spark Commerce * %% */ package org.sparkcommerce.common.enumeration.domain; import java.io.Serializable; import java.util.List; public interface DataDrivenEnumeration extends Serializable { public Long getId(); public void setId(Long id); public String getKey(); public void setKey(String key); public Boolean getModifiable(); public void setModifiable(Boolean modifiable); /** * Gets list of values associated with this enumeration. */ public List<DataDrivenEnumerationValue> getEnumValues(); /** * Sets list of values associated with this enumeration. */ public void setEnumValues(List<DataDrivenEnumerationValue> enumValues); /** * Incorrectly named, kept purely for API consistency * @deprecated use {@link #getEnumValues()} instead */ @Deprecated public List<DataDrivenEnumerationValue> getOrderItems(); /** * Incorrectly named, kept purely for API consistency * @deprecated use {@link #setEnumValues()} instead */ @Deprecated public void setOrderItems(List<DataDrivenEnumerationValue> orderItems); }
akdasari/SparkCommon
src/main/java/org/sparkcommerce/common/enumeration/domain/DataDrivenEnumeration.java
Java
apache-2.0
1,213
module.exports = function (grunt) { 'use strict'; // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), jsfiles: [ 'src/js/*.js', 'Gruntfile.js', '!*.min.js' ], watch: { js: { files: ['src/js/*.js'], tasks: ['newer:jshint:all'] }, jsTest: { files: ['test/unit/*.js'], tasks: ['newer:jshint:test', 'karma'] }, styles: { files: ['src/css/*.css'], tasks: ['autoprefixer'] }, gruntfile: { files: ['Gruntfile.js'] }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ 'examples/{,*/}*.html', 'examples/img/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', 'src/css/(,*/}*.css' ] } }, connect: { options: { port: 9000, // Change this to '*' to access the server from outside. hostname: 'localhost', livereload: 35729 }, livereload: { options: { open: true, keepalive: true, base: [ 'examples', 'bower_components', 'src' ] } }, test: { options: { port: 9001, base: [ 'examples', 'bower_components', 'src', 'test/' ] } }, dist: { options: { base: 'dist/' } } }, jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', 'src/{,*/}*.js' ], test: { options: { jshintrc: 'test/.jshintrc' }, src: ['test/unit/{,*/}*.js', 'test/e2e/{,*/}.js'] } }, autoprefixer: { options: { browsers: ['last 5 version', 'ie >= 8'] }, dist: { files: [{ expand: true, cwd: 'dist/css/', src: '{,*/}*.css', dest: 'dist/css/' }] } }, // Allow the use of non-minsafe AngularJS files. Automatically makes it // minsafe compatible so Uglify does not destroy the ng references ngmin: { dist: { files: [{ expand: true, cwd: 'src/js/', src: '{,*/}*.js', dest: 'src/js/' }] } }, cssmin: { dist: { files: { 'dist/css/ng-magnify.min.css': ['src/css/ng-magnify.css'] } } }, uglify: { dist: { files: { 'dist/js/ng-magnify.min.js': ['src/js/ng-magnify.js'] } } }, karma: { unit: { configFile: 'karma.conf.js', singleRun: true } /* custom: { configFile: 'karma.conf.js', autoWatch: true, singleRun: false } */ } }); grunt.registerTask('serve', [ 'autoprefixer', 'connect:livereload', 'watch' ]); grunt.registerTask('test', [ 'autoprefixer', 'connect:test', 'karma' ]); grunt.registerTask('build', [ 'autoprefixer', 'cssmin', 'uglify' ]); grunt.registerTask('default', [ 'newer:jshint', 'test', 'build' ]); };
sasa1kg/paisAdmin
bower_components/ng-magnify/Gruntfile.js
JavaScript
apache-2.0
3,489
--- title: calicoctl node checksystem redirect_from: latest/reference/calicoctl/commands/node/checksystem --- This section describes the `calicoctl node checksystem` command. Read the [calicoctl Overview]({{site.baseurl}}/{{page.version}}/reference/calicoctl) for a full list of calicoctl commands. ## Displaying the help text for 'calicoctl checksystem' command Run `calicoctl node checksystem --help` to display the following help menu for the command. ``` Usage: calicoctl node checksystem Options: -h --help Show this screen. Description: Check the compatibility of this compute host to run a Calico node instance. ``` ### Examples: ``` $ calicoctl checksystem WARNING: Unable to detect the xt_set module. Load with `modprobe xt_set` WARNING: Unable to detect the ipip module. Load with `modprobe ipip` ```
gunjan5/calico
v3.0/reference/calicoctl/commands/node/checksystem.md
Markdown
apache-2.0
844
/// \file LanguagePages.h \brief Interface to the LanguagePage object. /// /// Contains the interface to the object responsible for language specific /// pages. /// /// 2007 Sep 17 15:09:35 /// $ID$ /// $Author: John Nanney$ /// $Workfile$ /// $Log$ #ifndef LANGUAGEPAGES_H #define LANGUAGEPAGES_H #include "Lang.h" class LanguagePages { public: /// Constructor, initializes object. LanguagePages(); /// Destructor, cleans up when object is destroyed. ~LanguagePages(); /// Sets a language page from a given buffer. /// /// It is up to the caller to insure that the page text /// is formatted properly, no parsing is done here. /// /// @param lang the page's language /// @param pageText the page's text /// @param handOver whether or not the method will assume control of the buffer /// /// @return true on success, false on memory allocation failure bool setLanguagePage(uint8_t lang, uint8_t *pageText, bool handOver = false); /// Sets a header entry from a given buffer. /// /// @param lang the header's language /// @param pageText the header's text /// @param handOver whether or not the method will assume control of the buffer /// /// @return true on success, false on memory allocation failure bool setLanguageHeader(uint8_t lang, uint8_t *pageText, bool handOver); /// Sets a footer entry from a given buffer. /// /// @param lang the footer's language /// @param pageText the footer's text /// @param handOver whether or not the method will assume control of the buffer /// /// @return true on success, false on memory allocation failure bool setLanguageFooter(uint8_t lang, uint8_t *pageText, bool handOver); /// Returns page text for a given language. /// /// @param lang the language /// @param *len if not NULL, filled with the length of the page text /// /// @return the page text, or NULL if no entry uint8_t *getLanguagePage(uint8_t lang, long *len = NULL); /// Returns header text for a given language. /// /// @param lang the language /// @param *len if not NULL, filled with the length of the header text /// /// @return the header text, or NULL if no entry uint8_t *getLanguageHeader(uint8_t lang, long *len = NULL); /// Returns footer text for a given language. /// /// @param lang the language /// @param *len if not NULL, filled with the length of the footer text /// /// @return the footer text, or NULL if no entry uint8_t *getLanguageFooter(uint8_t lang, long *len = NULL); /// Reload all page, header, and footer entries from disk. void reloadPages(void); private: /// The array of page text entries. uint8_t *m_languagePages[MAX_LANGUAGES]; /// The array of header text entries. uint8_t *m_languageHeaders[MAX_LANGUAGES]; /// The array of footer text entries. uint8_t *m_languageFooters[MAX_LANGUAGES]; /// Array of sizes of page text entries. /// Includes NULL, a value indicates ownership. uint32_t m_languageAllocated[MAX_LANGUAGES]; /// Array of sizes of header text entries /// Includes NULL, a value indicates ownership. uint32_t m_languageAllocatedHeaders[MAX_LANGUAGES]; /// Array of sizes of footer text entries /// Includes NULL, a value indicates ownership. uint32_t m_languageAllocatedFooters[MAX_LANGUAGES]; /// Array of sizes of page text entries. uint32_t m_PageSize[MAX_LANGUAGES]; /// Array of sizes of header text entries. uint32_t m_HeaderSize[MAX_LANGUAGES]; /// Array of sizes of footer text entries. uint32_t m_FooterSize[MAX_LANGUAGES]; /// Flag to protect entries during load. bool m_loading; }; extern LanguagePages g_languagePages; int uint8strlen(uint8_t *str); #endif // LANGUAGEPAGES_H
karuradev/open-source-search-engine
LanguagePages.h
C
apache-2.0
3,727
# # Copyright (c) 2008-2015 Citrix Systems, 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. # from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_resource from nssrc.com.citrix.netscaler.nitro.resource.base.base_resource import base_response from nssrc.com.citrix.netscaler.nitro.service.options import options from nssrc.com.citrix.netscaler.nitro.exception.nitro_exception import nitro_exception from nssrc.com.citrix.netscaler.nitro.util.nitro_util import nitro_util class clusternodegroup(base_resource) : """ Configuration for Node group object type resource. """ def __init__(self) : self._name = "" self._strict = "" self._sticky = "" self._currentnodemask = 0 self._backupnodemask = 0 self._boundedentitiescntfrompe = 0 self._activelist = [] self._backuplist = [] self.___count = 0 @property def name(self) : ur"""Name of the nodegroup. The name uniquely identifies the nodegroup on the cluster.<br/>Minimum length = 1. """ try : return self._name except Exception as e: raise e @name.setter def name(self, name) : ur"""Name of the nodegroup. The name uniquely identifies the nodegroup on the cluster.<br/>Minimum length = 1 """ try : self._name = name except Exception as e: raise e @property def strict(self) : ur"""Specifies whether cluster nodes, that are not part of the nodegroup, will be used as backup for the nodegroup. * Enabled - When one of the nodes goes down, no other cluster node is picked up to replace it. When the node comes up, it will continue being part of the nodegroup. * Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.<br/>Default value: NO<br/>Possible values = YES, NO. """ try : return self._strict except Exception as e: raise e @strict.setter def strict(self, strict) : ur"""Specifies whether cluster nodes, that are not part of the nodegroup, will be used as backup for the nodegroup. * Enabled - When one of the nodes goes down, no other cluster node is picked up to replace it. When the node comes up, it will continue being part of the nodegroup. * Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.<br/>Default value: NO<br/>Possible values = YES, NO """ try : self._strict = strict except Exception as e: raise e @property def sticky(self) : ur"""Only one node can be bound to nodegroup with this option enabled. It specifies whether to prempt the traffic for the entities bound to nodegroup when owner node goes down and rejoins the cluster. * Enabled - When owner node goes down, backup node will become the owner node and takes the traffic for the entities bound to the nodegroup. When bound node rejoins the cluster, traffic for the entities bound to nodegroup will not be steered back to this bound node. Current owner will have the ownership till it goes down. * Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.<br/>Default value: NO<br/>Possible values = YES, NO. """ try : return self._sticky except Exception as e: raise e @sticky.setter def sticky(self, sticky) : ur"""Only one node can be bound to nodegroup with this option enabled. It specifies whether to prempt the traffic for the entities bound to nodegroup when owner node goes down and rejoins the cluster. * Enabled - When owner node goes down, backup node will become the owner node and takes the traffic for the entities bound to the nodegroup. When bound node rejoins the cluster, traffic for the entities bound to nodegroup will not be steered back to this bound node. Current owner will have the ownership till it goes down. * Disabled - When one of the nodes goes down, a non-nodegroup cluster node is picked up and acts as part of the nodegroup. When the original node of the nodegroup comes up, the backup node will be replaced.<br/>Default value: NO<br/>Possible values = YES, NO """ try : self._sticky = sticky except Exception as e: raise e @property def currentnodemask(self) : ur"""Bitmap of current nodes in this nodegroup. """ try : return self._currentnodemask except Exception as e: raise e @property def backupnodemask(self) : ur"""Bitmap of backup nodes in this nodegroup. """ try : return self._backupnodemask except Exception as e: raise e @property def boundedentitiescntfrompe(self) : ur"""Count of bounded entities to this nodegroup accoding to PE. """ try : return self._boundedentitiescntfrompe except Exception as e: raise e @property def activelist(self) : ur"""Active node list of this nodegroup. """ try : return self._activelist except Exception as e: raise e @property def backuplist(self) : ur"""Backup node list of this nodegroup. """ try : return self._backuplist except Exception as e: raise e def _get_nitro_response(self, service, response) : ur""" converts nitro response into object and returns the object array in case of get request. """ try : result = service.payload_formatter.string_to_resource(clusternodegroup_response, response, self.__class__.__name__) if(result.errorcode != 0) : if (result.errorcode == 444) : service.clear_session(self) if result.severity : if (result.severity == "ERROR") : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) else : raise nitro_exception(result.errorcode, str(result.message), str(result.severity)) return result.clusternodegroup except Exception as e : raise e def _get_object_name(self) : ur""" Returns the value of object identifier argument """ try : if self.name is not None : return str(self.name) return None except Exception as e : raise e @classmethod def add(cls, client, resource) : ur""" Use this API to add clusternodegroup. """ try : if type(resource) is not list : addresource = clusternodegroup() addresource.name = resource.name addresource.strict = resource.strict addresource.sticky = resource.sticky return addresource.add_resource(client) else : if (resource and len(resource) > 0) : addresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : addresources[i].name = resource[i].name addresources[i].strict = resource[i].strict addresources[i].sticky = resource[i].sticky result = cls.add_bulk_request(client, addresources) return result except Exception as e : raise e @classmethod def update(cls, client, resource) : ur""" Use this API to update clusternodegroup. """ try : if type(resource) is not list : updateresource = clusternodegroup() updateresource.name = resource.name updateresource.strict = resource.strict return updateresource.update_resource(client) else : if (resource and len(resource) > 0) : updateresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : updateresources[i].name = resource[i].name updateresources[i].strict = resource[i].strict result = cls.update_bulk_request(client, updateresources) return result except Exception as e : raise e @classmethod def unset(cls, client, resource, args) : ur""" Use this API to unset the properties of clusternodegroup resource. Properties that need to be unset are specified in args array. """ try : if type(resource) is not list : unsetresource = clusternodegroup() if type(resource) != type(unsetresource): unsetresource.name = resource else : unsetresource.name = resource.name return unsetresource.unset_resource(client, args) else : if type(resource[0]) != cls : if (resource and len(resource) > 0) : unsetresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : unsetresources[i].name = resource[i] else : if (resource and len(resource) > 0) : unsetresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : unsetresources[i].name = resource[i].name result = cls.unset_bulk_request(client, unsetresources, args) return result except Exception as e : raise e @classmethod def delete(cls, client, resource) : ur""" Use this API to delete clusternodegroup. """ try : if type(resource) is not list : deleteresource = clusternodegroup() if type(resource) != type(deleteresource): deleteresource.name = resource else : deleteresource.name = resource.name return deleteresource.delete_resource(client) else : if type(resource[0]) != cls : if (resource and len(resource) > 0) : deleteresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : deleteresources[i].name = resource[i] else : if (resource and len(resource) > 0) : deleteresources = [ clusternodegroup() for _ in range(len(resource))] for i in range(len(resource)) : deleteresources[i].name = resource[i].name result = cls.delete_bulk_request(client, deleteresources) return result except Exception as e : raise e @classmethod def get(cls, client, name="", option_="") : ur""" Use this API to fetch all the clusternodegroup resources that are configured on netscaler. """ try : if not name : obj = clusternodegroup() response = obj.get_resources(client, option_) else : if type(name) != cls : if type(name) is not list : obj = clusternodegroup() obj.name = name response = obj.get_resource(client, option_) else : if name and len(name) > 0 : response = [clusternodegroup() for _ in range(len(name))] obj = [clusternodegroup() for _ in range(len(name))] for i in range(len(name)) : obj[i] = clusternodegroup() obj[i].name = name[i] response[i] = obj[i].get_resource(client, option_) return response except Exception as e : raise e @classmethod def get_filtered(cls, client, filter_) : ur""" Use this API to fetch filtered set of clusternodegroup resources. filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = clusternodegroup() option_ = options() option_.filter = filter_ response = obj.getfiltered(client, option_) return response except Exception as e : raise e @classmethod def count(cls, client) : ur""" Use this API to count the clusternodegroup resources configured on NetScaler. """ try : obj = clusternodegroup() option_ = options() option_.count = True response = obj.get_resources(client, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e : raise e @classmethod def count_filtered(cls, client, filter_) : ur""" Use this API to count filtered the set of clusternodegroup resources. Filter string should be in JSON format.eg: "port:80,servicetype:HTTP". """ try : obj = clusternodegroup() option_ = options() option_.count = True option_.filter = filter_ response = obj.getfiltered(client, option_) if response : return response[0].__dict__['___count'] return 0 except Exception as e : raise e class Strict: YES = "YES" NO = "NO" class Sticky: YES = "YES" NO = "NO" class clusternodegroup_response(base_response) : def __init__(self, length=1) : self.clusternodegroup = [] self.errorcode = 0 self.message = "" self.severity = "" self.sessionid = "" self.clusternodegroup = [clusternodegroup() for _ in range(length)]
benfinke/ns_python
nssrc/com/citrix/netscaler/nitro/resource/config/cluster/clusternodegroup.py
Python
apache-2.0
12,615
/* * 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. */ /** * @author Anton Avtamonov */ package javax.swing.event; import java.util.EventListener; import javax.swing.tree.ExpandVetoException; public interface TreeWillExpandListener extends EventListener { void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException; void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException; }
freeVM/freeVM
enhanced/java/classlib/modules/swing/src/main/java/common/javax/swing/event/TreeWillExpandListener.java
Java
apache-2.0
1,179
--- id: version-2.7.1-kubernetes-helm title: Get started in Kubernetes sidebar_label: Run Pulsar in Kubernetes original_id: kubernetes-helm --- This section guides you through every step of installing and running Apache Pulsar with Helm on Kubernetes quickly, including the following sections: - Install the Apache Pulsar on Kubernetes using Helm - Start and stop Apache Pulsar - Create topics using `pulsar-admin` - Produce and consume messages using Pulsar clients - Monitor Apache Pulsar status with Prometheus and Grafana For deploying a Pulsar cluster for production usage, read the documentation on [how to configure and install a Pulsar Helm chart](helm-deploy.md). ## Prerequisite - Kubernetes server 1.14.0+ - kubectl 1.14.0+ - Helm 3.0+ > #### Tip > For the following steps, step 2 and step 3 are for **developers** and step 4 and step 5 are for **administrators**. ## Step 0: Prepare a Kubernetes cluster Before installing a Pulsar Helm chart, you have to create a Kubernetes cluster. You can follow [the instructions](helm-prepare.md) to prepare a Kubernetes cluster. We use [Minikube](https://minikube.sigs.k8s.io/docs/start/) in this quick start guide. To prepare a Kubernetes cluster, follow these steps: 1. Create a Kubernetes cluster on Minikube. ```bash minikube start --memory=8192 --cpus=4 --kubernetes-version=<k8s-version> ``` The `<k8s-version>` can be any [Kubernetes version supported by your Minikube installation](https://minikube.sigs.k8s.io/docs/reference/configuration/kubernetes/), such as `v1.16.1`. 2. Set `kubectl` to use Minikube. ```bash kubectl config use-context minikube ``` 3. To use the [Kubernetes Dashboard](https://kubernetes.io/docs/tasks/access-application-cluster/web-ui-dashboard/) with the local Kubernetes cluster on Minikube, enter the command below: ```bash minikube dashboard ``` The command automatically triggers opening a webpage in your browser. ## Step 1: Install Pulsar Helm chart 0. Add Pulsar charts repo. ```bash helm repo add apache https://pulsar.apache.org/charts ``` ```bash helm repo update ``` 1. Clone the Pulsar Helm chart repository. ```bash git clone https://github.com/apache/pulsar-helm-chart cd pulsar-helm-chart ``` 2. Run the script `prepare_helm_release.sh` to create secrets required for installing the Apache Pulsar Helm chart. The username `pulsar` and password `pulsar` are used for logging into the Grafana dashboard and Pulsar Manager. ```bash ./scripts/pulsar/prepare_helm_release.sh \ -n pulsar \ -k pulsar-mini \ -c ``` 3. Use the Pulsar Helm chart to install a Pulsar cluster to Kubernetes. > **NOTE** > You need to specify `--set initialize=true` when installing Pulsar the first time. This command installs and starts Apache Pulsar. ```bash helm install \ --values examples/values-minikube.yaml \ --set initialize=true \ --namespace pulsar \ pulsar-mini apache/pulsar ``` 4. Check the status of all pods. ```bash kubectl get pods -n pulsar ``` If all pods start up successfully, you can see that the `STATUS` is changed to `Running` or `Completed`. **Output** ```bash NAME READY STATUS RESTARTS AGE pulsar-mini-bookie-0 1/1 Running 0 9m27s pulsar-mini-bookie-init-5gphs 0/1 Completed 0 9m27s pulsar-mini-broker-0 1/1 Running 0 9m27s pulsar-mini-grafana-6b7bcc64c7-4tkxd 1/1 Running 0 9m27s pulsar-mini-prometheus-5fcf5dd84c-w8mgz 1/1 Running 0 9m27s pulsar-mini-proxy-0 1/1 Running 0 9m27s pulsar-mini-pulsar-init-t7cqt 0/1 Completed 0 9m27s pulsar-mini-pulsar-manager-9bcbb4d9f-htpcs 1/1 Running 0 9m27s pulsar-mini-toolset-0 1/1 Running 0 9m27s pulsar-mini-zookeeper-0 1/1 Running 0 9m27s ``` 5. Check the status of all services in the namespace `pulsar`. ```bash kubectl get services -n pulsar ``` **Output** ```bash NAME TYPE CLUSTER-IP EXTERNAL-IP PORT(S) AGE pulsar-mini-bookie ClusterIP None <none> 3181/TCP,8000/TCP 11m pulsar-mini-broker ClusterIP None <none> 8080/TCP,6650/TCP 11m pulsar-mini-grafana LoadBalancer 10.106.141.246 <pending> 3000:31905/TCP 11m pulsar-mini-prometheus ClusterIP None <none> 9090/TCP 11m pulsar-mini-proxy LoadBalancer 10.97.240.109 <pending> 80:32305/TCP,6650:31816/TCP 11m pulsar-mini-pulsar-manager LoadBalancer 10.103.192.175 <pending> 9527:30190/TCP 11m pulsar-mini-toolset ClusterIP None <none> <none> 11m pulsar-mini-zookeeper ClusterIP None <none> 2888/TCP,3888/TCP,2181/TCP 11m ``` ## Step 2: Use pulsar-admin to create Pulsar tenants/namespaces/topics `pulsar-admin` is the CLI (command-Line Interface) tool for Pulsar. In this step, you can use `pulsar-admin` to create resources, including tenants, namespaces, and topics. 1. Enter the `toolset` container. ```bash kubectl exec -it -n pulsar pulsar-mini-toolset-0 -- /bin/bash ``` 2. In the `toolset` container, create a tenant named `apache`. ```bash bin/pulsar-admin tenants create apache ``` Then you can list the tenants to see if the tenant is created successfully. ```bash bin/pulsar-admin tenants list ``` You should see a similar output as below. The tenant `apache` has been successfully created. ```bash "apache" "public" "pulsar" ``` 3. In the `toolset` container, create a namespace named `pulsar` in the tenant `apache`. ```bash bin/pulsar-admin namespaces create apache/pulsar ``` Then you can list the namespaces of tenant `apache` to see if the namespace is created successfully. ```bash bin/pulsar-admin namespaces list apache ``` You should see a similar output as below. The namespace `apache/pulsar` has been successfully created. ```bash "apache/pulsar" ``` 4. In the `toolset` container, create a topic `test-topic` with `4` partitions in the namespace `apache/pulsar`. ```bash bin/pulsar-admin topics create-partitioned-topic apache/pulsar/test-topic -p 4 ``` 5. In the `toolset` container, list all the partitioned topics in the namespace `apache/pulsar`. ```bash bin/pulsar-admin topics list-partitioned-topics apache/pulsar ``` Then you can see all the partitioned topics in the namespace `apache/pulsar`. ```bash "persistent://apache/pulsar/test-topic" ``` ## Step 3: Use Pulsar client to produce and consume messages You can use the Pulsar client to create producers and consumers to produce and consume messages. By default, the Pulsar Helm chart exposes the Pulsar cluster through a Kubernetes `LoadBalancer`. In Minikube, you can use the following command to check the proxy service. ```bash kubectl get services -n pulsar | grep pulsar-mini-proxy ``` You will see a similar output as below. ```bash pulsar-mini-proxy LoadBalancer 10.97.240.109 <pending> 80:32305/TCP,6650:31816/TCP 28m ``` This output tells what are the node ports that Pulsar cluster's binary port and HTTP port are mapped to. The port after `80:` is the HTTP port while the port after `6650:` is the binary port. Then you can find the IP address and exposed ports of your Minikube server by running the following command. ```bash minikube service pulsar-mini-proxy -n pulsar ``` **Output** ```bash |-----------|-------------------|-------------|-------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|-------------------|-------------|-------------------------| | pulsar | pulsar-mini-proxy | http/80 | http://172.17.0.4:32305 | | | | pulsar/6650 | http://172.17.0.4:31816 | |-----------|-------------------|-------------|-------------------------| 🏃 Starting tunnel for service pulsar-mini-proxy. |-----------|-------------------|-------------|------------------------| | NAMESPACE | NAME | TARGET PORT | URL | |-----------|-------------------|-------------|------------------------| | pulsar | pulsar-mini-proxy | | http://127.0.0.1:61853 | | | | | http://127.0.0.1:61854 | |-----------|-------------------|-------------|------------------------| ``` At this point, you can get the service URLs to connect to your Pulsar client. Here are URL examples: ``` webServiceUrl=http://127.0.0.1:61853/ brokerServiceUrl=pulsar://127.0.0.1:61854/ ``` Then you can proceed with the following steps: 1. Download the Apache Pulsar tarball from the [downloads page](https://pulsar.apache.org/en/download/). 2. Decompress the tarball based on your download file. ```bash tar -xf <file-name>.tar.gz ``` 3. Expose `PULSAR_HOME`. (1) Enter the directory of the decompressed download file. (2) Expose `PULSAR_HOME` as the environment variable. ```bash export PULSAR_HOME=$(pwd) ``` 4. Configure the Pulsar client. In the `${PULSAR_HOME}/conf/client.conf` file, replace `webServiceUrl` and `brokerServiceUrl` with the service URLs you get from the above steps. 5. Create a subscription to consume messages from `apache/pulsar/test-topic`. ```bash bin/pulsar-client consume -s sub apache/pulsar/test-topic -n 0 ``` 6. Open a new terminal. In the new terminal, create a producer and send 10 messages to the `test-topic` topic. ```bash bin/pulsar-client produce apache/pulsar/test-topic -m "---------hello apache pulsar-------" -n 10 ``` 7. Verify the results. - From the producer side **Output** The messages have been produced successfully. ```bash 18:15:15.489 [main] INFO org.apache.pulsar.client.cli.PulsarClientTool - 10 messages successfully produced ``` - From the consumer side **Output** At the same time, you can receive the messages as below. ```bash ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ----- got message ----- ---------hello apache pulsar------- ``` ## Step 4: Use Pulsar Manager to manage the cluster [Pulsar Manager](administration-pulsar-manager.md) is a web-based GUI management tool for managing and monitoring Pulsar. 1. By default, the `Pulsar Manager` is exposed as a separate `LoadBalancer`. You can open the Pulsar Manager UI using the following command: ```bash minikube service -n pulsar pulsar-mini-pulsar-manager ``` 2. The Pulsar Manager UI will be open in your browser. You can use the username `pulsar` and password `pulsar` to log into Pulsar Manager. 3. In Pulsar Manager UI, you can create an environment. - Click `New Environment` button in the top-left corner. - Type `pulsar-mini` for the field `Environment Name` in the popup window. - Type `http://pulsar-mini-broker:8080` for the field `Service URL` in the popup window. - Click `Confirm` button in the popup window. 4. After successfully created an environment, you are redirected to the `tenants` page of that environment. Then you can create `tenants`, `namespaces` and `topics` using the Pulsar Manager. ## Step 5: Use Prometheus and Grafana to monitor cluster Grafana is an open-source visualization tool, which can be used for visualizing time series data into dashboards. 1. By default, the Grafana is exposed as a separate `LoadBalancer`. You can open the Grafana UI using the following command: ```bash minikube service pulsar-mini-grafana -n pulsar ``` 2. The Grafana UI is open in your browser. You can use the username `pulsar` and password `pulsar` to log into the Grafana Dashboard. 3. You can view dashboards for different components of a Pulsar cluster.
massakam/pulsar
site2/website/versioned_docs/version-2.7.1/getting-started-helm.md
Markdown
apache-2.0
13,211
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/gamelift/GameLift_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace GameLift { namespace Model { enum class GameServerProtectionPolicy { NOT_SET, NO_PROTECTION, FULL_PROTECTION }; namespace GameServerProtectionPolicyMapper { AWS_GAMELIFT_API GameServerProtectionPolicy GetGameServerProtectionPolicyForName(const Aws::String& name); AWS_GAMELIFT_API Aws::String GetNameForGameServerProtectionPolicy(GameServerProtectionPolicy value); } // namespace GameServerProtectionPolicyMapper } // namespace Model } // namespace GameLift } // namespace Aws
aws/aws-sdk-cpp
aws-cpp-sdk-gamelift/include/aws/gamelift/model/GameServerProtectionPolicy.h
C
apache-2.0
751
/* * Copyright 2012 Harald Wellmann. * * 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.ops4j.pax.cdi.test; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.not; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; import static org.ops4j.pax.cdi.test.support.TestConfiguration.cdiProviderBundles; import static org.ops4j.pax.cdi.test.support.TestConfiguration.paxCdiProviderAdapter; import static org.ops4j.pax.cdi.test.support.TestConfiguration.paxCdiProviderWebAdapter; import static org.ops4j.pax.cdi.test.support.TestConfiguration.paxWebBundles; import static org.ops4j.pax.cdi.test.support.TestConfiguration.regressionDefaults; import static org.ops4j.pax.cdi.test.support.TestConfiguration.workspaceBundle; import static org.ops4j.pax.exam.CoreOptions.mavenBundle; import static org.ops4j.pax.exam.CoreOptions.options; import static org.ops4j.pax.exam.CoreOptions.systemProperty; import javax.inject.Inject; import javax.servlet.ServletContext; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.ops4j.pax.cdi.api.Info; import org.ops4j.pax.cdi.spi.CdiContainer; import org.ops4j.pax.cdi.spi.CdiContainerFactory; import org.ops4j.pax.exam.Configuration; import org.ops4j.pax.exam.Option; import org.ops4j.pax.exam.junit.PaxExam; import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy; import org.ops4j.pax.exam.spi.reactors.PerClass; import org.ops4j.pax.exam.util.Filter; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.client.apache.ApacheHttpClient; import com.sun.jersey.client.apache.config.ApacheHttpClientConfig; import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig; @RunWith(PaxExam.class) @ExamReactorStrategy(PerClass.class) public class ServletTest { @Inject @Filter(timeout = 100000000) private CdiContainerFactory containerFactory; @Inject @Filter(timeout = 100000000) private CdiContainer container; @Inject @Filter(timeout = 100000000) private ServletContext servletContext; private String httpPort = System.getProperty("org.osgi.service.http.port", "8181"); @Configuration public Option[] config() { return options( regressionDefaults(), // doesn't work for WABs // workspaceBundle("org.ops4j.pax.cdi", "pax-cdi-samples/pax-cdi-sample1-web"), workspaceBundle("org.ops4j.pax.cdi.samples", "pax-cdi-sample1"), mavenBundle("org.ops4j.pax.cdi.samples", "pax-cdi-sample1-web", Info.getPaxCdiVersion()), cdiProviderBundles(), paxCdiProviderAdapter(), paxCdiProviderWebAdapter(), // Pax Web systemProperty("org.osgi.service.http.port").value(httpPort), paxWebBundles(), mavenBundle("com.sun.jersey", "jersey-core").version("1.13"), mavenBundle("com.sun.jersey", "jersey-client").version("1.13"), mavenBundle("com.sun.jersey.contribs", "jersey-apache-client").version("1.13"), mavenBundle("org.apache.servicemix.bundles", "org.apache.servicemix.bundles.commons-httpclient", "3.1_7"), mavenBundle("commons-codec", "commons-codec", "1.6"), mavenBundle("org.slf4j", "jcl-over-slf4j", "1.6.0")); } @Before public void before() { // injecting container and servletContext guarantees that initialization has completed // before running the tests assertThat(container, is(notNullValue())); assertThat(servletContext, is(notNullValue())); } @Test public void checkContainers() { assertThat(containerFactory.getContainers().size(), is(2)); } @Test public void servletInjection() { Client client = Client.create(); WebResource resource = client.resource(String.format("http://localhost:%s/sample1/message", httpPort)); assertThat(resource.get(String.class), is("Message from managed bean\r\n")); } @Test public void servletInjectionWithRequestScope() { Client client = Client.create(); WebResource resource = client.resource(String.format("http://localhost:%s/sample1/random", httpPort)); String id1 = resource.get(String.class); String id2 = resource.get(String.class); assertThat(id1, not(id2)); } @Test public void servletInjectionWithApplicationScope() { Client client = Client.create(); WebResource resource = client.resource(String.format("http://localhost:%s/sample1/applId", httpPort)); String id1 = resource.get(String.class); String id2 = resource.get(String.class); assertThat(id1, is(id2)); } @Test public void servletInjectionWithSessionScope() throws InterruptedException { DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); config.getProperties().put(ApacheHttpClientConfig.PROPERTY_HANDLE_COOKIES, true); Client client = ApacheHttpClient.create(config); WebResource resource = client.resource(String.format("http://localhost:%s/sample1/session", httpPort)); String text = resource.get(String.class); assertThat(text, is("It worked!\n")); resource = client.resource(String.format("http://localhost:%s/sample1/timestamp", httpPort)); String timestamp1 = resource.get(String.class); Thread.sleep(500); // force new session Client client2 = ApacheHttpClient.create(config); client2.resource(String.format("http://localhost:%s/sample1/session", httpPort)).get(String.class); WebResource resource2 = client2.resource(String.format("http://localhost:%s/sample1/timestamp", httpPort)); String timestamp3 = resource2.get(String.class); assertThat(timestamp3, is(not(timestamp1))); String timestamp2 = resource.get(String.class); assertThat(timestamp1, is(timestamp2)); String timestamp4 = resource2.get(String.class); assertThat(timestamp4, is(timestamp3)); } @Test public void checkInvalidateSession() { Client client = Client.create(); WebResource contextRoot = client.resource(String.format("http://localhost:%s/sample1", httpPort)); WebResource resource1 = contextRoot.path("session"); assertThat(resource1.get(String.class), is("It worked!\n")); WebResource resource2 = contextRoot.path("invalidate").queryParam("isBeanConstructed", ""); assertThat(resource2.get(String.class), is("true")); WebResource resource3 = contextRoot.path("invalidate"); assertThat(resource3.get(String.class), is("")); WebResource resource4 = contextRoot.path("invalidate").queryParam("isBeanDestroyed", ""); assertThat(resource4.get(String.class), is("false")); } @Test public void checkOsgiServiceInjection() { Client client = Client.create(); WebResource contextRoot = client.resource(String.format("http://localhost:%s/sample1", httpPort)); WebResource resource1 = contextRoot.path("ice"); String output = resource1.get(String.class); assertThat(output, containsString("Chocolate by filter")); assertThat(output, containsString("++++ Hazelnut")); } }
grgrzybek/org.ops4j.pax.cdi
itest/src/it/itest-standalone/src/test/java/org/ops4j/pax/cdi/test/ServletTest.java
Java
apache-2.0
7,994
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.engine.impl.cmd; import java.util.Collections; import org.camunda.bpm.engine.history.UserOperationLogEntry; import org.camunda.bpm.engine.impl.cfg.CommandChecker; import org.camunda.bpm.engine.impl.interceptor.Command; import org.camunda.bpm.engine.impl.interceptor.CommandContext; import org.camunda.bpm.engine.impl.persistence.entity.PropertyChange; import org.camunda.bpm.engine.impl.persistence.entity.PropertyEntity; import org.camunda.bpm.engine.impl.persistence.entity.PropertyManager; /** * @author Daniel Meyer * */ public class DeletePropertyCmd implements Command<Object> { protected String name; /** * @param name */ public DeletePropertyCmd(String name) { this.name = name; } public Object execute(CommandContext commandContext) { commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkDeleteProperty); final PropertyManager propertyManager = commandContext.getPropertyManager(); PropertyEntity propertyEntity = propertyManager.findPropertyById(name); if(propertyEntity != null) { propertyManager.delete(propertyEntity); commandContext.getOperationLogManager().logPropertyOperation(UserOperationLogEntry.OPERATION_TYPE_DELETE, Collections.singletonList(new PropertyChange("name", null, name))); } return null; } }
camunda/camunda-bpm-platform
engine/src/main/java/org/camunda/bpm/engine/impl/cmd/DeletePropertyCmd.java
Java
apache-2.0
2,179
/** * * Copyright 2020 Florian Schmaus * * 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. */ /** * XMPPTCPConnection Stream Managment Predicates. */ package org.jivesoftware.smack.sm.predicates.tcp;
igniterealtime/Smack
smack-tcp/src/main/java/org/jivesoftware/smack/sm/predicates/tcp/package-info.java
Java
apache-2.0
712
package master import ( "net" "reflect" "sort" "strings" "testing" "time" "github.com/cloudflare/cfssl/helpers" apiv1 "k8s.io/api/core/v1" extensionsapiv1beta1 "k8s.io/api/extensions/v1beta1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime/schema" "k8s.io/apimachinery/pkg/util/diff" apiserveroptions "k8s.io/apiserver/pkg/server/options" "k8s.io/apiserver/pkg/storage/storagebackend" utilconfig "k8s.io/apiserver/pkg/util/flag" pluginwebhook "k8s.io/apiserver/plugin/pkg/audit/webhook" kubeapiserveroptions "k8s.io/kubernetes/cmd/kube-apiserver/app/options" cmapp "k8s.io/kubernetes/cmd/kube-controller-manager/app/options" "k8s.io/kubernetes/pkg/api/legacyscheme" "k8s.io/kubernetes/pkg/apis/componentconfig" kubeoptions "k8s.io/kubernetes/pkg/kubeapiserver/options" kubeletclient "k8s.io/kubernetes/pkg/kubelet/client" schedulerapp "k8s.io/kubernetes/plugin/cmd/kube-scheduler/app" configapi "github.com/openshift/origin/pkg/cmd/server/api" ) var expectedGroupPreferredVersions []string = []string{ // keep this sorted: "admission.k8s.io/v1beta1", // not persisted "admissionregistration.k8s.io/v1beta1", "apps/v1beta1", "authentication.k8s.io/v1", "authorization.k8s.io/v1", "authorization.openshift.io/v1", "autoscaling/v1", "batch/v1", "certificates.k8s.io/v1beta1", "componentconfig/v1alpha1", "events.k8s.io/v1beta1", "extensions/v1beta1", "imagepolicy.k8s.io/v1alpha1", "networking.k8s.io/v1", "policy/v1beta1", "rbac.authorization.k8s.io/v1", "scheduling.k8s.io/v1alpha1", "settings.k8s.io/v1alpha1", "storage.k8s.io/v1", "user.openshift.io/v1", "v1", } func TestPreferredGroupVersions(t *testing.T) { s := legacyscheme.Registry.AllPreferredGroupVersions() expected := strings.Join(expectedGroupPreferredVersions, ",") if s != expected { t.Logf("expected: %#v", expected) t.Logf("got: %#v", s) t.Errorf("unexpected preferred group versions: %v", diff.StringDiff(expected, s)) } } func TestAPIServerDefaults(t *testing.T) { defaults := kubeapiserveroptions.NewServerRunOptions() // This is a snapshot of the default config // If the default changes (new fields are added, or default values change), we want to know // Once we've reacted to the changes appropriately in BuildKubernetesMasterConfig(), update this expected default to match the new upstream defaults expectedDefaults := &kubeapiserveroptions.ServerRunOptions{ ServiceNodePortRange: kubeoptions.DefaultServiceNodePortRange, MasterCount: 1, GenericServerRunOptions: &apiserveroptions.ServerRunOptions{ MaxRequestsInFlight: 400, MaxMutatingRequestsInFlight: 200, MinRequestTimeout: 1800, RequestTimeout: time.Duration(60) * time.Second, }, Admission: &apiserveroptions.AdmissionOptions{ PluginNames: []string{"AlwaysAdmit"}, RecommendedPluginOrder: []string{"NamespaceLifecycle", "Initializers", "MutatingAdmissionWebhook", "ValidatingAdmissionWebhook"}, //ignored DefaultOffPlugins: []string{"Initializers", "MutatingAdmissionWebhook", "ValidatingAdmissionWebhook"}, //ignored }, Etcd: &apiserveroptions.EtcdOptions{ StorageConfig: storagebackend.Config{ ServerList: nil, Prefix: "/registry", DeserializationCacheSize: 0, Quorum: true, CompactionInterval: 300000000000, // five minutes }, DefaultStorageMediaType: "application/vnd.kubernetes.protobuf", DeleteCollectionWorkers: 1, EnableGarbageCollection: true, EnableWatchCache: true, DefaultWatchCacheSize: 100, }, SecureServing: &apiserveroptions.SecureServingOptions{ BindAddress: net.ParseIP("0.0.0.0"), BindPort: 6443, ServerCert: apiserveroptions.GeneratableKeyCert{ CertDirectory: "/var/run/kubernetes", PairName: "apiserver", }, }, InsecureServing: &kubeoptions.InsecureServingOptions{ BindAddress: net.ParseIP("127.0.0.1"), BindPort: 8080, }, EndpointReconcilerType: "master-count", //ignored EventTTL: 1 * time.Hour, KubeletConfig: kubeletclient.KubeletClientConfig{ Port: 10250, ReadOnlyPort: 10255, PreferredAddressTypes: []string{ string(apiv1.NodeHostName), string(apiv1.NodeInternalDNS), string(apiv1.NodeInternalIP), string(apiv1.NodeExternalDNS), string(apiv1.NodeExternalIP), }, EnableHttps: true, HTTPTimeout: time.Duration(5) * time.Second, }, // we currently overwrite this entire stanza, but we should be trying to collapse onto the upstream // flag or config mechanism for kube. Audit: &apiserveroptions.AuditOptions{ LogOptions: apiserveroptions.AuditLogOptions{ Format: "json", }, WebhookOptions: apiserveroptions.AuditWebhookOptions{ Mode: "batch", BatchConfig: pluginwebhook.BatchBackendConfig{ BufferSize: 10000, MaxBatchSize: 400, MaxBatchWait: time.Duration(30000000000), ThrottleQPS: 10, ThrottleBurst: 15, InitialBackoff: time.Duration(10000000000), }, }, }, Features: &apiserveroptions.FeatureOptions{ EnableProfiling: true, }, Authentication: &kubeoptions.BuiltInAuthenticationOptions{ Anonymous: &kubeoptions.AnonymousAuthenticationOptions{Allow: true}, BootstrapToken: &kubeoptions.BootstrapTokenAuthenticationOptions{}, ClientCert: &apiserveroptions.ClientCertAuthenticationOptions{}, Keystone: &kubeoptions.KeystoneAuthenticationOptions{}, OIDC: &kubeoptions.OIDCAuthenticationOptions{}, PasswordFile: &kubeoptions.PasswordFileAuthenticationOptions{}, RequestHeader: &apiserveroptions.RequestHeaderAuthenticationOptions{}, ServiceAccounts: &kubeoptions.ServiceAccountAuthenticationOptions{ Lookup: true, }, TokenFile: &kubeoptions.TokenFileAuthenticationOptions{}, WebHook: &kubeoptions.WebHookAuthenticationOptions{CacheTTL: 2 * time.Minute}, TokenSuccessCacheTTL: 10 * time.Second, TokenFailureCacheTTL: 0, }, Authorization: &kubeoptions.BuiltInAuthorizationOptions{ Mode: "AlwaysAllow", WebhookCacheAuthorizedTTL: 5 * time.Minute, WebhookCacheUnauthorizedTTL: 30 * time.Second, }, CloudProvider: &kubeoptions.CloudProviderOptions{}, StorageSerialization: &kubeoptions.StorageSerializationOptions{ StorageVersions: legacyscheme.Registry.AllPreferredGroupVersions(), DefaultStorageVersions: legacyscheme.Registry.AllPreferredGroupVersions(), }, APIEnablement: &kubeoptions.APIEnablementOptions{ RuntimeConfig: utilconfig.ConfigurationMap{}, }, EnableLogsHandler: true, // we disable this } // clear the non-serializeable bit defaults.Admission.Plugins = nil if !reflect.DeepEqual(defaults, expectedDefaults) { t.Logf("expected defaults, actual defaults: \n%s", diff.ObjectReflectDiff(expectedDefaults, defaults)) t.Errorf("Got different defaults than expected, adjust in BuildKubernetesMasterConfig and update expectedDefaults") } } // sortedGCIgnoredResources sorts by Group, then Resource. type sortedGCIgnoredResources []componentconfig.GroupResource func (r sortedGCIgnoredResources) Len() int { return len(r) } func (r sortedGCIgnoredResources) Less(i, j int) bool { if r[i].Group < r[j].Group { return true } else if r[i].Group > r[j].Group { return false } return r[i].Resource < r[j].Resource } func (r sortedGCIgnoredResources) Swap(i, j int) { r[i], r[j] = r[j], r[i] } func TestCMServerDefaults(t *testing.T) { defaults := cmapp.NewCMServer() // We need to sort GCIgnoredResources because it's built from a map, which means the insertion // order is random. sort.Sort(sortedGCIgnoredResources(defaults.GCIgnoredResources)) // This is a snapshot of the default config // If the default changes (new fields are added, or default values change), we want to know // Once we've reacted to the changes appropriately in BuildKubernetesMasterConfig(), update this expected default to match the new upstream defaults expectedDefaults := &cmapp.CMServer{ KubeControllerManagerConfiguration: componentconfig.KubeControllerManagerConfiguration{ Port: 10252, // disabled Address: "0.0.0.0", ConcurrentEndpointSyncs: 5, ConcurrentRCSyncs: 5, ConcurrentRSSyncs: 5, ConcurrentDaemonSetSyncs: 2, ConcurrentJobSyncs: 5, ConcurrentResourceQuotaSyncs: 5, ConcurrentDeploymentSyncs: 5, ConcurrentNamespaceSyncs: 10, ConcurrentSATokenSyncs: 5, ConcurrentServiceSyncs: 1, ConcurrentGCSyncs: 20, ConfigureCloudRoutes: true, NodeCIDRMaskSize: 24, ServiceSyncPeriod: metav1.Duration{Duration: 5 * time.Minute}, ResourceQuotaSyncPeriod: metav1.Duration{Duration: 5 * time.Minute}, NamespaceSyncPeriod: metav1.Duration{Duration: 5 * time.Minute}, PVClaimBinderSyncPeriod: metav1.Duration{Duration: 15 * time.Second}, HorizontalPodAutoscalerSyncPeriod: metav1.Duration{Duration: 30 * time.Second}, DeploymentControllerSyncPeriod: metav1.Duration{Duration: 30 * time.Second}, MinResyncPeriod: metav1.Duration{Duration: 12 * time.Hour}, RegisterRetryCount: 10, RouteReconciliationPeriod: metav1.Duration{Duration: 10 * time.Second}, PodEvictionTimeout: metav1.Duration{Duration: 5 * time.Minute}, NodeMonitorGracePeriod: metav1.Duration{Duration: 40 * time.Second}, NodeStartupGracePeriod: metav1.Duration{Duration: 60 * time.Second}, NodeMonitorPeriod: metav1.Duration{Duration: 5 * time.Second}, HorizontalPodAutoscalerUpscaleForbiddenWindow: metav1.Duration{Duration: 3 * time.Minute}, HorizontalPodAutoscalerDownscaleForbiddenWindow: metav1.Duration{Duration: 5 * time.Minute}, HorizontalPodAutoscalerTolerance: 0.1, HorizontalPodAutoscalerUseRESTClients: true, // we ignore this for now ClusterName: "kubernetes", TerminatedPodGCThreshold: 12500, VolumeConfiguration: componentconfig.VolumeConfiguration{ EnableDynamicProvisioning: true, EnableHostPathProvisioning: false, FlexVolumePluginDir: "/usr/libexec/kubernetes/kubelet-plugins/volume/exec/", PersistentVolumeRecyclerConfiguration: componentconfig.PersistentVolumeRecyclerConfiguration{ MaximumRetry: 3, MinimumTimeoutNFS: 300, IncrementTimeoutNFS: 30, MinimumTimeoutHostPath: 60, IncrementTimeoutHostPath: 30, }, }, ContentType: "application/vnd.kubernetes.protobuf", KubeAPIQPS: 20.0, KubeAPIBurst: 30, LeaderElection: componentconfig.LeaderElectionConfiguration{ ResourceLock: "endpoints", LeaderElect: true, LeaseDuration: metav1.Duration{Duration: 15 * time.Second}, RenewDeadline: metav1.Duration{Duration: 10 * time.Second}, RetryPeriod: metav1.Duration{Duration: 2 * time.Second}, }, ClusterSigningCertFile: "/etc/kubernetes/ca/ca.pem", ClusterSigningKeyFile: "/etc/kubernetes/ca/ca.key", ClusterSigningDuration: metav1.Duration{Duration: helpers.OneYear}, EnableGarbageCollector: true, GCIgnoredResources: []componentconfig.GroupResource{ {Group: "extensions", Resource: "replicationcontrollers"}, {Group: "", Resource: "bindings"}, {Group: "", Resource: "componentstatuses"}, {Group: "", Resource: "events"}, {Group: "authentication.k8s.io", Resource: "tokenreviews"}, {Group: "authorization.k8s.io", Resource: "subjectaccessreviews"}, {Group: "authorization.k8s.io", Resource: "selfsubjectaccessreviews"}, {Group: "authorization.k8s.io", Resource: "localsubjectaccessreviews"}, {Group: "authorization.k8s.io", Resource: "selfsubjectrulesreviews"}, {Group: "apiregistration.k8s.io", Resource: "apiservices"}, {Group: "apiextensions.k8s.io", Resource: "customresourcedefinitions"}, }, DisableAttachDetachReconcilerSync: false, ReconcilerSyncLoopPeriod: metav1.Duration{Duration: 60 * time.Second}, Controllers: []string{"*"}, EnableTaintManager: true, }, } // Because we sorted the defaults, we need to sort the expectedDefaults too. sort.Sort(sortedGCIgnoredResources(expectedDefaults.GCIgnoredResources)) if !reflect.DeepEqual(defaults, expectedDefaults) { t.Logf("expected defaults, actual defaults: \n%s", diff.ObjectReflectDiff(expectedDefaults, defaults)) t.Errorf("Got different defaults than expected, adjust in BuildKubernetesMasterConfig and update expectedDefaults") } } func TestSchedulerServerDefaults(t *testing.T) { defaults, err := schedulerapp.NewOptions() if err != nil { t.Fatal(err) } if err := defaults.ReallyApplyDefaults(); err != nil { t.Fatal(err) } if err := defaults.Complete(); err != nil { t.Fatal(err) } provider := "DefaultProvider" // This is a snapshot of the default config // If the default changes (new fields are added, or default values change), we want to know // Once we've reacted to the changes appropriately in BuildKubernetesMasterConfig(), update this expected default to match the new upstream defaults expectedDefaults := &componentconfig.KubeSchedulerConfiguration{ SchedulerName: "default-scheduler", AlgorithmSource: componentconfig.SchedulerAlgorithmSource{ Provider: &provider, }, HardPodAffinitySymmetricWeight: 1, LeaderElection: componentconfig.KubeSchedulerLeaderElectionConfiguration{ LeaderElectionConfiguration: componentconfig.LeaderElectionConfiguration{ ResourceLock: "endpoints", LeaderElect: false, // we turn this on LeaseDuration: metav1.Duration{ Duration: 15 * time.Second, }, RenewDeadline: metav1.Duration{ Duration: 10 * time.Second, }, RetryPeriod: metav1.Duration{ Duration: 2 * time.Second, }, }, LockObjectNamespace: "kube-system", LockObjectName: "kube-scheduler", }, ClientConnection: componentconfig.ClientConnectionConfiguration{ ContentType: "application/vnd.kubernetes.protobuf", QPS: 50, Burst: 100, }, HealthzBindAddress: "0.0.0.0:0", // we disable this MetricsBindAddress: "0.0.0.0:0", FailureDomains: "kubernetes.io/hostname,failure-domain.beta.kubernetes.io/zone,failure-domain.beta.kubernetes.io/region", } if !reflect.DeepEqual(defaults.GetConfig(), expectedDefaults) { t.Logf("expected defaults, actual defaults: \n%s", diff.ObjectReflectDiff(expectedDefaults, defaults.GetConfig())) t.Errorf("Got different defaults than expected, adjust in BuildKubernetesMasterConfig and update expectedDefaults") } } func TestGetAPIGroupVersionOverrides(t *testing.T) { testcases := map[string]struct { DisabledVersions map[string][]string ExpectedDisabledVersions []schema.GroupVersion ExpectedEnabledVersions []schema.GroupVersion }{ "empty": { DisabledVersions: nil, ExpectedDisabledVersions: []schema.GroupVersion{}, ExpectedEnabledVersions: []schema.GroupVersion{apiv1.SchemeGroupVersion, extensionsapiv1beta1.SchemeGroupVersion}, }, "* -> v1": { DisabledVersions: map[string][]string{"": {"*"}}, ExpectedDisabledVersions: []schema.GroupVersion{apiv1.SchemeGroupVersion}, ExpectedEnabledVersions: []schema.GroupVersion{extensionsapiv1beta1.SchemeGroupVersion}, }, "v1": { DisabledVersions: map[string][]string{"": {"v1"}}, ExpectedDisabledVersions: []schema.GroupVersion{apiv1.SchemeGroupVersion}, ExpectedEnabledVersions: []schema.GroupVersion{extensionsapiv1beta1.SchemeGroupVersion}, }, "* -> v1beta1": { DisabledVersions: map[string][]string{"extensions": {"*"}}, ExpectedDisabledVersions: []schema.GroupVersion{extensionsapiv1beta1.SchemeGroupVersion}, ExpectedEnabledVersions: []schema.GroupVersion{apiv1.SchemeGroupVersion}, }, "extensions/v1beta1": { DisabledVersions: map[string][]string{"extensions": {"v1beta1"}}, ExpectedDisabledVersions: []schema.GroupVersion{extensionsapiv1beta1.SchemeGroupVersion}, ExpectedEnabledVersions: []schema.GroupVersion{apiv1.SchemeGroupVersion}, }, } for k, tc := range testcases { config := configapi.MasterConfig{KubernetesMasterConfig: &configapi.KubernetesMasterConfig{DisabledAPIGroupVersions: tc.DisabledVersions}} overrides := getAPIResourceConfig(config) for _, expected := range tc.ExpectedDisabledVersions { if overrides.AnyResourcesForVersionEnabled(expected) { t.Errorf("%s: Expected %v", k, expected) } } for _, expected := range tc.ExpectedEnabledVersions { if !overrides.AllResourcesForVersionEnabled(expected) { t.Errorf("%s: Expected %v", k, expected) } } } }
crobby/oshinko-cli
vendor/github.com/openshift/origin/pkg/cmd/server/kubernetes/master/master_config_test.go
GO
apache-2.0
17,363
//// [tests/cases/compiler/externalModuleExportingGenericClass.ts] //// //// [externalModuleExportingGenericClass_file0.ts] class C<T> { foo: T; } export = C; //// [externalModuleExportingGenericClass_file1.ts] import a = require('./externalModuleExportingGenericClass_file0'); var v: a; // this should report error var v2: any = (new a()).foo; var v3: number = (new a<number>()).foo; //// [externalModuleExportingGenericClass_file0.js] "use strict"; var C = (function () { function C() { } return C; }()); module.exports = C; //// [externalModuleExportingGenericClass_file1.js] "use strict"; exports.__esModule = true; var a = require("./externalModuleExportingGenericClass_file0"); var v; // this should report error var v2 = (new a()).foo; var v3 = (new a()).foo;
chuckjaz/TypeScript
tests/baselines/reference/externalModuleExportingGenericClass.js
JavaScript
apache-2.0
810
/* * 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. */ module.exports = angular.module('trafficOps.table.regionPhysLocations', []) .controller('TableRegionPhysLocationsController', require('./TableRegionPhysLocationsController'));
orifinkelman/incubator-trafficcontrol
traffic_ops/experimental/ui/app/src/common/modules/table/regionPhysLocations/index.js
JavaScript
apache-2.0
986
/* * 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.cassandra.cql3; import java.util.Collections; import java.util.ArrayList; import java.util.List; import org.apache.cassandra.config.CFMetaData; import org.apache.cassandra.config.ColumnDefinition; import org.apache.cassandra.cql3.Term.Raw; import org.apache.cassandra.cql3.restrictions.Restriction; import org.apache.cassandra.cql3.restrictions.SingleColumnRestriction; import org.apache.cassandra.cql3.statements.Bound; import org.apache.cassandra.db.marshal.CollectionType; import org.apache.cassandra.db.marshal.ListType; import org.apache.cassandra.db.marshal.MapType; import org.apache.cassandra.exceptions.InvalidRequestException; import static org.apache.cassandra.cql3.statements.RequestValidations.checkFalse; import static org.apache.cassandra.cql3.statements.RequestValidations.checkTrue; /** * Relations encapsulate the relationship between an entity of some kind, and * a value (term). For example, <key> > "start" or "colname1" = "somevalue". * */ public final class SingleColumnRelation extends Relation { private final ColumnIdentifier.Raw entity; private final Term.Raw mapKey; private final Term.Raw value; private final List<Term.Raw> inValues; private SingleColumnRelation(ColumnIdentifier.Raw entity, Term.Raw mapKey, Operator type, Term.Raw value, List<Term.Raw> inValues) { this.entity = entity; this.mapKey = mapKey; this.relationType = type; this.value = value; this.inValues = inValues; } /** * Creates a new relation. * * @param entity the kind of relation this is; what the term is being compared to. * @param mapKey the key into the entity identifying the value the term is being compared to. * @param type the type that describes how this entity relates to the value. * @param value the value being compared. */ public SingleColumnRelation(ColumnIdentifier.Raw entity, Term.Raw mapKey, Operator type, Term.Raw value) { this(entity, mapKey, type, value, null); } /** * Creates a new relation. * * @param entity the kind of relation this is; what the term is being compared to. * @param type the type that describes how this entity relates to the value. * @param value the value being compared. */ public SingleColumnRelation(ColumnIdentifier.Raw entity, Operator type, Term.Raw value) { this(entity, null, type, value); } public static SingleColumnRelation createInRelation(ColumnIdentifier.Raw entity, List<Term.Raw> inValues) { return new SingleColumnRelation(entity, null, Operator.IN, null, inValues); } public ColumnIdentifier.Raw getEntity() { return entity; } public Term.Raw getMapKey() { return mapKey; } @Override protected Term toTerm(List<? extends ColumnSpecification> receivers, Raw raw, String keyspace, VariableSpecifications boundNames) throws InvalidRequestException { assert receivers.size() == 1; Term term = raw.prepare(keyspace, receivers.get(0)); term.collectMarkerSpecification(boundNames); return term; } public SingleColumnRelation withNonStrictOperator() { switch (relationType) { case GT: return new SingleColumnRelation(entity, Operator.GTE, value); case LT: return new SingleColumnRelation(entity, Operator.LTE, value); default: return this; } } @Override public String toString() { String entityAsString = entity.toString(); if (mapKey != null) entityAsString = String.format("%s[%s]", entityAsString, mapKey); if (isIN()) return String.format("%s IN %s", entityAsString, inValues); return String.format("%s %s %s", entityAsString, relationType, value); } @Override protected Restriction newEQRestriction(CFMetaData cfm, VariableSpecifications boundNames) throws InvalidRequestException { ColumnDefinition columnDef = toColumnDefinition(cfm, entity); if (mapKey == null) { Term term = toTerm(toReceivers(cfm, columnDef), value, cfm.ksName, boundNames); return new SingleColumnRestriction.EQ(columnDef, term); } List<? extends ColumnSpecification> receivers = toReceivers(cfm, columnDef); Term entryKey = toTerm(Collections.singletonList(receivers.get(0)), mapKey, cfm.ksName, boundNames); Term entryValue = toTerm(Collections.singletonList(receivers.get(1)), value, cfm.ksName, boundNames); return new SingleColumnRestriction.Contains(columnDef, entryKey, entryValue); } @Override protected Restriction newINRestriction(CFMetaData cfm, VariableSpecifications boundNames) throws InvalidRequestException { ColumnDefinition columnDef = cfm.getColumnDefinition(getEntity().prepare(cfm)); List<? extends ColumnSpecification> receivers = toReceivers(cfm, columnDef); List<Term> terms = toTerms(receivers, inValues, cfm.ksName, boundNames); if (terms == null) { Term term = toTerm(receivers, value, cfm.ksName, boundNames); return new SingleColumnRestriction.InWithMarker(columnDef, (Lists.Marker) term); } return new SingleColumnRestriction.InWithValues(columnDef, terms); } @Override protected Restriction newSliceRestriction(CFMetaData cfm, VariableSpecifications boundNames, Bound bound, boolean inclusive) throws InvalidRequestException { ColumnDefinition columnDef = toColumnDefinition(cfm, entity); Term term = toTerm(toReceivers(cfm, columnDef), value, cfm.ksName, boundNames); return new SingleColumnRestriction.Slice(columnDef, bound, inclusive, term); } @Override protected Restriction newContainsRestriction(CFMetaData cfm, VariableSpecifications boundNames, boolean isKey) throws InvalidRequestException { ColumnDefinition columnDef = toColumnDefinition(cfm, entity); Term term = toTerm(toReceivers(cfm, columnDef), value, cfm.ksName, boundNames); return new SingleColumnRestriction.Contains(columnDef, term, isKey); } /** * Returns the receivers for this relation. * * @param cfm the Column Family meta data * @param columnDef the column definition * @return the receivers for the specified relation. * @throws InvalidRequestException if the relation is invalid */ private List<? extends ColumnSpecification> toReceivers(CFMetaData cfm, ColumnDefinition columnDef) throws InvalidRequestException { ColumnSpecification receiver = columnDef; checkFalse(columnDef.isCompactValue(), "Predicates on the non-primary-key column (%s) of a COMPACT table are not yet supported", columnDef.name); if (isIN()) { // For partition keys we only support IN for the last name so far checkFalse(columnDef.isPartitionKey() && !isLastPartitionKey(cfm, columnDef), "Partition KEY part %s cannot be restricted by IN relation (only the last part of the partition key can)", columnDef.name); // We only allow IN on the row key and the clustering key so far, never on non-PK columns, and this even if // there's an index // Note: for backward compatibility reason, we conside a IN of 1 value the same as a EQ, so we let that // slide. checkFalse(!columnDef.isPrimaryKeyColumn() && !canHaveOnlyOneValue(), "IN predicates on non-primary-key columns (%s) is not yet supported", columnDef.name); } else if (isSlice()) { // Non EQ relation is not supported without token(), even if we have a 2ndary index (since even those // are ordered by partitioner). // Note: In theory we could allow it for 2ndary index queries with ALLOW FILTERING, but that would // probably require some special casing // Note bis: This is also why we don't bother handling the 'tuple' notation of #4851 for keys. If we // lift the limitation for 2ndary // index with filtering, we'll need to handle it though. checkFalse(columnDef.isPartitionKey(), "Only EQ and IN relation are supported on the partition key (unless you use the token() function)"); } checkFalse(isContainsKey() && !(receiver.type instanceof MapType), "Cannot use CONTAINS KEY on non-map column %s", receiver.name); if (mapKey != null) { checkFalse(receiver.type instanceof ListType, "Indexes on list entries (%s[index] = value) are not currently supported.", receiver.name); checkTrue(receiver.type instanceof MapType, "Column %s cannot be used as a map", receiver.name); checkTrue(receiver.type.isMultiCell(), "Map-entry equality predicates on frozen map column %s are not supported", receiver.name); checkTrue(isEQ(), "Only EQ relations are supported on map entries"); } if (receiver.type.isCollection()) { // We don't support relations against entire collections (unless they're frozen), like "numbers = {1, 2, 3}" checkFalse(receiver.type.isMultiCell() && !isLegalRelationForNonFrozenCollection(), "Collection column '%s' (%s) cannot be restricted by a '%s' relation", receiver.name, receiver.type.asCQL3Type(), operator()); if (isContainsKey() || isContains()) { receiver = makeCollectionReceiver(receiver, isContainsKey()); } else if (receiver.type.isMultiCell() && mapKey != null && isEQ()) { List<ColumnSpecification> receivers = new ArrayList<>(2); receivers.add(makeCollectionReceiver(receiver, true)); receivers.add(makeCollectionReceiver(receiver, false)); return receivers; } } return Collections.singletonList(receiver); } private ColumnSpecification makeCollectionReceiver(ColumnSpecification receiver, boolean forKey) { return ((CollectionType<?>) receiver.type).makeCollectionReceiver(receiver, forKey); } private boolean isLegalRelationForNonFrozenCollection() { return isContainsKey() || isContains() || isMapEntryEquality(); } private boolean isMapEntryEquality() { return mapKey != null && isEQ(); } /** * Checks if the specified column is the last column of the partition key. * * @param cfm the column family meta data * @param columnDef the column to check * @return <code>true</code> if the specified column is the last column of the partition key, <code>false</code> * otherwise. */ private static boolean isLastPartitionKey(CFMetaData cfm, ColumnDefinition columnDef) { return columnDef.position() == cfm.partitionKeyColumns().size() - 1; } private boolean canHaveOnlyOneValue() { return isEQ() || (isIN() && inValues != null && inValues.size() == 1); } }
LatencyUtils/cassandra-stress2
src/java/org/apache/cassandra/cql3/SingleColumnRelation.java
Java
apache-2.0
12,585
-- SQL to create the initial tables for the MediaWiki database. -- This is read and executed by the install script; you should -- not have to run it by itself unless doing a manual install. -- This is a shared schema file used for both MySQL and SQLite installs. -- -- General notes: -- -- If possible, create tables as InnoDB to benefit from the -- superior resiliency against crashes and ability to read -- during writes (and write during reads!) -- -- Only the 'searchindex' table requires MyISAM due to the -- requirement for fulltext index support, which is missing -- from InnoDB. -- -- -- The MySQL table backend for MediaWiki currently uses -- 14-character BINARY or VARBINARY fields to store timestamps. -- The format is YYYYMMDDHHMMSS, which is derived from the -- text format of MySQL's TIMESTAMP fields. -- -- Historically TIMESTAMP fields were used, but abandoned -- in early 2002 after a lot of trouble with the fields -- auto-updating. -- -- The Postgres backend uses TIMESTAMPTZ fields for timestamps, -- and we will migrate the MySQL definitions at some point as -- well. -- -- -- The /*_*/ comments in this and other files are -- replaced with the defined table prefix by the installer -- and updater scripts. If you are installing or running -- updates manually, you will need to manually insert the -- table prefix if any when running these scripts. -- -- -- The user table contains basic account information, -- authentication keys, etc. -- -- Some multi-wiki sites may share a single central user table -- between separate wikis using the $wgSharedDB setting. -- -- Note that when a external authentication plugin is used, -- user table entries still need to be created to store -- preferences and to key tracking information in the other -- tables. -- CREATE TABLE /*_*/user ( user_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Usernames must be unique, must not be in the form of -- an IP address. _Shouldn't_ allow slashes or case -- conflicts. Spaces are allowed, and are _not_ converted -- to underscores like titles. See the User::newFromName() for -- the specific tests that usernames have to pass. user_name varchar(255) binary NOT NULL default '', -- Optional 'real name' to be displayed in credit listings user_real_name varchar(255) binary NOT NULL default '', -- Password hashes, see User::crypt() and User::comparePasswords() -- in User.php for the algorithm user_password tinyblob NOT NULL, -- When using 'mail me a new password', a random -- password is generated and the hash stored here. -- The previous password is left in place until -- someone actually logs in with the new password, -- at which point the hash is moved to user_password -- and the old password is invalidated. user_newpassword tinyblob NOT NULL, -- Timestamp of the last time when a new password was -- sent, for throttling and expiring purposes -- Emailed passwords will expire $wgNewPasswordExpiry -- (a week) after being set. If user_newpass_time is NULL -- (eg. created by mail) it doesn't expire. user_newpass_time binary(14), -- Note: email should be restricted, not public info. -- Same with passwords. user_email tinytext NOT NULL, -- If the browser sends an If-Modified-Since header, a 304 response is -- suppressed if the value in this field for the current user is later than -- the value in the IMS header. That is, this field is an invalidation timestamp -- for the browser cache of logged-in users. Among other things, it is used -- to prevent pages generated for a previously logged in user from being -- displayed after a session expiry followed by a fresh login. user_touched binary(14) NOT NULL default '', -- A pseudorandomly generated value that is stored in -- a cookie when the "remember password" feature is -- used (previously, a hash of the password was used, but -- this was vulnerable to cookie-stealing attacks) user_token binary(32) NOT NULL default '', -- Initially NULL; when a user's e-mail address has been -- validated by returning with a mailed token, this is -- set to the current timestamp. user_email_authenticated binary(14), -- Randomly generated token created when the e-mail address -- is set and a confirmation test mail sent. user_email_token binary(32), -- Expiration date for the user_email_token user_email_token_expires binary(14), -- Timestamp of account registration. -- Accounts predating this schema addition may contain NULL. user_registration binary(14), -- Count of edits and edit-like actions. -- -- *NOT* intended to be an accurate copy of COUNT(*) WHERE rev_user=user_id -- May contain NULL for old accounts if batch-update scripts haven't been -- run, as well as listing deleted edits and other myriad ways it could be -- out of sync. -- -- Meant primarily for heuristic checks to give an impression of whether -- the account has been used much. -- user_editcount int ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/user_name ON /*_*/user (user_name); CREATE INDEX /*i*/user_email_token ON /*_*/user (user_email_token); CREATE INDEX /*i*/user_email ON /*_*/user (user_email(50)); -- -- User permissions have been broken out to a separate table; -- this allows sites with a shared user table to have different -- permissions assigned to a user in each project. -- -- This table replaces the old user_rights field which used a -- comma-separated blob. -- CREATE TABLE /*_*/user_groups ( -- Key to user_id ug_user int unsigned NOT NULL default 0, -- Group names are short symbolic string keys. -- The set of group names is open-ended, though in practice -- only some predefined ones are likely to be used. -- -- At runtime $wgGroupPermissions will associate group keys -- with particular permissions. A user will have the combined -- permissions of any group they're explicitly in, plus -- the implicit '*' and 'user' groups. ug_group varbinary(255) NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/ug_user_group ON /*_*/user_groups (ug_user,ug_group); CREATE INDEX /*i*/ug_group ON /*_*/user_groups (ug_group); -- Stores the groups the user has once belonged to. -- The user may still belong to these groups (check user_groups). -- Users are not autopromoted to groups from which they were removed. CREATE TABLE /*_*/user_former_groups ( -- Key to user_id ufg_user int unsigned NOT NULL default 0, ufg_group varbinary(255) NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/ufg_user_group ON /*_*/user_former_groups (ufg_user,ufg_group); -- -- Stores notifications of user talk page changes, for the display -- of the "you have new messages" box -- CREATE TABLE /*_*/user_newtalk ( -- Key to user.user_id user_id int NOT NULL default 0, -- If the user is an anonymous user their IP address is stored here -- since the user_id of 0 is ambiguous user_ip varbinary(40) NOT NULL default '', -- The highest timestamp of revisions of the talk page viewed -- by this user user_last_timestamp varbinary(14) NULL default NULL ) /*$wgDBTableOptions*/; -- Indexes renamed for SQLite in 1.14 CREATE INDEX /*i*/un_user_id ON /*_*/user_newtalk (user_id); CREATE INDEX /*i*/un_user_ip ON /*_*/user_newtalk (user_ip); -- -- User preferences and perhaps other fun stuff. :) -- Replaces the old user.user_options blob, with a couple nice properties: -- -- 1) We only store non-default settings, so changes to the defauls -- are now reflected for everybody, not just new accounts. -- 2) We can more easily do bulk lookups, statistics, or modifications of -- saved options since it's a sane table structure. -- CREATE TABLE /*_*/user_properties ( -- Foreign key to user.user_id up_user int NOT NULL, -- Name of the option being saved. This is indexed for bulk lookup. up_property varbinary(255) NOT NULL, -- Property value as a string. up_value blob ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/user_properties_user_property ON /*_*/user_properties (up_user,up_property); CREATE INDEX /*i*/user_properties_property ON /*_*/user_properties (up_property); -- -- Core of the wiki: each page has an entry here which identifies -- it by title and contains some essential metadata. -- CREATE TABLE /*_*/page ( -- Unique identifier number. The page_id will be preserved across -- edits and rename operations, but not deletions and recreations. page_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- A page name is broken into a namespace and a title. -- The namespace keys are UI-language-independent constants, -- defined in includes/Defines.php page_namespace int NOT NULL, -- The rest of the title, as text. -- Spaces are transformed into underscores in title storage. page_title varchar(255) binary NOT NULL, -- Comma-separated set of permission keys indicating who -- can move or edit the page. page_restrictions tinyblob NOT NULL, -- Number of times this page has been viewed. page_counter bigint unsigned NOT NULL default 0, -- 1 indicates the article is a redirect. page_is_redirect tinyint unsigned NOT NULL default 0, -- 1 indicates this is a new entry, with only one edit. -- Not all pages with one edit are new pages. page_is_new tinyint unsigned NOT NULL default 0, -- Random value between 0 and 1, used for Special:Randompage page_random real unsigned NOT NULL, -- This timestamp is updated whenever the page changes in -- a way requiring it to be re-rendered, invalidating caches. -- Aside from editing this includes permission changes, -- creation or deletion of linked pages, and alteration -- of contained templates. page_touched binary(14) NOT NULL default '', -- This timestamp is updated whenever a page is re-parsed and -- it has all the link tracking tables updated for it. This is -- useful for de-duplicating expensive backlink update jobs. page_links_updated varbinary(14) NULL default NULL, -- Handy key to revision.rev_id of the current revision. -- This may be 0 during page creation, but that shouldn't -- happen outside of a transaction... hopefully. page_latest int unsigned NOT NULL, -- Uncompressed length in bytes of the page's current source text. page_len int unsigned NOT NULL, -- content model, see CONTENT_MODEL_XXX constants page_content_model varbinary(32) DEFAULT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/name_title ON /*_*/page (page_namespace,page_title); CREATE INDEX /*i*/page_random ON /*_*/page (page_random); CREATE INDEX /*i*/page_len ON /*_*/page (page_len); CREATE INDEX /*i*/page_redirect_namespace_len ON /*_*/page (page_is_redirect, page_namespace, page_len); -- -- Every edit of a page creates also a revision row. -- This stores metadata about the revision, and a reference -- to the text storage backend. -- CREATE TABLE /*_*/revision ( -- Unique ID to identify each revision rev_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Key to page_id. This should _never_ be invalid. rev_page int unsigned NOT NULL, -- Key to text.old_id, where the actual bulk text is stored. -- It's possible for multiple revisions to use the same text, -- for instance revisions where only metadata is altered -- or a rollback to a previous version. rev_text_id int unsigned NOT NULL, -- Text comment summarizing the change. -- This text is shown in the history and other changes lists, -- rendered in a subset of wiki markup by Linker::formatComment() rev_comment tinyblob NOT NULL, -- Key to user.user_id of the user who made this edit. -- Stores 0 for anonymous edits and for some mass imports. rev_user int unsigned NOT NULL default 0, -- Text username or IP address of the editor. rev_user_text varchar(255) binary NOT NULL default '', -- Timestamp of when revision was created rev_timestamp binary(14) NOT NULL default '', -- Records whether the user marked the 'minor edit' checkbox. -- Many automated edits are marked as minor. rev_minor_edit tinyint unsigned NOT NULL default 0, -- Restrictions on who can access this revision rev_deleted tinyint unsigned NOT NULL default 0, -- Length of this revision in bytes rev_len int unsigned, -- Key to revision.rev_id -- This field is used to add support for a tree structure (The Adjacency List Model) rev_parent_id int unsigned default NULL, -- SHA-1 text content hash in base-36 rev_sha1 varbinary(32) NOT NULL default '', -- content model, see CONTENT_MODEL_XXX constants rev_content_model varbinary(32) DEFAULT NULL, -- content format, see CONTENT_FORMAT_XXX constants rev_content_format varbinary(64) DEFAULT NULL ) /*$wgDBTableOptions*/ MAX_ROWS=10000000 AVG_ROW_LENGTH=1024; -- In case tables are created as MyISAM, use row hints for MySQL <5.0 to avoid 4GB limit CREATE UNIQUE INDEX /*i*/rev_page_id ON /*_*/revision (rev_page, rev_id); CREATE INDEX /*i*/rev_timestamp ON /*_*/revision (rev_timestamp); CREATE INDEX /*i*/page_timestamp ON /*_*/revision (rev_page,rev_timestamp); CREATE INDEX /*i*/user_timestamp ON /*_*/revision (rev_user,rev_timestamp); CREATE INDEX /*i*/usertext_timestamp ON /*_*/revision (rev_user_text,rev_timestamp); CREATE INDEX /*i*/page_user_timestamp ON /*_*/revision (rev_page,rev_user,rev_timestamp); -- -- Holds text of individual page revisions. -- -- Field names are a holdover from the 'old' revisions table in -- MediaWiki 1.4 and earlier: an upgrade will transform that -- table into the 'text' table to minimize unnecessary churning -- and downtime. If upgrading, the other fields will be left unused. -- CREATE TABLE /*_*/text ( -- Unique text storage key number. -- Note that the 'oldid' parameter used in URLs does *not* -- refer to this number anymore, but to rev_id. -- -- revision.rev_text_id is a key to this column old_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Depending on the contents of the old_flags field, the text -- may be convenient plain text, or it may be funkily encoded. old_text mediumblob NOT NULL, -- Comma-separated list of flags: -- gzip: text is compressed with PHP's gzdeflate() function. -- utf8: text was stored as UTF-8. -- If $wgLegacyEncoding option is on, rows *without* this flag -- will be converted to UTF-8 transparently at load time. -- object: text field contained a serialized PHP object. -- The object either contains multiple versions compressed -- together to achieve a better compression ratio, or it refers -- to another row where the text can be found. old_flags tinyblob NOT NULL ) /*$wgDBTableOptions*/ MAX_ROWS=10000000 AVG_ROW_LENGTH=10240; -- In case tables are created as MyISAM, use row hints for MySQL <5.0 to avoid 4GB limit -- -- Holding area for deleted articles, which may be viewed -- or restored by admins through the Special:Undelete interface. -- The fields generally correspond to the page, revision, and text -- fields, with several caveats. -- CREATE TABLE /*_*/archive ( -- Primary key ar_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, ar_namespace int NOT NULL default 0, ar_title varchar(255) binary NOT NULL default '', -- Newly deleted pages will not store text in this table, -- but will reference the separately existing text rows. -- This field is retained for backwards compatibility, -- so old archived pages will remain accessible after -- upgrading from 1.4 to 1.5. -- Text may be gzipped or otherwise funky. ar_text mediumblob NOT NULL, -- Basic revision stuff... ar_comment tinyblob NOT NULL, ar_user int unsigned NOT NULL default 0, ar_user_text varchar(255) binary NOT NULL, ar_timestamp binary(14) NOT NULL default '', ar_minor_edit tinyint NOT NULL default 0, -- See ar_text note. ar_flags tinyblob NOT NULL, -- When revisions are deleted, their unique rev_id is stored -- here so it can be retained after undeletion. This is necessary -- to retain permalinks to given revisions after accidental delete -- cycles or messy operations like history merges. -- -- Old entries from 1.4 will be NULL here, and a new rev_id will -- be created on undeletion for those revisions. ar_rev_id int unsigned, -- For newly deleted revisions, this is the text.old_id key to the -- actual stored text. To avoid breaking the block-compression scheme -- and otherwise making storage changes harder, the actual text is -- *not* deleted from the text table, merely hidden by removal of the -- page and revision entries. -- -- Old entries deleted under 1.2-1.4 will have NULL here, and their -- ar_text and ar_flags fields will be used to create a new text -- row upon undeletion. ar_text_id int unsigned, -- rev_deleted for archives ar_deleted tinyint unsigned NOT NULL default 0, -- Length of this revision in bytes ar_len int unsigned, -- Reference to page_id. Useful for sysadmin fixing of large pages -- merged together in the archives, or for cleanly restoring a page -- at its original ID number if possible. -- -- Will be NULL for pages deleted prior to 1.11. ar_page_id int unsigned, -- Original previous revision ar_parent_id int unsigned default NULL, -- SHA-1 text content hash in base-36 ar_sha1 varbinary(32) NOT NULL default '', -- content model, see CONTENT_MODEL_XXX constants ar_content_model varbinary(32) DEFAULT NULL, -- content format, see CONTENT_FORMAT_XXX constants ar_content_format varbinary(64) DEFAULT NULL ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/name_title_timestamp ON /*_*/archive (ar_namespace,ar_title,ar_timestamp); CREATE INDEX /*i*/ar_usertext_timestamp ON /*_*/archive (ar_user_text,ar_timestamp); CREATE INDEX /*i*/ar_revid ON /*_*/archive (ar_rev_id); -- -- Track page-to-page hyperlinks within the wiki. -- CREATE TABLE /*_*/pagelinks ( -- Key to the page_id of the page containing the link. pl_from int unsigned NOT NULL default 0, -- Key to page_namespace/page_title of the target page. -- The target page may or may not exist, and due to renames -- and deletions may refer to different page records as time -- goes by. pl_namespace int NOT NULL default 0, pl_title varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/pl_from ON /*_*/pagelinks (pl_from,pl_namespace,pl_title); CREATE UNIQUE INDEX /*i*/pl_namespace ON /*_*/pagelinks (pl_namespace,pl_title,pl_from); -- -- Track template inclusions. -- CREATE TABLE /*_*/templatelinks ( -- Key to the page_id of the page containing the link. tl_from int unsigned NOT NULL default 0, -- Key to page_namespace/page_title of the target page. -- The target page may or may not exist, and due to renames -- and deletions may refer to different page records as time -- goes by. tl_namespace int NOT NULL default 0, tl_title varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/tl_from ON /*_*/templatelinks (tl_from,tl_namespace,tl_title); CREATE UNIQUE INDEX /*i*/tl_namespace ON /*_*/templatelinks (tl_namespace,tl_title,tl_from); -- -- Track links to images *used inline* -- We don't distinguish live from broken links here, so -- they do not need to be changed on upload/removal. -- CREATE TABLE /*_*/imagelinks ( -- Key to page_id of the page containing the image / media link. il_from int unsigned NOT NULL default 0, -- Filename of target image. -- This is also the page_title of the file's description page; -- all such pages are in namespace 6 (NS_FILE). il_to varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/il_from ON /*_*/imagelinks (il_from,il_to); CREATE UNIQUE INDEX /*i*/il_to ON /*_*/imagelinks (il_to,il_from); -- -- Track category inclusions *used inline* -- This tracks a single level of category membership -- CREATE TABLE /*_*/categorylinks ( -- Key to page_id of the page defined as a category member. cl_from int unsigned NOT NULL default 0, -- Name of the category. -- This is also the page_title of the category's description page; -- all such pages are in namespace 14 (NS_CATEGORY). cl_to varchar(255) binary NOT NULL default '', -- A binary string obtained by applying a sortkey generation algorithm -- (Collation::getSortKey()) to page_title, or cl_sortkey_prefix . "\n" -- . page_title if cl_sortkey_prefix is nonempty. cl_sortkey varbinary(230) NOT NULL default '', -- A prefix for the raw sortkey manually specified by the user, either via -- [[Category:Foo|prefix]] or {{defaultsort:prefix}}. If nonempty, it's -- concatenated with a line break followed by the page title before the sortkey -- conversion algorithm is run. We store this so that we can update -- collations without reparsing all pages. -- Note: If you change the length of this field, you also need to change -- code in LinksUpdate.php. See bug 25254. cl_sortkey_prefix varchar(255) binary NOT NULL default '', -- This isn't really used at present. Provided for an optional -- sorting method by approximate addition time. cl_timestamp timestamp NOT NULL, -- Stores $wgCategoryCollation at the time cl_sortkey was generated. This -- can be used to install new collation versions, tracking which rows are not -- yet updated. '' means no collation, this is a legacy row that needs to be -- updated by updateCollation.php. In the future, it might be possible to -- specify different collations per category. cl_collation varbinary(32) NOT NULL default '', -- Stores whether cl_from is a category, file, or other page, so we can -- paginate the three categories separately. This never has to be updated -- after the page is created, since none of these page types can be moved to -- any other. cl_type ENUM('page', 'subcat', 'file') NOT NULL default 'page' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/cl_from ON /*_*/categorylinks (cl_from,cl_to); -- We always sort within a given category, and within a given type. FIXME: -- Formerly this index didn't cover cl_type (since that didn't exist), so old -- callers won't be using an index: fix this? CREATE INDEX /*i*/cl_sortkey ON /*_*/categorylinks (cl_to,cl_type,cl_sortkey,cl_from); -- Used by the API (and some extensions) CREATE INDEX /*i*/cl_timestamp ON /*_*/categorylinks (cl_to,cl_timestamp); -- FIXME: Not used, delete this CREATE INDEX /*i*/cl_collation ON /*_*/categorylinks (cl_collation); -- -- Track all existing categories. Something is a category if 1) it has an en- -- try somewhere in categorylinks, or 2) it once did. Categories might not -- have corresponding pages, so they need to be tracked separately. -- CREATE TABLE /*_*/category ( -- Primary key cat_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Name of the category, in the same form as page_title (with underscores). -- If there is a category page corresponding to this category, by definition, -- it has this name (in the Category namespace). cat_title varchar(255) binary NOT NULL, -- The numbers of member pages (including categories and media), subcatego- -- ries, and Image: namespace members, respectively. These are signed to -- make underflow more obvious. We make the first number include the second -- two for better sorting: subtracting for display is easy, adding for order- -- ing is not. cat_pages int signed NOT NULL default 0, cat_subcats int signed NOT NULL default 0, cat_files int signed NOT NULL default 0 ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/cat_title ON /*_*/category (cat_title); -- For Special:Mostlinkedcategories CREATE INDEX /*i*/cat_pages ON /*_*/category (cat_pages); -- -- Track links to external URLs -- CREATE TABLE /*_*/externallinks ( -- Primary key el_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- page_id of the referring page el_from int unsigned NOT NULL default 0, -- The URL el_to blob NOT NULL, -- In the case of HTTP URLs, this is the URL with any username or password -- removed, and with the labels in the hostname reversed and converted to -- lower case. An extra dot is added to allow for matching of either -- example.com or *.example.com in a single scan. -- Example: -- http://user:[email protected]/page.html -- becomes -- http://com.example.sub./page.html -- which allows for fast searching for all pages under example.com with the -- clause: -- WHERE el_index LIKE 'http://com.example.%' el_index blob NOT NULL ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/el_from ON /*_*/externallinks (el_from, el_to(40)); CREATE INDEX /*i*/el_to ON /*_*/externallinks (el_to(60), el_from); CREATE INDEX /*i*/el_index ON /*_*/externallinks (el_index(60)); -- -- Track interlanguage links -- CREATE TABLE /*_*/langlinks ( -- page_id of the referring page ll_from int unsigned NOT NULL default 0, -- Language code of the target ll_lang varbinary(20) NOT NULL default '', -- Title of the target, including namespace ll_title varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/ll_from ON /*_*/langlinks (ll_from, ll_lang); CREATE INDEX /*i*/ll_lang ON /*_*/langlinks (ll_lang, ll_title); -- -- Track inline interwiki links -- CREATE TABLE /*_*/iwlinks ( -- page_id of the referring page iwl_from int unsigned NOT NULL default 0, -- Interwiki prefix code of the target iwl_prefix varbinary(20) NOT NULL default '', -- Title of the target, including namespace iwl_title varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/iwl_from ON /*_*/iwlinks (iwl_from, iwl_prefix, iwl_title); CREATE INDEX /*i*/iwl_prefix_title_from ON /*_*/iwlinks (iwl_prefix, iwl_title, iwl_from); CREATE INDEX /*i*/iwl_prefix_from_title ON /*_*/iwlinks (iwl_prefix, iwl_from, iwl_title); -- -- Contains a single row with some aggregate info -- on the state of the site. -- CREATE TABLE /*_*/site_stats ( -- The single row should contain 1 here. ss_row_id int unsigned NOT NULL, -- Total number of page views, if hit counters are enabled. ss_total_views bigint unsigned default 0, -- Total number of edits performed. ss_total_edits bigint unsigned default 0, -- An approximate count of pages matching the following criteria: -- * in namespace 0 -- * not a redirect -- * contains the text '[[' -- See Article::isCountable() in includes/Article.php ss_good_articles bigint unsigned default 0, -- Total pages, theoretically equal to SELECT COUNT(*) FROM page; except faster ss_total_pages bigint default '-1', -- Number of users, theoretically equal to SELECT COUNT(*) FROM user; ss_users bigint default '-1', -- Number of users that still edit ss_active_users bigint default '-1', -- Number of images, equivalent to SELECT COUNT(*) FROM image ss_images int default 0 ) /*$wgDBTableOptions*/; -- Pointless index to assuage developer superstitions CREATE UNIQUE INDEX /*i*/ss_row_id ON /*_*/site_stats (ss_row_id); -- -- Stores an ID for every time any article is visited; -- depending on $wgHitcounterUpdateFreq, it is -- periodically cleared and the page_counter column -- in the page table updated for all the articles -- that have been visited.) -- CREATE TABLE /*_*/hitcounter ( hc_id int unsigned NOT NULL ) ENGINE=HEAP MAX_ROWS=25000; -- -- The internet is full of jerks, alas. Sometimes it's handy -- to block a vandal or troll account. -- CREATE TABLE /*_*/ipblocks ( -- Primary key, introduced for privacy. ipb_id int NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Blocked IP address in dotted-quad form or user name. ipb_address tinyblob NOT NULL, -- Blocked user ID or 0 for IP blocks. ipb_user int unsigned NOT NULL default 0, -- User ID who made the block. ipb_by int unsigned NOT NULL default 0, -- User name of blocker ipb_by_text varchar(255) binary NOT NULL default '', -- Text comment made by blocker. ipb_reason tinyblob NOT NULL, -- Creation (or refresh) date in standard YMDHMS form. -- IP blocks expire automatically. ipb_timestamp binary(14) NOT NULL default '', -- Indicates that the IP address was banned because a banned -- user accessed a page through it. If this is 1, ipb_address -- will be hidden, and the block identified by block ID number. ipb_auto bool NOT NULL default 0, -- If set to 1, block applies only to logged-out users ipb_anon_only bool NOT NULL default 0, -- Block prevents account creation from matching IP addresses ipb_create_account bool NOT NULL default 1, -- Block triggers autoblocks ipb_enable_autoblock bool NOT NULL default '1', -- Time at which the block will expire. -- May be "infinity" ipb_expiry varbinary(14) NOT NULL default '', -- Start and end of an address range, in hexadecimal -- Size chosen to allow IPv6 -- FIXME: these fields were originally blank for single-IP blocks, -- but now they are populated. No migration was ever done. They -- should be fixed to be blank again for such blocks (bug 49504). ipb_range_start tinyblob NOT NULL, ipb_range_end tinyblob NOT NULL, -- Flag for entries hidden from users and Sysops ipb_deleted bool NOT NULL default 0, -- Block prevents user from accessing Special:Emailuser ipb_block_email bool NOT NULL default 0, -- Block allows user to edit their own talk page ipb_allow_usertalk bool NOT NULL default 0, -- ID of the block that caused this block to exist -- Autoblocks set this to the original block -- so that the original block being deleted also -- deletes the autoblocks ipb_parent_block_id int default NULL ) /*$wgDBTableOptions*/; -- Unique index to support "user already blocked" messages -- Any new options which prevent collisions should be included CREATE UNIQUE INDEX /*i*/ipb_address ON /*_*/ipblocks (ipb_address(255), ipb_user, ipb_auto, ipb_anon_only); CREATE INDEX /*i*/ipb_user ON /*_*/ipblocks (ipb_user); CREATE INDEX /*i*/ipb_range ON /*_*/ipblocks (ipb_range_start(8), ipb_range_end(8)); CREATE INDEX /*i*/ipb_timestamp ON /*_*/ipblocks (ipb_timestamp); CREATE INDEX /*i*/ipb_expiry ON /*_*/ipblocks (ipb_expiry); CREATE INDEX /*i*/ipb_parent_block_id ON /*_*/ipblocks (ipb_parent_block_id); -- -- Uploaded images and other files. -- CREATE TABLE /*_*/image ( -- Filename. -- This is also the title of the associated description page, -- which will be in namespace 6 (NS_FILE). img_name varchar(255) binary NOT NULL default '' PRIMARY KEY, -- File size in bytes. img_size int unsigned NOT NULL default 0, -- For images, size in pixels. img_width int NOT NULL default 0, img_height int NOT NULL default 0, -- Extracted Exif metadata stored as a serialized PHP array. img_metadata mediumblob NOT NULL, -- For images, bits per pixel if known. img_bits int NOT NULL default 0, -- Media type as defined by the MEDIATYPE_xxx constants img_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL, -- major part of a MIME media type as defined by IANA -- see http://www.iana.org/assignments/media-types/ img_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown", -- minor part of a MIME media type as defined by IANA -- the minor parts are not required to adher to any standard -- but should be consistent throughout the database -- see http://www.iana.org/assignments/media-types/ img_minor_mime varbinary(100) NOT NULL default "unknown", -- Description field as entered by the uploader. -- This is displayed in image upload history and logs. img_description tinyblob NOT NULL, -- user_id and user_name of uploader. img_user int unsigned NOT NULL default 0, img_user_text varchar(255) binary NOT NULL, -- Time of the upload. img_timestamp varbinary(14) NOT NULL default '', -- SHA-1 content hash in base-36 img_sha1 varbinary(32) NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/img_usertext_timestamp ON /*_*/image (img_user_text,img_timestamp); -- Used by Special:ListFiles for sort-by-size CREATE INDEX /*i*/img_size ON /*_*/image (img_size); -- Used by Special:Newimages and Special:ListFiles CREATE INDEX /*i*/img_timestamp ON /*_*/image (img_timestamp); -- Used in API and duplicate search CREATE INDEX /*i*/img_sha1 ON /*_*/image (img_sha1(10)); -- Used to get media of one type CREATE INDEX /*i*/img_media_mime ON /*_*/image (img_media_type,img_major_mime,img_minor_mime); -- -- Previous revisions of uploaded files. -- Awkwardly, image rows have to be moved into -- this table at re-upload time. -- CREATE TABLE /*_*/oldimage ( -- Base filename: key to image.img_name oi_name varchar(255) binary NOT NULL default '', -- Filename of the archived file. -- This is generally a timestamp and '!' prepended to the base name. oi_archive_name varchar(255) binary NOT NULL default '', -- Other fields as in image... oi_size int unsigned NOT NULL default 0, oi_width int NOT NULL default 0, oi_height int NOT NULL default 0, oi_bits int NOT NULL default 0, oi_description tinyblob NOT NULL, oi_user int unsigned NOT NULL default 0, oi_user_text varchar(255) binary NOT NULL, oi_timestamp binary(14) NOT NULL default '', oi_metadata mediumblob NOT NULL, oi_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL, oi_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") NOT NULL default "unknown", oi_minor_mime varbinary(100) NOT NULL default "unknown", oi_deleted tinyint unsigned NOT NULL default 0, oi_sha1 varbinary(32) NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/oi_usertext_timestamp ON /*_*/oldimage (oi_user_text,oi_timestamp); CREATE INDEX /*i*/oi_name_timestamp ON /*_*/oldimage (oi_name,oi_timestamp); -- oi_archive_name truncated to 14 to avoid key length overflow CREATE INDEX /*i*/oi_name_archive_name ON /*_*/oldimage (oi_name,oi_archive_name(14)); CREATE INDEX /*i*/oi_sha1 ON /*_*/oldimage (oi_sha1(10)); -- -- Record of deleted file data -- CREATE TABLE /*_*/filearchive ( -- Unique row id fa_id int NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Original base filename; key to image.img_name, page.page_title, etc fa_name varchar(255) binary NOT NULL default '', -- Filename of archived file, if an old revision fa_archive_name varchar(255) binary default '', -- Which storage bin (directory tree or object store) the file data -- is stored in. Should be 'deleted' for files that have been deleted; -- any other bin is not yet in use. fa_storage_group varbinary(16), -- SHA-1 of the file contents plus extension, used as a key for storage. -- eg 8f8a562add37052a1848ff7771a2c515db94baa9.jpg -- -- If NULL, the file was missing at deletion time or has been purged -- from the archival storage. fa_storage_key varbinary(64) default '', -- Deletion information, if this file is deleted. fa_deleted_user int, fa_deleted_timestamp binary(14) default '', fa_deleted_reason text, -- Duped fields from image fa_size int unsigned default 0, fa_width int default 0, fa_height int default 0, fa_metadata mediumblob, fa_bits int default 0, fa_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL, fa_major_mime ENUM("unknown", "application", "audio", "image", "text", "video", "message", "model", "multipart") default "unknown", fa_minor_mime varbinary(100) default "unknown", fa_description tinyblob, fa_user int unsigned default 0, fa_user_text varchar(255) binary, fa_timestamp binary(14) default '', -- Visibility of deleted revisions, bitfield fa_deleted tinyint unsigned NOT NULL default 0, -- sha1 hash of file content fa_sha1 varbinary(32) NOT NULL default '' ) /*$wgDBTableOptions*/; -- pick out by image name CREATE INDEX /*i*/fa_name ON /*_*/filearchive (fa_name, fa_timestamp); -- pick out dupe files CREATE INDEX /*i*/fa_storage_group ON /*_*/filearchive (fa_storage_group, fa_storage_key); -- sort by deletion time CREATE INDEX /*i*/fa_deleted_timestamp ON /*_*/filearchive (fa_deleted_timestamp); -- sort by uploader CREATE INDEX /*i*/fa_user_timestamp ON /*_*/filearchive (fa_user_text,fa_timestamp); -- find file by sha1, 10 bytes will be enough for hashes to be indexed CREATE INDEX /*i*/fa_sha1 ON /*_*/filearchive (fa_sha1(10)); -- -- Store information about newly uploaded files before they're -- moved into the actual filestore -- CREATE TABLE /*_*/uploadstash ( us_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- the user who uploaded the file. us_user int unsigned NOT NULL, -- file key. this is how applications actually search for the file. -- this might go away, or become the primary key. us_key varchar(255) NOT NULL, -- the original path us_orig_path varchar(255) NOT NULL, -- the temporary path at which the file is actually stored us_path varchar(255) NOT NULL, -- which type of upload the file came from (sometimes) us_source_type varchar(50), -- the date/time on which the file was added us_timestamp varbinary(14) NOT NULL, us_status varchar(50) NOT NULL, -- chunk counter starts at 0, current offset is stored in us_size us_chunk_inx int unsigned NULL, -- Serialized file properties from File::getPropsFromPath us_props blob, -- file size in bytes us_size int unsigned NOT NULL, -- this hash comes from File::sha1Base36(), and is 31 characters us_sha1 varchar(31) NOT NULL, us_mime varchar(255), -- Media type as defined by the MEDIATYPE_xxx constants, should duplicate definition in the image table us_media_type ENUM("UNKNOWN", "BITMAP", "DRAWING", "AUDIO", "VIDEO", "MULTIMEDIA", "OFFICE", "TEXT", "EXECUTABLE", "ARCHIVE") default NULL, -- image-specific properties us_image_width int unsigned, us_image_height int unsigned, us_image_bits smallint unsigned ) /*$wgDBTableOptions*/; -- sometimes there's a delete for all of a user's stuff. CREATE INDEX /*i*/us_user ON /*_*/uploadstash (us_user); -- pick out files by key, enforce key uniqueness CREATE UNIQUE INDEX /*i*/us_key ON /*_*/uploadstash (us_key); -- the abandoned upload cleanup script needs this CREATE INDEX /*i*/us_timestamp ON /*_*/uploadstash (us_timestamp); -- -- Primarily a summary table for Special:Recentchanges, -- this table contains some additional info on edits from -- the last few days, see Article::editUpdates() -- CREATE TABLE /*_*/recentchanges ( rc_id int NOT NULL PRIMARY KEY AUTO_INCREMENT, rc_timestamp varbinary(14) NOT NULL default '', -- This is no longer used -- Field kept in database for downgrades -- @todo: add drop patch with 1.24 rc_cur_time varbinary(14) NOT NULL default '', -- As in revision rc_user int unsigned NOT NULL default 0, rc_user_text varchar(255) binary NOT NULL, -- When pages are renamed, their RC entries do _not_ change. rc_namespace int NOT NULL default 0, rc_title varchar(255) binary NOT NULL default '', -- as in revision... rc_comment varchar(255) binary NOT NULL default '', rc_minor tinyint unsigned NOT NULL default 0, -- Edits by user accounts with the 'bot' rights key are -- marked with a 1 here, and will be hidden from the -- default view. rc_bot tinyint unsigned NOT NULL default 0, -- Set if this change corresponds to a page creation rc_new tinyint unsigned NOT NULL default 0, -- Key to page_id (was cur_id prior to 1.5). -- This will keep links working after moves while -- retaining the at-the-time name in the changes list. rc_cur_id int unsigned NOT NULL default 0, -- rev_id of the given revision rc_this_oldid int unsigned NOT NULL default 0, -- rev_id of the prior revision, for generating diff links. rc_last_oldid int unsigned NOT NULL default 0, -- The type of change entry (RC_EDIT,RC_NEW,RC_LOG,RC_EXTERNAL) rc_type tinyint unsigned NOT NULL default 0, -- The source of the change entry (replaces rc_type) -- default of '' is temporary, needed for initial migration rc_source varchar(16) binary not null default '', -- If the Recent Changes Patrol option is enabled, -- users may mark edits as having been reviewed to -- remove a warning flag on the RC list. -- A value of 1 indicates the page has been reviewed. rc_patrolled tinyint unsigned NOT NULL default 0, -- Recorded IP address the edit was made from, if the -- $wgPutIPinRC option is enabled. rc_ip varbinary(40) NOT NULL default '', -- Text length in characters before -- and after the edit rc_old_len int, rc_new_len int, -- Visibility of recent changes items, bitfield rc_deleted tinyint unsigned NOT NULL default 0, -- Value corresponding to log_id, specific log entries rc_logid int unsigned NOT NULL default 0, -- Store log type info here, or null rc_log_type varbinary(255) NULL default NULL, -- Store log action or null rc_log_action varbinary(255) NULL default NULL, -- Log params rc_params blob NULL ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/rc_timestamp ON /*_*/recentchanges (rc_timestamp); CREATE INDEX /*i*/rc_namespace_title ON /*_*/recentchanges (rc_namespace, rc_title); CREATE INDEX /*i*/rc_cur_id ON /*_*/recentchanges (rc_cur_id); CREATE INDEX /*i*/new_name_timestamp ON /*_*/recentchanges (rc_new,rc_namespace,rc_timestamp); CREATE INDEX /*i*/rc_ip ON /*_*/recentchanges (rc_ip); CREATE INDEX /*i*/rc_ns_usertext ON /*_*/recentchanges (rc_namespace, rc_user_text); CREATE INDEX /*i*/rc_user_text ON /*_*/recentchanges (rc_user_text, rc_timestamp); CREATE TABLE /*_*/watchlist ( -- Key to user.user_id wl_user int unsigned NOT NULL, -- Key to page_namespace/page_title -- Note that users may watch pages which do not exist yet, -- or existed in the past but have been deleted. wl_namespace int NOT NULL default 0, wl_title varchar(255) binary NOT NULL default '', -- Timestamp used to send notification e-mails and show "updated since last visit" markers on -- history and recent changes / watchlist. Set to NULL when the user visits the latest revision -- of the page, which means that they should be sent an e-mail on the next change. wl_notificationtimestamp varbinary(14) ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/wl_user ON /*_*/watchlist (wl_user, wl_namespace, wl_title); CREATE INDEX /*i*/namespace_title ON /*_*/watchlist (wl_namespace, wl_title); -- -- When using the default MySQL search backend, page titles -- and text are munged to strip markup, do Unicode case folding, -- and prepare the result for MySQL's fulltext index. -- -- This table must be MyISAM; InnoDB does not support the needed -- fulltext index. -- CREATE TABLE /*_*/searchindex ( -- Key to page_id si_page int unsigned NOT NULL, -- Munged version of title si_title varchar(255) NOT NULL default '', -- Munged version of body text si_text mediumtext NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=utf8; CREATE UNIQUE INDEX /*i*/si_page ON /*_*/searchindex (si_page); CREATE FULLTEXT INDEX /*i*/si_title ON /*_*/searchindex (si_title); CREATE FULLTEXT INDEX /*i*/si_text ON /*_*/searchindex (si_text); -- -- Recognized interwiki link prefixes -- CREATE TABLE /*_*/interwiki ( -- The interwiki prefix, (e.g. "Meatball", or the language prefix "de") iw_prefix varchar(32) NOT NULL, -- The URL of the wiki, with "$1" as a placeholder for an article name. -- Any spaces in the name will be transformed to underscores before -- insertion. iw_url blob NOT NULL, -- The URL of the file api.php iw_api blob NOT NULL, -- The name of the database (for a connection to be established with wfGetLB( 'wikiid' )) iw_wikiid varchar(64) NOT NULL, -- A boolean value indicating whether the wiki is in this project -- (used, for example, to detect redirect loops) iw_local bool NOT NULL, -- Boolean value indicating whether interwiki transclusions are allowed. iw_trans tinyint NOT NULL default 0 ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/iw_prefix ON /*_*/interwiki (iw_prefix); -- -- Used for caching expensive grouped queries -- CREATE TABLE /*_*/querycache ( -- A key name, generally the base name of of the special page. qc_type varbinary(32) NOT NULL, -- Some sort of stored value. Sizes, counts... qc_value int unsigned NOT NULL default 0, -- Target namespace+title qc_namespace int NOT NULL default 0, qc_title varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/qc_type ON /*_*/querycache (qc_type,qc_value); -- -- For a few generic cache operations if not using Memcached -- CREATE TABLE /*_*/objectcache ( keyname varbinary(255) NOT NULL default '' PRIMARY KEY, value mediumblob, exptime datetime ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/exptime ON /*_*/objectcache (exptime); -- -- Cache of interwiki transclusion -- CREATE TABLE /*_*/transcache ( tc_url varbinary(255) NOT NULL, tc_contents text, tc_time binary(14) NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/tc_url_idx ON /*_*/transcache (tc_url); CREATE TABLE /*_*/logging ( -- Log ID, for referring to this specific log entry, probably for deletion and such. log_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Symbolic keys for the general log type and the action type -- within the log. The output format will be controlled by the -- action field, but only the type controls categorization. log_type varbinary(32) NOT NULL default '', log_action varbinary(32) NOT NULL default '', -- Timestamp. Duh. log_timestamp binary(14) NOT NULL default '19700101000000', -- The user who performed this action; key to user_id log_user int unsigned NOT NULL default 0, -- Name of the user who performed this action log_user_text varchar(255) binary NOT NULL default '', -- Key to the page affected. Where a user is the target, -- this will point to the user page. log_namespace int NOT NULL default 0, log_title varchar(255) binary NOT NULL default '', log_page int unsigned NULL, -- Freeform text. Interpreted as edit history comments. log_comment varchar(255) NOT NULL default '', -- miscellaneous parameters: -- LF separated list (old system) or serialized PHP array (new system) log_params blob NOT NULL, -- rev_deleted for logs log_deleted tinyint unsigned NOT NULL default 0 ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/type_time ON /*_*/logging (log_type, log_timestamp); CREATE INDEX /*i*/user_time ON /*_*/logging (log_user, log_timestamp); CREATE INDEX /*i*/page_time ON /*_*/logging (log_namespace, log_title, log_timestamp); CREATE INDEX /*i*/times ON /*_*/logging (log_timestamp); CREATE INDEX /*i*/log_user_type_time ON /*_*/logging (log_user, log_type, log_timestamp); CREATE INDEX /*i*/log_page_id_time ON /*_*/logging (log_page,log_timestamp); CREATE INDEX /*i*/type_action ON /*_*/logging (log_type, log_action, log_timestamp); CREATE INDEX /*i*/log_user_text_type_time ON /*_*/logging (log_user_text, log_type, log_timestamp); CREATE INDEX /*i*/log_user_text_time ON /*_*/logging (log_user_text, log_timestamp); CREATE TABLE /*_*/log_search ( -- The type of ID (rev ID, log ID, rev timestamp, username) ls_field varbinary(32) NOT NULL, -- The value of the ID ls_value varchar(255) NOT NULL, -- Key to log_id ls_log_id int unsigned NOT NULL default 0 ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/ls_field_val ON /*_*/log_search (ls_field,ls_value,ls_log_id); CREATE INDEX /*i*/ls_log_id ON /*_*/log_search (ls_log_id); -- Jobs performed by parallel apache threads or a command-line daemon CREATE TABLE /*_*/job ( job_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Command name -- Limited to 60 to prevent key length overflow job_cmd varbinary(60) NOT NULL default '', -- Namespace and title to act on -- Should be 0 and '' if the command does not operate on a title job_namespace int NOT NULL, job_title varchar(255) binary NOT NULL, -- Timestamp of when the job was inserted -- NULL for jobs added before addition of the timestamp job_timestamp varbinary(14) NULL default NULL, -- Any other parameters to the command -- Stored as a PHP serialized array, or an empty string if there are no parameters job_params blob NOT NULL, -- Random, non-unique, number used for job acquisition (for lock concurrency) job_random integer unsigned NOT NULL default 0, -- The number of times this job has been locked job_attempts integer unsigned NOT NULL default 0, -- Field that conveys process locks on rows via process UUIDs job_token varbinary(32) NOT NULL default '', -- Timestamp when the job was locked job_token_timestamp varbinary(14) NULL default NULL, -- Base 36 SHA1 of the job parameters relevant to detecting duplicates job_sha1 varbinary(32) NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/job_sha1 ON /*_*/job (job_sha1); CREATE INDEX /*i*/job_cmd_token ON /*_*/job (job_cmd,job_token,job_random); CREATE INDEX /*i*/job_cmd_token_id ON /*_*/job (job_cmd,job_token,job_id); CREATE INDEX /*i*/job_cmd ON /*_*/job (job_cmd, job_namespace, job_title, job_params(128)); CREATE INDEX /*i*/job_timestamp ON /*_*/job (job_timestamp); -- Details of updates to cached special pages CREATE TABLE /*_*/querycache_info ( -- Special page name -- Corresponds to a qc_type value qci_type varbinary(32) NOT NULL default '', -- Timestamp of last update qci_timestamp binary(14) NOT NULL default '19700101000000' ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/qci_type ON /*_*/querycache_info (qci_type); -- For each redirect, this table contains exactly one row defining its target CREATE TABLE /*_*/redirect ( -- Key to the page_id of the redirect page rd_from int unsigned NOT NULL default 0 PRIMARY KEY, -- Key to page_namespace/page_title of the target page. -- The target page may or may not exist, and due to renames -- and deletions may refer to different page records as time -- goes by. rd_namespace int NOT NULL default 0, rd_title varchar(255) binary NOT NULL default '', rd_interwiki varchar(32) default NULL, rd_fragment varchar(255) binary default NULL ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/rd_ns_title ON /*_*/redirect (rd_namespace,rd_title,rd_from); -- Used for caching expensive grouped queries that need two links (for example double-redirects) CREATE TABLE /*_*/querycachetwo ( -- A key name, generally the base name of of the special page. qcc_type varbinary(32) NOT NULL, -- Some sort of stored value. Sizes, counts... qcc_value int unsigned NOT NULL default 0, -- Target namespace+title qcc_namespace int NOT NULL default 0, qcc_title varchar(255) binary NOT NULL default '', -- Target namespace+title2 qcc_namespacetwo int NOT NULL default 0, qcc_titletwo varchar(255) binary NOT NULL default '' ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/qcc_type ON /*_*/querycachetwo (qcc_type,qcc_value); CREATE INDEX /*i*/qcc_title ON /*_*/querycachetwo (qcc_type,qcc_namespace,qcc_title); CREATE INDEX /*i*/qcc_titletwo ON /*_*/querycachetwo (qcc_type,qcc_namespacetwo,qcc_titletwo); -- Used for storing page restrictions (i.e. protection levels) CREATE TABLE /*_*/page_restrictions ( -- Field for an ID for this restrictions row (sort-key for Special:ProtectedPages) pr_id int unsigned NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Page to apply restrictions to (Foreign Key to page). pr_page int NOT NULL, -- The protection type (edit, move, etc) pr_type varbinary(60) NOT NULL, -- The protection level (Sysop, autoconfirmed, etc) pr_level varbinary(60) NOT NULL, -- Whether or not to cascade the protection down to pages transcluded. pr_cascade tinyint NOT NULL, -- Field for future support of per-user restriction. pr_user int NULL, -- Field for time-limited protection. pr_expiry varbinary(14) NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/pr_pagetype ON /*_*/page_restrictions (pr_page,pr_type); CREATE INDEX /*i*/pr_typelevel ON /*_*/page_restrictions (pr_type,pr_level); CREATE INDEX /*i*/pr_level ON /*_*/page_restrictions (pr_level); CREATE INDEX /*i*/pr_cascade ON /*_*/page_restrictions (pr_cascade); -- Protected titles - nonexistent pages that have been protected CREATE TABLE /*_*/protected_titles ( pt_namespace int NOT NULL, pt_title varchar(255) binary NOT NULL, pt_user int unsigned NOT NULL, pt_reason tinyblob, pt_timestamp binary(14) NOT NULL, pt_expiry varbinary(14) NOT NULL default '', pt_create_perm varbinary(60) NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/pt_namespace_title ON /*_*/protected_titles (pt_namespace,pt_title); CREATE INDEX /*i*/pt_timestamp ON /*_*/protected_titles (pt_timestamp); -- Name/value pairs indexed by page_id CREATE TABLE /*_*/page_props ( pp_page int NOT NULL, pp_propname varbinary(60) NOT NULL, pp_value blob NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/pp_page_propname ON /*_*/page_props (pp_page,pp_propname); CREATE UNIQUE INDEX /*i*/pp_propname_page ON /*_*/page_props (pp_propname,pp_page); -- A table to log updates, one text key row per update. CREATE TABLE /*_*/updatelog ( ul_key varchar(255) NOT NULL PRIMARY KEY, ul_value blob ) /*$wgDBTableOptions*/; -- A table to track tags for revisions, logs and recent changes. CREATE TABLE /*_*/change_tag ( -- RCID for the change ct_rc_id int NULL, -- LOGID for the change ct_log_id int NULL, -- REVID for the change ct_rev_id int NULL, -- Tag applied ct_tag varchar(255) NOT NULL, -- Parameters for the tag, presently unused ct_params blob NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/change_tag_rc_tag ON /*_*/change_tag (ct_rc_id,ct_tag); CREATE UNIQUE INDEX /*i*/change_tag_log_tag ON /*_*/change_tag (ct_log_id,ct_tag); CREATE UNIQUE INDEX /*i*/change_tag_rev_tag ON /*_*/change_tag (ct_rev_id,ct_tag); -- Covering index, so we can pull all the info only out of the index. CREATE INDEX /*i*/change_tag_tag_id ON /*_*/change_tag (ct_tag,ct_rc_id,ct_rev_id,ct_log_id); -- Rollup table to pull a LIST of tags simply without ugly GROUP_CONCAT -- that only works on MySQL 4.1+ CREATE TABLE /*_*/tag_summary ( -- RCID for the change ts_rc_id int NULL, -- LOGID for the change ts_log_id int NULL, -- REVID for the change ts_rev_id int NULL, -- Comma-separated list of tags ts_tags blob NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/tag_summary_rc_id ON /*_*/tag_summary (ts_rc_id); CREATE UNIQUE INDEX /*i*/tag_summary_log_id ON /*_*/tag_summary (ts_log_id); CREATE UNIQUE INDEX /*i*/tag_summary_rev_id ON /*_*/tag_summary (ts_rev_id); CREATE TABLE /*_*/valid_tag ( vt_tag varchar(255) NOT NULL PRIMARY KEY ) /*$wgDBTableOptions*/; -- Table for storing localisation data CREATE TABLE /*_*/l10n_cache ( -- Language code lc_lang varbinary(32) NOT NULL, -- Cache key lc_key varchar(255) NOT NULL, -- Value lc_value mediumblob NOT NULL ) /*$wgDBTableOptions*/; CREATE INDEX /*i*/lc_lang_key ON /*_*/l10n_cache (lc_lang, lc_key); -- Table for caching JSON message blobs for the resource loader CREATE TABLE /*_*/msg_resource ( -- Resource name mr_resource varbinary(255) NOT NULL, -- Language code mr_lang varbinary(32) NOT NULL, -- JSON blob mr_blob mediumblob NOT NULL, -- Timestamp of last update mr_timestamp binary(14) NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/mr_resource_lang ON /*_*/msg_resource (mr_resource, mr_lang); -- Table for administering which message is contained in which resource CREATE TABLE /*_*/msg_resource_links ( mrl_resource varbinary(255) NOT NULL, -- Message key mrl_message varbinary(255) NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/mrl_message_resource ON /*_*/msg_resource_links (mrl_message, mrl_resource); -- Table caching which local files a module depends on that aren't -- registered directly, used for fast retrieval of file dependency. -- Currently only used for tracking images that CSS depends on CREATE TABLE /*_*/module_deps ( -- Module name md_module varbinary(255) NOT NULL, -- Skin name md_skin varbinary(32) NOT NULL, -- JSON blob with file dependencies md_deps mediumblob NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/md_module_skin ON /*_*/module_deps (md_module, md_skin); -- Holds all the sites known to the wiki. CREATE TABLE /*_*/sites ( -- Numeric id of the site site_id INT UNSIGNED NOT NULL PRIMARY KEY AUTO_INCREMENT, -- Global identifier for the site, ie 'enwiktionary' site_global_key varbinary(32) NOT NULL, -- Type of the site, ie 'mediawiki' site_type varbinary(32) NOT NULL, -- Group of the site, ie 'wikipedia' site_group varbinary(32) NOT NULL, -- Source of the site data, ie 'local', 'wikidata', 'my-magical-repo' site_source varbinary(32) NOT NULL, -- Language code of the sites primary language. site_language varbinary(32) NOT NULL, -- Protocol of the site, ie 'http://', 'irc://', '//' -- This field is an index for lookups and is build from type specific data in site_data. site_protocol varbinary(32) NOT NULL, -- Domain of the site in reverse order, ie 'org.mediawiki.www.' -- This field is an index for lookups and is build from type specific data in site_data. site_domain VARCHAR(255) NOT NULL, -- Type dependent site data. site_data BLOB NOT NULL, -- If site.tld/path/key:pageTitle should forward users to the page on -- the actual site, where "key" is the local identifier. site_forward bool NOT NULL, -- Type dependent site config. -- For instance if template transclusion should be allowed if it's a MediaWiki. site_config BLOB NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/sites_global_key ON /*_*/sites (site_global_key); CREATE INDEX /*i*/sites_type ON /*_*/sites (site_type); CREATE INDEX /*i*/sites_group ON /*_*/sites (site_group); CREATE INDEX /*i*/sites_source ON /*_*/sites (site_source); CREATE INDEX /*i*/sites_language ON /*_*/sites (site_language); CREATE INDEX /*i*/sites_protocol ON /*_*/sites (site_protocol); CREATE INDEX /*i*/sites_domain ON /*_*/sites (site_domain); CREATE INDEX /*i*/sites_forward ON /*_*/sites (site_forward); -- Links local site identifiers to their corresponding site. CREATE TABLE /*_*/site_identifiers ( -- Key on site.site_id si_site INT UNSIGNED NOT NULL, -- local key type, ie 'interwiki' or 'langlink' si_type varbinary(32) NOT NULL, -- local key value, ie 'en' or 'wiktionary' si_key varbinary(32) NOT NULL ) /*$wgDBTableOptions*/; CREATE UNIQUE INDEX /*i*/site_ids_type ON /*_*/site_identifiers (si_type, si_key); CREATE INDEX /*i*/site_ids_site ON /*_*/site_identifiers (si_site); CREATE INDEX /*i*/site_ids_key ON /*_*/site_identifiers (si_key); -- vim: sw=2 sts=2 et
AngLi-Leon/peloton
mediawiki-dataset/schema-versions/0042.12-Dec-2013.b57e4570913cbe385fe515f3a0adb8a3c7de55cf.tables.sql
SQL
apache-2.0
59,488
/* * 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.reifier; import org.apache.camel.Processor; import org.apache.camel.ResumeStrategy; import org.apache.camel.Route; import org.apache.camel.model.ProcessorDefinition; import org.apache.camel.model.ResumableDefinition; import org.apache.camel.processor.resume.ResumableProcessor; import org.apache.camel.util.ObjectHelper; public class ResumableReifier extends ProcessorReifier<ResumableDefinition> { protected ResumableReifier(Route route, ProcessorDefinition<?> definition) { super(route, ResumableDefinition.class.cast(definition)); } @Override public Processor createProcessor() throws Exception { Processor childProcessor = createChildProcessor(false); ResumeStrategy resumeStrategy = resolveResumeStrategy(); ObjectHelper.notNull(resumeStrategy, "resumeStrategy", definition); route.setResumeStrategy(resumeStrategy); return new ResumableProcessor(resumeStrategy, childProcessor); } protected ResumeStrategy resolveResumeStrategy() { ResumeStrategy strategy = definition.getResumeStrategyBean(); if (strategy == null) { String ref = parseString(definition.getResumeStrategy()); strategy = mandatoryLookup(ref, ResumeStrategy.class); } return strategy; } }
christophd/camel
core/camel-core-reifier/src/main/java/org/apache/camel/reifier/ResumableReifier.java
Java
apache-2.0
2,127
<?php class Login{ /** * @var LibLogin */ private $lib; function __construct(){ if(get_config('password')=='94a5f0635f5e7163fc23346870d55b52'){ redirect('Help#DefaultPassword'); } $this->lib = get_lib('LibLogin'); } public function main(){ get_lib('LibTemplate')->set_title('用户密码验证'); get_core()->view('header'); get_core()->view('login'); get_core()->view('footer'); } public function logout(){ $this->lib->logout(); redirect('Login'); } public function post(){ $this->lib->set_password(get_core('LyPost')->get('password'),true); if($this->lib->v()){ if(get_core('LyPost')->get('redirect')) redirect(get_core('LyPost')->get('redirect')); else redirect(get_url()); }else{ if(get_core('LyPost')->get('redirect')) redirect(get_url('Login?status=error&redirect='.urlencode(get_core('LyPost')->get('redirect')))); else redirect(get_url('Login?status=error')); } } } ?>
work4team/jxmb
ThinkPHP/Library/Vendor/fm/LySystem/LyPage/Login.php
PHP
apache-2.0
952
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.gmf.esb.impl; import org.eclipse.emf.common.notify.Notification; import java.util.Collection; import org.eclipse.emf.common.notify.NotificationChain; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.InternalEObject; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.util.EObjectContainmentEList; import org.eclipse.emf.ecore.util.InternalEList; import org.wso2.developerstudio.eclipse.gmf.esb.EsbElement; import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage; import org.wso2.developerstudio.eclipse.gmf.esb.MediatorFlow; import org.wso2.developerstudio.eclipse.gmf.esb.ProxyServiceFaultContainer; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Proxy Service Fault Container</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.wso2.developerstudio.eclipse.gmf.esb.impl.ProxyServiceFaultContainerImpl#getMediatorFlow <em>Mediator Flow</em>}</li> * </ul> * * @generated */ public class ProxyServiceFaultContainerImpl extends EsbNodeImpl implements ProxyServiceFaultContainer { /** * The cached value of the '{@link #getMediatorFlow() <em>Mediator Flow</em>}' containment reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMediatorFlow() * @generated * @ordered */ protected MediatorFlow mediatorFlow; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected ProxyServiceFaultContainerImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return EsbPackage.Literals.PROXY_SERVICE_FAULT_CONTAINER; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public MediatorFlow getMediatorFlow() { return mediatorFlow; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public NotificationChain basicSetMediatorFlow(MediatorFlow newMediatorFlow, NotificationChain msgs) { MediatorFlow oldMediatorFlow = mediatorFlow; mediatorFlow = newMediatorFlow; if (eNotificationRequired()) { ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW, oldMediatorFlow, newMediatorFlow); if (msgs == null) msgs = notification; else msgs.add(notification); } return msgs; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMediatorFlow(MediatorFlow newMediatorFlow) { if (newMediatorFlow != mediatorFlow) { NotificationChain msgs = null; if (mediatorFlow != null) msgs = ((InternalEObject)mediatorFlow).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW, null, msgs); if (newMediatorFlow != null) msgs = ((InternalEObject)newMediatorFlow).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW, null, msgs); msgs = basicSetMediatorFlow(newMediatorFlow, msgs); if (msgs != null) msgs.dispatch(); } else if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW, newMediatorFlow, newMediatorFlow)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) { switch (featureID) { case EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW: return basicSetMediatorFlow(null, msgs); } return super.eInverseRemove(otherEnd, featureID, msgs); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW: return getMediatorFlow(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW: setMediatorFlow((MediatorFlow)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW: setMediatorFlow((MediatorFlow)null); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case EsbPackage.PROXY_SERVICE_FAULT_CONTAINER__MEDIATOR_FLOW: return mediatorFlow != null; } return super.eIsSet(featureID); } } //ProxyServiceFaultContainerImpl
nwnpallewela/devstudio-tooling-esb
plugins/org.wso2.developerstudio.eclipse.gmf.esb/src/org/wso2/developerstudio/eclipse/gmf/esb/impl/ProxyServiceFaultContainerImpl.java
Java
apache-2.0
5,187
package gov.hhs.onc.dcdt.config.instance.impl; import com.fasterxml.jackson.annotation.JsonTypeName; import gov.hhs.onc.dcdt.beans.impl.AbstractToolDomainAddressBean; import gov.hhs.onc.dcdt.beans.utils.ToolBeanFactoryUtils; import gov.hhs.onc.dcdt.collections.impl.AbstractToolPredicate; import gov.hhs.onc.dcdt.collections.impl.AbstractToolTransformer; import gov.hhs.onc.dcdt.config.instance.InstanceDnsConfig; import gov.hhs.onc.dcdt.crypto.DataEncoding; import gov.hhs.onc.dcdt.crypto.certs.CertificateInfo; import gov.hhs.onc.dcdt.crypto.certs.SignatureAlgorithm; import gov.hhs.onc.dcdt.crypto.credentials.CredentialInfo; import gov.hhs.onc.dcdt.crypto.keys.KeyInfo; import gov.hhs.onc.dcdt.crypto.utils.CertificateUtils; import gov.hhs.onc.dcdt.dns.DnsKeyAlgorithmType; import gov.hhs.onc.dcdt.dns.DnsRecordType; import gov.hhs.onc.dcdt.dns.config.ARecordConfig; import gov.hhs.onc.dcdt.dns.config.CertRecordConfig; import gov.hhs.onc.dcdt.dns.config.CnameRecordConfig; import gov.hhs.onc.dcdt.dns.config.DnsRecordConfig; import gov.hhs.onc.dcdt.dns.config.MxRecordConfig; import gov.hhs.onc.dcdt.dns.config.NsRecordConfig; import gov.hhs.onc.dcdt.dns.config.PtrRecordConfig; import gov.hhs.onc.dcdt.dns.config.SoaRecordConfig; import gov.hhs.onc.dcdt.dns.config.SrvRecordConfig; import gov.hhs.onc.dcdt.dns.config.TargetedDnsRecordConfig; import gov.hhs.onc.dcdt.dns.config.TxtRecordConfig; import gov.hhs.onc.dcdt.dns.utils.ToolDnsNameUtils; import gov.hhs.onc.dcdt.dns.utils.ToolDnsRecordUtils; import gov.hhs.onc.dcdt.mail.MailAddress; import gov.hhs.onc.dcdt.testcases.discovery.DiscoveryTestcase; import gov.hhs.onc.dcdt.testcases.discovery.credentials.DiscoveryTestcaseCredential; import gov.hhs.onc.dcdt.testcases.discovery.credentials.DiscoveryTestcaseCredentialLocation; import gov.hhs.onc.dcdt.utils.ToolArrayUtils; import gov.hhs.onc.dcdt.utils.ToolCollectionUtils; import gov.hhs.onc.dcdt.utils.ToolEnumUtils; import java.util.ArrayList; import java.util.EnumMap; import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import javax.annotation.Nullable; import org.apache.commons.collections4.CollectionUtils; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.AbstractApplicationContext; import org.xbill.DNS.Name; import org.xbill.DNS.Record; import org.xbill.DNS.ReverseMap; @JsonTypeName("instanceDnsConfig") public class InstanceDnsConfigImpl extends AbstractToolDomainAddressBean implements InstanceDnsConfig { public static class AuthoritativeDnsConfigPredicate extends AbstractToolPredicate<InstanceDnsConfig> { private DnsRecordType questionRecordType; private Name questionName; public AuthoritativeDnsConfigPredicate(DnsRecordType questionRecordType, Name questionName) { this.questionRecordType = questionRecordType; this.questionName = questionName; } @Override protected boolean evaluateInternal(InstanceDnsConfig dnsConfig) throws Exception { return dnsConfig.isAuthoritative(this.questionRecordType, this.questionName); } } private class ReverseMapPtrRecordConfigTransformer extends AbstractToolTransformer<ARecordConfig, PtrRecordConfig> { @Override protected PtrRecordConfig transformInternal(ARecordConfig aRecordConfig) throws Exception { PtrRecordConfig ptrRecordConfig = ToolBeanFactoryUtils.createBeanOfType(InstanceDnsConfigImpl.this.appContext, PtrRecordConfig.class); // noinspection ConstantConditions ptrRecordConfig.setName(ReverseMap.fromAddress(aRecordConfig.getAddress())); ptrRecordConfig.setTarget(aRecordConfig.getName()); return ptrRecordConfig; } } private class DiscoveryTestcaseCredentialCertRecordConfigTransformer extends AbstractToolTransformer<DiscoveryTestcaseCredential, CertRecordConfig> { @Override protected CertRecordConfig transformInternal(DiscoveryTestcaseCredential discoveryTestcaseCred) throws Exception { CertRecordConfig certRecordConfig = ToolBeanFactoryUtils.createBeanOfType(InstanceDnsConfigImpl.this.appContext, CertRecordConfig.class); // noinspection ConstantConditions certRecordConfig.setName(ToolDnsNameUtils.toAbsolute(discoveryTestcaseCred.getLocation().getMailAddress().toAddressName())); // noinspection ConstantConditions KeyInfo discoveryTestcaseCredKeyInfo = discoveryTestcaseCred.getCredentialInfo().getKeyDescriptor(); CertificateInfo discoveryTestcaseCredCertInfo = discoveryTestcaseCred.getCredentialInfo().getCertificateDescriptor(); // noinspection ConstantConditions SignatureAlgorithm discoveryTestcaseCredCertSigAlg = discoveryTestcaseCredCertInfo.getSignatureAlgorithm(); // noinspection ConstantConditions DnsKeyAlgorithmType discoveryTestcaseCredKeyAlgType = ToolEnumUtils.findByPredicate(DnsKeyAlgorithmType.class, enumItem -> (enumItem.getSignatureAlgorithm() == discoveryTestcaseCredCertSigAlg)); // noinspection ConstantConditions certRecordConfig.setKeyAlgorithmType(discoveryTestcaseCredKeyAlgType); // noinspection ConstantConditions certRecordConfig.setKeyTag(ToolDnsRecordUtils.getKeyTag(discoveryTestcaseCredKeyAlgType, discoveryTestcaseCredKeyInfo.getPublicKey())); // noinspection ConstantConditions certRecordConfig.setCertificateData(CertificateUtils.writeCertificate(discoveryTestcaseCredCertInfo.getCertificate(), DataEncoding.DER)); return certRecordConfig; } } private class DiscoveryTestcaseCredentialCertRecordPredicate extends AbstractToolPredicate<DiscoveryTestcaseCredential> { @Override protected boolean evaluateInternal(DiscoveryTestcaseCredential discoveryTestcaseCred) throws Exception { DiscoveryTestcaseCredentialLocation discoveryTestcaseCredLoc; MailAddress discoveryTestcaseCredLocMailAddr; CredentialInfo discoveryTestcaseCredInfo; KeyInfo discoveryTestcaseCredKeyInfo; // noinspection ConstantConditions return discoveryTestcaseCred.hasLocation() && (discoveryTestcaseCredLoc = discoveryTestcaseCred.getLocation()).getType().isDns() && discoveryTestcaseCredLoc.hasMailAddress() && (discoveryTestcaseCredLocMailAddr = discoveryTestcaseCredLoc.getMailAddress()).getBindingType().isBound() && ToolDnsNameUtils.toAbsolute(discoveryTestcaseCredLocMailAddr.getDomainName()).equals(InstanceDnsConfigImpl.this.domainName) && discoveryTestcaseCred.hasCredentialInfo() && (discoveryTestcaseCredInfo = discoveryTestcaseCred.getCredentialInfo()).hasKeyDescriptor() && (discoveryTestcaseCredKeyInfo = discoveryTestcaseCredInfo.getKeyDescriptor()).hasKeyAlgorithm() && discoveryTestcaseCredKeyInfo.hasPublicKey() && discoveryTestcaseCredInfo.hasCertificateDescriptor() && discoveryTestcaseCredInfo.getCertificateDescriptor().hasCertificate(); } } private AbstractApplicationContext appContext; private List<ARecordConfig> aRecordsConfigs; private List<CertRecordConfig> certRecordConfigs; private List<CnameRecordConfig> cnameRecordConfigs; private List<MxRecordConfig> mxRecordConfigs; private List<NsRecordConfig> nsRecordConfigs; private List<PtrRecordConfig> ptrRecordConfigs; private SoaRecordConfig soaRecordConfig; private List<SrvRecordConfig> srvRecordConfigs; private List<TxtRecordConfig> txtRecordConfigs; private Map<Name, Map<DnsRecordType, List<Record>>> nameRecordsMap = new TreeMap<>(); @Nullable @Override public List<Record> findAnswers(Record questionRecord) { // noinspection ConstantConditions return this.findAnswers(ToolEnumUtils.findByCode(DnsRecordType.class, questionRecord.getType()), questionRecord.getName()); } @Nullable @Override public List<Record> findAnswers(DnsRecordType questionRecordType, Name questionName) { Map<DnsRecordType, List<Record>> recordsMap = this.nameRecordsMap.get(questionName); return ((recordsMap != null) ? recordsMap.get(((questionRecordType != DnsRecordType.AAAA) ? questionRecordType : DnsRecordType.A)) : null); } @Override public boolean isAuthoritative(Record questionRecord) { // noinspection ConstantConditions return this.isAuthoritative(ToolEnumUtils.findByCode(DnsRecordType.class, questionRecord.getType()), questionRecord.getName()); } @Override public boolean isAuthoritative(DnsRecordType questionRecordType, Name questionName) { return (this.isAuthoritative() && ((questionRecordType != DnsRecordType.PTR) ? questionName.subdomain(this.domainName) : questionName.equals(ReverseMap .fromAddress(this.ipAddr)))); } @Override public boolean isAuthoritative() { return (this.hasDomainName() && this.hasIpAddress() && this.hasSoaRecordConfig()); } @Override public void afterPropertiesSet() throws Exception { if (!this.hasDomainName() || !this.hasIpAddress()) { return; } this.domainName = ToolDnsNameUtils.toAbsolute(this.domainName); List<? extends DnsRecordConfig<? extends Record>> recordConfigs = null; ARecordConfig aRecordConfig; TargetedDnsRecordConfig<? extends Record> targetedRecordConfig; SoaRecordConfig soaRecordConfig; Name recordName; Record record; Map<DnsRecordType, List<Record>> recordsMap; for (DnsRecordType recordType : EnumSet.allOf(DnsRecordType.class)) { if (!recordType.isProcessed()) { continue; } switch (recordType) { case A: recordConfigs = this.aRecordsConfigs; break; case CERT: // noinspection ConstantConditions recordConfigs = (this.certRecordConfigs = ToolCollectionUtils.nullIfEmpty(CollectionUtils.collect( CollectionUtils.select( ToolBeanFactoryUtils .getBeansOfType(this.appContext, DiscoveryTestcase.class) .stream() .flatMap( discoveryTestcase -> (discoveryTestcase.hasCredentials() ? discoveryTestcase.getCredentials().stream() : Stream .empty())).collect(Collectors.toList()), new DiscoveryTestcaseCredentialCertRecordPredicate()), new DiscoveryTestcaseCredentialCertRecordConfigTransformer(), new ArrayList<>()))); break; case CNAME: recordConfigs = this.cnameRecordConfigs; break; case MX: recordConfigs = this.mxRecordConfigs; break; case NS: recordConfigs = this.nsRecordConfigs; break; case PTR: recordConfigs = (this.ptrRecordConfigs = ToolCollectionUtils.nullIfEmpty(CollectionUtils.collect(this.aRecordsConfigs, new ReverseMapPtrRecordConfigTransformer(), new ArrayList<>()))); break; case SOA: recordConfigs = ToolArrayUtils.asList(this.soaRecordConfig); break; case SRV: recordConfigs = this.srvRecordConfigs; break; case TXT: recordConfigs = this.txtRecordConfigs; break; } if (CollectionUtils.isEmpty(recordConfigs)) { continue; } // noinspection ConstantConditions for (DnsRecordConfig<? extends Record> recordConfig : recordConfigs) { switch (recordType) { case A: if ((aRecordConfig = ((ARecordConfig) recordConfig)).getAddress() == null) { aRecordConfig.setAddress(this.ipAddr); } break; case CNAME: case MX: case NS: case SRV: if ((targetedRecordConfig = (TargetedDnsRecordConfig<? extends Record>) recordConfig).getTarget() == null) { targetedRecordConfig.setTarget(this.domainName); } targetedRecordConfig.setTarget(ToolDnsNameUtils.toAbsolute(targetedRecordConfig.getTarget())); break; case SOA: (soaRecordConfig = ((SoaRecordConfig) recordConfig)).setAdmin(ToolDnsNameUtils.toAbsolute(soaRecordConfig.getAdmin())); soaRecordConfig.setHost(ToolDnsNameUtils.toAbsolute(soaRecordConfig.getHost())); break; } if (((recordName = recordConfig.getName()) == null) || !recordName.isAbsolute()) { recordConfig.setName(ToolDnsNameUtils.toAbsolute(ToolDnsNameUtils.fromLabels(recordName, this.domainName))); } if (!this.nameRecordsMap.containsKey((recordName = (record = recordConfig.toRecord()).getName()))) { this.nameRecordsMap.put(recordName, new EnumMap<>(DnsRecordType.class)); } if (!(recordsMap = this.nameRecordsMap.get(recordName)).containsKey(recordType)) { recordsMap.put(recordType, new ArrayList<>()); } recordsMap.get(recordType).add(record); } } } @Override public void setApplicationContext(ApplicationContext appContext) throws BeansException { this.appContext = (AbstractApplicationContext) appContext; } @Override public boolean hasARecordConfigs() { return !CollectionUtils.isEmpty(this.aRecordsConfigs); } @Nullable @Override public List<ARecordConfig> getARecordConfigs() { return this.aRecordsConfigs; } @Override public void setARecordConfigs(@Nullable List<ARecordConfig> aRecordConfigs) { this.aRecordsConfigs = aRecordConfigs; } @Override public boolean hasCertRecordConfigs() { return !CollectionUtils.isEmpty(this.certRecordConfigs); } @Nullable @Override public List<CertRecordConfig> getCertRecordConfigs() { return this.certRecordConfigs; } @Override public boolean hasCnameRecordConfigs() { return !CollectionUtils.isEmpty(this.cnameRecordConfigs); } @Nullable @Override public List<CnameRecordConfig> getCnameRecordConfigs() { return this.cnameRecordConfigs; } @Override public void setCnameRecordConfigs(@Nullable List<CnameRecordConfig> cnameRecordConfigs) { this.cnameRecordConfigs = cnameRecordConfigs; } @Override public boolean hasMxRecordConfigs() { return !CollectionUtils.isEmpty(this.mxRecordConfigs); } @Nullable @Override public List<MxRecordConfig> getMxRecordConfigs() { return this.mxRecordConfigs; } @Override public void setMxRecordConfigs(@Nullable List<MxRecordConfig> mxRecordConfigs) { this.mxRecordConfigs = mxRecordConfigs; } @Override public Map<Name, Map<DnsRecordType, List<Record>>> getNameRecordsMap() { return this.nameRecordsMap; } @Override public boolean hasNsRecordConfigs() { return !CollectionUtils.isEmpty(this.nsRecordConfigs); } @Nullable @Override public List<NsRecordConfig> getNsRecordConfigs() { return this.nsRecordConfigs; } @Override public void setNsRecordConfigs(@Nullable List<NsRecordConfig> nsRecordConfigs) { this.nsRecordConfigs = nsRecordConfigs; } @Override public boolean hasPtrRecordConfigs() { return !CollectionUtils.isEmpty(this.ptrRecordConfigs); } @Nullable @Override public List<PtrRecordConfig> getPtrRecordConfigs() { return this.ptrRecordConfigs; } @Override public boolean hasSoaRecordConfig() { return this.soaRecordConfig != null; } @Nullable @Override public SoaRecordConfig getSoaRecordConfig() { return this.soaRecordConfig; } @Override public void setSoaRecordConfig(@Nullable SoaRecordConfig soaRecordConfig) { this.soaRecordConfig = soaRecordConfig; } @Override public boolean hasSrvRecordConfigs() { return !CollectionUtils.isEmpty(this.srvRecordConfigs); } @Nullable @Override public List<SrvRecordConfig> getSrvRecordConfigs() { return this.srvRecordConfigs; } @Override public void setSrvRecordConfigs(@Nullable List<SrvRecordConfig> srvRecordConfigs) { this.srvRecordConfigs = srvRecordConfigs; } @Override public boolean hasTxtRecordConfigs() { return !CollectionUtils.isEmpty(this.txtRecordConfigs); } @Nullable @Override public List<TxtRecordConfig> getTxtRecordConfigs() { return this.txtRecordConfigs; } @Override public void setTxtRecordConfigs(@Nullable List<TxtRecordConfig> txtRecordConfigs) { this.txtRecordConfigs = txtRecordConfigs; } }
esacinc/dcdt
dcdt-core/src/main/java/gov/hhs/onc/dcdt/config/instance/impl/InstanceDnsConfigImpl.java
Java
apache-2.0
18,066
'use strict'; // Employees controller angular.module('employees').controller('EmployeesController', ['$scope', '$stateParams', '$location', 'Authentication', 'Employees', 'Organizations','Projects', function ($scope, $stateParams, $location, Authentication, Employees, Organizations,Projects) { $scope.authentication = Authentication; $scope.roles = [ 'Junior Software Developer', 'Software Developer', 'Senior Software Developer', 'Junior QA Engineer', 'QA Engineer', 'Senior QA Engineer', 'Tech Lead', 'QA Lead', 'Engineering Manager', 'QA Manager', 'Architect', 'BU Head' ]; // Create new Employee $scope.create = function () { // Create new Employee object var employee = new Employees({ firstName: this.firstName, lastName: this.lastName, skills: this.skills, role: this.role }); // Redirect after save employee.$save(function (response) { $location.path('employees/' + response._id); // Clear form fields $scope.firstName = ''; $scope.lastName = ''; $scope.skills = ''; $scope.role = ''; }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Remove existing Employee $scope.remove = function (employee) { if (employee) { employee.$remove(); for (var i in $scope.employees) { if ($scope.employees [i] === employee) { $scope.employees.splice(i, 1); } } } else { $scope.employee.$remove(function () { $location.path('employees'); }); } }; // Update existing Employee $scope.update = function () { var employee = $scope.employee; employee.$update(function () { $location.path('employees/' + employee._id); }, function (errorResponse) { $scope.error = errorResponse.data.message; }); }; // Find a list of Employees $scope.find = function () { $scope.employees = Employees.query(); }; // Find existing Employee $scope.findOne = function () { $scope.employee = Employees.get({ employeeId: $stateParams.employeeId }); $scope.employee.$promise.then(function (employee) { var indexOf = $scope.roles.indexOf(employee.role); employee.role = $scope.roles[indexOf]; }); $scope.organizations = Organizations.query(); $scope.projects = Projects.query(); }; } ]);
rohitghatol/Dashboard-Mean
public/modules/employees/controllers/employees.client.controller.js
JavaScript
apache-2.0
2,576
import React from 'react'; import { useIsMountedRef } from 'core/presentation'; import { mount } from 'enzyme'; describe('useIsMountedRef hook', () => { let useIsMountedRefSpy: jasmine.Spy; let TestComponent: React.FunctionComponent; let ref: React.RefObject<boolean>; let isMountedInRender: boolean; beforeEach(() => { useIsMountedRefSpy = jasmine.createSpy('useIsMountedRef', useIsMountedRef).and.callThrough(); TestComponent = function() { ref = useIsMountedRefSpy(); isMountedInRender = ref.current; return null; }; }); it('ref.current is false inside the initial render', () => { mount(<TestComponent />); expect(useIsMountedRefSpy).toHaveBeenCalledTimes(1); expect(isMountedInRender).toBe(false); }); it('ref.current is true after the initial render', () => { mount(<TestComponent />); expect(useIsMountedRefSpy).toHaveBeenCalledTimes(1); expect(ref.current).toBe(true); }); it('ref.current is true during and after the next render', () => { const component = mount(<TestComponent />); component.setProps({}); expect(useIsMountedRefSpy).toHaveBeenCalledTimes(2); expect(isMountedInRender).toBe(true); expect(ref.current).toBe(true); }); it('ref.current remains true on subsequent renders', () => { const component = mount(<TestComponent />); component.setProps({}); component.setProps({}); component.setProps({}); expect(useIsMountedRefSpy).toHaveBeenCalledTimes(4); expect(isMountedInRender).toBe(true); expect(ref.current).toBe(true); }); it('ref.current is false after the component unmounts', async done => { const component = mount(<TestComponent />); expect(ref.current).toBe(true); component.unmount(); setTimeout(() => { expect(ref.current).toBe(false); done(); }); }); });
icfantv/deck
app/scripts/modules/core/src/presentation/hooks/useIsMountedRef.hook.spec.tsx
TypeScript
apache-2.0
1,864
"""Generated client library for containeranalysis version v1alpha1.""" # NOTE: This file is autogenerated and should not be edited by hand. from apitools.base.py import base_api from googlecloudsdk.third_party.apis.containeranalysis.v1alpha1 import containeranalysis_v1alpha1_messages as messages class ContaineranalysisV1alpha1(base_api.BaseApiClient): """Generated client library for service containeranalysis version v1alpha1.""" MESSAGES_MODULE = messages BASE_URL = u'https://containeranalysis.googleapis.com/' _PACKAGE = u'containeranalysis' _SCOPES = [u'https://www.googleapis.com/auth/cloud-platform'] _VERSION = u'v1alpha1' _CLIENT_ID = '1042881264118.apps.googleusercontent.com' _CLIENT_SECRET = 'x_Tw5K8nnjoRAqULM9PFAC2b' _USER_AGENT = 'x_Tw5K8nnjoRAqULM9PFAC2b' _CLIENT_CLASS_NAME = u'ContaineranalysisV1alpha1' _URL_VERSION = u'v1alpha1' _API_KEY = None def __init__(self, url='', credentials=None, get_credentials=True, http=None, model=None, log_request=False, log_response=False, credentials_args=None, default_global_params=None, additional_http_headers=None): """Create a new containeranalysis handle.""" url = url or self.BASE_URL super(ContaineranalysisV1alpha1, self).__init__( url, credentials=credentials, get_credentials=get_credentials, http=http, model=model, log_request=log_request, log_response=log_response, credentials_args=credentials_args, default_global_params=default_global_params, additional_http_headers=additional_http_headers) self.projects_notes_occurrences = self.ProjectsNotesOccurrencesService(self) self.projects_notes = self.ProjectsNotesService(self) self.projects_occurrences = self.ProjectsOccurrencesService(self) self.projects = self.ProjectsService(self) self.providers_notes_occurrences = self.ProvidersNotesOccurrencesService(self) self.providers_notes = self.ProvidersNotesService(self) self.providers = self.ProvidersService(self) class ProjectsNotesOccurrencesService(base_api.BaseApiService): """Service class for the projects_notes_occurrences resource.""" _NAME = u'projects_notes_occurrences' def __init__(self, client): super(ContaineranalysisV1alpha1.ProjectsNotesOccurrencesService, self).__init__(client) self._upload_configs = { } def List(self, request, global_params=None): """Lists the names of Occurrences linked to a particular Note. Args: request: (ContaineranalysisProjectsNotesOccurrencesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListNoteOccurrencesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}/occurrences', http_method=u'GET', method_id=u'containeranalysis.projects.notes.occurrences.list', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'filter', u'pageSize', u'pageToken'], relative_path=u'v1alpha1/{+name}/occurrences', request_field='', request_type_name=u'ContaineranalysisProjectsNotesOccurrencesListRequest', response_type_name=u'ListNoteOccurrencesResponse', supports_download=False, ) class ProjectsNotesService(base_api.BaseApiService): """Service class for the projects_notes resource.""" _NAME = u'projects_notes' def __init__(self, client): super(ContaineranalysisV1alpha1.ProjectsNotesService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a new note. Args: request: (ContaineranalysisProjectsNotesCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes', http_method=u'POST', method_id=u'containeranalysis.projects.notes.create', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'name', u'noteId'], relative_path=u'v1alpha1/{+parent}/notes', request_field=u'note', request_type_name=u'ContaineranalysisProjectsNotesCreateRequest', response_type_name=u'Note', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes the given note from the system. Args: request: (ContaineranalysisProjectsNotesDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}', http_method=u'DELETE', method_id=u'containeranalysis.projects.notes.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProjectsNotesDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Returns the requested occurrence. Args: request: (ContaineranalysisProjectsNotesGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}', http_method=u'GET', method_id=u'containeranalysis.projects.notes.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProjectsNotesGetRequest', response_type_name=u'Note', supports_download=False, ) def GetIamPolicy(self, request, global_params=None): """Gets the access control policy for a note or occurrence resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsNotesGetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('GetIamPolicy') return self._RunMethod( config, request, global_params=global_params) GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}:getIamPolicy', http_method=u'POST', method_id=u'containeranalysis.projects.notes.getIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:getIamPolicy', request_field=u'getIamPolicyRequest', request_type_name=u'ContaineranalysisProjectsNotesGetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def List(self, request, global_params=None): """Lists all notes for a given project. Filters can be used on this. field to list all notes with a specific parameter. Args: request: (ContaineranalysisProjectsNotesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListNotesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes', http_method=u'GET', method_id=u'containeranalysis.projects.notes.list', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'filter', u'name', u'pageSize', u'pageToken'], relative_path=u'v1alpha1/{+parent}/notes', request_field='', request_type_name=u'ContaineranalysisProjectsNotesListRequest', response_type_name=u'ListNotesResponse', supports_download=False, ) def SetIamPolicy(self, request, global_params=None): """Sets the access control policy on the specified note or occurrence. resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsNotesSetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('SetIamPolicy') return self._RunMethod( config, request, global_params=global_params) SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}:setIamPolicy', http_method=u'POST', method_id=u'containeranalysis.projects.notes.setIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:setIamPolicy', request_field=u'setIamPolicyRequest', request_type_name=u'ContaineranalysisProjectsNotesSetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified note or occurrence. resource. Requires list permission on the project (e.g., "storage.objects.list" on the containing bucket for testing permission of an object). Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsNotesTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}:testIamPermissions', http_method=u'POST', method_id=u'containeranalysis.projects.notes.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:testIamPermissions', request_field=u'testIamPermissionsRequest', request_type_name=u'ContaineranalysisProjectsNotesTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) def Update(self, request, global_params=None): """Updates an existing note. Args: request: (Note) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Update') return self._RunMethod( config, request, global_params=global_params) Update.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/notes/{notesId}', http_method=u'PUT', method_id=u'containeranalysis.projects.notes.update', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='<request>', request_type_name=u'Note', response_type_name=u'Note', supports_download=False, ) class ProjectsOccurrencesService(base_api.BaseApiService): """Service class for the projects_occurrences resource.""" _NAME = u'projects_occurrences' def __init__(self, client): super(ContaineranalysisV1alpha1.ProjectsOccurrencesService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a new occurrence. Args: request: (ContaineranalysisProjectsOccurrencesCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Occurrence) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences', http_method=u'POST', method_id=u'containeranalysis.projects.occurrences.create', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'name'], relative_path=u'v1alpha1/{+parent}/occurrences', request_field=u'occurrence', request_type_name=u'ContaineranalysisProjectsOccurrencesCreateRequest', response_type_name=u'Occurrence', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes the given occurrence from the system. Args: request: (ContaineranalysisProjectsOccurrencesDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}', http_method=u'DELETE', method_id=u'containeranalysis.projects.occurrences.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProjectsOccurrencesDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Returns the requested occurrence. Args: request: (ContaineranalysisProjectsOccurrencesGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Occurrence) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}', http_method=u'GET', method_id=u'containeranalysis.projects.occurrences.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProjectsOccurrencesGetRequest', response_type_name=u'Occurrence', supports_download=False, ) def GetIamPolicy(self, request, global_params=None): """Gets the access control policy for a note or occurrence resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsOccurrencesGetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('GetIamPolicy') return self._RunMethod( config, request, global_params=global_params) GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}:getIamPolicy', http_method=u'POST', method_id=u'containeranalysis.projects.occurrences.getIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:getIamPolicy', request_field=u'getIamPolicyRequest', request_type_name=u'ContaineranalysisProjectsOccurrencesGetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def GetNotes(self, request, global_params=None): """Gets the note that this occurrence is attached to. Args: request: (ContaineranalysisProjectsOccurrencesGetNotesRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('GetNotes') return self._RunMethod( config, request, global_params=global_params) GetNotes.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}/notes', http_method=u'GET', method_id=u'containeranalysis.projects.occurrences.getNotes', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}/notes', request_field='', request_type_name=u'ContaineranalysisProjectsOccurrencesGetNotesRequest', response_type_name=u'Note', supports_download=False, ) def List(self, request, global_params=None): """Lists all occurrences for a given project/Digest. Filters can be used on. this field to list all digests containing a specific occurrence in a project. Args: request: (ContaineranalysisProjectsOccurrencesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListOccurrencesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences', http_method=u'GET', method_id=u'containeranalysis.projects.occurrences.list', ordered_params=[u'parent'], path_params=[u'parent'], query_params=[u'filter', u'name', u'pageSize', u'pageToken'], relative_path=u'v1alpha1/{+parent}/occurrences', request_field='', request_type_name=u'ContaineranalysisProjectsOccurrencesListRequest', response_type_name=u'ListOccurrencesResponse', supports_download=False, ) def SetIamPolicy(self, request, global_params=None): """Sets the access control policy on the specified note or occurrence. resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsOccurrencesSetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('SetIamPolicy') return self._RunMethod( config, request, global_params=global_params) SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}:setIamPolicy', http_method=u'POST', method_id=u'containeranalysis.projects.occurrences.setIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:setIamPolicy', request_field=u'setIamPolicyRequest', request_type_name=u'ContaineranalysisProjectsOccurrencesSetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified note or occurrence. resource. Requires list permission on the project (e.g., "storage.objects.list" on the containing bucket for testing permission of an object). Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProjectsOccurrencesTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}:testIamPermissions', http_method=u'POST', method_id=u'containeranalysis.projects.occurrences.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:testIamPermissions', request_field=u'testIamPermissionsRequest', request_type_name=u'ContaineranalysisProjectsOccurrencesTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) def Update(self, request, global_params=None): """Updates an existing occurrence. Args: request: (Occurrence) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Occurrence) The response message. """ config = self.GetMethodConfig('Update') return self._RunMethod( config, request, global_params=global_params) Update.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/projects/{projectsId}/occurrences/{occurrencesId}', http_method=u'PUT', method_id=u'containeranalysis.projects.occurrences.update', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='<request>', request_type_name=u'Occurrence', response_type_name=u'Occurrence', supports_download=False, ) class ProjectsService(base_api.BaseApiService): """Service class for the projects resource.""" _NAME = u'projects' def __init__(self, client): super(ContaineranalysisV1alpha1.ProjectsService, self).__init__(client) self._upload_configs = { } class ProvidersNotesOccurrencesService(base_api.BaseApiService): """Service class for the providers_notes_occurrences resource.""" _NAME = u'providers_notes_occurrences' def __init__(self, client): super(ContaineranalysisV1alpha1.ProvidersNotesOccurrencesService, self).__init__(client) self._upload_configs = { } def List(self, request, global_params=None): """Lists the names of Occurrences linked to a particular Note. Args: request: (ContaineranalysisProvidersNotesOccurrencesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListNoteOccurrencesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}/occurrences', http_method=u'GET', method_id=u'containeranalysis.providers.notes.occurrences.list', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'filter', u'pageSize', u'pageToken'], relative_path=u'v1alpha1/{+name}/occurrences', request_field='', request_type_name=u'ContaineranalysisProvidersNotesOccurrencesListRequest', response_type_name=u'ListNoteOccurrencesResponse', supports_download=False, ) class ProvidersNotesService(base_api.BaseApiService): """Service class for the providers_notes resource.""" _NAME = u'providers_notes' def __init__(self, client): super(ContaineranalysisV1alpha1.ProvidersNotesService, self).__init__(client) self._upload_configs = { } def Create(self, request, global_params=None): """Creates a new note. Args: request: (ContaineranalysisProvidersNotesCreateRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Create') return self._RunMethod( config, request, global_params=global_params) Create.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes', http_method=u'POST', method_id=u'containeranalysis.providers.notes.create', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'noteId', u'parent'], relative_path=u'v1alpha1/{+name}/notes', request_field=u'note', request_type_name=u'ContaineranalysisProvidersNotesCreateRequest', response_type_name=u'Note', supports_download=False, ) def Delete(self, request, global_params=None): """Deletes the given note from the system. Args: request: (ContaineranalysisProvidersNotesDeleteRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Empty) The response message. """ config = self.GetMethodConfig('Delete') return self._RunMethod( config, request, global_params=global_params) Delete.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}', http_method=u'DELETE', method_id=u'containeranalysis.providers.notes.delete', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProvidersNotesDeleteRequest', response_type_name=u'Empty', supports_download=False, ) def Get(self, request, global_params=None): """Returns the requested occurrence. Args: request: (ContaineranalysisProvidersNotesGetRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Get') return self._RunMethod( config, request, global_params=global_params) Get.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}', http_method=u'GET', method_id=u'containeranalysis.providers.notes.get', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='', request_type_name=u'ContaineranalysisProvidersNotesGetRequest', response_type_name=u'Note', supports_download=False, ) def GetIamPolicy(self, request, global_params=None): """Gets the access control policy for a note or occurrence resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProvidersNotesGetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('GetIamPolicy') return self._RunMethod( config, request, global_params=global_params) GetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}:getIamPolicy', http_method=u'POST', method_id=u'containeranalysis.providers.notes.getIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:getIamPolicy', request_field=u'getIamPolicyRequest', request_type_name=u'ContaineranalysisProvidersNotesGetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def List(self, request, global_params=None): """Lists all notes for a given project. Filters can be used on this. field to list all notes with a specific parameter. Args: request: (ContaineranalysisProvidersNotesListRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ListNotesResponse) The response message. """ config = self.GetMethodConfig('List') return self._RunMethod( config, request, global_params=global_params) List.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes', http_method=u'GET', method_id=u'containeranalysis.providers.notes.list', ordered_params=[u'name'], path_params=[u'name'], query_params=[u'filter', u'pageSize', u'pageToken', u'parent'], relative_path=u'v1alpha1/{+name}/notes', request_field='', request_type_name=u'ContaineranalysisProvidersNotesListRequest', response_type_name=u'ListNotesResponse', supports_download=False, ) def SetIamPolicy(self, request, global_params=None): """Sets the access control policy on the specified note or occurrence. resource. Requires "containeranalysis.notes.setIamPolicy" or "containeranalysis.occurrences.setIamPolicy" permission if the resource is a note or occurrence, respectively. Attempting this RPC on a resource without the needed permission will note in a PERMISSION_DENIED error. Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProvidersNotesSetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy) The response message. """ config = self.GetMethodConfig('SetIamPolicy') return self._RunMethod( config, request, global_params=global_params) SetIamPolicy.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}:setIamPolicy', http_method=u'POST', method_id=u'containeranalysis.providers.notes.setIamPolicy', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:setIamPolicy', request_field=u'setIamPolicyRequest', request_type_name=u'ContaineranalysisProvidersNotesSetIamPolicyRequest', response_type_name=u'Policy', supports_download=False, ) def TestIamPermissions(self, request, global_params=None): """Returns permissions that a caller has on the specified note or occurrence. resource. Requires list permission on the project (e.g., "storage.objects.list" on the containing bucket for testing permission of an object). Attempting this RPC on a non-existent resource will note in a NOT_FOUND error if the user has list permission on the project, or a PERMISSION_DENIED error otherwise. Args: request: (ContaineranalysisProvidersNotesTestIamPermissionsRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (TestIamPermissionsResponse) The response message. """ config = self.GetMethodConfig('TestIamPermissions') return self._RunMethod( config, request, global_params=global_params) TestIamPermissions.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}:testIamPermissions', http_method=u'POST', method_id=u'containeranalysis.providers.notes.testIamPermissions', ordered_params=[u'resource'], path_params=[u'resource'], query_params=[], relative_path=u'v1alpha1/{+resource}:testIamPermissions', request_field=u'testIamPermissionsRequest', request_type_name=u'ContaineranalysisProvidersNotesTestIamPermissionsRequest', response_type_name=u'TestIamPermissionsResponse', supports_download=False, ) def Update(self, request, global_params=None): """Updates an existing note. Args: request: (Note) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Note) The response message. """ config = self.GetMethodConfig('Update') return self._RunMethod( config, request, global_params=global_params) Update.method_config = lambda: base_api.ApiMethodInfo( flat_path=u'v1alpha1/providers/{providersId}/notes/{notesId}', http_method=u'PUT', method_id=u'containeranalysis.providers.notes.update', ordered_params=[u'name'], path_params=[u'name'], query_params=[], relative_path=u'v1alpha1/{+name}', request_field='<request>', request_type_name=u'Note', response_type_name=u'Note', supports_download=False, ) class ProvidersService(base_api.BaseApiService): """Service class for the providers resource.""" _NAME = u'providers' def __init__(self, client): super(ContaineranalysisV1alpha1.ProvidersService, self).__init__(client) self._upload_configs = { }
KaranToor/MA450
google-cloud-sdk/lib/googlecloudsdk/third_party/apis/containeranalysis/v1alpha1/containeranalysis_v1alpha1_client.py
Python
apache-2.0
36,932
"""Trace module.""" import os TRACE_SOW_DIR = os.path.join('.sow', 'trace')
ThoughtWorksInc/treadmill
treadmill/apptrace/__init__.py
Python
apache-2.0
83
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.testing.drivers; import org.openqa.selenium.Capabilities; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.Augmenter; import org.openqa.selenium.remote.LocalFileDetector; import org.openqa.selenium.remote.RemoteWebDriver; import java.net.MalformedURLException; import java.net.URL; import java.util.function.Supplier; public class RemoteSupplier implements Supplier<WebDriver> { private static OutOfProcessSeleniumServer server = new OutOfProcessSeleniumServer(); private static volatile boolean started; private Capabilities desiredCapabilities; public RemoteSupplier(Capabilities desiredCapabilities) { this.desiredCapabilities = desiredCapabilities; } @Override public WebDriver get() { if (desiredCapabilities == null || !Boolean.getBoolean("selenium.browser.remote")) { return null; } String externalServer = System.getProperty("selenium.externalServer"); URL serverUrl; if (externalServer != null) { try { serverUrl = new URL(externalServer); } catch (MalformedURLException e) { throw new RuntimeException(e); } } else { if (!started) { startServer(); } serverUrl = server.getWebDriverUrl(); } RemoteWebDriver driver = new RemoteWebDriver(serverUrl, desiredCapabilities); driver.setFileDetector(new LocalFileDetector()); return new Augmenter().augment(driver); } private synchronized void startServer() { if (started) { return; } server.start("standalone"); started = true; } }
SeleniumHQ/selenium
java/test/org/openqa/selenium/testing/drivers/RemoteSupplier.java
Java
apache-2.0
2,400
<html><head> </head> <body leftmargin="0" rightmargin="0" topmargin="0" bottommargin="0" bgproperties="fixed" alink="#3333FF" bgcolor="white" link="#3333FF" marginheight="0" marginwidth="0" text="#3333FF" vlink="#3333FF"><div style="visibility: hidden; position: absolute; overflow: hidden; padding: 0px; width: 1599px; left: -1600px; top: 0px;" id="WzTtDiV"></div> <table align="center" border="0" cellpadding="0" cellspacing="0" width="740"> <tbody><tr> </tr> </tbody></table> <div style="height:700px;width:500px;border:1px solid #ccc;font:16px/26px Georgia, Garamond, Serif;overflow:auto;"> <table style="border-bottom-width:0; border-bottom-style:none;" border="0" cellpadding="0" cellspacing="0" width="740"> <tbody> <tr> <td align="center" height="20" nowrap="nowrap" valign="middle" width="130"> <p>&nbsp;</p> </td> <td colspan="2" style="border-bottom-width:1; border-bottom-color:rgb(0,51,255); border-bottom-style:solid;" align="left" height="30" nowrap="nowrap" valign="middle" width="450"> <p style="margin-right:2; margin-left:15;" align="left"><font face="Trebuchet MS"><span style="font-size:10pt;"><b>Refractive&nbsp;Index&nbsp;of&nbsp;Gem</b></span></font> </p></td> </tr> <tr> <td align="center" height="20" nowrap="nowrap" valign="middle" width="130"> <p>&nbsp;</p> </td> <td style="border-bottom-width:1; border-bottom-color:rgb(0,51,255); border-bottom-style:solid;" align="center" valign="top" width="207"> <p style="margin-right:5; margin-left:15;" align="left"><font face="Trebuchet MS" size="2">Hematite<br>Cuprite<br>Proustite<br>Moissanite<br>Rutile<br>Anatase<br></font><b><font face="Trebuchet MS" size="2">Diamond<br></font></b><font face="Trebuchet MS" size="2">Sphalerite<br>Strontium Titanate<br>Stibiotantalite<br>Vanadinite<br>Crocoite<br>Wulfenite<br>Tantalite<br>Cubic Zirconia<br>Phosgenite<br>Zincite<br>Cassiterite<br>Simpsonite<br>Zircon, High<br>Powellite<br>Scheelite<br>Sphene<br>Andradite (Garnet)<br>Demantoid (Garnet)<br>Angelsite<br>Purpurite<br>Zircon, Medium<br>Fayalite (Olivine)<br>Bahianite<br>Cerussite<br>Gahnite<br>Spessartine (Garnet)<br>Painite<br>Zircon, Low<br>Almandine (Garnet)<br>Benitoite<br>Ruby (Corundum)<br>Sapphire (Corundum)<br>Shattuckite<br>Rhodolite (Garnet)<br>Alexandrite<br>Hessonite (Garnet)<br>Genthelvite<br>Uvarovite (Garnet)<br>Chrysoberyl<br>Staurolite<br>Periclase<br>Gahnospinel<br>Tsavorite (Garnet)<br>Pyrope (Garnet)<br>Grossular (Garnet)<br>Pyroxmangite<br>Azurite<br>Aegirine<br>Bastnäsite<br>Taaffeite<br>Epidote<br>Sapphirine<br>Rhodonite<br>Spinel (synthetic)<br>Spinel<br>Kyanite<br>Serendibite<br>Rhodizite<br>Tanzanite (Zoisite)<br>Thulite (Zoisite)<br></font><font face="Trebuchet MS"><span style="font-size:9pt;">Hydrogrossular</span></font><font face="Trebuchet MS" size="2"> (Garnet)<br>Willemite<br>Hypersthene<br>Zoisite<br>Dunilite<br>Legrandite<br>Axinite<br>Clinozoisite<br>Dumortierite<br>Chrome Diopside<br>Sinhalite<br>Kornerupine<br>Diopside<br>Idocrase<br>Vesuvianite<br>Bronzite<br>Boracite<br>Malachite<br>Sillimanite<br>Spodumene<br>Hiddenite (Spodumene)<br>Kunzite (Spodumene)<br>Ludlamite<br>Phenakite<br> Peridot (Olivine)<br>Enstatite<br>Euclase<br>Childrenite<br>Dioptase<br>Allanite<br>Jadeite (Jade)<br>Barite<br>Poldervaartite<br>Siderite<br>Apatite<br>Andalusite<br>Danburite<br>Friedelite<br>Kentbrooksite<br>Datolite<br>Smithsonite<br>Celestite<br>Richterite<br>Burbankite<br>Tourmaline (all colors)<br>Actinolite<br>Hemimorphite<br>Prehnite<br>Turquoise<br>Suolunite<br>Topaz<br>Pezzottaite<br>Lazulite<br>Brazilianite<br>Nephrite (Jade)<br>Pectolite<br>Phosphophyllite</font><font face="Trebuchet MS"><span style="font-size:9pt;"><br></span></font><font face="Trebuchet MS" size="2">Montebrasite<br>Chondrodite<br>Herderite<br>Ekanite<br>Colemanite<br>Howlite<br>Zektzerite<br>Rhodochrosite<br>Amblygonite<br>Anorthite (Feldspar)<br>Chrysocolla<br>Emerald (Beryl)<br>Augelite<br>Morganite (Beryl)<br>Anhydrite<br>Vivianite<br>Beryl Family<br>Bixbite (Beryl)<br>Aquamarine (Beryl)<br>Goshenite (Beryl)<br>Heliodor (Beryl)<br>Emerald (synth. hydro)<br>Bytownite (Feldspar)<br>Tremolite<br>Variscite<br>Labradorite (Feldspar)<br>Emerald (synth. flux)<br>Beryllonite<br>Hambergite<br>Coral<br>Adventurine (Quartz)<br>Amethyst<br>Ametrine<br>Citrine<br>Jasper (Quartz)<br>Prasiolite (Quartz)<br>Quartz (all colors)<br>Tiger eye (Quartz)<br>Chkalovite<br>Andesine (Feldspar)<br>Oligoclase (Feldspar)<br>Steatite<br>Amber<br>Scapolite<br>Ivory<br>Agate<br>Carnelian<br>Chalcedony<br>Chrysoprase<br>Onyx<br>Iolite<br>Shortite<br>Peristerite<br>Aragonite<br>Pearl<br>Apophyllite<br>Witherite<br>Albite (Feldspar)<br>Unakite<br>Maw-Sit-Sit<br>Glass (man-made)<br>Orthoclase (Feldspar)<br>Sanidine (Feldspar)<br>Moonstone (Feldspar)<br>Amazonite (Feldspar)<br>Microline (Feldspar)<br>Poudretteite<br>Magnesite<br>Leucite<br>Petalite<br>Dolomite<br>Lapis Lazuli (Lazurite)<br>Thomsonite<br>Ulexite<br>Hauyne<br>Cancrinite<br>Tugtupite<br>Serpentine<br>Calcite<br>Sodalite<br>Hackmanite<br>Natrolite<br>Thaumasite<br>Moldavite<br>Tektite<br>Obsidian<br>Fluorite<br>Opal<br>Sellaite<br>Water (at</font><font face="Trebuchet MS" size="2"> 20°C</font><font face="Trebuchet MS" size="2">)<br>Villiaumite<br><b>Air (as a reference)<br></b>Gold<br>Silver<br>&nbsp;</font> </p></td> <td style="border-bottom-width:1; border-bottom-color:rgb(0,51,255); border-bottom-style:solid;" align="left" valign="top" width="403"> <font face="Trebuchet MS" size="2">2.880 - 3.220<br>2.848 (iso)<br>2.792 - 3.088<br>2.648 - 2.691<br>2.620 - 2.900<br>2.488 - 2.564<br></font><b><font face="Trebuchet MS" size="2">2.417</font></b><font face="Trebuchet MS" size="2"> (iso)</font><b><font face="Trebuchet MS" size="2"><br></font></b><font face="Trebuchet MS" size="2">2.400 (iso)<br>2.400 (iso)<br>2.37 - 2.46<br>2.350 - 2.416<br>2.290 - 2.660<br>2.280 - 2.405<br>2.260 - 2.430<br>2.170 (iso)<br>2.114 - 2.145<br>2.013 - 2.029<br>1.995 - 2.095<br>1.976 - 2.045<br>1.970 - 2.025<br>1.967 - 1.985<br>1.918 - 1.936<br>1.900 - 2.034<br>1.880 - 1.940<br>1.880 - 1.888<br>1.877 - 1.894<br>1.850 - 1.920<br>1.840 - 1.970<br>1.827 - 1.879<br>1.810 - 1.920<br>1.803 - 2.078<br>1.790 - 1.820 (iso)<br>1.790 - 1.810<br>1.787 - 1.816<br>1.780 - 1.850<br>1.775 - 1.830<br>1.757 - 1.804<br>1.757 - 1.779<br>1.757 - 1.779<br>1.752 - 1.815<br>1.745 - 1.760<br>1.745 - 1.759<br>1.742 - 1.748<br>1.742 - 1.745<br>1.740 - 1.870<br>1.740 - 1.777<br>1.736 - 1.762<br>1.736 (iso)<br>1.735 - 1.790<br>1.735 - 1.744<br>1.730 - 1.766<br>1.730 - 1.760<br>1.726 - 1748<br>1.720 - 1.850<br>1.720 - 1.839<br>1.717 - 1.818<br>1.717 - 1.730<br>1.715 - 1.797<br>1.714 - 1.723<br>1.711 - 1.752<br>1.710 - 1.740<br>1.710 - 1.735<br>1.710 - 1.735<br>1.701 - 1.706<br>1.694 (iso)<br>1.692 - 1.705<br>1.692 - 1.705<br>1.690 - 1.730<br>1.690 - 1.723<br>1.686 - 1.772<br>1.685 - 1.725<br>1.677 - 1.718<br>1.675 - 1.740<br>1.672 - 1.694<br>1.670 - 1.734<br>1.668 - 1.723<br>1.668 - 1.702<br>1.665 - 1.712<br>1.665 - 1.700<br>1.664 - 1.721<br>1.655 - 1.761<br>1.655 - 1.761<br>1.665 - 1.703<br>1.658 - 1.673<br>1.655 - 1.909<br>1.654 - 1.683<br>1.653 - 1.682<br>1.653 - 1.682<br>1.653 - 1.682<br>1.650 - 1.697<br>1.650 - 1.695<br>1.650 - 1.681<br>1.650 - 1.680<br>1.650 - 1.677<br>1.649 - 1.691<br>1.645 - 1.720<br>1.640 - 1.828<br>1.640 - 1.667<br>1.636 - 1.648<br>1.634 - 1.656<br>1.633 - 1.873<br>1.628 - 1.650<br>1.627 - 1.650<br>1.627 - 1.639<br>1.625 - 1.664<br>1.623 - 1.628<br>1.621 - 1.675<br>1.620 - 1.850<br>1.619 - 1.635<br>1.615 - 1.636<br>1.615 - 1.627<br>1.614 - 1.666<br>1.614 - 1.655<br>1.614 - 1.636<br>1.611 - 1.665<br>1.610 - 1.650<br>1.610 - 1.623<br>1.609 - 1.643<br>1.607 - 1.619<br>1.604 - 1.662<br>1.602 - 1.625<br>1.600 - 1.640<br>1.595 - 1.645<br>1.595 - 1.621<br>1.594 - 1.616<br>1.592 - 1.675<br>1.591 - 1.624<br>1.590 - 1.596<br>1.586 - 1.614<br>1.583 - 1.608<br>1.582 - 1.584<br>1.578 - 1.840<br>1.578 - 1.612<br>1.577 - 1.590<br>1.575 - 1.635<br>1.575 - 1.602<br>1.574 - 1.588<br>1.572 - 1.600<br>1.570 - 1.614<br>1.569 - 1.675<br>1.563 - 1.620<br>1.568 - 1.572<br>1.567 - 1.590<br>1.566 - 1.602<br>1.566 - 1.579<br>1.563 - 1.620<br>1.561 - 1.570<br>1.560 - 1.643<br>1.560 - 1.594<br>1.560 - 1.572<br>1.553 - 1.580<br>1.552 - 1.562<br>1.550 - 1.630<br>1.550 - 1.580<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.553<br>1.544 - 1.549<br>1.543 - 1.551<br>1.542 - 1.549<br>1.539 - 1.600<br>1.539 - 1.545<br>1.536 - 1.596<br>1.535 - 1.555<br>1.535 - 1.539<br>1.535 - 1.539<br>1.535 - 1.539<br>1.535 - 1.539<br>1.535 - 1.539<br>1.533 - 1.596<br>1.531 - 1.570<br>1.531 - 1.546<br>1.530 - 1.685<br>1.530 - 1.685<br>1.530 - 1.543<br>1.529 - 1.677<br>1.527 - 1.538<br>1.525 - 1.760<br>1.520 - 1.680<br>1.520 - 1.550<br>1.518 - 1.539<br>1.518 - 1.534<br>1.518 - 1.526<br>1.514 - 1.539<br>1.514 - 1.539<br>1.510 - 1.532<br>1.509 - 1.717<br>1.504 - 1.510<br>1.502 - 1.520<br>1.500 - 1.703<br>1.500 (iso)<br>1.497 - 1.544<br>1.496 - 1.519<br>1.496 - 1.505<br>1.495 - 1.528<br>1.494 - 1.504<br>1.490 - 1.575<br>1.486 - 1.740<br>1.483 - 1.487<br>1.483 - 1.487<br>1.473 - 1.496<br>1.464 - 1.507<br>1.460 - 1.540<br>1.460 - 1.540<br>1.450 - 1.520<br>1.432 - 1.434<br>1.370 - 1.470<br>1.37 - 1.39<br>1.3328<br>1.327 (iso)<br><b>1.0003<br></b>0.470 (iso)<br>0.180 (iso)<br>&nbsp;</font> </td> </tr> <tr> <td align="center" height="20" nowrap="nowrap" valign="middle" width="130"> <p>&nbsp;</p> </td> <td colspan="3" align="left" height="30" nowrap="nowrap" valign="baseline" width="610"> <p style="margin-right:2; margin-left:15;" align="left"><font face="Trebuchet MS"><span style="font-size:10pt;">Note: Values may be approximate.</span></font></p> </td> </tr> </tbody></table></div> <p>&nbsp;</p> </td></tr><tr><td valign="BOTTOM"></td> </tr> </tbody></table> </body></html>
santuchal/kuber_gemological_lab_private_web_app
gem/Refractive_index.html
HTML
apache-2.0
13,682
package com.querydsl.jpa.codegen.ant; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertFalse; import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.Set; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ErrorCollector; import org.junit.rules.TemporaryFolder; public class AntJPADomainExporterTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); @Rule public ErrorCollector errors = new ErrorCollector(); @Test public void test() throws IOException { AntJPADomainExporter exporter = new AntJPADomainExporter(); exporter.setNamePrefix("Q"); exporter.setNameSuffix(""); Path outputFolder = folder.getRoot().toPath(); exporter.setTargetFolder(outputFolder.toFile().getAbsolutePath()); exporter.setPersistenceUnitName("h2"); exporter.execute(); File origRoot = new File("../querydsl-jpa/target/generated-test-sources/java"); Set<File> files = exporter.getGeneratedFiles(); assertFalse(files.isEmpty()); for (File file : files) { Path relativeFile = outputFolder.relativize(file.toPath()); Path origFile = origRoot.toPath().resolve(relativeFile); String reference = new String(java.nio.file.Files.readAllBytes(origFile), StandardCharsets.UTF_8); String content = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); errors.checkThat("Mismatch for " + file.getPath(), content, is(equalTo(reference))); } } }
lpandzic/querydsl
querydsl-jpa-codegen/src/test/java/com/querydsl/jpa/codegen/ant/AntJPADomainExporterTest.java
Java
apache-2.0
1,736
#!/usr/bin/env python # # Copyright 2007 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. # """Web-based User Interface for appstats. This is a simple set of webapp-based request handlers that display the collected statistics and let you drill down on the information in various ways. Template files are in the templates/ subdirectory. Static files are in the static/ subdirectory. The templates are written to work with either Django 0.96 or Django 1.0, and most likely they also work with Django 1.1. """ import cgi import email.Utils import logging import mimetypes import os import re import sys import time from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext.webapp import util from google.appengine.ext.appstats import recording DEBUG = recording.config.DEBUG from google.appengine.ext.webapp import template import django def render(tmplname, data): """Helper function to render a template.""" here = os.path.dirname(__file__) tmpl = os.path.join(here, 'templates', tmplname) data['env'] = os.environ try: return template.render(tmpl, data) except Exception, err: logging.exception('Failed to render %s', tmpl) return 'Problematic template %s: %s' % (tmplname, err) class SummaryHandler(webapp.RequestHandler): """Request handler for the main stats page (/stats/).""" def get(self): recording.dont_record() if not self.request.path.endswith('/'): self.redirect(self.request.path + '/') return summaries = recording.load_summary_protos() allstats = {} pathstats = {} pivot_path_rpc = {} pivot_rpc_path = {} for index, summary in enumerate(summaries): path_key = recording.config.extract_key(summary) if path_key not in pathstats: pathstats[path_key] = [1, index+1] else: values = pathstats[path_key] values[0] += 1 if len(values) >= 11: if values[-1]: values.append(0) else: values.append(index+1) if path_key not in pivot_path_rpc: pivot_path_rpc[path_key] = {} for x in summary.rpc_stats_list(): rpc_key = x.service_call_name() value = x.total_amount_of_calls() if rpc_key in allstats: allstats[rpc_key] += value else: allstats[rpc_key] = value if rpc_key not in pivot_path_rpc[path_key]: pivot_path_rpc[path_key][rpc_key] = 0 pivot_path_rpc[path_key][rpc_key] += value if rpc_key not in pivot_rpc_path: pivot_rpc_path[rpc_key] = {} if path_key not in pivot_rpc_path[rpc_key]: pivot_rpc_path[rpc_key][path_key] = 0 pivot_rpc_path[rpc_key][path_key] += value allstats_by_count = [] for k, v in allstats.iteritems(): pivot = sorted(pivot_rpc_path[k].iteritems(), key=lambda x: (-x[1], x[0])) allstats_by_count.append((k, v, pivot)) allstats_by_count.sort(key=lambda x: (-x[1], x[0])) pathstats_by_count = [] for path_key, values in pathstats.iteritems(): pivot = sorted(pivot_path_rpc[path_key].iteritems(), key=lambda x: (-x[1], x[0])) rpc_count = sum(x[1] for x in pivot) pathstats_by_count.append((path_key, rpc_count, values[0], values[1:], pivot)) pathstats_by_count.sort(key=lambda x: (-x[1], -x[2], x[0])) data = {'requests': summaries, 'allstats_by_count': allstats_by_count, 'pathstats_by_count': pathstats_by_count, } self.response.out.write(render('main.html', data)) class DetailsHandler(webapp.RequestHandler): """Request handler for the details page (/stats/details).""" def get(self): recording.dont_record() time_key = self.request.get('time') timestamp = None record = None if time_key: try: timestamp = int(time_key) * 0.001 except Exception: pass if timestamp: record = recording.load_full_proto(timestamp) if record is None: self.response.set_status(404) self.response.out.write(render('details.html', {})) return rpcstats_map = {} for rpc_stat in record.individual_stats_list(): key = rpc_stat.service_call_name() count, real, api = rpcstats_map.get(key, (0, 0, 0)) count += 1 real += rpc_stat.duration_milliseconds() api += rpc_stat.api_mcycles() rpcstats_map[key] = (count, real, api) rpcstats_by_count = [ (name, count, real, recording.mcycles_to_msecs(api)) for name, (count, real, api) in rpcstats_map.iteritems()] rpcstats_by_count.sort(key=lambda x: -x[1]) real_total = 0 api_total_mcycles = 0 for i, rpc_stat in enumerate(record.individual_stats_list()): real_total += rpc_stat.duration_milliseconds() api_total_mcycles += rpc_stat.api_mcycles() api_total = recording.mcycles_to_msecs(api_total_mcycles) charged_total = recording.mcycles_to_msecs(record.processor_mcycles() + api_total_mcycles) data = {'sys': sys, 'record': record, 'rpcstats_by_count': rpcstats_by_count, 'real_total': real_total, 'api_total': api_total, 'charged_total': charged_total, 'file_url': './file', } self.response.out.write(render('details.html', data)) class FileHandler(webapp.RequestHandler): """Request handler for displaying any text file in the system. NOTE: This gives any admin of your app full access to your source code. """ def get(self): recording.dont_record() lineno = self.request.get('n') try: lineno = int(lineno) except: lineno = 0 filename = self.request.get('f') or '' orig_filename = filename match = re.match('<path\[(\d+)\]>(.*)', filename) if match: index, tail = match.groups() index = int(index) if index < len(sys.path): filename = sys.path[index] + tail try: fp = open(filename) except IOError, err: self.response.out.write('<h1>IOError</h1><pre>%s</pre>' % cgi.escape(str(err))) self.response.set_status(404) else: try: data = {'fp': fp, 'filename': filename, 'orig_filename': orig_filename, 'lineno': lineno, } self.response.out.write(render('file.html', data)) finally: fp.close() class StaticHandler(webapp.RequestHandler): """Request handler to serve static files. Only files directory in the static subdirectory are rendered this way (no subdirectories). """ def get(self): here = os.path.dirname(__file__) fn = self.request.path i = fn.rfind('/') fn = fn[i+1:] fn = os.path.join(here, 'static', fn) ctype, encoding = mimetypes.guess_type(fn) assert ctype and '/' in ctype, repr(ctype) expiry = 3600 expiration = email.Utils.formatdate(time.time() + expiry, usegmt=True) fp = open(fn, 'rb') try: self.response.out.write(fp.read()) finally: fp.close() self.response.headers['Content-type'] = ctype self.response.headers['Cache-Control'] = 'public, max-age=expiry' self.response.headers['Expires'] = expiration if django.VERSION[:2] < (0, 97): from django.template import defaultfilters def safe(text, dummy=None): return text defaultfilters.register.filter("safe", safe) URLMAP = [ ('.*/details', DetailsHandler), ('.*/file', FileHandler), ('.*/static/.*', StaticHandler), ('.*', SummaryHandler), ] def main(): """Main program. Auth check, then create and run the WSGIApplication.""" if not os.getenv('SERVER_SOFTWARE', '').startswith('Dev'): if not users.is_current_user_admin(): if users.get_current_user() is None: print 'Status: 302' print 'Location:', users.create_login_url(os.getenv('PATH_INFO', '')) else: print 'Status: 403' print print 'Forbidden' return app = webapp.WSGIApplication(URLMAP, debug=DEBUG) util.run_bare_wsgi_app(app) if __name__ == '__main__': main()
SRabbelier/Melange
thirdparty/google_appengine/google/appengine/ext/appstats/ui.py
Python
apache-2.0
8,746
/* * 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.test.dunit; import org.apache.geode.internal.util.DebuggerSupport; /** * <code>DebuggerUtils</code> provides static utility methods that facilitate runtime debugging. * * These methods can be used directly: <code>DebuggerUtils.attachDebugger(...)</code>, however, they * are intended to be referenced through static import: * * <pre> * import static org.apache.geode.test.dunit.DebuggerUtils.*; * ... * attachDebugger(...); * </pre> * * Extracted from DistributedTestCase. * * @see org.apache.geode.internal.util.DebuggerSupport */ public class DebuggerUtils { protected DebuggerUtils() {} @SuppressWarnings("serial") public static void attachDebugger(final VM vm, final String message) { vm.invoke( new SerializableRunnable(DebuggerSupport.class.getSimpleName() + " waitForJavaDebugger") { public void run() { DebuggerSupport.waitForJavaDebugger(message); } }); } }
prasi-in/geode
geode-core/src/test/java/org/apache/geode/test/dunit/DebuggerUtils.java
Java
apache-2.0
1,770
# -*- coding: utf-8 -*- # # 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. # from airflow.contrib.hooks.datastore_hook import DatastoreHook from airflow.contrib.hooks.gcs_hook import GoogleCloudStorageHook from airflow.exceptions import AirflowException from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DatastoreExportOperator(BaseOperator): """ Export entities from Google Cloud Datastore to Cloud Storage :param bucket: name of the cloud storage bucket to backup data :type bucket: str :param namespace: optional namespace path in the specified Cloud Storage bucket to backup data. If this namespace does not exist in GCS, it will be created. :type namespace: str :param datastore_conn_id: the name of the Datastore connection id to use :type datastore_conn_id: str :param cloud_storage_conn_id: the name of the cloud storage connection id to force-write backup :type cloud_storage_conn_id: str :param delegate_to: The account to impersonate, if any. For this to work, the service account making the request must have domain-wide delegation enabled. :type delegate_to: str :param entity_filter: description of what data from the project is included in the export, refer to https://cloud.google.com/datastore/docs/reference/rest/Shared.Types/EntityFilter :type entity_filter: dict :param labels: client-assigned labels for cloud storage :type labels: dict :param polling_interval_in_seconds: number of seconds to wait before polling for execution status again :type polling_interval_in_seconds: int :param overwrite_existing: if the storage bucket + namespace is not empty, it will be emptied prior to exports. This enables overwriting existing backups. :type overwrite_existing: bool """ @apply_defaults def __init__(self, bucket, namespace=None, datastore_conn_id='google_cloud_default', cloud_storage_conn_id='google_cloud_default', delegate_to=None, entity_filter=None, labels=None, polling_interval_in_seconds=10, overwrite_existing=False, *args, **kwargs): super(DatastoreExportOperator, self).__init__(*args, **kwargs) self.datastore_conn_id = datastore_conn_id self.cloud_storage_conn_id = cloud_storage_conn_id self.delegate_to = delegate_to self.bucket = bucket self.namespace = namespace self.entity_filter = entity_filter self.labels = labels self.polling_interval_in_seconds = polling_interval_in_seconds self.overwrite_existing = overwrite_existing if kwargs.get('xcom_push') is not None: raise AirflowException("'xcom_push' was deprecated, use 'BaseOperator.do_xcom_push' instead") def execute(self, context): self.log.info('Exporting data to Cloud Storage bucket ' + self.bucket) if self.overwrite_existing and self.namespace: gcs_hook = GoogleCloudStorageHook(self.cloud_storage_conn_id) objects = gcs_hook.list(self.bucket, prefix=self.namespace) for o in objects: gcs_hook.delete(self.bucket, o) ds_hook = DatastoreHook(self.datastore_conn_id, self.delegate_to) result = ds_hook.export_to_storage_bucket(bucket=self.bucket, namespace=self.namespace, entity_filter=self.entity_filter, labels=self.labels) operation_name = result['name'] result = ds_hook.poll_operation_until_done(operation_name, self.polling_interval_in_seconds) state = result['metadata']['common']['state'] if state != 'SUCCESSFUL': raise AirflowException('Operation failed: result={}'.format(result)) return result
r39132/airflow
airflow/contrib/operators/datastore_export_operator.py
Python
apache-2.0
4,882
package org.drip.product.rates; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2014 Lakshmi Krishnamurthy * Copyright (C) 2013 Lakshmi Krishnamurthy * Copyright (C) 2012 Lakshmi Krishnamurthy * Copyright (C) 2011 Lakshmi Krishnamurthy * * This file is part of DRIP, a free-software/open-source library for fixed income analysts and developers - * http://www.credit-trader.org/Begin.html * * DRIP is a free, full featured, fixed income rates, credit, and FX analytics library with a focus towards * pricing/valuation, risk, and market making. * * 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. */ /** * EDFComponent contains the implementation of the Euro-dollar future contract/valuation (EDF). It exports * the following functionality: * - Standard/Custom Constructor for the EDFComponent * - Dates: Effective, Maturity, Coupon dates and Product settlement Parameters * - Coupon/Notional Outstanding as well as schedules * - Market Parameters: Discount, Forward, Credit, Treasury, EDSF Curves * - Cash Flow Periods: Coupon flows and (Optionally) Loss Flows * - Valuation: Named Measure Generation * - Calibration: The codes and constraints generation * - Jacobians: Quote/DF and PV/DF micro-Jacobian generation * - Serialization into and de-serialization out of byte arrays * * @author Lakshmi Krishnamurthy */ public class EDFComponent extends org.drip.product.definition.RatesComponent { private double _dblNotional = 100.; private java.lang.String _strIR = ""; private java.lang.String _strEDCode = ""; private java.lang.String _strDC = "Act/360"; private java.lang.String _strCalendar = "USD"; private double _dblMaturity = java.lang.Double.NaN; private double _dblEffective = java.lang.Double.NaN; private org.drip.product.params.FactorSchedule _notlSchedule = null; private org.drip.param.valuation.CashSettleParams _settleParams = null; @Override protected org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> calibMeasures ( final org.drip.param.valuation.ValuationParams valParams, final org.drip.param.pricer.PricerParams pricerParams, final org.drip.param.definition.ComponentMarketParams mktParams, final org.drip.param.valuation.QuotingParams quotingParams) { return null; } /** * Construct an EDFComponent Instance * * @param dtEffective Effective Date * @param dtMaturity Maturity Date * @param strIR IR Curve * @param strDC Day Count * @param strCalendar Calendar * * @throws java.lang.Exception Thrown if the inputs are invalid */ public EDFComponent ( final org.drip.analytics.date.JulianDate dtEffective, final org.drip.analytics.date.JulianDate dtMaturity, final java.lang.String strIR, final java.lang.String strDC, final java.lang.String strCalendar) throws java.lang.Exception { if (null == dtEffective || null == dtMaturity || null == (_strIR = strIR) || _strIR.isEmpty() || (_dblMaturity = dtMaturity.getJulian()) <= (_dblEffective = dtEffective.getJulian())) throw new java.lang.Exception ("EDFComponent ctr:: Invalid Params!"); _strDC = strDC; _strCalendar = strCalendar; _notlSchedule = org.drip.product.params.FactorSchedule.CreateBulletSchedule(); } /** * Construct an EDFComponent Component * * @param strFullEDCode EDF Component Code * @param dt Start Date * @param strIR IR Curve * * @throws java.lang.Exception Thrown if the inputs are invalid */ public EDFComponent ( final java.lang.String strFullEDCode, final org.drip.analytics.date.JulianDate dt, final java.lang.String strIR) throws java.lang.Exception { if (null == dt || null == (_strIR = strIR) || _strIR.isEmpty()) throw new java.lang.Exception ("EDFComponent ctr:: Invalid Params!"); java.lang.String strEDCode = strFullEDCode; if (4 != strEDCode.length() || !strEDCode.toUpperCase().startsWith ("ED")) throw new java.lang.Exception ("EDFComponent ctr:: Unknown EDF Code " + strEDCode); _strCalendar = strIR; int iEffectiveMonth = -1; int iYearDigit = new java.lang.Integer ("" + strEDCode.charAt (3)).intValue(); if (10 <= iYearDigit) throw new java.lang.Exception ("EDFComponent ctr:: Invalid ED year in " + strEDCode); char chMonth = strEDCode.charAt (2); if ('H' == chMonth) iEffectiveMonth = org.drip.analytics.date.JulianDate.MARCH; else if ('M' == chMonth) iEffectiveMonth = org.drip.analytics.date.JulianDate.JUNE; else if ('U' == chMonth) iEffectiveMonth = org.drip.analytics.date.JulianDate.SEPTEMBER; else if ('Z' == chMonth) iEffectiveMonth = org.drip.analytics.date.JulianDate.DECEMBER; else throw new java.lang.Exception ("EDFComponent ctr:: Unknown Month in " + strEDCode); org.drip.analytics.date.JulianDate dtEDEffective = dt.getFirstEDFStartDate (3); while (iYearDigit != (org.drip.analytics.date.JulianDate.Year (dtEDEffective.getJulian()) % 10)) dtEDEffective = dtEDEffective.addYears (1); org.drip.analytics.date.JulianDate dtEffective = org.drip.analytics.date.JulianDate.CreateFromYMD (org.drip.analytics.date.JulianDate.Year (dtEDEffective.getJulian()), iEffectiveMonth, 15); _dblEffective = dtEffective.getJulian(); _dblMaturity = dtEffective.addMonths (3).getJulian(); _notlSchedule = org.drip.product.params.FactorSchedule.CreateBulletSchedule(); } /** * EDFComponent de-serialization from input byte array * * @param ab Byte Array * * @throws java.lang.Exception Thrown if EDFComponent cannot be properly de-serialized */ public EDFComponent ( final byte[] ab) throws java.lang.Exception { if (null == ab || 0 == ab.length) throw new java.lang.Exception ("EDFComponent de-serializer: Invalid input Byte array"); java.lang.String strRawString = new java.lang.String (ab); if (null == strRawString || strRawString.isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Empty state"); java.lang.String strSerializedEDFuture = strRawString.substring (0, strRawString.indexOf (getObjectTrailer())); if (null == strSerializedEDFuture || strSerializedEDFuture.isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate state"); java.lang.String[] astrField = org.drip.quant.common.StringUtil.Split (strSerializedEDFuture, getFieldDelimiter()); if (null == astrField || 7 > astrField.length) throw new java.lang.Exception ("EDFComponent de-serializer: Invalid reqd field set"); // double dblVersion = new java.lang.Double (astrField[0]); if (null == astrField[1] || astrField[1].isEmpty() || org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[1])) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate notional"); _dblNotional = new java.lang.Double (astrField[1]); if (null == astrField[2] || astrField[2].isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate IR curve name"); if (!org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[2])) _strIR = astrField[2]; else _strIR = ""; if (null == astrField[3] || astrField[3].isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate EDF code"); if (!org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[3])) _strEDCode = astrField[3]; else _strEDCode = ""; if (null == astrField[4] || astrField[4].isEmpty() || org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[4])) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate maturity date"); _dblMaturity = new java.lang.Double (astrField[4]); if (null == astrField[5] || astrField[5].isEmpty() || org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[5])) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate effective date"); _dblEffective = new java.lang.Double (astrField[5]); if (null == astrField[6] || astrField[6].isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate notional schedule"); if (org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[6])) _notlSchedule = null; else _notlSchedule = new org.drip.product.params.FactorSchedule (astrField[6].getBytes()); if (null == astrField[7] || astrField[7].isEmpty()) throw new java.lang.Exception ("EDFComponent de-serializer: Cannot locate cash settle params"); if (org.drip.service.stream.Serializer.NULL_SER_STRING.equalsIgnoreCase (astrField[7])) _settleParams = null; else _settleParams = new org.drip.param.valuation.CashSettleParams (astrField[7].getBytes()); } @Override public java.lang.String getPrimaryCode() { return _strEDCode + "." + _strIR; } @Override public void setPrimaryCode (final java.lang.String strCode) { _strEDCode = strCode; } @Override public java.lang.String[] getSecondaryCode() { java.lang.String strPrimaryCode = getPrimaryCode(); int iNumTokens = 0; java.lang.String astrCodeTokens[] = new java.lang.String[2]; java.util.StringTokenizer stCodeTokens = new java.util.StringTokenizer (strPrimaryCode, "."); while (stCodeTokens.hasMoreTokens()) astrCodeTokens[iNumTokens++] = stCodeTokens.nextToken(); return new java.lang.String[] {astrCodeTokens[0]}; } @Override public java.lang.String getComponentName() { return _strEDCode; } @Override public java.lang.String getTreasuryCurveName() { return ""; } @Override public java.lang.String getEDSFCurveName() { return ""; } @Override public double getInitialNotional() { return _dblNotional; } @Override public double getNotional ( final double dblDate) throws java.lang.Exception { if (null == _notlSchedule || !org.drip.quant.common.NumberUtil.IsValid (dblDate)) throw new java.lang.Exception ("EDFComponent::getNotional => Got NaN date"); return _notlSchedule.getFactor (dblDate); } @Override public double getCoupon ( final double dblValue, final org.drip.param.definition.ComponentMarketParams mktParams) throws java.lang.Exception { return 0.; } @Override public double getNotional ( final double dblDate1, final double dblDate2) throws java.lang.Exception { if (null == _notlSchedule || !org.drip.quant.common.NumberUtil.IsValid (dblDate1) || !org.drip.quant.common.NumberUtil.IsValid (dblDate2)) throw new java.lang.Exception ("EDFComponent::getNotional => Got NaN date"); return _notlSchedule.getFactor (dblDate1, dblDate2); } @Override public boolean setCurves ( final java.lang.String strIR, final java.lang.String strIRTSY, final java.lang.String strCC) { if (null == strIR || strIR.isEmpty()) return false; _strIR = strIR; return true; } @Override public java.lang.String getIRCurveName() { return _strIR; } @Override public java.lang.String getForwardCurveName() { return ""; } @Override public java.lang.String getCreditCurveName() { return ""; } @Override public org.drip.analytics.date.JulianDate getEffectiveDate() { try { return new org.drip.analytics.date.JulianDate (_dblEffective); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } @Override public org.drip.analytics.date.JulianDate getMaturityDate() { try { return new org.drip.analytics.date.JulianDate (_dblMaturity); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } @Override public org.drip.analytics.date.JulianDate getFirstCouponDate() { return null; } @Override public java.util.List<org.drip.analytics.period.CashflowPeriod> getCashFlowPeriod() { return org.drip.analytics.period.CashflowPeriod.GetSinglePeriod (_dblEffective, _dblMaturity, _strCalendar); } @Override public org.drip.param.valuation.CashSettleParams getCashSettleParams() { return _settleParams; } @Override public org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> value ( final org.drip.param.valuation.ValuationParams valParams, final org.drip.param.pricer.PricerParams pricerParams, final org.drip.param.definition.ComponentMarketParams mktParams, final org.drip.param.valuation.QuotingParams quotingParams) { if (null == valParams || null == mktParams || valParams.valueDate() >= _dblMaturity) return null; org.drip.analytics.rates.DiscountCurve dc = mktParams.getDiscountCurve(); if (null == dc) return null; long lStart = System.nanoTime(); org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapResult = new org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double>(); try { double dblCashSettle = null == _settleParams ? valParams.cashPayDate() : _settleParams.cashSettleDate (valParams.valueDate()); double dblUnadjustedAnnuity = dc.df (_dblMaturity) / dc.df (_dblEffective) / dc.df (dblCashSettle); double dblAdjustedAnnuity = dblUnadjustedAnnuity / dc.df (dblCashSettle); mapResult.put ("PV", dblAdjustedAnnuity * _dblNotional * 0.01 * getNotional (_dblEffective, _dblMaturity)); mapResult.put ("Price", 100. * dblAdjustedAnnuity); mapResult.put ("Rate", ((1. / dblUnadjustedAnnuity) - 1.) / org.drip.analytics.daycount.Convention.YearFraction (_dblEffective, _dblMaturity, _strDC, false, _dblMaturity, null, _strCalendar)); } catch (java.lang.Exception e) { e.printStackTrace(); } mapResult.put ("CalcTime", (System.nanoTime() - lStart) * 1.e-09); return mapResult; } @Override public java.util.Set<java.lang.String> getMeasureNames() { java.util.Set<java.lang.String> setstrMeasureNames = new java.util.TreeSet<java.lang.String>(); setstrMeasureNames.add ("CalcTime"); setstrMeasureNames.add ("Price"); setstrMeasureNames.add ("PV"); setstrMeasureNames.add ("Rate"); return setstrMeasureNames; } @Override public org.drip.quant.calculus.WengertJacobian calcPVDFMicroJack ( final org.drip.param.valuation.ValuationParams valParams, final org.drip.param.pricer.PricerParams pricerParams, final org.drip.param.definition.ComponentMarketParams mktParams, final org.drip.param.valuation.QuotingParams quotingParams) { if (null == valParams || valParams.valueDate() >= getMaturityDate().getJulian() || null == mktParams || null == mktParams.getDiscountCurve()) return null; try { org.drip.analytics.support.CaseInsensitiveTreeMap<java.lang.Double> mapMeasures = value (valParams, pricerParams, mktParams, quotingParams); if (null == mapMeasures) return null; double dblPV = mapMeasures.get ("PV"); org.drip.analytics.rates.DiscountCurve dc = mktParams.getDiscountCurve(); double dblDFEffective = dc.df (_dblEffective); double dblDFMaturity = dc.df (getMaturityDate().getJulian()); org.drip.quant.calculus.WengertJacobian wjDFEffective = dc.jackDDFDQuote (_dblEffective); org.drip.quant.calculus.WengertJacobian wjDFMaturity = dc.jackDDFDQuote (getMaturityDate().getJulian()); if (null == wjDFEffective || null == wjDFMaturity) return null; org.drip.quant.calculus.WengertJacobian wjPVDFMicroJack = new org.drip.quant.calculus.WengertJacobian (1, wjDFMaturity.numParameters()); for (int i = 0; i < wjDFMaturity.numParameters(); ++i) { if (!wjPVDFMicroJack.accumulatePartialFirstDerivative (0, i, wjDFMaturity.getFirstDerivative (0, i) / dblDFEffective)) return null; if (!wjPVDFMicroJack.accumulatePartialFirstDerivative (0, i, -wjDFEffective.getFirstDerivative (0, i) * dblDFMaturity / dblDFEffective / dblDFEffective)) return null; } return adjustPVDFMicroJackForCashSettle (valParams.cashPayDate(), dblPV, dc, wjPVDFMicroJack) ? wjPVDFMicroJack : null; } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } @Override public org.drip.quant.calculus.WengertJacobian calcQuoteDFMicroJack ( final java.lang.String strQuote, final org.drip.param.valuation.ValuationParams valParams, final org.drip.param.pricer.PricerParams pricerParams, final org.drip.param.definition.ComponentMarketParams mktParams, final org.drip.param.valuation.QuotingParams quotingParams) { if (null == valParams || valParams.valueDate() >= getMaturityDate().getJulian() || null == strQuote || null == mktParams || null == mktParams.getDiscountCurve()) return null; if ("Rate".equalsIgnoreCase (strQuote)) { try { org.drip.analytics.rates.DiscountCurve dc = mktParams.getDiscountCurve(); double dblDFEffective = dc.df (_dblEffective); double dblDFMaturity = dc.df (getMaturityDate().getJulian()); org.drip.quant.calculus.WengertJacobian wjDFEffective = dc.jackDDFDQuote (_dblEffective); org.drip.quant.calculus.WengertJacobian wjDFMaturity = dc.jackDDFDQuote (getMaturityDate().getJulian()); if (null == wjDFEffective || null == wjDFMaturity) return null; org.drip.quant.calculus.WengertJacobian wjDFMicroJack = new org.drip.quant.calculus.WengertJacobian (1, wjDFMaturity.numParameters()); for (int i = 0; i < wjDFMaturity.numParameters(); ++i) { if (!wjDFMicroJack.accumulatePartialFirstDerivative (0, i, wjDFMaturity.getFirstDerivative (0, i) / dblDFEffective)) return null; if (!wjDFMicroJack.accumulatePartialFirstDerivative (0, i, -1. * wjDFEffective.getFirstDerivative (0, i) * dblDFMaturity / dblDFEffective / dblDFEffective)) return null; } return wjDFMicroJack; } catch (java.lang.Exception e) { e.printStackTrace(); } } return null; } @Override public org.drip.state.estimator.PredictorResponseWeightConstraint generateCalibPRLC ( final org.drip.param.valuation.ValuationParams valParams, final org.drip.param.pricer.PricerParams pricerParams, final org.drip.param.definition.ComponentMarketParams mktParams, final org.drip.param.valuation.QuotingParams quotingParams, final org.drip.state.representation.LatentStateMetricMeasure lsmm) { if (null == valParams || valParams.valueDate() >= _dblMaturity || null == lsmm || !(lsmm instanceof org.drip.analytics.rates.RatesLSMM) || !org.drip.analytics.rates.DiscountCurve.LATENT_STATE_DISCOUNT.equalsIgnoreCase (lsmm.getID())) return null; org.drip.analytics.rates.RatesLSMM ratesLSMM = (org.drip.analytics.rates.RatesLSMM) lsmm; if (org.drip.analytics.rates.DiscountCurve.QUANTIFICATION_METRIC_DISCOUNT_FACTOR.equalsIgnoreCase (ratesLSMM.getQuantificationMetric())) { try { org.drip.analytics.rates.TurnListDiscountFactor tldf = ratesLSMM.turnsDiscount(); double dblTurnMaturityDF = null == tldf ? 1. : tldf.turnAdjust (valParams.valueDate(), _dblMaturity); if (org.drip.quant.common.StringUtil.MatchInStringArray (ratesLSMM.getManifestMeasure(), new java.lang.String[] {"Price"}, false)) { org.drip.state.estimator.PredictorResponseWeightConstraint prlc = new org.drip.state.estimator.PredictorResponseWeightConstraint(); return prlc.addPredictorResponseWeight (_dblMaturity, -dblTurnMaturityDF) && prlc.addPredictorResponseWeight (_dblEffective, 0.01 * ratesLSMM.getMeasureQuoteValue()) && prlc.updateValue (0.) && prlc.addDResponseWeightDQuote (_dblMaturity, 0.) && prlc.addDResponseWeightDQuote (_dblEffective, 0.01) && prlc.updateDValueDQuote (0.) ? prlc : null; } if (org.drip.quant.common.StringUtil.MatchInStringArray (ratesLSMM.getManifestMeasure(), new java.lang.String[] {"PV"}, false)) { org.drip.state.estimator.PredictorResponseWeightConstraint prlc = new org.drip.state.estimator.PredictorResponseWeightConstraint(); return prlc.addPredictorResponseWeight (_dblMaturity, -dblTurnMaturityDF) && prlc.addPredictorResponseWeight (_dblEffective, ratesLSMM.getMeasureQuoteValue()) && prlc.updateValue (0.) && prlc.addDResponseWeightDQuote (_dblMaturity, 0.) && prlc.addDResponseWeightDQuote (_dblEffective, 1.) && prlc.updateDValueDQuote (0.) ? prlc : null; } if (org.drip.quant.common.StringUtil.MatchInStringArray (ratesLSMM.getManifestMeasure(), new java.lang.String[] {"Rate"}, false)) { org.drip.state.estimator.PredictorResponseWeightConstraint prlc = new org.drip.state.estimator.PredictorResponseWeightConstraint(); double dblTurnEffectiveDF = null == tldf ? 1. : tldf.turnAdjust (valParams.valueDate(), _dblMaturity); double dblDCF = org.drip.analytics.daycount.Convention.YearFraction (_dblEffective, _dblMaturity, _strDC, false, _dblMaturity, null, _strCalendar); double dblDF = 1. / (1. + (ratesLSMM.getMeasureQuoteValue() * dblDCF)); return prlc.addPredictorResponseWeight (_dblMaturity, -dblTurnMaturityDF) && prlc.addPredictorResponseWeight (_dblEffective, dblTurnEffectiveDF * dblDF) && prlc.updateValue (0.) && prlc.addDResponseWeightDQuote (_dblMaturity, 0.) && prlc.addDResponseWeightDQuote (_dblEffective, -1. * dblDCF * dblTurnEffectiveDF * dblDF * dblDF) && prlc.updateDValueDQuote (0.) ? prlc : null; } } catch (java.lang.Exception e) { e.printStackTrace(); } } return null; } @Override public byte[] serialize() { java.lang.StringBuffer sb = new java.lang.StringBuffer(); sb.append (org.drip.service.stream.Serializer.VERSION + getFieldDelimiter()); sb.append (_dblNotional + getFieldDelimiter()); if (null == _strIR || _strIR.isEmpty()) sb.append (org.drip.service.stream.Serializer.NULL_SER_STRING + getFieldDelimiter()); else sb.append (_strIR + getFieldDelimiter()); if (null == _strEDCode || _strEDCode.isEmpty()) sb.append (org.drip.service.stream.Serializer.NULL_SER_STRING + getFieldDelimiter()); else sb.append (_strEDCode + getFieldDelimiter()); sb.append (_dblMaturity + getFieldDelimiter()); sb.append (_dblEffective + getFieldDelimiter()); if (null == _notlSchedule) sb.append (org.drip.service.stream.Serializer.NULL_SER_STRING + getFieldDelimiter()); else sb.append (new java.lang.String (_notlSchedule.serialize()) + getFieldDelimiter()); if (null == _settleParams) sb.append (org.drip.service.stream.Serializer.NULL_SER_STRING); else sb.append (new java.lang.String (_settleParams.serialize())); return sb.append (getObjectTrailer()).toString().getBytes(); } @Override public org.drip.service.stream.Serializer deserialize ( final byte[] ab) { try { return new EDFComponent (ab); } catch (java.lang.Exception e) { e.printStackTrace(); } return null; } public static final void main ( final java.lang.String[] astrArgs) throws java.lang.Exception { EDFComponent edf = new EDFComponent (org.drip.analytics.date.JulianDate.Today(), org.drip.analytics.date.JulianDate.Today().addTenor ("1Y"), "GBP", "Act/360", "GBP"); byte[] abEDF = edf.serialize(); System.out.println (new java.lang.String (abEDF)); EDFComponent edfDeser = new EDFComponent (abEDF); System.out.println (new java.lang.String (edfDeser.serialize())); } }
tectronics/splinelibrary
2.3/src/org/drip/product/rates/EDFComponent.java
Java
apache-2.0
24,362
--- id: version-2.8.2-concepts-clients title: Pulsar Clients sidebar_label: Clients original_id: concepts-clients --- Pulsar exposes a client API with language bindings for [Java](client-libraries-java.md), [Go](client-libraries-go.md), [Python](client-libraries-python.md), [C++](client-libraries-cpp.md) and [C#](client-libraries-dotnet.md). The client API optimizes and encapsulates Pulsar's client-broker communication protocol and exposes a simple and intuitive API for use by applications. Under the hood, the current official Pulsar client libraries support transparent reconnection and/or connection failover to brokers, queuing of messages until acknowledged by the broker, and heuristics such as connection retries with backoff. > **Custom client libraries** > If you'd like to create your own client library, we recommend consulting the documentation on Pulsar's custom [binary protocol](developing-binary-protocol.md). ## Client setup phase Before an application creates a producer/consumer, the Pulsar client library needs to initiate a setup phase including two steps: 1. The client attempts to determine the owner of the topic by sending an HTTP lookup request to the broker. The request could reach one of the active brokers which, by looking at the (cached) zookeeper metadata knows who is serving the topic or, in case nobody is serving it, tries to assign it to the least loaded broker. 1. Once the client library has the broker address, it creates a TCP connection (or reuse an existing connection from the pool) and authenticates it. Within this connection, client and broker exchange binary commands from a custom protocol. At this point the client sends a command to create producer/consumer to the broker, which will comply after having validated the authorization policy. Whenever the TCP connection breaks, the client immediately re-initiates this setup phase and keeps trying with exponential backoff to re-establish the producer or consumer until the operation succeeds. ## Reader interface In Pulsar, the "standard" [consumer interface](concepts-messaging.md#consumers) involves using consumers to listen on [topics](reference-terminology.md#topic), process incoming messages, and finally acknowledge those messages when they are processed. Whenever a new subscription is created, it is initially positioned at the end of the topic (by default), and consumers associated with that subscription begin reading with the first message created afterwards. Whenever a consumer connects to a topic using a pre-existing subscription, it begins reading from the earliest message un-acked within that subscription. In summary, with the consumer interface, subscription cursors are automatically managed by Pulsar in response to [message acknowledgements](concepts-messaging.md#acknowledgement). The **reader interface** for Pulsar enables applications to manually manage cursors. When you use a reader to connect to a topic---rather than a consumer---you need to specify *which* message the reader begins reading from when it connects to a topic. When connecting to a topic, the reader interface enables you to begin with: * The **earliest** available message in the topic * The **latest** available message in the topic * Some other message between the earliest and the latest. If you select this option, you'll need to explicitly provide a message ID. Your application will be responsible for "knowing" this message ID in advance, perhaps fetching it from a persistent data store or cache. The reader interface is helpful for use cases like using Pulsar to provide effectively-once processing semantics for a stream processing system. For this use case, it's essential that the stream processing system be able to "rewind" topics to a specific message and begin reading there. The reader interface provides Pulsar clients with the low-level abstraction necessary to "manually position" themselves within a topic. Internally, the reader interface is implemented as a consumer using an exclusive, non-durable subscription to the topic with a randomly-allocated name. [ **IMPORTANT** ] Unlike subscription/consumer, readers are non-durable in nature and does not prevent data in a topic from being deleted, thus it is ***strongly*** advised that [data retention](cookbooks-retention-expiry.md) be configured. If data retention for a topic is not configured for an adequate amount of time, messages that the reader has not yet read might be deleted . This causes the readers to essentially skip messages. Configuring the data retention for a topic guarantees the reader with a certain duration to read a message. Please also note that a reader can have a "backlog", but the metric is only used for users to know how behind the reader is. The metric is not considered for any backlog quota calculations. ![The Pulsar consumer and reader interfaces](assets/pulsar-reader-consumer-interfaces.png) Here's a Java example that begins reading from the earliest available message on a topic: ```java import org.apache.pulsar.client.api.Message; import org.apache.pulsar.client.api.MessageId; import org.apache.pulsar.client.api.Reader; // Create a reader on a topic and for a specific message (and onward) Reader<byte[]> reader = pulsarClient.newReader() .topic("reader-api-test") .startMessageId(MessageId.earliest) .create(); while (true) { Message message = reader.readNext(); // Process the message } ``` To create a reader that reads from the latest available message: ```java Reader<byte[]> reader = pulsarClient.newReader() .topic(topic) .startMessageId(MessageId.latest) .create(); ``` To create a reader that reads from some message between the earliest and the latest: ```java byte[] msgIdBytes = // Some byte array MessageId id = MessageId.fromByteArray(msgIdBytes); Reader<byte[]> reader = pulsarClient.newReader() .topic(topic) .startMessageId(id) .create(); ```
massakam/pulsar
site2/website/versioned_docs/version-2.8.2/concepts-clients.md
Markdown
apache-2.0
5,959
/* * Copyright (c) 2010-2018. Axon Framework * * 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.axonframework.eventsourcing.eventstore.jdbc; import org.axonframework.common.jdbc.PersistenceExceptionResolver; /** * SQLErrorCodesResolver is an implementation of PersistenceExceptionResolver used to resolve sql error codes to see if * it is an duplicate key constraint violation. * <p/> * * @author Kristian Rosenvold * @since 2.2 */ public class JdbcSQLErrorCodesResolver implements PersistenceExceptionResolver { @Override public boolean isDuplicateKeyViolation(Exception exception) { return causeIsEntityExistsException(exception); } private boolean causeIsEntityExistsException(Throwable exception) { return exception instanceof java.sql.SQLIntegrityConstraintViolationException || (exception.getCause() != null && causeIsEntityExistsException(exception.getCause())); } }
krosenvold/AxonFramework
eventsourcing/src/main/java/org/axonframework/eventsourcing/eventstore/jdbc/JdbcSQLErrorCodesResolver.java
Java
apache-2.0
1,463
/* * Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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 <aws/gamelift/GameLift_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace GameLift { namespace Model { enum class GameSessionPlacementState { NOT_SET, PENDING, FULFILLED, CANCELLED, TIMED_OUT }; namespace GameSessionPlacementStateMapper { AWS_GAMELIFT_API GameSessionPlacementState GetGameSessionPlacementStateForName(const Aws::String& name); AWS_GAMELIFT_API Aws::String GetNameForGameSessionPlacementState(GameSessionPlacementState value); } // namespace GameSessionPlacementStateMapper } // namespace Model } // namespace GameLift } // namespace Aws
chiaming0914/awe-cpp-sdk
aws-cpp-sdk-gamelift/include/aws/gamelift/model/GameSessionPlacementState.h
C
apache-2.0
1,216
/*! * Bootstrap v3.3.5 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! * Generated using the Bootstrap Customizer (http://getbootstrap.com/customize/?id=e2c1c6fb427e9f0784a0) * Config saved to config.json and https://gist.github.com/e2c1c6fb427e9f0784a0 */ /*! * Bootstrap v3.3.5 (http://getbootstrap.com) * Copyright 2011-2015 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ .btn-default, .btn-primary, .btn-success, .btn-info, .btn-warning, .btn-danger { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 1px rgba(0, 0, 0, 0.075); } .btn-default:active, .btn-primary:active, .btn-success:active, .btn-info:active, .btn-warning:active, .btn-danger:active, .btn-default.active, .btn-primary.active, .btn-success.active, .btn-info.active, .btn-warning.active, .btn-danger.active { -webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125); } .btn-default.disabled, .btn-primary.disabled, .btn-success.disabled, .btn-info.disabled, .btn-warning.disabled, .btn-danger.disabled, .btn-default[disabled], .btn-primary[disabled], .btn-success[disabled], .btn-info[disabled], .btn-warning[disabled], .btn-danger[disabled], fieldset[disabled] .btn-default, fieldset[disabled] .btn-primary, fieldset[disabled] .btn-success, fieldset[disabled] .btn-info, fieldset[disabled] .btn-warning, fieldset[disabled] .btn-danger { -webkit-box-shadow: none; box-shadow: none; } .btn-default .badge, .btn-primary .badge, .btn-success .badge, .btn-info .badge, .btn-warning .badge, .btn-danger .badge { text-shadow: none; } .btn:active, .btn.active { background-image: none; } .btn-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #e0e0e0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#e0e0e0)); background-image: linear-gradient(to bottom, #ffffff 0%, #e0e0e0 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe0e0e0', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #dbdbdb; text-shadow: 0 1px 0 #fff; border-color: #ccc; } .btn-default:hover, .btn-default:focus { background-color: #e0e0e0; background-position: 0 -15px; } .btn-default:active, .btn-default.active { background-color: #e0e0e0; border-color: #dbdbdb; } .btn-default.disabled, .btn-default[disabled], fieldset[disabled] .btn-default, .btn-default.disabled:hover, .btn-default[disabled]:hover, fieldset[disabled] .btn-default:hover, .btn-default.disabled:focus, .btn-default[disabled]:focus, fieldset[disabled] .btn-default:focus, .btn-default.disabled.focus, .btn-default[disabled].focus, fieldset[disabled] .btn-default.focus, .btn-default.disabled:active, .btn-default[disabled]:active, fieldset[disabled] .btn-default:active, .btn-default.disabled.active, .btn-default[disabled].active, fieldset[disabled] .btn-default.active { background-color: #e0e0e0; background-image: none; } .btn-primary { background-image: -webkit-linear-gradient(top, #337ab7 0%, #265a88 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #265a88 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#265a88)); background-image: linear-gradient(to bottom, #337ab7 0%, #265a88 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff265a88', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #245580; } .btn-primary:hover, .btn-primary:focus { background-color: #265a88; background-position: 0 -15px; } .btn-primary:active, .btn-primary.active { background-color: #265a88; border-color: #245580; } .btn-primary.disabled, .btn-primary[disabled], fieldset[disabled] .btn-primary, .btn-primary.disabled:hover, .btn-primary[disabled]:hover, fieldset[disabled] .btn-primary:hover, .btn-primary.disabled:focus, .btn-primary[disabled]:focus, fieldset[disabled] .btn-primary:focus, .btn-primary.disabled.focus, .btn-primary[disabled].focus, fieldset[disabled] .btn-primary.focus, .btn-primary.disabled:active, .btn-primary[disabled]:active, fieldset[disabled] .btn-primary:active, .btn-primary.disabled.active, .btn-primary[disabled].active, fieldset[disabled] .btn-primary.active { background-color: #265a88; background-image: none; } .btn-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #419641 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#419641)); background-image: linear-gradient(to bottom, #5cb85c 0%, #419641 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff419641', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #3e8f3e; } .btn-success:hover, .btn-success:focus { background-color: #419641; background-position: 0 -15px; } .btn-success:active, .btn-success.active { background-color: #419641; border-color: #3e8f3e; } .btn-success.disabled, .btn-success[disabled], fieldset[disabled] .btn-success, .btn-success.disabled:hover, .btn-success[disabled]:hover, fieldset[disabled] .btn-success:hover, .btn-success.disabled:focus, .btn-success[disabled]:focus, fieldset[disabled] .btn-success:focus, .btn-success.disabled.focus, .btn-success[disabled].focus, fieldset[disabled] .btn-success.focus, .btn-success.disabled:active, .btn-success[disabled]:active, fieldset[disabled] .btn-success:active, .btn-success.disabled.active, .btn-success[disabled].active, fieldset[disabled] .btn-success.active { background-color: #419641; background-image: none; } .btn-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #2aabd2 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#2aabd2)); background-image: linear-gradient(to bottom, #5bc0de 0%, #2aabd2 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff2aabd2', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #28a4c9; } .btn-info:hover, .btn-info:focus { background-color: #2aabd2; background-position: 0 -15px; } .btn-info:active, .btn-info.active { background-color: #2aabd2; border-color: #28a4c9; } .btn-info.disabled, .btn-info[disabled], fieldset[disabled] .btn-info, .btn-info.disabled:hover, .btn-info[disabled]:hover, fieldset[disabled] .btn-info:hover, .btn-info.disabled:focus, .btn-info[disabled]:focus, fieldset[disabled] .btn-info:focus, .btn-info.disabled.focus, .btn-info[disabled].focus, fieldset[disabled] .btn-info.focus, .btn-info.disabled:active, .btn-info[disabled]:active, fieldset[disabled] .btn-info:active, .btn-info.disabled.active, .btn-info[disabled].active, fieldset[disabled] .btn-info.active { background-color: #2aabd2; background-image: none; } .btn-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #eb9316 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#eb9316)); background-image: linear-gradient(to bottom, #f0ad4e 0%, #eb9316 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffeb9316', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #e38d13; } .btn-warning:hover, .btn-warning:focus { background-color: #eb9316; background-position: 0 -15px; } .btn-warning:active, .btn-warning.active { background-color: #eb9316; border-color: #e38d13; } .btn-warning.disabled, .btn-warning[disabled], fieldset[disabled] .btn-warning, .btn-warning.disabled:hover, .btn-warning[disabled]:hover, fieldset[disabled] .btn-warning:hover, .btn-warning.disabled:focus, .btn-warning[disabled]:focus, fieldset[disabled] .btn-warning:focus, .btn-warning.disabled.focus, .btn-warning[disabled].focus, fieldset[disabled] .btn-warning.focus, .btn-warning.disabled:active, .btn-warning[disabled]:active, fieldset[disabled] .btn-warning:active, .btn-warning.disabled.active, .btn-warning[disabled].active, fieldset[disabled] .btn-warning.active { background-color: #eb9316; background-image: none; } .btn-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c12e2a 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c12e2a)); background-image: linear-gradient(to bottom, #d9534f 0%, #c12e2a 100%); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc12e2a', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); background-repeat: repeat-x; border-color: #b92c28; } .btn-danger:hover, .btn-danger:focus { background-color: #c12e2a; background-position: 0 -15px; } .btn-danger:active, .btn-danger.active { background-color: #c12e2a; border-color: #b92c28; } .btn-danger.disabled, .btn-danger[disabled], fieldset[disabled] .btn-danger, .btn-danger.disabled:hover, .btn-danger[disabled]:hover, fieldset[disabled] .btn-danger:hover, .btn-danger.disabled:focus, .btn-danger[disabled]:focus, fieldset[disabled] .btn-danger:focus, .btn-danger.disabled.focus, .btn-danger[disabled].focus, fieldset[disabled] .btn-danger.focus, .btn-danger.disabled:active, .btn-danger[disabled]:active, fieldset[disabled] .btn-danger:active, .btn-danger.disabled.active, .btn-danger[disabled].active, fieldset[disabled] .btn-danger.active { background-color: #c12e2a; background-image: none; } .thumbnail, .img-thumbnail { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); background-color: #e8e8e8; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); background-color: #2e6da4; } .navbar-default { background-image: -webkit-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: -o-linear-gradient(top, #ffffff 0%, #f8f8f8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#f8f8f8)); background-image: linear-gradient(to bottom, #ffffff 0%, #f8f8f8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#fff8f8f8', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border-radius: 4px; -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.15), 0 1px 5px rgba(0, 0, 0, 0.075); } .navbar-default .navbar-nav > .open > a, .navbar-default .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); background-image: -o-linear-gradient(top, #dbdbdb 0%, #e2e2e2 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dbdbdb), to(#e2e2e2)); background-image: linear-gradient(to bottom, #dbdbdb 0%, #e2e2e2 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdbdbdb', endColorstr='#ffe2e2e2', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.075); } .navbar-brand, .navbar-nav > li > a { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.25); } .navbar-inverse { background-image: -webkit-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: -o-linear-gradient(top, #3c3c3c 0%, #222222 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#3c3c3c), to(#222222)); background-image: linear-gradient(to bottom, #3c3c3c 0%, #222222 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff3c3c3c', endColorstr='#ff222222', GradientType=0); filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); border-radius: 4px; } .navbar-inverse .navbar-nav > .open > a, .navbar-inverse .navbar-nav > .active > a { background-image: -webkit-linear-gradient(top, #080808 0%, #0f0f0f 100%); background-image: -o-linear-gradient(top, #080808 0%, #0f0f0f 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#080808), to(#0f0f0f)); background-image: linear-gradient(to bottom, #080808 0%, #0f0f0f 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff080808', endColorstr='#ff0f0f0f', GradientType=0); -webkit-box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); box-shadow: inset 0 3px 9px rgba(0, 0, 0, 0.25); } .navbar-inverse .navbar-brand, .navbar-inverse .navbar-nav > li > a { text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.25); } .navbar-static-top, .navbar-fixed-top, .navbar-fixed-bottom { border-radius: 0; } @media (max-width: 767px) { .navbar .navbar-nav .open .dropdown-menu > .active > a, .navbar .navbar-nav .open .dropdown-menu > .active > a:hover, .navbar .navbar-nav .open .dropdown-menu > .active > a:focus { color: #fff; background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); } } .alert { text-shadow: 0 1px 0 rgba(255, 255, 255, 0.2); -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.25), 0 1px 2px rgba(0, 0, 0, 0.05); } .alert-success { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #c8e5bc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#c8e5bc)); background-image: linear-gradient(to bottom, #dff0d8 0%, #c8e5bc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffc8e5bc', GradientType=0); border-color: #b2dba1; } .alert-info { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #b9def0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#b9def0)); background-image: linear-gradient(to bottom, #d9edf7 0%, #b9def0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffb9def0', GradientType=0); border-color: #9acfea; } .alert-warning { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #f8efc0 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#f8efc0)); background-image: linear-gradient(to bottom, #fcf8e3 0%, #f8efc0 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fff8efc0', GradientType=0); border-color: #f5e79e; } .alert-danger { background-image: -webkit-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #e7c3c3 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#e7c3c3)); background-image: linear-gradient(to bottom, #f2dede 0%, #e7c3c3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffe7c3c3', GradientType=0); border-color: #dca7a7; } .progress { background-image: -webkit-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #ebebeb 0%, #f5f5f5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#ebebeb), to(#f5f5f5)); background-image: linear-gradient(to bottom, #ebebeb 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffebebeb', endColorstr='#fff5f5f5', GradientType=0); } .progress-bar { background-image: -webkit-linear-gradient(top, #337ab7 0%, #286090 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #286090 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#286090)); background-image: linear-gradient(to bottom, #337ab7 0%, #286090 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff286090', GradientType=0); } .progress-bar-success { background-image: -webkit-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: -o-linear-gradient(top, #5cb85c 0%, #449d44 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5cb85c), to(#449d44)); background-image: linear-gradient(to bottom, #5cb85c 0%, #449d44 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5cb85c', endColorstr='#ff449d44', GradientType=0); } .progress-bar-info { background-image: -webkit-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: -o-linear-gradient(top, #5bc0de 0%, #31b0d5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#5bc0de), to(#31b0d5)); background-image: linear-gradient(to bottom, #5bc0de 0%, #31b0d5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5bc0de', endColorstr='#ff31b0d5', GradientType=0); } .progress-bar-warning { background-image: -webkit-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: -o-linear-gradient(top, #f0ad4e 0%, #ec971f 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f0ad4e), to(#ec971f)); background-image: linear-gradient(to bottom, #f0ad4e 0%, #ec971f 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff0ad4e', endColorstr='#ffec971f', GradientType=0); } .progress-bar-danger { background-image: -webkit-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: -o-linear-gradient(top, #d9534f 0%, #c9302c 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9534f), to(#c9302c)); background-image: linear-gradient(to bottom, #d9534f 0%, #c9302c 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9534f', endColorstr='#ffc9302c', GradientType=0); } .progress-bar-striped { background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: -o-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent); } .list-group { border-radius: 4px; -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.075); } .list-group-item.active, .list-group-item.active:hover, .list-group-item.active:focus { text-shadow: 0 -1px 0 #286090; background-image: -webkit-linear-gradient(top, #337ab7 0%, #2b669a 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2b669a 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2b669a)); background-image: linear-gradient(to bottom, #337ab7 0%, #2b669a 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2b669a', GradientType=0); border-color: #2b669a; } .list-group-item.active .badge, .list-group-item.active:hover .badge, .list-group-item.active:focus .badge { text-shadow: none; } .panel { -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05); } .panel-default > .panel-heading { background-image: -webkit-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -o-linear-gradient(top, #f5f5f5 0%, #e8e8e8 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f5f5f5), to(#e8e8e8)); background-image: linear-gradient(to bottom, #f5f5f5 0%, #e8e8e8 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff5f5f5', endColorstr='#ffe8e8e8', GradientType=0); } .panel-primary > .panel-heading { background-image: -webkit-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -o-linear-gradient(top, #337ab7 0%, #2e6da4 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#337ab7), to(#2e6da4)); background-image: linear-gradient(to bottom, #337ab7 0%, #2e6da4 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff337ab7', endColorstr='#ff2e6da4', GradientType=0); } .panel-success > .panel-heading { background-image: -webkit-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: -o-linear-gradient(top, #dff0d8 0%, #d0e9c6 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#dff0d8), to(#d0e9c6)); background-image: linear-gradient(to bottom, #dff0d8 0%, #d0e9c6 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffdff0d8', endColorstr='#ffd0e9c6', GradientType=0); } .panel-info > .panel-heading { background-image: -webkit-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: -o-linear-gradient(top, #d9edf7 0%, #c4e3f3 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#d9edf7), to(#c4e3f3)); background-image: linear-gradient(to bottom, #d9edf7 0%, #c4e3f3 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffd9edf7', endColorstr='#ffc4e3f3', GradientType=0); } .panel-warning > .panel-heading { background-image: -webkit-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: -o-linear-gradient(top, #fcf8e3 0%, #faf2cc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#fcf8e3), to(#faf2cc)); background-image: linear-gradient(to bottom, #fcf8e3 0%, #faf2cc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fffcf8e3', endColorstr='#fffaf2cc', GradientType=0); } .panel-danger > .panel-heading { background-image: -webkit-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: -o-linear-gradient(top, #f2dede 0%, #ebcccc 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#f2dede), to(#ebcccc)); background-image: linear-gradient(to bottom, #f2dede 0%, #ebcccc 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#fff2dede', endColorstr='#ffebcccc', GradientType=0); } .well { background-image: -webkit-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: -o-linear-gradient(top, #e8e8e8 0%, #f5f5f5 100%); background-image: -webkit-gradient(linear, left top, left bottom, from(#e8e8e8), to(#f5f5f5)); background-image: linear-gradient(to bottom, #e8e8e8 0%, #f5f5f5 100%); background-repeat: repeat-x; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffe8e8e8', endColorstr='#fff5f5f5', GradientType=0); border-color: #dcdcdc; -webkit-box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.05), 0 1px 0 rgba(255, 255, 255, 0.1); }
Am3o/eShop
WebShopStart/src/main/webapp/bootstrap/css/bootstrap-theme.css
CSS
apache-2.0
26,020
/* * Copyright (c) 2017 Cisco 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. */ #ifndef __ABF_H__ #define __ABF_H__ #include <vnet/fib/fib_node.h> #define ABF_PLUGIN_VERSION_MAJOR 1 #define ABF_PLUGIN_VERSION_MINOR 0 /** * An ACL based Forwarding 'policy'. * This comprises the ACL index to match against and the forwarding * path to take if the match is successful. * * ABF policies are then 'attached' to interfaces. An input feature * will run through the list of policies a match will divert the packet, * if all miss then we continues down the interface's feature arc */ typedef struct abf_policy_t_ { /** * Linkage into the FIB graph */ fib_node_t ap_node; /** * ACL index to match */ u32 ap_acl; /** * The path-list describing how to forward in case of a match */ fib_node_index_t ap_pl; /** * Sibling index on the path-list */ u32 ap_sibling; /** * The policy ID - as configured by the client */ u32 ap_id; } abf_policy_t; /** * Get an ABF object from its VPP index */ extern abf_policy_t *abf_policy_get (index_t index); /** * Find a ABF object from the client's policy ID * * @param policy_id Client's defined policy ID * @return VPP's object index */ extern index_t abf_policy_find (u32 policy_id); /** * The FIB node type for ABF policies */ extern fib_node_type_t abf_policy_fib_node_type; /** * Create or update an ABF Policy * * @param policy_id User defined Policy ID * @param acl_index The ACL the policy with match on * @param rpaths The set of paths to add to the forwarding set * @return error code */ extern int abf_policy_update (u32 policy_id, u32 acl_index, const fib_route_path_t * rpaths); /** * Delete paths from an ABF Policy. If no more paths exist, the policy * is deleted. * * @param policy_id User defined Policy ID * @param rpaths The set of paths to forward remove */ extern int abf_policy_delete (u32 policy_id, const fib_route_path_t * rpaths); /** * Callback function invoked during a walk of all policies */ typedef int (*abf_policy_walk_cb_t) (index_t index, void *ctx); /** * Walk/visit each of the ABF policies */ extern void abf_policy_walk (abf_policy_walk_cb_t cb, void *ctx); /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */ #endif
FDio/vpp
src/plugins/abf/abf_policy.h
C
apache-2.0
2,885
#! /usr/bin/env ruby require 'spec_provider_helper' require 'puppet/provider/force10_portchannel/dell_ftos' provider_class = Puppet::Type.type(:force10_portchannel).provider(:dell_ftos) describe provider_class do before do @portchannel = stub_everything 'portchannel' @portchannel.stubs(:name).returns('152') @portchannel.stubs(:params_to_hash) @portchannels = [ @portchannel ] @switch = stub_everything 'switch' @switch.stubs(:portchannel).returns(@portchannels) @switch.stubs(:params_to_hash).returns({}) @device = stub_everything 'device' @device.stubs(:switch).returns(@switch) @resource = stub('resource', :desc => "INT") @provider = provider_class.new(@device, @resource) end it "should have a parent of Puppet::Provider::Dell_ftos" do provider_class.should < Puppet::Provider::Dell_ftos end it "should have an instances method" do provider_class.should respond_to(:instances) end describe "when looking up instances at prefetch" do before do @device.stubs(:command).yields(@device) end it "should delegate to the device portchannel fetcher" do @device.expects(:switch).returns(@switch) @switch.expects(:portchannel).with('152').returns(@portchannel) @portchannel.expects(:params_to_hash) provider_class.lookup(@device, '152') end it "should return the given configuration data" do @device.expects(:switch).returns(@switch) @switch.expects(:portchannel).with('152').returns(@portchannel) @portchannel.expects(:params_to_hash).returns({ :desc => "INT" }) provider_class.lookup(@device, '152').should == { :desc => "INT" } end end describe "when the configuration is being flushed" do it "should call the device configuration update method with current and past properties" do @instance = provider_class.new(@device, :ensure => :present, :name => '152', :mtu => '1110') @instance.resource = @resource @resource.stubs(:[]).with(:name).returns('152') @instance.stubs(:device).returns(@device) @switch.expects(:portchannel).with('152').returns(@portchannel) @switch.stubs(:facts).returns({}) @portchannel.expects(:update).with({:ensure => :present, :name => '152', :mtu => '1110'}, {:ensure => :present, :name => '152', :mtu => '1110'}) @portchannel.expects(:update).never #@instance.desc = "FOOBAR" @instance.flush end end end
sushilrai/dell-force10
spec/unit/puppet/provider/force10_portchannel/force10_portchannel_spec.rb
Ruby
apache-2.0
2,469
/* * Copyright 2010 JBoss 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 org.drools.event.rule.impl; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import org.drools.definition.rule.Rule; import org.drools.impl.SerializedRule; import org.drools.runtime.rule.FactHandle; import org.drools.runtime.rule.PropagationContext; public class SerializablePropagationContext implements PropagationContext, Externalizable { private FactHandle factHandle; private long propgationNumber; private Rule rule; private int type; public SerializablePropagationContext() { } public SerializablePropagationContext(PropagationContext propagationContext) { this.factHandle = propagationContext.getFactHandle(); this.propgationNumber = propagationContext.getPropagationNumber(); this.rule = propagationContext.getRule(); this.type = propagationContext.getType(); } public void writeExternal(ObjectOutput out) throws IOException { out.writeObject( this.factHandle ); out.writeLong( this.propgationNumber ); new SerializedRule( rule ).writeExternal( out ); } public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { this.factHandle = ( FactHandle ) in.readObject(); this.propgationNumber = in.readLong(); this.rule = new SerializedRule(); ((SerializedRule)this.rule).readExternal( in ); } public FactHandle getFactHandle() { return this.factHandle; } public long getPropagationNumber() { return this.propgationNumber; } public Rule getRule() { return this.rule; } public int getType() { return this.type; } @Override public String toString() { return "==>[SerializablePropagationContext: getFactHandle()=" + getFactHandle() + ", getPropagationNumber()=" + getPropagationNumber() + ", getRule()=" + getRule() + ", getType()=" + getType() + "]"; } }
mswiderski/drools
drools-core/src/main/java/org/drools/event/rule/impl/SerializablePropagationContext.java
Java
apache-2.0
2,673
/** * OPCBase class declaration * * 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. */ #ifndef NIFI_MINIFI_CPP_OPCBASE_H #define NIFI_MINIFI_CPP_OPCBASE_H #include <string> #include "opc.h" #include "core/Processor.h" #include "core/ProcessSession.h" #include "core/Core.h" #include "core/Property.h" namespace org { namespace apache { namespace nifi { namespace minifi { namespace processors { class BaseOPCProcessor : public core::Processor { public: static core::Property OPCServerEndPoint; static core::Property ApplicationURI; static core::Property Username; static core::Property Password; static core::Property CertificatePath; static core::Property KeyPath; static core::Property TrustedPath; BaseOPCProcessor(std::string name, utils::Identifier uuid = utils::Identifier()) : Processor(name, uuid) { } virtual void onSchedule(const std::shared_ptr<core::ProcessContext> &context, const std::shared_ptr<core::ProcessSessionFactory> &factory) override; protected: virtual bool reconnect(); std::shared_ptr<logging::Logger> logger_; opc::ClientPtr connection_; std::string endPointURL_; std::string applicationURI_; std::string username_; std::string password_; std::string certpath_; std::string keypath_; std::string trustpath_; std::vector<char> certBuffer_; std::vector<char> keyBuffer_; std::vector<std::vector<char>> trustBuffers_; virtual std::set<core::Property> getSupportedProperties() const {return {OPCServerEndPoint, ApplicationURI, Username, Password, CertificatePath, KeyPath, TrustedPath};} }; } /* namespace processors */ } /* namespace minifi */ } /* namespace nifi */ } /* namespace apache */ } /* namespace org */ #endif //NIFI_MINIFI_CPP_OPCBASE_H
jdye64/nifi-minifi-cpp
extensions/opc/include/opcbase.h
C
apache-2.0
2,491
package org.wso2.carbon.event.template.manager.admin.dto.configuration; public class AttributeMappingDTO { private String fromAttribute; private String toAttribute; private String attributeType; public String getFromAttribute() { return fromAttribute; } public void setFromAttribute(String fromAttribute) { this.fromAttribute = fromAttribute; } public String getToAttribute() { return toAttribute; } public void setToAttribute(String toAttribute) { this.toAttribute = toAttribute; } public String getAttributeType() { return attributeType; } public void setAttributeType(String attributeType) { this.attributeType = attributeType; } }
lgobinath/carbon-analytics-common
components/template-manager/org.wso2.carbon.event.template.manager.admin/src/main/java/org/wso2/carbon/event/template/manager/admin/dto/configuration/AttributeMappingDTO.java
Java
apache-2.0
750
/* * 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.tinkerpop.gremlin.process.traversal.step.sideEffect; import org.apache.tinkerpop.gremlin.process.traversal.Operator; import org.apache.tinkerpop.gremlin.process.traversal.Traversal; import org.apache.tinkerpop.gremlin.process.traversal.Traverser; import org.apache.tinkerpop.gremlin.process.traversal.step.ByModulating; import org.apache.tinkerpop.gremlin.process.traversal.step.SideEffectCapable; import org.apache.tinkerpop.gremlin.process.traversal.step.TraversalParent; import org.apache.tinkerpop.gremlin.process.traversal.step.util.BulkSet; import org.apache.tinkerpop.gremlin.process.traversal.traverser.TraverserRequirement; import org.apache.tinkerpop.gremlin.process.traversal.util.TraversalUtil; import org.apache.tinkerpop.gremlin.structure.util.StringFactory; import org.apache.tinkerpop.gremlin.util.function.BulkSetSupplier; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.function.Supplier; /** * @author Marko A. Rodriguez (http://markorodriguez.com) */ public final class AggregateLocalStep<S> extends SideEffectStep<S> implements SideEffectCapable<Collection, Collection>, TraversalParent, ByModulating { private Traversal.Admin<S, Object> storeTraversal = null; private String sideEffectKey; public AggregateLocalStep(final Traversal.Admin traversal, final String sideEffectKey) { super(traversal); this.sideEffectKey = sideEffectKey; this.getTraversal().getSideEffects().registerIfAbsent(this.sideEffectKey, (Supplier) BulkSetSupplier.instance(), Operator.addAll); } @Override protected void sideEffect(final Traverser.Admin<S> traverser) { final BulkSet<Object> bulkSet = new BulkSet<>(); TraversalUtil.produce(traverser, this.storeTraversal).ifProductive(p -> bulkSet.add(p, traverser.bulk())); this.getTraversal().getSideEffects().add(this.sideEffectKey, bulkSet); } @Override public String getSideEffectKey() { return this.sideEffectKey; } @Override public String toString() { return StringFactory.stepString(this, this.sideEffectKey, this.storeTraversal); } @Override public List<Traversal.Admin<S, Object>> getLocalChildren() { return null == this.storeTraversal ? Collections.emptyList() : Collections.singletonList(this.storeTraversal); } @Override public void modulateBy(final Traversal.Admin<?, ?> storeTraversal) { this.storeTraversal = this.integrateChild(storeTraversal); } @Override public void replaceLocalChild(final Traversal.Admin<?, ?> oldTraversal, final Traversal.Admin<?, ?> newTraversal) { if (null != this.storeTraversal && this.storeTraversal.equals(oldTraversal)) this.storeTraversal = this.integrateChild(newTraversal); } @Override public Set<TraverserRequirement> getRequirements() { return this.getSelfAndChildRequirements(TraverserRequirement.SIDE_EFFECTS, TraverserRequirement.BULK); } @Override public AggregateLocalStep<S> clone() { final AggregateLocalStep<S> clone = (AggregateLocalStep<S>) super.clone(); if (null != this.storeTraversal) clone.storeTraversal = this.storeTraversal.clone(); return clone; } @Override public void setTraversal(final Traversal.Admin<?, ?> parentTraversal) { super.setTraversal(parentTraversal); this.integrateChild(this.storeTraversal); } @Override public int hashCode() { int result = super.hashCode() ^ this.sideEffectKey.hashCode(); if (this.storeTraversal != null) result ^= this.storeTraversal.hashCode(); return result; } }
apache/tinkerpop
gremlin-core/src/main/java/org/apache/tinkerpop/gremlin/process/traversal/step/sideEffect/AggregateLocalStep.java
Java
apache-2.0
4,564
/* CryptoTweets, a game built using Enyo 2.0 */ /* common Unicode strings for use directly in content */ var Unicode = { nbsp: "\u00A0", mdash: "\u2014", leftwardArrow: "\u2190", upwardArrow: "\u2191", rightwardArrow: "\u2192", downwardArrow: "\u2193" }; /** swap two elements of an array or object */ function swapElements(obj, idx1, idx2) { var hold = obj[idx1]; obj[idx1] = obj[idx2]; obj[idx2] = hold; } /** call a function for each letter in the range 'A' to 'Z'. Additional arguments are passed into the callback. */ function forEachLetter(that, fn) { // copy arguments into new array with space for letter in front */ var args = enyo.cloneArray(arguments, 2); args.unshift(""); var aCode = 'A'.charCodeAt(0); var zCode = 'Z'.charCodeAt(0); for (var chCode = aCode; chCode <= zCode; ++chCode) { args[0] = String.fromCharCode(chCode); fn.apply(that, args); } } /** takes a string, returns an array where the 0 element is the string truncated at the last space before length and the second string is the remainder after spaces are trimmed. remainder is null if there's nothing left. */ function wrapStringAtSpace(str, length) { str = str.replace(/ +/g, " ").trim(); if (str.length <= length) return [str, null]; /* chop string at length bytes */ var trimmed = str.slice(0, length); /* find last space in string */ var lastSpace = trimmed.lastIndexOf(' '); /* chop off spaces and left over characters */ if (lastSpace !== -1) { trimmed = trimmed.slice(0, lastSpace).trim(); } /* prepare remainder using offsets */ remainder = str.slice(trimmed.length).trim(); return [trimmed, remainder]; } /** identify hashtags in a string and save start & end positions to an array for use in determining if they should be encrypted or not */ function findHashTags(str) { var hashTagRE = /#[a-zA-Z0-9_]+/g; var results = []; var match; while ((match = hashTagRE.exec(str))) { results.push(match.index, match.index + match[0].length - 1); } return results; } /** generate a new cypher alphabet for the letters A-Z where no encrypted letter maps to the original one. The distribution is probably not uniform, but it works well enough for game purposes */ function generateCypherAlphabet() { var alpha = [ "A","B","C","D","E","F","G","H","I", "J","K","L","M","N","O","P","Q","R", "S","T","U","V","W","X","Y","Z"]; // we'll go through alphabet and randomly swap each letter with // another letter in the string, rejecting swaps that would put a // letter back in its original position. for (var i = 0; i < 26; ++i) { var swapPos; do { swapPos = enyo.irand(26); // and skip over a swap that puts the letter // back in its original position } while (alpha[swapPos] === String.fromCharCode(65 + i) || alpha[i] === String.fromCharCode(65 + swapPos)); swapElements(alpha, i, swapPos); } return alpha; }
RedMage/MightyTomato
support/apps/cryptotweets/source/utils.js
JavaScript
apache-2.0
2,875
// Copyright 2015 Samsung Electronics Co., Ltd. // Copyright 2015 University of Szeged. // // 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. var func = function(a, b) { return a + b; } // check function type try { [0].reduceRight(new Object()); assert(false); } catch(e) { assert(e instanceof TypeError); } // check for init value try { [].reduceRight(func); assert(false); } catch(e) { assert(e instanceof TypeError); } try { var arg2; [].reduceRight(func, arg2); assert(false); } catch(e) { assert(e instanceof TypeError); } try { var a = new Array(); a.length = 10; a.reduceRight(func); assert (false); } catch (e) { assert (e instanceof TypeError) } // various checks assert([].reduceRight(func, 1) === 1); assert([0].reduceRight(func) === 0); assert([0, 1].reduceRight(func) === 1); assert([0, 1].reduceRight(func, 1) === 2); assert([0, 1, 2, 3].reduceRight(func, 1) === 7); assert (["A","B"].reduceRight(func) === "BA"); assert (["A","B"].reduceRight(func, "Init:") === "Init:BA"); assert ([0, 1].reduceRight(func, 3.2) === 4.2); assert ([0, "x", 1].reduceRight(func) === "1x0"); assert ([0, "x", 1].reduceRight(func, 3.2) === "4.2x0"); var long_array = [0, 1]; assert (long_array.reduceRight(func,10) === 11); long_array[10000] = 1; assert (long_array.reduceRight(func,10) === 12); var accessed = false; function callbackfn(prevVal, curVal, idx, obj) { accessed = true; return typeof prevVal === "undefined"; } var obj = { 0: 11, length: 1 }; assert (Array.prototype.reduceRight.call(obj, callbackfn, undefined) === true && accessed);
tilmannOSG/jerryscript
tests/jerry/array-prototype-reduce-right.js
JavaScript
apache-2.0
2,106
/* * Copyright 2012-2016 the Flamingo Community. * * 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. */ Ext.ns('Flamingo.view.workflowdesigner.property.ankus'); Ext.define('Flamingo.view.workflowdesigner.property.ankus.ALG_ANKUS_NORMAL', { extend: 'Flamingo.view.workflowdesigner.property._NODE_ALG', alias: 'widget.ALG_ANKUS_NORMAL', requires: [ 'Flamingo.view.workflowdesigner.property._ConfigurationBrowserField', 'Flamingo.view.workflowdesigner.property._BrowserField', 'Flamingo.view.workflowdesigner.property._ColumnGrid', 'Flamingo.view.workflowdesigner.property._DependencyGrid', 'Flamingo.view.workflowdesigner.property._NameValueGrid', 'Flamingo.view.workflowdesigner.property._KeyValueGrid', 'Flamingo.view.workflowdesigner.property._EnvironmentGrid' ], width: 450, height: 320, items: [ { title: 'Parameter', xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 170 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'textfield', name: 'indexList', fieldLabel: 'Identifier Attribute(Index)', vtype: 'commaseperatednum', allowBlank: false }, { xtype: 'textfield', name: 'exceptionIndexList', fieldLabel: 'Analysis Exemption Identifier List', vtype: 'commaseperatednum', allowBlank: true }, { xtype: 'radiogroup', fieldLabel: 'Print normal property', allowBlank: true, columns: 2, itemId: 'myRadio', items: [ { xtype: 'radiofield', boxLabel: 'True', name: 'remainAllFields', checked: true, inputValue: 'true' }, { xtype: 'radiofield', boxLabel: 'False', name: 'remainAllFields', checked: false, inputValue: 'false' } ] }, { xtype: 'fieldcontainer', fieldLabel: 'Delimiter', tooltip: 'Wrong delimiter can cause failure.', layout: 'hbox', items: [ { xtype: 'fieldcontainer', layout: 'hbox', items: [ { xtype: 'combo', name: 'delimiter', value: '\'\\t\'', flex: 1, forceSelection: true, multiSelect: false, editable: false, readOnly: this.readOnly, displayField: 'name', valueField: 'value', mode: 'local', queryMode: 'local', triggerAction: 'all', tpl: '<tpl for="."><div class="x-boundlist-item" data-qtip="{description}">{name}</div></tpl>', store: Ext.create('Ext.data.Store', { fields: ['name', 'value', 'description'], data: [ { name: 'Double Colon', value: '::', description: '::' }, { name: 'Comma', value: ',', description: ',' }, { name: 'Pipe', value: '|', description: '|' }, { name: 'Tab', value: '\'\\t\'', description: '\'\\t\'' }, { name: 'Blank', value: '\'\\s\'', description: '\'\\s\'' }, { name: 'User Defined', value: 'CUSTOM', description: 'User Defined' } ] }), listeners: { change: function (combo, newValue, oldValue, eOpts) { // 콤보 값에 따라 관련 textfield 를 enable | disable 처리한다. var customValueField = combo.nextSibling('textfield'); if (newValue === 'CUSTOM') { customValueField.enable(); customValueField.isValid(); } else { customValueField.disable(); if (newValue) { customValueField.setValue(newValue); } else { customValueField.setValue(','); } } } } }, { xtype: 'textfield', name: 'delimiterValue', vtype: 'exceptcommaspace', flex: 1, disabled: true, readOnly: this.readOnly, allowBlank: false, value: '\\t' } ] } ] } ] }, { title: 'MapReduce', xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'textfield', name: 'jar', fieldLabel: 'JAR Path', value: ANKUS.JAR, disabledCls: 'disabled-plain', readOnly: true }, { xtype: 'textfield', name: 'driver', fieldLabel: 'Driver', value: 'Normalization', disabledCls: 'disabled-plain', readOnly: true } ] }, { title: 'I/O Path', xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ // Ankus MapReduce가 동작하는데 필요한 입력 경로를 지정한다. 이 경로는 N개 지정가능하다. { xtype: '_inputGrid', title: 'Input Path', flex: 1 }, // Ankus MapReduce가 동작하는데 필요한 출력 경로를 지정한다. 이 경로는 오직 1개만 지정가능하다. { xtype: 'fieldcontainer', fieldLabel: 'Output path', defaults: { hideLabel: true, margin: "5 0 0 0" // Same as CSS ordering (top, right, bottom, left) }, layout: 'hbox', items: [ { xtype: '_browserField', name: 'output', allowBlank: false, readOnly: false, flex: 1 } ] } ] }, { title: 'Hadoop Configuration', xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'displayfield', height: 20, value: 'Enter a key and a value of Configuration.set () method used in Hadoop Mapreduce.' }, { xtype: '_keyValueGrid', flex: 1 } ] }, { title: 'References', xtype: 'form', border: false, autoScroll: true, defaults: { labelWidth: 100 }, layout: { type: 'vbox', align: 'stretch' }, items: [ { xtype: 'displayfield', height: 20, value: '<a href="http://www.openankus.org/display/AN/3.2.1+Normalization" target="_blank">Normalization</a>' } ] } ], /** * UI 컴포넌트의 Key를 필터링한다. * * ex) 다음과 같이 필터를 설정할 수 있다. * propFilters: { * // 추가할 프라퍼티 * add : [ * {'test1': '1'}, * {'test2': '2'} * ], * * // 변경할 프라퍼티 * modify: [ * {'delimiterType': 'delimiterType2'}, * {'config': 'config2'} * ], * * // 삭제할 프라퍼티 * remove: ['script', 'metadata'] * } */ propFilters: { add: [], modify: [], remove: ['config'] }, /** * MapReduce의 커맨드 라인 파라미터를 수동으로 설정한다. * 커맨드 라인 파라미터는 Flamingo2 Workflow Engine에서 props.mapreduce를 Key로 꺼내어 구성한다. * * @param props UI 상에서 구성한 컴포넌트의 Key Value값 */ afterPropertySet: function (props) { props.mapreduce = { "driver": props.driver ? props.driver : '', "jar": props.jar ? props.jar : '', "confKey": props.hadoopKeys ? props.hadoopKeys : '', "confValue": props.hadoopValues ? props.hadoopValues : '', params: [] }; if (props.input) { props.mapreduce.params.push("-input", props.input); } if (props.output) { props.mapreduce.params.push("-output", props.output); } if (props.indexList) { props.mapreduce.params.push("-indexList", props.indexList); } if (props.exceptionIndexList) { props.mapreduce.params.push("-exceptionIndexList", props.exceptionIndexList); } if (props.remainAllFields) { props.mapreduce.params.push("-remainAllFields", props.remainAllFields); } if (props.delimiter) { if (props.delimiter == 'CUSTOM') { props.mapreduce.params.push("-delimiter", props.delimiterValue); } else { props.mapreduce.params.push("-delimiter", props.delimiter); } } this.callParent(arguments); } });
hyokun31/wisekb-management-platform
wisekb-web/src/main/webapp/flamingo/app/view/workflowdesigner/property/ankus/ALG_ANKUS_NORMAL.js
JavaScript
apache-2.0
14,122
/*! ****************************************************************************** * * Pentaho Data Integration * * Copyright (C) 2002-2014 by Pentaho : http://www.pentaho.com * ******************************************************************************* * * 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.pentaho.di.trans.steps.orabulkloader; import org.junit.BeforeClass; import org.junit.Test; import org.pentaho.di.core.KettleClientEnvironment; import org.pentaho.di.core.database.DatabaseMeta; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.core.logging.LoggingObjectInterface; import org.pentaho.di.trans.steps.mock.StepMockHelper; import java.io.File; import static org.junit.Assert.assertEquals; import static org.mockito.Matchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; /** * User: Dzmitry Stsiapanau Date: 4/8/14 Time: 1:44 PM */ public class OraBulkLoaderTest { @BeforeClass public static void setupBeforeClass() throws KettleException { KettleClientEnvironment.init(); } @Test public void testCreateCommandLine() throws Exception { StepMockHelper<OraBulkLoaderMeta, OraBulkLoaderData> stepMockHelper = new StepMockHelper<OraBulkLoaderMeta, OraBulkLoaderData>( "TEST_CREATE_COMMANDLINE", OraBulkLoaderMeta.class, OraBulkLoaderData.class ); when( stepMockHelper.logChannelInterfaceFactory.create( any(), any( LoggingObjectInterface.class ) ) ).thenReturn( stepMockHelper.logChannelInterface ); when( stepMockHelper.trans.isRunning() ).thenReturn( true ); OraBulkLoader oraBulkLoader = new OraBulkLoader( stepMockHelper.stepMeta, stepMockHelper.stepDataInterface, 0, stepMockHelper.transMeta, stepMockHelper.trans ); File tmp = File.createTempFile( "testCreateCOmmandLine", "tmp" ); OraBulkLoaderMeta meta = new OraBulkLoaderMeta(); meta.setSqlldr( tmp.getAbsolutePath() ); meta.setControlFile( tmp.getAbsolutePath() ); DatabaseMeta dm = mock( DatabaseMeta.class ); when( dm.getUsername() ).thenReturn( "user" ); when( dm.getPassword() ).thenReturn( "Encrypted 2be98afc86aa7f2e4cb298b5eeab387f5" ); meta.setDatabaseMeta( dm ); String cmd = oraBulkLoader.createCommandLine( meta, true ); String expected = tmp.getAbsolutePath() + " control='" + tmp.getAbsolutePath() + "' userid=user/PENTAHO@"; assertEquals( "Comandline for oracle bulkloader is not as expected", expected, cmd ); } }
a186/pentaho-kettle
engine/test-src/org/pentaho/di/trans/steps/orabulkloader/OraBulkLoaderTest.java
Java
apache-2.0
3,088
package org.interledger.codecs; import org.interledger.codecs.packettypes.InterledgerPacketType; /** * An implementation of {@link Codec} that reads and writes instances of * {@link InterledgerPacketType}. */ public interface InterledgerPacketTypeCodec extends Codec<InterledgerPacketType> { }
interledger/java-ilp-core
src/main/java/org/interledger/codecs/InterledgerPacketTypeCodec.java
Java
apache-2.0
300
#! /usr/bin/python ''' Interface to BBC /programmes JSON etc - Identifies PID of current programme on a chosen channel - Provides output for PIDs in a chosen format (XML, RDF etc) - Identifies currently playing tracks on radio channels TODO ''' import cjson import pytz import string import time import urllib from dateutil.parser import parse from datetime import datetime, timedelta, tzinfo from Axon.Ipc import producerFinished from Axon.Ipc import shutdownMicroprocess from Axon.Component import component from Axon.ThreadedComponent import threadedcomponent from Kamaelia.Apps.SocialBookmarks.Print import Print class GMT(tzinfo): def utcoffset(self,dt): return timedelta(hours=0,minutes=0) def tzname(self,dt): return "GMT" def dst(self,dt): return timedelta(0) class WhatsOn(threadedcomponent): Inboxes = { "inbox" : "Receives a channel name to investigate in the 'key' format from self.channels", "datain" : "Return path for requests to HTTP getter component", "control" : "" } Outboxes = { "outbox" : "If a channel is on air, sends out programme info [pid,title,timeoffset,duration,expectedstarttime]", "dataout" : "URLs out for data requests to HTTP getter", "signal" : "" } def __init__(self, proxy = False): super(WhatsOn, self).__init__() self.proxy = proxy # Define channel schedule URLs and DVB bridge channel formats self.channels = {"bbcone" : ["bbc one", "/bbcone/programmes/schedules/north_west"], "bbctwo" : ["bbc two", "/bbctwo/programmes/schedules/england"], "bbcthree" : ["bbc three", "/bbcthree/programmes/schedules"], "bbcfour" : ["bbc four", "/bbcfour/programmes/schedules"], "cbbc" : ["cbbc channel", "/cbbc/programmes/schedules"], "cbeebies" : ["cbeebies", "/cbeebies/programmes/schedules"], "bbcnews" : ["bbc news", "/bbcnews/programmes/schedules"], "radio1" : ["bbc radio 1", "/radio1/programmes/schedules/england"], "radio2" : ["bbc radio 2", "/radio2/programmes/schedules"], "radio3" : ["bbc radio 3", "/radio3/programmes/schedules"], "radio4" : ["bbc radio 4", "/radio4/programmes/schedules/fm"], "5live" : ["bbc r5l", "/5live/programmes/schedules"], "worldservice" : ["bbc world sv.", "/worldservice/programmes/schedules"], "6music" : ["bbc 6 music", "/6music/programmes/schedules"], "radio7" : ["bbc radio 7", "/radio7/programmes/schedules"], "1xtra" : ["bbc r1x", "/1xtra/programmes/schedules"], "bbcparliament" : ["bbc parliament", "/parliament/programmes/schedules"], "asiannetwork" : ["bbc asian net.", "/asiannetwork/programmes/schedules"], "sportsextra" : ["bbc r5sx", "/5livesportsextra/programmes/schedules"]} def finished(self): while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.send(msg, "signal") return True return False def main(self): while not self.finished(): if self.dataReady("inbox"): channel = self.recv("inbox") time.sleep(1) # Temporary delay to ensure not hammering /programmes # Setup in case of URL errors later data = None # Define URLs for getting schedule data and DVB bridge information # By BBC convention, schedule info runs to 5am the next day if datetime.utcnow().hour < 5: scheduleurl = "http://www.bbc.co.uk" + self.channels[channel][1] + "/" + time.strftime("%Y/%m/%d",time.gmtime(time.time()-86400)) + ".json" else: scheduleurl = "http://www.bbc.co.uk" + self.channels[channel][1] + "/" + time.strftime("%Y/%m/%d",time.gmtime(time.time())) + ".json" #syncschedurl = "http://beta.kamaelia.org:8082/dvb-bridge?command=channel&args=" + urllib.quote(self.channels[channel][0]) #synctimeurl = "http://beta.kamaelia.org:8082/dvb-bridge?command=time" syncschedurl = "http://10.92.164.147:8082/dvb-bridge?command=channel&args=" + urllib.quote(self.channels[channel][0]) synctimeurl = "http://10.92.164.147:8082/dvb-bridge?command=time" content = None # # Grab SyncTV time data to work out the offset between local (NTP) and BBC time (roughly) # self.send([synctimeurl], "dataout") # while not self.dataReady("datain"): # self.pause() # yield 1 # recvdata = self.recv("datain") # if recvdata[0] == "OK": # content = recvdata[1] # else: # content = None # Work out time difference between local time and BBC time if content != None: try: decodedcontent = cjson.decode(content) if decodedcontent[0] == "OK": difference = time.time() - decodedcontent[2]['time'] except cjson.DecodeError: e = sys.exc_info()[1] Print("cjson.DecodeError:", e.message) if 'difference' in locals(): # FIXME *SOB* # Grab actual programme start time from DVB bridge channel page self.send([syncschedurl], "dataout") while not self.dataReady("datain"): self.pause() # Add timeout ? # yield 1 recvdata = self.recv("datain") if recvdata[0] == "OK": content = recvdata[1] else: content = None if content != None: try: decodedcontent = cjson.decode(content) if decodedcontent[0] == "OK": proginfo = decodedcontent[2]['info'] except cjson.DecodeError: e = sys.exc_info()[1] Print("cjson.DecodeError:", e.message) # Grab BBC schedule data for given channel self.send([scheduleurl], "dataout") while not self.dataReady("datain"): self.pause() # FIXME Add timeout? # yield 1 recvdata = self.recv("datain") if recvdata[0] == "OK": content = recvdata[1] else: content = None # Read and decode schedule if content != None: try: decodedcontent = cjson.decode(content) except cjson.DecodeError: e = sys.exc_info()[1] Print("cjson.DecodeError:", e.message) if 'proginfo' in locals(): showdate = proginfo['NOW']['startdate'] showtime = proginfo['NOW']['starttime'] actualstart = proginfo['changed'] showdatetime = datetime.strptime(str(showdate[0]) + "-" + str(showdate[1]) + "-" + str(showdate[2]) + " " + str(showtime[0]) + ":" + str(showtime[1]) + ":" + str(showtime[2]),"%Y-%m-%d %H:%M:%S") # SyncTV (DVB Bridge) produced data - let's trust that if 'decodedcontent' in locals(): for programme in decodedcontent['schedule']['day']['broadcasts']: starttime = parse(programme['start']) gmt = pytz.timezone("GMT") starttime = starttime.astimezone(gmt) starttime = starttime.replace(tzinfo=None) # Attempt to identify which DVB bridge programme corresponds to the /programmes schedule to get PID if showdatetime == starttime or (showdatetime + timedelta(minutes=1) == starttime and string.lower(proginfo['NOW']['name']) == string.lower(programme['programme']['display_titles']['title'])) or (showdatetime - timedelta(minutes=1) == starttime and string.lower(proginfo['NOW']['name']) == string.lower(programme['programme']['display_titles']['title'])): duration = (proginfo['NOW']['duration'][0] * 60 * 60) + (proginfo['NOW']['duration'][1] * 60) + proginfo['NOW']['duration'][2] progdate = parse(programme['start']) tz = progdate.tzinfo utcoffset = datetime.strptime(str(tz.utcoffset(progdate)),"%H:%M:%S") utcoffset = utcoffset.hour * 60 * 60 # Something's not right with the code below #TODO #FIXME timestamp = time.mktime(showdatetime.timetuple()) + utcoffset if 'difference' in locals(): offset = (timestamp - actualstart) - difference else: offset = timestamp - actualstart pid = programme['programme']['pid'] title = programme['programme']['display_titles']['title'] # Fix for unicode errors caused by some /programmes titles if (not isinstance(title,str)) and (not isinstance(title,unicode)): title = str(title) Print(pid,title,offset,duration,showdatetime, "GMT",utcoffset) data = [pid,title,offset,duration,timestamp,utcoffset] else: # Couldn't use the DVB Bridge, so work out what's on NOW here utcdatetime = datetime.now() # Analyse schedule if 'decodedcontent' in locals(): for programme in decodedcontent['schedule']['day']['broadcasts']: starttime = parse(programme['start']) starttime = starttime.replace(tzinfo=None) endtime = parse(programme['end']) endtime = endtime.replace(tzinfo=None) if (utcdatetime >= starttime) & (utcdatetime < endtime): pid = programme['programme']['pid'] title = programme['programme']['display_titles']['title'] # Fix for unicode errors caused by some /programmes titles if (not isinstance(title,str)) and (not isinstance(title,unicode)): title = str(title) # Has to assume no offset between scheduled and actual programme start time as it knows no better because of the lack of DVB bridge progdate = parse(programme['start']) tz = progdate.tzinfo utcoffset = datetime.strptime(str(tz.utcoffset(progdate)),"%H:%M:%S") utcoffset = utcoffset.hour * 60 * 60 timestamp = time.mktime(progdate.timetuple()) - utcoffset Print(pid,title,0,programme['duration'],programme['start'],utcoffset) data = [pid,title,0,programme['duration'],timestamp,utcoffset] self.send(data,"outbox") if not self.anyReady(): self.pause() # yield 1 class NowPlaying(component): Inboxes = { "inbox" : "", "control" : "" } Outboxes = { "outbox" : "", "signal" : "" } def __init__(self, proxy = False): super(NowPlaying, self).__init__() self.proxy = proxy self.channels = {"radio1" : "/radio1/nowplaying/latest"} def finished(self): while self.dataReady("control"): msg = self.recv("control") if isinstance(msg, producerFinished) or isinstance(msg, shutdownMicroprocess): self.send(msg, "signal") return True return False def main(self): while not self.finished(): if self.dataReady("inbox"): # TODO This component is unfinished as it was never found to be needed channel = self.recv("inbox") time.sleep(1) # Temporary delay to ensure not hammering /programmes nowplayingurl = "http://www.bbc.co.uk" + self.channels[channel] + ".json" npdata = None # Grab BBC data self.send([nowplayingurl], "dataout") while not self.dataReady("datain"): yield 1 self.pause() recvdata = self.recv("datain") if recvdata[0] == "OK": content = recvdata[1] else: content = None # Read and decode now playing info if content != None: try: decodedcontent = cjson.decode(content) except cjson.DecodeError: e = sys.exc_info()[1] Print("cjson.DecodeError:", e.message) # Analyse now playing info if decodedcontent: # Not finished! - now playing json file is empty if nothing is playing! npdata = False self.send(npdata,"outbox") self.pause() yield 1
sparkslabs/kamaelia_
Code/Python/Kamaelia/Kamaelia/Apps/SocialBookmarks/BBCProgrammes.py
Python
apache-2.0
14,561
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.snapshots; import org.elasticsearch.ElasticsearchCorruptionException; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.blobstore.BlobContainer; import org.elasticsearch.common.blobstore.BlobMetaData; import org.elasticsearch.common.blobstore.BlobPath; import org.elasticsearch.common.blobstore.BlobStore; import org.elasticsearch.common.blobstore.fs.FsBlobStore; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.io.Streams; import org.elasticsearch.common.io.stream.BytesStreamOutput; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.FromXContentBuilder; import org.elasticsearch.common.xcontent.ToXContent; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.index.translog.BufferedChecksumStreamOutput; import org.elasticsearch.repositories.blobstore.ChecksumBlobStoreFormat; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.greaterThan; public class BlobStoreFormatIT extends AbstractSnapshotIntegTestCase { private static final ParseFieldMatcher parseFieldMatcher = new ParseFieldMatcher(Settings.EMPTY); public static final String BLOB_CODEC = "blob"; private static class BlobObj implements ToXContent, FromXContentBuilder<BlobObj> { public static final BlobObj PROTO = new BlobObj(""); private final String text; public BlobObj(String text) { this.text = text; } public String getText() { return text; } @Override public BlobObj fromXContent(XContentParser parser, ParseFieldMatcher parseFieldMatcher) throws IOException { String text = null; XContentParser.Token token = parser.currentToken(); if (token == null) { token = parser.nextToken(); } if (token == XContentParser.Token.START_OBJECT) { while ((token = parser.nextToken()) != XContentParser.Token.END_OBJECT) { if (token != XContentParser.Token.FIELD_NAME) { throw new ElasticsearchParseException("unexpected token [{}]", token); } String currentFieldName = parser.currentName(); token = parser.nextToken(); if (token.isValue()) { if ("text" .equals(currentFieldName)) { text = parser.text(); } else { throw new ElasticsearchParseException("unexpected field [{}]", currentFieldName); } } else { throw new ElasticsearchParseException("unexpected token [{}]", token); } } } if (text == null) { throw new ElasticsearchParseException("missing mandatory parameter text"); } return new BlobObj(text); } @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { builder.field("text", getText()); return builder; } } public void testBlobStoreOperations() throws IOException { BlobStore blobStore = createTestBlobStore(); BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath()); ChecksumBlobStoreFormat<BlobObj> checksumJSON = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, false, XContentType.JSON); ChecksumBlobStoreFormat<BlobObj> checksumSMILE = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, false, XContentType.SMILE); ChecksumBlobStoreFormat<BlobObj> checksumSMILECompressed = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, true, XContentType.SMILE); // Write blobs in different formats checksumJSON.write(new BlobObj("checksum json"), blobContainer, "check-json"); checksumSMILE.write(new BlobObj("checksum smile"), blobContainer, "check-smile"); checksumSMILECompressed.write(new BlobObj("checksum smile compressed"), blobContainer, "check-smile-comp"); // Assert that all checksum blobs can be read by all formats assertEquals(checksumJSON.read(blobContainer, "check-json").getText(), "checksum json"); assertEquals(checksumSMILE.read(blobContainer, "check-json").getText(), "checksum json"); assertEquals(checksumJSON.read(blobContainer, "check-smile").getText(), "checksum smile"); assertEquals(checksumSMILE.read(blobContainer, "check-smile").getText(), "checksum smile"); assertEquals(checksumJSON.read(blobContainer, "check-smile-comp").getText(), "checksum smile compressed"); assertEquals(checksumSMILE.read(blobContainer, "check-smile-comp").getText(), "checksum smile compressed"); } public void testCompressionIsApplied() throws IOException { BlobStore blobStore = createTestBlobStore(); BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath()); StringBuilder veryRedundantText = new StringBuilder(); for (int i = 0; i < randomIntBetween(100, 300); i++) { veryRedundantText.append("Blah "); } ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, false, randomBoolean() ? XContentType.SMILE : XContentType.JSON); ChecksumBlobStoreFormat<BlobObj> checksumFormatComp = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, true, randomBoolean() ? XContentType.SMILE : XContentType.JSON); BlobObj blobObj = new BlobObj(veryRedundantText.toString()); checksumFormatComp.write(blobObj, blobContainer, "blob-comp"); checksumFormat.write(blobObj, blobContainer, "blob-not-comp"); Map<String, BlobMetaData> blobs = blobContainer.listBlobsByPrefix("blob-"); assertEquals(blobs.size(), 2); assertThat(blobs.get("blob-not-comp").length(), greaterThan(blobs.get("blob-comp").length())); } public void testBlobCorruption() throws IOException { BlobStore blobStore = createTestBlobStore(); BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath()); String testString = randomAsciiOfLength(randomInt(10000)); BlobObj blobObj = new BlobObj(testString); ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, randomBoolean(), randomBoolean() ? XContentType.SMILE : XContentType.JSON); checksumFormat.write(blobObj, blobContainer, "test-path"); assertEquals(checksumFormat.read(blobContainer, "test-path").getText(), testString); randomCorruption(blobContainer, "test-path"); try { checksumFormat.read(blobContainer, "test-path"); fail("Should have failed due to corruption"); } catch (ElasticsearchCorruptionException ex) { assertThat(ex.getMessage(), containsString("test-path")); } catch (EOFException ex) { // This can happen if corrupt the byte length } } public void testAtomicWrite() throws Exception { final BlobStore blobStore = createTestBlobStore(); final BlobContainer blobContainer = blobStore.blobContainer(BlobPath.cleanPath()); String testString = randomAsciiOfLength(randomInt(10000)); final CountDownLatch block = new CountDownLatch(1); final CountDownLatch unblock = new CountDownLatch(1); final BlobObj blobObj = new BlobObj(testString) { @Override public XContentBuilder toXContent(XContentBuilder builder, ToXContent.Params params) throws IOException { super.toXContent(builder, params); // Block before finishing writing try { block.countDown(); unblock.await(5, TimeUnit.SECONDS); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } return builder; } }; final ChecksumBlobStoreFormat<BlobObj> checksumFormat = new ChecksumBlobStoreFormat<>(BLOB_CODEC, "%s", BlobObj.PROTO, parseFieldMatcher, randomBoolean(), randomBoolean() ? XContentType.SMILE : XContentType.JSON); ExecutorService threadPool = Executors.newFixedThreadPool(1); try { Future<Void> future = threadPool.submit(new Callable<Void>() { @Override public Void call() throws Exception { checksumFormat.writeAtomic(blobObj, blobContainer, "test-blob"); return null; } }); block.await(5, TimeUnit.SECONDS); assertFalse(blobContainer.blobExists("test-blob")); unblock.countDown(); future.get(); assertTrue(blobContainer.blobExists("test-blob")); } finally { threadPool.shutdown(); } } protected BlobStore createTestBlobStore() throws IOException { Settings settings = Settings.builder().build(); return new FsBlobStore(settings, randomRepoPath()); } protected void randomCorruption(BlobContainer blobContainer, String blobName) throws IOException { byte[] buffer = new byte[(int) blobContainer.listBlobsByPrefix(blobName).get(blobName).length()]; long originalChecksum = checksum(buffer); try (InputStream inputStream = blobContainer.readBlob(blobName)) { Streams.readFully(inputStream, buffer); } do { int location = randomIntBetween(0, buffer.length - 1); buffer[location] = (byte) (buffer[location] ^ 42); } while (originalChecksum == checksum(buffer)); blobContainer.deleteBlob(blobName); // delete original before writing new blob BytesArray bytesArray = new BytesArray(buffer); try (StreamInput stream = bytesArray.streamInput()) { blobContainer.writeBlob(blobName, stream, bytesArray.length()); } } private long checksum(byte[] buffer) throws IOException { try (BytesStreamOutput streamOutput = new BytesStreamOutput()) { try (BufferedChecksumStreamOutput checksumOutput = new BufferedChecksumStreamOutput(streamOutput)) { checksumOutput.write(buffer); return checksumOutput.getChecksum(); } } } }
MaineC/elasticsearch
core/src/test/java/org/elasticsearch/snapshots/BlobStoreFormatIT.java
Java
apache-2.0
12,136
# # 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. """Base task runner""" import getpass import os import subprocess import threading from airflow.configuration import conf from airflow.exceptions import AirflowConfigException from airflow.utils.configuration import tmp_configuration_copy from airflow.utils.log.logging_mixin import LoggingMixin from airflow.utils.net import get_hostname PYTHONPATH_VAR = 'PYTHONPATH' class BaseTaskRunner(LoggingMixin): """ Runs Airflow task instances by invoking the `airflow tasks run` command with raw mode enabled in a subprocess. :param local_task_job: The local task job associated with running the associated task instance. :type local_task_job: airflow.jobs.local_task_job.LocalTaskJob """ def __init__(self, local_task_job): # Pass task instance context into log handlers to setup the logger. super().__init__(local_task_job.task_instance) self._task_instance = local_task_job.task_instance popen_prepend = [] if self._task_instance.run_as_user: self.run_as_user = self._task_instance.run_as_user else: try: self.run_as_user = conf.get('core', 'default_impersonation') except AirflowConfigException: self.run_as_user = None # Add sudo commands to change user if we need to. Needed to handle SubDagOperator # case using a SequentialExecutor. self.log.debug("Planning to run as the %s user", self.run_as_user) if self.run_as_user and (self.run_as_user != getpass.getuser()): # We want to include any environment variables now, as we won't # want to have to specify them in the sudo call - they would show # up in `ps` that way! And run commands now, as the other user # might not be able to run the cmds to get credentials cfg_path = tmp_configuration_copy(chmod=0o600) # Give ownership of file to user; only they can read and write subprocess.call(['sudo', 'chown', self.run_as_user, cfg_path], close_fds=True) # propagate PYTHONPATH environment variable pythonpath_value = os.environ.get(PYTHONPATH_VAR, '') popen_prepend = ['sudo', '-E', '-H', '-u', self.run_as_user] if pythonpath_value: popen_prepend.append(f'{PYTHONPATH_VAR}={pythonpath_value}') else: # Always provide a copy of the configuration file settings. Since # we are running as the same user, and can pass through environment # variables then we don't need to include those in the config copy # - the runner can read/execute those values as it needs cfg_path = tmp_configuration_copy(chmod=0o600) self._cfg_path = cfg_path self._command = popen_prepend + self._task_instance.command_as_list( raw=True, pickle_id=local_task_job.pickle_id, mark_success=local_task_job.mark_success, job_id=local_task_job.id, pool=local_task_job.pool, cfg_path=cfg_path, ) self.process = None def _read_task_logs(self, stream): while True: line = stream.readline() if isinstance(line, bytes): line = line.decode('utf-8') if not line: break self.log.info( 'Job %s: Subtask %s %s', self._task_instance.job_id, self._task_instance.task_id, line.rstrip('\n'), ) def run_command(self, run_with=None): """ Run the task command. :param run_with: list of tokens to run the task command with e.g. ``['bash', '-c']`` :type run_with: list :return: the process that was run :rtype: subprocess.Popen """ run_with = run_with or [] full_cmd = run_with + self._command self.log.info("Running on host: %s", get_hostname()) self.log.info('Running: %s', full_cmd) # pylint: disable=subprocess-popen-preexec-fn proc = subprocess.Popen( full_cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, close_fds=True, env=os.environ.copy(), preexec_fn=os.setsid, ) # Start daemon thread to read subprocess logging output log_reader = threading.Thread( target=self._read_task_logs, args=(proc.stdout,), ) log_reader.daemon = True log_reader.start() return proc def start(self): """Start running the task instance in a subprocess.""" raise NotImplementedError() def return_code(self): """ :return: The return code associated with running the task instance or None if the task is not yet done. :rtype: int """ raise NotImplementedError() def terminate(self): """Kill the running task instance.""" raise NotImplementedError() def on_finish(self): """A callback that should be called when this is done running.""" if self._cfg_path and os.path.isfile(self._cfg_path): if self.run_as_user: subprocess.call(['sudo', 'rm', self._cfg_path], close_fds=True) else: os.remove(self._cfg_path)
airbnb/airflow
airflow/task/task_runner/base_task_runner.py
Python
apache-2.0
6,243
/** * 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.metron.writer.hdfs; import java.io.FileOutputStream; import java.io.IOException; import java.lang.invoke.MethodHandles; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.client.HdfsDataOutputStream; import org.apache.metron.common.configuration.writer.WriterConfiguration; import org.apache.storm.hdfs.bolt.format.FileNameFormat; import org.apache.storm.hdfs.bolt.rotation.FileRotationPolicy; import org.apache.storm.hdfs.bolt.rotation.TimedRotationPolicy; import org.apache.storm.hdfs.bolt.sync.SyncPolicy; import org.apache.storm.hdfs.common.rotation.RotationAction; import org.json.simple.JSONObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SourceHandler { private static final Logger LOG = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass()); List<RotationAction> rotationActions = new ArrayList<>(); FileRotationPolicy rotationPolicy; SyncPolicy syncPolicy; FileNameFormat fileNameFormat; SourceHandlerCallback cleanupCallback; private long offset = 0; private transient FSDataOutputStream out; private transient final Object writeLock = new Object(); protected transient Timer rotationTimer; // only used for TimedRotationPolicy protected transient FileSystem fs; protected transient Path currentFile; public SourceHandler(List<RotationAction> rotationActions , FileRotationPolicy rotationPolicy , SyncPolicy syncPolicy , FileNameFormat fileNameFormat , SourceHandlerCallback cleanupCallback) throws IOException { this.rotationActions = rotationActions; this.rotationPolicy = rotationPolicy; this.syncPolicy = syncPolicy; this.fileNameFormat = fileNameFormat; this.cleanupCallback = cleanupCallback; initialize(); } protected void handle(JSONObject message, String sensor, WriterConfiguration config, SyncPolicyCreator syncPolicyCreator) throws IOException { byte[] bytes = (message.toJSONString() + "\n").getBytes(); synchronized (this.writeLock) { try { out.write(bytes); } catch (IOException writeException) { LOG.warn("IOException while writing output", writeException); // If the stream is closed, attempt to rotate the file and try again, hoping it's transient if (writeException.getMessage().contains("Stream Closed")) { LOG.warn("Output Stream was closed. Attempting to rotate file and continue"); rotateOutputFile(); // If this write fails, the exception will be allowed to bubble up. out.write(bytes); } else { throw writeException; } } this.offset += bytes.length; if (this.syncPolicy.mark(null, this.offset)) { LOG.debug("Calling hsync per Sync Policy"); if (this.out instanceof HdfsDataOutputStream) { ((HdfsDataOutputStream) this.out) .hsync(EnumSet.of(HdfsDataOutputStream.SyncFlag.UPDATE_LENGTH)); } else { this.out.hsync(); } //recreate the sync policy for the next batch just in case something changed in the config //and the sync policy depends on the config. LOG.debug("Recreating sync policy"); this.syncPolicy = syncPolicyCreator.create(sensor, config); } } if (this.rotationPolicy.mark(null, this.offset)) { LOG.debug("Rotating due to rotationPolicy"); rotateOutputFile(); // synchronized this.offset = 0; this.rotationPolicy.reset(); } } private void initialize() throws IOException { LOG.debug("Initializing Source Handler"); this.fs = FileSystem.get(new Configuration()); this.currentFile = createOutputFile(); LOG.debug("Source Handler initialized with starting file: {}", currentFile); if(this.rotationPolicy instanceof TimedRotationPolicy){ long interval = ((TimedRotationPolicy)this.rotationPolicy).getInterval(); this.rotationTimer = new Timer(true); TimerTask task = new TimerTask() { @Override public void run() { try { LOG.debug("Rotating output file from TimerTask"); rotateOutputFile(); } catch(IOException e){ LOG.warn("IOException during scheduled file rotation.", e); } } }; this.rotationTimer.scheduleAtFixedRate(task, interval, interval); } } // Closes the output file, but ensures any RotationActions are performed. protected void rotateOutputFile() throws IOException { LOG.debug("Rotating output file..."); long start = System.currentTimeMillis(); synchronized (this.writeLock) { closeOutputFile(); // Want to use the callback to make sure we have an accurate count of open files. cleanupCallback(); LOG.debug("Performing {} file rotation actions.", this.rotationActions.size()); for (RotationAction action : this.rotationActions) { action.execute(this.fs, this.currentFile); } } long time = System.currentTimeMillis() - start; LOG.info("File rotation took {} ms", time); } private Path createOutputFile() throws IOException { // The rotation is set to 0. With the way open files are tracked and managed with the callback, there will // never be data that would go into a rotation > 0. Instead a new SourceHandler, and by extension file, will // be created. Path path = new Path(this.fileNameFormat.getPath(), this.fileNameFormat.getName(0, System.currentTimeMillis())); LOG.debug("Creating new output file: {}", path.getName()); if(fs.getScheme().equals("file")) { //in the situation where we're running this in a local filesystem, flushing doesn't work. fs.mkdirs(path.getParent()); this.out = new FSDataOutputStream(new FileOutputStream(path.toString()), null); } else { this.out = this.fs.create(path); } return path; } protected void closeOutputFile() throws IOException { this.out.close(); } private void cleanupCallback() { this.cleanupCallback.removeKey(); } public void close() { try { closeOutputFile(); if(rotationTimer != null) { rotationTimer.cancel(); } // Don't call cleanup, to avoid HashMap's ConcurrentModificationException while iterating } catch (IOException e) { throw new RuntimeException("Unable to close output file.", e); } } @Override public String toString() { return "SourceHandler{" + "rotationActions=" + rotationActions + ", rotationPolicy=" + rotationPolicy + ", syncPolicy=" + syncPolicy + ", fileNameFormat=" + fileNameFormat + ", offset=" + offset + ", out=" + out + ", writeLock=" + writeLock + ", rotationTimer=" + rotationTimer + ", fs=" + fs + ", currentFile=" + currentFile + '}'; } }
apache/incubator-metron
metron-platform/metron-writer/src/main/java/org/apache/metron/writer/hdfs/SourceHandler.java
Java
apache-2.0
8,054
/* * Copyright (c) 2008-2017, Hazelcast, Inc. 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. */ /** * Hazelcast Starter allows starting Hazelcast instances of arbitrary version in the same JVM. */ package com.hazelcast.test.starter;
tombujok/hazelcast
hazelcast/src/test/java/com/hazelcast/test/starter/package-info.java
Java
apache-2.0
766
<html xmlns:wicket> <wicket:panel> <br/> <div wicket:id="permissionMessage"></div> <br/> </wicket:panel> </html>
petebrew/dccd-webui
src/main/java/nl/knaw/dans/dccd/web/project/UnauthorizedDendroEntityPanel.html
HTML
apache-2.0
115
--- external help file: Microsoft.Azure.Commands.Dns.dll-Help.xml Module Name: AzureRM.Dns ms.assetid: 45DF71E0-77E1-4D20-AD09-2C06680F659F online version: https://docs.microsoft.com/en-us/powershell/module/azurerm.dns/new-azurermdnsrecordset schema: 2.0.0 --- # New-AzureRmDnsRecordSet ## SYNOPSIS Creates a DNS record set. ## SYNTAX ### Fields ``` New-AzureRmDnsRecordSet -Name <String> -ZoneName <String> -ResourceGroupName <String> -Ttl <UInt32> -RecordType <RecordType> [-Metadata <Hashtable>] [-DnsRecords <DnsRecordBase[]>] [-Overwrite] [-Force] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ### Object ``` New-AzureRmDnsRecordSet -Name <String> -Zone <DnsZone> -Ttl <UInt32> -RecordType <RecordType> [-Metadata <Hashtable>] [-DnsRecords <DnsRecordBase[]>] [-Overwrite] [-Force] [-DefaultProfile <IAzureContextContainer>] [-WhatIf] [-Confirm] [<CommonParameters>] ``` ## DESCRIPTION The **New-AzureRmDnsRecordSet** cmdlet creates a new Domain Name System (DNS) record set with the specified name and type in the specified zone. A **RecordSet** object is a set of DNS records with the same name and type. Note that the name is relative to the zone and not the fully qualified name. The *DnsRecords* parameter specifies the records in the record set. This parameter takes an array of DNS records, constructed using New-AzureRmDnsRecordConfig. You can use the pipeline operator to pass a **DnsZone** object to this cmdlet, or you can pass a **DnsZone** object as the *Zone* parameter, or alternatively you can specify the zone by name. You can use the *Confirm* parameter and $ConfirmPreference Windows PowerShell variable to control whether the cmdlet prompts you for confirmation. If a matching **RecordSet** already exists (same name and record type), you must specify the *Overwrite* parameter, otherwise the cmdlet will not create a new **RecordSet** . ## EXAMPLES ### Example 1: Create a RecordSet of type A ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -IPv4Address 1.2.3.4 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records # When creating a RecordSet containing a single record, the above sequence can also be condensed into a single line: PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords (New-AzureRmDnsRecordConfig -IPv4Address 1.2.3.4) # To create a record set containing multiple records, use New-AzureRmDnsRecordConfig to add each record to the $Records array, # then call New-AzureRmDnsRecordSet, as follows: PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -IPv4Address 1.2.3.4 PS C:\> $Records += New-AzureRmDnsRecordConfig -IPv4Address 5.6.7.8 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This example creates a **RecordSet** named www in the zone myzone.com. The record set is of type A and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. ### Example 2: Create a RecordSet of type AAAA ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Ipv6Address 2001:db8::1 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType AAAA -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This example creates a **RecordSet** named www in the zone myzone.com. The record set is of type AAAA and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 3: Create a RecordSet of type CNAME ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Cname www.contoso.com PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType CNAME -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This example creates a **RecordSet** named www in the zone myzone.com. The record set is of type CNAME and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 4: Create a RecordSet of type MX ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Exchange "mail.microsoft.com" -Preference 5 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType AAAA -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** named www in the zone myzone.com. The record set is of type MX and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 5: Create a RecordSet of type NS ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Nsdname ns1-01.azure-dns.com PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "ns1" -RecordType NS -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** named ns1 in the zone myzone.com. The record set is of type NS and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 6: Create a RecordSet of type PTR ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Ptrdname www.contoso.com PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "4" -RecordType PTR -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "3.2.1.in-addr.arpa" -DnsRecords $Records ``` This command creates a **RecordSet** named 4 in the zone 3.2.1.in-addr.arpa. The record set is of type PTR and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 7: Create a RecordSet of type SRV ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Priority 0 -Weight 5 -Port 8080 -Target sipservice.contoso.com PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "_sip._tcp" -RecordType SRV -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** named _sip._tcp in the zone myzone.com. The record set is of type SRV and has a TTL of 1 hour (3600 seconds). It contains a single DNS record, pointing to the IP address 2001.2.3.4. The service (sip) and the protocol (tcp) are specified as part of the record set name, not as part of the record data. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 8: Create a RecordSet of type TXT ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Value "This is a TXT Record" PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "text" -RecordType TXT -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** named text in the zone myzone.com. The record set is of type TXT and has a TTL of 1 hour (3600 seconds). It contains a single DNS record. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 9: Create a RecordSet at the zone apex ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Ipv4Address 1.2.3.4 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "@" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** at the apex (or root) of the zone myzone.com. To do this, the record set name is specified as "@" (including the double-quotes). You cannot create CNAME records at the apex of a zone. This is a constraint of the DNS standards; it is not a limitation of Azure DNS. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 10: Create a wildcard Record Set ``` PS C:\> $Records = @() PS C:\> $Records += New-AzureRmDnsRecordConfig -Ipv4Address 1.2.3.4 PS C:\> $RecordSet = New-AzureRmDnsRecordSet -Name "*" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords $Records ``` This command creates a **RecordSet** named * in the zone myzone.com. This is a wildcard record set. To create a **RecordSet** using only one line of pn_PowerShell_short, or to create a record set with multiple records, see Example 1. ### Example 11: Create an empty record set ``` PS C:\>$RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords @() ``` This command creates a **RecordSet** named www in the zone myzone.com. The record set is of type A and has a TTL of 1 hour (3600 seconds). This is an empty record set, which acts as a placeholder to which you can later add records. ### Example 12: Create a record set and suppress all confirmation ``` PS C:\>$RecordSet = New-AzureRmDnsRecordSet -Name "www" -RecordType A -ResourceGroupName "MyResourceGroup" -TTL 3600 -ZoneName "myzone.com" -DnsRecords (New-AzureRmDnsRecordConfig -Ipv4Address 1.2.3.4) -Confirm:$False -Overwrite ``` This command creates a **RecordSet**. The *Overwrite* parameter ensures that this record set overwrites any pre-existing record set with the same name and type (existing records in that record set are lost). The *Confirm* parameter with a value of $False suppresses the confirmation prompt. ## PARAMETERS ### -DefaultProfile The credentials, account, tenant, and subscription used for communication with azure ```yaml Type: IAzureContextContainer Parameter Sets: (All) Aliases: AzureRmContext, AzureCredential Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -DnsRecords Specifies the array of DNS records to include in the record set. You can use the New-AzureRmDnsRecordConfig cmdlet to create DNS record objects. See the examples for more information. ```yaml Type: DnsRecordBase[] Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -Force This parameter is deprecated for this cmdlet. It will be removed in a future release. To control whether this cmdlet prompts you for comfirmation, use the *Confirm* parameter. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Metadata Specifies an array of metadata to associate with the RecordSet. Metadata is specified using name-value pairs that are represented as hash tables, for example @(@{"Name"="dept"; "Value"="shopping"}, @{"Name"="env"; "Value"="production"}). ```yaml Type: Hashtable Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Name Specifies the name of the **RecordSet** to create. ```yaml Type: String Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Overwrite Indicates that this cmdlet overwrites the specified **RecordSet** if it already exists. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RecordType Specifies the type of DNS record to create. Valid values are: - A - AAAA - CNAME - MX - NS - PTR - SRV - TXT SOA records are created automatically when the zone is created and cannot be created manually. ```yaml Type: RecordType Parameter Sets: (All) Aliases: Accepted values: A, AAAA, CAA, CNAME, MX, NS, PTR, SOA, SRV, TXT Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -ResourceGroupName Specifies the resource group that contains the DNS zone. You must also specify the *ZoneName* parameter to specify the zone name. Alternatively, you can specify the zone and resource group by passing in a DNS Zone object using the *Zone* parameter. ```yaml Type: String Parameter Sets: Fields Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Ttl Specifies the Time to Live (TTL) for the DNS RecordSet. ```yaml Type: UInt32 Parameter Sets: (All) Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Zone Specifies the DnsZone in which to create the **RecordSet**. Alternatively, you can specify the zone using the *ZoneName* and *ResourceGroupName* parameters. ```yaml Type: DnsZone Parameter Sets: Object Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` ### -ZoneName Specifies the name of the zone in which to create the **RecordSet**. You must also specify the resource group containing the zone using the *ResourceGroupName* parameter. Alternatively, you can specify the zone and resource group by passing in a DNS Zone object using the *Zone* parameter. ```yaml Type: String Parameter Sets: Fields Aliases: Required: True Position: Named Default value: None Accept pipeline input: True (ByPropertyName) Accept wildcard characters: False ``` ### -Confirm Prompts you for confirmation before running the cmdlet. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: cf Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf Shows what would happen if the cmdlet runs. The cmdlet is not run. ```yaml Type: SwitchParameter Parameter Sets: (All) Aliases: wi Required: False Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see about_CommonParameters (http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### Microsoft.Azure.Commands.Dns.DnsZone You can pipe a DnsZone object to this cmdlet. ## OUTPUTS ### Microsoft.Azure.Commands.Dns.DnsRecordSet This cmdlet returns a **RecordSet** object. ## NOTES You can use the *Confirm* parameter to control whether this cmdlet prompts you for confirmation. By default, the cmdlet prompts you for confirmation if the $ConfirmPreference Windows PowerShell variable has a value of Medium or lower. If you specify *Confirm* or *Confirm:$True*, this cmdlet prompts you for confirmation before it runs. If you specify *Confirm:$False*, the cmdlet does not prompt you for confirmation. ## RELATED LINKS [Add-AzureRmDnsRecordConfig](./Add-AzureRmDnsRecordConfig.md) [Get-AzureRmDnsRecordSet](./Get-AzureRmDnsRecordSet.md) [New-AzureRmDnsRecordConfig](./New-AzureRmDnsRecordConfig.md) [Remove-AzureRmDnsRecordSet](./Remove-AzureRmDnsRecordSet.md) [Set-AzureRmDnsRecordSet](./Set-AzureRmDnsRecordSet.md)
devigned/azure-powershell
src/ResourceManager/Dns/Commands.Dns/help/New-AzureRmDnsRecordSet.md
Markdown
apache-2.0
16,140
This module handles the derivation from an algebrized query of two things: - A SQL projection: a mapping from columns mentioned in the body of the query to columns in the output. - A Datalog projection: a function that consumes rows of the appropriate shape (as defined by the SQL projection) to yield one of the four kinds of Datalog query result. These two must naturally coordinate, and so they are both produced here.
ncalexan/mentat
query-projector/README.md
Markdown
apache-2.0
424
#pragma once #ifndef _H_SCENE_EP #define _H_SCENE_EP #include "Geometry.h" #include "ParticleSystem.h" namespace Geometry { class Scene { public: Scene(); ~Scene(); Geometry * get_Geometry( void ); void SetGeometry(Geometry *geo); ParticleSystem * GetParticleSystem(void); void SetParticleSystem(ParticleSystem *part); private: Geometry* mGeometry; ParticleSystem* mParticles; }; } #endif
ohbknights/IDS6938-SimulationTechniques
Lecture9/geometry/Scene.h
C
apache-2.0
418
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/acm-pca/ACMPCA_EXPORTS.h> #include <aws/core/client/AWSErrorMarshaller.h> namespace Aws { namespace Client { class AWS_ACMPCA_API ACMPCAErrorMarshaller : public Aws::Client::JsonErrorMarshaller { public: Aws::Client::AWSError<Aws::Client::CoreErrors> FindErrorByName(const char* exceptionName) const override; }; } // namespace Client } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-acm-pca/include/aws/acm-pca/ACMPCAErrorMarshaller.h
C
apache-2.0
509
package com.xthena.bridge.form; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import com.xthena.api.form.FormConnector; import com.xthena.api.form.FormDTO; import org.springframework.jdbc.core.JdbcTemplate; public class DatabaseFormConnector implements FormConnector { private JdbcTemplate jdbcTemplate; @Override public List<FormDTO> getAll(String scopeId) { String sql = "select id,name from FORM_TEMPLATE"; List<Map<String, Object>> list = jdbcTemplate.queryForList(sql); List<FormDTO> formDtos = new ArrayList<FormDTO>(); for (Map<String, Object> map : list) { FormDTO formDto = new FormDTO(); formDtos.add(formDto); formDto.setId(map.get("id").toString()); formDto.setName(map.get("name").toString()); } return formDtos; } @Resource public void setJdbcTemplate(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } }
jianbingfang/xhf
src/main/java/com/xthena/bridge/form/DatabaseFormConnector.java
Java
apache-2.0
1,032
/* * Copyright 2000-2016 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.jetbrains.python.psi.impl; import com.intellij.lang.ASTNode; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiPolyVariantReference; import com.intellij.psi.PsiReference; import com.intellij.psi.util.QualifiedName; import com.jetbrains.python.PyNames; import com.jetbrains.python.PyTokenTypes; import com.jetbrains.python.PythonDialectsTokenSetProvider; import com.jetbrains.python.psi.*; import com.jetbrains.python.psi.impl.references.PyOperatorReference; import com.jetbrains.python.psi.resolve.PyResolveContext; import com.jetbrains.python.psi.types.*; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.List; import java.util.Optional; /** * @author yole */ public class PySubscriptionExpressionImpl extends PyElementImpl implements PySubscriptionExpression { public PySubscriptionExpressionImpl(ASTNode astNode) { super(astNode); } @NotNull public PyExpression getOperand() { return childToPsiNotNull(PythonDialectsTokenSetProvider.INSTANCE.getExpressionTokens(), 0); } @NotNull @Override public PyExpression getRootOperand() { PyExpression operand = getOperand(); while (operand instanceof PySubscriptionExpression) { operand = ((PySubscriptionExpression)operand).getOperand(); } return operand; } @Nullable public PyExpression getIndexExpression() { return childToPsi(PythonDialectsTokenSetProvider.INSTANCE.getExpressionTokens(), 1); } @Override protected void acceptPyVisitor(final PyElementVisitor pyVisitor) { pyVisitor.visitPySubscriptionExpression(this); } @Nullable @Override public PyType getType(@NotNull TypeEvalContext context, @NotNull TypeEvalContext.Key key) { final PsiPolyVariantReference reference = getReference(PyResolveContext.noImplicits().withTypeEvalContext(context)); final List<PyType> members = new ArrayList<>(); final PyExpression indexExpression = getIndexExpression(); final PyType type = indexExpression != null ? context.getType(getOperand()) : null; if (type instanceof PyTupleType) { final PyTupleType tupleType = (PyTupleType)type; return Optional .ofNullable(PyConstantExpressionEvaluator.evaluate(indexExpression)) .map(value -> PyUtil.as(value, Integer.class)) .map(tupleType::getElementType) .orElse(null); } for (PsiElement resolved : PyUtil.multiResolveTopPriority(reference)) { PyType res = null; if (resolved instanceof PyCallable) { res = ((PyCallable)resolved).getCallType(context, this); } if (PyTypeChecker.isUnknown(res) || res instanceof PyNoneType) { final PyClass cls = (type instanceof PyClassType) ? ((PyClassType)type).getPyClass() : null; if (cls != null && PyABCUtil.isSubclass(cls, PyNames.MAPPING, context)) { return res; } if (type instanceof PyCollectionType) { res = ((PyCollectionType)type).getIteratedItemType(); } } members.add(res); } return PyUnionType.union(members); } @Override public PsiReference getReference() { return getReference(PyResolveContext.noImplicits()); } @NotNull @Override public PsiPolyVariantReference getReference(@NotNull PyResolveContext context) { return new PyOperatorReference(this, context); } @Override public PyExpression getQualifier() { return getOperand(); } @Nullable @Override public QualifiedName asQualifiedName() { return PyPsiUtils.asQualifiedName(this); } @Override public boolean isQualified() { return getQualifier() != null; } @Override public String getReferencedName() { String res = PyNames.GETITEM; switch (AccessDirection.of(this)) { case READ: res = PyNames.GETITEM; break; case WRITE: res = PyNames.SETITEM; break; case DELETE: res = PyNames.DELITEM; break; } return res; } @Override public ASTNode getNameElement() { return getNode().findChildByType(PyTokenTypes.LBRACKET); } }
semonte/intellij-community
python/src/com/jetbrains/python/psi/impl/PySubscriptionExpressionImpl.java
Java
apache-2.0
4,737
/* * -----------------------------------------------------------------------\ * SilverWare *   * Copyright (C) 2010 - 2013 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 verticle; import io.silverware.microservices.annotations.Deployment; import io.vertx.core.AbstractVerticle; import io.vertx.core.logging.Logger; import io.vertx.core.logging.LoggerFactory; /** * @author <a href="mailto:[email protected]">Martin Štefanko</a> */ @Deployment(config = "src/main/resources/example.json") public class MyVerticle extends AbstractVerticle { private Logger log = LoggerFactory.getLogger(MyVerticle.class); @Override public void start() throws Exception { log.info(this.getClass().getName() + " is starting..."); vertx.setPeriodic(1000, id -> { log.info("The value of foo: " + config().getString("foo")); }); } @Override public void stop() throws Exception { log.info(this.getClass().getSimpleName() + " is stopping"); } }
px3/SilverWare-Demos
quickstarts/vertx-deployment-options/src/main/java/verticle/MyVerticle.java
Java
apache-2.0
1,647
insert into role (id, role_name) values (1, 'Seller'); insert into role (id, role_name) values (2, 'Buyer'); insert into rgroup (id, group_name) values (1, 'customer_group'); insert into group_role (group_id, role_id) values (1, 1); insert into group_role (group_id, role_id) values (1, 2);
galahade/Common_SSO
security/src/main/resources/config/sql/Group_Role_data.sql
SQL
apache-2.0
290
// Copyright (c) 2017 VMware, Inc. 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. package registry import ( "net/http" ) // Modifier modifies request type Modifier interface { Modify(*http.Request) error }
wemeya/harbor
src/common/utils/registry/modifier.go
GO
apache-2.0
742
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/redshift/model/DescribeNodeConfigurationOptionsRequest.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> using namespace Aws::Redshift::Model; using namespace Aws::Utils; DescribeNodeConfigurationOptionsRequest::DescribeNodeConfigurationOptionsRequest() : m_actionType(ActionType::NOT_SET), m_actionTypeHasBeenSet(false), m_clusterIdentifierHasBeenSet(false), m_snapshotIdentifierHasBeenSet(false), m_ownerAccountHasBeenSet(false), m_filtersHasBeenSet(false), m_markerHasBeenSet(false), m_maxRecords(0), m_maxRecordsHasBeenSet(false) { } Aws::String DescribeNodeConfigurationOptionsRequest::SerializePayload() const { Aws::StringStream ss; ss << "Action=DescribeNodeConfigurationOptions&"; if(m_actionTypeHasBeenSet) { ss << "ActionType=" << ActionTypeMapper::GetNameForActionType(m_actionType) << "&"; } if(m_clusterIdentifierHasBeenSet) { ss << "ClusterIdentifier=" << StringUtils::URLEncode(m_clusterIdentifier.c_str()) << "&"; } if(m_snapshotIdentifierHasBeenSet) { ss << "SnapshotIdentifier=" << StringUtils::URLEncode(m_snapshotIdentifier.c_str()) << "&"; } if(m_ownerAccountHasBeenSet) { ss << "OwnerAccount=" << StringUtils::URLEncode(m_ownerAccount.c_str()) << "&"; } if(m_filtersHasBeenSet) { unsigned filtersCount = 1; for(auto& item : m_filters) { item.OutputToStream(ss, "Filter.", filtersCount, ""); filtersCount++; } } if(m_markerHasBeenSet) { ss << "Marker=" << StringUtils::URLEncode(m_marker.c_str()) << "&"; } if(m_maxRecordsHasBeenSet) { ss << "MaxRecords=" << m_maxRecords << "&"; } ss << "Version=2012-12-01"; return ss.str(); } void DescribeNodeConfigurationOptionsRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const { uri.SetQueryString(SerializePayload()); }
awslabs/aws-sdk-cpp
aws-cpp-sdk-redshift/source/model/DescribeNodeConfigurationOptionsRequest.cpp
C++
apache-2.0
2,021
/* * Copyright 2014 Adam Mackler * * 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.bitcoinj.utils; import org.bitcoinj.core.Coin; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import java.math.BigDecimal; import java.text.*; import java.text.AttributedCharacterIterator.Attribute; import java.util.HashSet; import java.util.Locale; import java.util.Set; import static org.bitcoinj.core.Coin.*; import static org.bitcoinj.core.NetworkParameters.MAX_MONEY; import static org.bitcoinj.utils.BtcAutoFormat.Style.CODE; import static org.bitcoinj.utils.BtcAutoFormat.Style.SYMBOL; import static org.bitcoinj.utils.BtcFixedFormat.REPEATING_DOUBLETS; import static org.bitcoinj.utils.BtcFixedFormat.REPEATING_TRIPLETS; import static java.text.NumberFormat.Field.DECIMAL_SEPARATOR; import static java.util.Locale.*; import static org.junit.Assert.*; @RunWith(Parameterized.class) public class BtcFormatTest { @Parameters public static Set<Locale[]> data() { Set<Locale[]> localeSet = new HashSet<>(); for (Locale locale : Locale.getAvailableLocales()) { localeSet.add(new Locale[]{locale}); } return localeSet; } public BtcFormatTest(Locale defaultLocale) { Locale.setDefault(defaultLocale); } @Test public void prefixTest() { // prefix b/c symbol is prefixed BtcFormat usFormat = BtcFormat.getSymbolInstance(Locale.US); assertEquals("฿1.00", usFormat.format(COIN)); assertEquals("฿1.01", usFormat.format(101000000)); assertEquals("₥฿0.01", usFormat.format(1000)); assertEquals("₥฿1,011.00", usFormat.format(101100000)); assertEquals("₥฿1,000.01", usFormat.format(100001000)); assertEquals("µ฿1,000,001.00", usFormat.format(100000100)); assertEquals("µ฿1,000,000.10", usFormat.format(100000010)); assertEquals("µ฿1,000,000.01", usFormat.format(100000001)); assertEquals("µ฿1.00", usFormat.format(100)); assertEquals("µ฿0.10", usFormat.format(10)); assertEquals("µ฿0.01", usFormat.format(1)); } @Ignore("non-determinism between OpenJDK versions") @Test public void suffixTest() { BtcFormat deFormat = BtcFormat.getSymbolInstance(Locale.GERMANY); // int assertEquals("1,00 ฿", deFormat.format(100000000)); assertEquals("1,01 ฿", deFormat.format(101000000)); assertEquals("1.011,00 ₥฿", deFormat.format(101100000)); assertEquals("1.000,01 ₥฿", deFormat.format(100001000)); assertEquals("1.000.001,00 µ฿", deFormat.format(100000100)); assertEquals("1.000.000,10 µ฿", deFormat.format(100000010)); assertEquals("1.000.000,01 µ฿", deFormat.format(100000001)); } @Test public void defaultLocaleTest() { assertEquals( "Default Locale is " + Locale.getDefault().toString(), BtcFormat.getInstance().pattern(), BtcFormat.getInstance(Locale.getDefault()).pattern() ); assertEquals( "Default Locale is " + Locale.getDefault().toString(), BtcFormat.getCodeInstance().pattern(), BtcFormat.getCodeInstance(Locale.getDefault()).pattern() ); } @Test public void symbolCollisionTest() { Locale[] locales = BtcFormat.getAvailableLocales(); for (int i = 0; i < locales.length; ++i) { String cs = ((DecimalFormat)NumberFormat.getCurrencyInstance(locales[i])). getDecimalFormatSymbols().getCurrencySymbol(); if (cs.contains("฿")) { BtcFormat bf = BtcFormat.getSymbolInstance(locales[i]); String coin = bf.format(COIN); assertTrue(coin.contains("Ƀ")); assertFalse(coin.contains("฿")); String milli = bf.format(valueOf(10000)); assertTrue(milli.contains("₥Ƀ")); assertFalse(milli.contains("฿")); String micro = bf.format(valueOf(100)); assertTrue(micro.contains("µɃ")); assertFalse(micro.contains("฿")); BtcFormat ff = BtcFormat.builder().scale(0).locale(locales[i]).pattern("¤#.#").build(); assertEquals("Ƀ", ((BtcFixedFormat)ff).symbol()); assertEquals("Ƀ", ff.coinSymbol()); coin = ff.format(COIN); assertTrue(coin.contains("Ƀ")); assertFalse(coin.contains("฿")); BtcFormat mlff = BtcFormat.builder().scale(3).locale(locales[i]).pattern("¤#.#").build(); assertEquals("₥Ƀ", ((BtcFixedFormat)mlff).symbol()); assertEquals("Ƀ", mlff.coinSymbol()); milli = mlff.format(valueOf(10000)); assertTrue(milli.contains("₥Ƀ")); assertFalse(milli.contains("฿")); BtcFormat mcff = BtcFormat.builder().scale(6).locale(locales[i]).pattern("¤#.#").build(); assertEquals("µɃ", ((BtcFixedFormat)mcff).symbol()); assertEquals("Ƀ", mcff.coinSymbol()); micro = mcff.format(valueOf(100)); assertTrue(micro.contains("µɃ")); assertFalse(micro.contains("฿")); } if (cs.contains("Ƀ")) { // NB: We don't know of any such existing locale, but check anyway. BtcFormat bf = BtcFormat.getInstance(locales[i]); String coin = bf.format(COIN); assertTrue(coin.contains("฿")); assertFalse(coin.contains("Ƀ")); String milli = bf.format(valueOf(10000)); assertTrue(milli.contains("₥฿")); assertFalse(milli.contains("Ƀ")); String micro = bf.format(valueOf(100)); assertTrue(micro.contains("µ฿")); assertFalse(micro.contains("Ƀ")); } } } @Ignore("non-determinism between OpenJDK versions") @Test public void argumentTypeTest() { BtcFormat usFormat = BtcFormat.getSymbolInstance(Locale.US); // longs are tested above // Coin assertEquals("µ฿1,000,000.01", usFormat.format(COIN.add(valueOf(1)))); // Integer assertEquals("µ฿21,474,836.47" ,usFormat.format(Integer.MAX_VALUE)); assertEquals("(µ฿21,474,836.48)" ,usFormat.format(Integer.MIN_VALUE)); // Long assertEquals("µ฿92,233,720,368,547,758.07" ,usFormat.format(Long.MAX_VALUE)); assertEquals("(µ฿92,233,720,368,547,758.08)" ,usFormat.format(Long.MIN_VALUE)); // BigInteger assertEquals("µ฿0.10" ,usFormat.format(java.math.BigInteger.TEN)); assertEquals("฿0.00" ,usFormat.format(java.math.BigInteger.ZERO)); // BigDecimal assertEquals("฿1.00" ,usFormat.format(java.math.BigDecimal.ONE)); assertEquals("฿0.00" ,usFormat.format(java.math.BigDecimal.ZERO)); // use of Double not encouraged but no way to stop user from converting one to BigDecimal assertEquals( "฿179,769,313,486,231,570,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000.00", usFormat.format(java.math.BigDecimal.valueOf(Double.MAX_VALUE))); assertEquals("฿0.00", usFormat.format(java.math.BigDecimal.valueOf(Double.MIN_VALUE))); assertEquals( "฿340,282,346,638,528,860,000,000,000,000,000,000,000.00", usFormat.format(java.math.BigDecimal.valueOf(Float.MAX_VALUE))); // Bad type try { usFormat.format("1"); fail("should not have tried to format a String"); } catch (IllegalArgumentException e) { } } @Test public void columnAlignmentTest() { BtcFormat germany = BtcFormat.getCoinInstance(2,BtcFixedFormat.REPEATING_PLACES); char separator = germany.symbols().getDecimalSeparator(); Coin[] rows = {MAX_MONEY, MAX_MONEY.subtract(SATOSHI), Coin.parseCoin("1234"), COIN, COIN.add(SATOSHI), COIN.subtract(SATOSHI), COIN.divide(1000).add(SATOSHI), COIN.divide(1000), COIN.divide(1000).subtract(SATOSHI), valueOf(100), valueOf(1000), valueOf(10000), SATOSHI}; FieldPosition fp = new FieldPosition(DECIMAL_SEPARATOR); String[] output = new String[rows.length]; int[] indexes = new int[rows.length]; int maxIndex = 0; for (int i = 0; i < rows.length; i++) { output[i] = germany.format(rows[i], new StringBuffer(), fp).toString(); indexes[i] = fp.getBeginIndex(); if (indexes[i] > maxIndex) maxIndex = indexes[i]; } for (int i = 0; i < output.length; i++) { // uncomment to watch printout // System.out.println(repeat(" ", (maxIndex - indexes[i])) + output[i]); assertEquals(output[i].indexOf(separator), indexes[i]); } } @Test public void repeatingPlaceTest() { BtcFormat mega = BtcFormat.getInstance(-6, US); Coin value = MAX_MONEY.subtract(SATOSHI); assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_PLACES)); assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_PLACES)); assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_PLACES)); assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_PLACES)); assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_PLACES)); assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_DOUBLETS)); assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_DOUBLETS)); assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_DOUBLETS)); assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_DOUBLETS)); assertEquals("20.99999999999999", mega.format(value, 0, BtcFixedFormat.REPEATING_TRIPLETS)); assertEquals("20.99999999999999", mega.format(value, 1, BtcFixedFormat.REPEATING_TRIPLETS)); assertEquals("20.99999999999999", mega.format(value, 2, BtcFixedFormat.REPEATING_TRIPLETS)); assertEquals("20.99999999999999", mega.format(value, 3, BtcFixedFormat.REPEATING_TRIPLETS)); assertEquals("1.00000005", BtcFormat.getCoinInstance(US). format(COIN.add(Coin.valueOf(5)), 0, BtcFixedFormat.REPEATING_PLACES)); } @Test public void characterIteratorTest() { BtcFormat usFormat = BtcFormat.getInstance(Locale.US); AttributedCharacterIterator i = usFormat.formatToCharacterIterator(parseCoin("1234.5")); java.util.Set<Attribute> a = i.getAllAttributeKeys(); assertTrue("Missing currency attribute", a.contains(NumberFormat.Field.CURRENCY)); assertTrue("Missing integer attribute", a.contains(NumberFormat.Field.INTEGER)); assertTrue("Missing fraction attribute", a.contains(NumberFormat.Field.FRACTION)); assertTrue("Missing decimal separator attribute", a.contains(NumberFormat.Field.DECIMAL_SEPARATOR)); assertTrue("Missing grouping separator attribute", a.contains(NumberFormat.Field.GROUPING_SEPARATOR)); assertTrue("Missing currency attribute", a.contains(NumberFormat.Field.CURRENCY)); char c; i = BtcFormat.getCodeInstance(Locale.US).formatToCharacterIterator(new BigDecimal("0.19246362747414458")); // formatted as "µBTC 192,463.63" assertEquals(0, i.getBeginIndex()); assertEquals(15, i.getEndIndex()); int n = 0; for(c = i.first(); i.getAttribute(NumberFormat.Field.CURRENCY) != null; c = i.next()) { n++; } assertEquals(4, n); n = 0; for(i.next(); i.getAttribute(NumberFormat.Field.INTEGER) != null && i.getAttribute(NumberFormat.Field.GROUPING_SEPARATOR) != NumberFormat.Field.GROUPING_SEPARATOR; c = i.next()) { n++; } assertEquals(3, n); assertEquals(NumberFormat.Field.INTEGER, i.getAttribute(NumberFormat.Field.INTEGER)); n = 0; for(c = i.next(); i.getAttribute(NumberFormat.Field.INTEGER) != null; c = i.next()) { n++; } assertEquals(3, n); assertEquals(NumberFormat.Field.DECIMAL_SEPARATOR, i.getAttribute(NumberFormat.Field.DECIMAL_SEPARATOR)); n = 0; for(c = i.next(); c != CharacterIterator.DONE; c = i.next()) { n++; assertNotNull(i.getAttribute(NumberFormat.Field.FRACTION)); } assertEquals(2,n); // immutability check BtcFormat fa = BtcFormat.getSymbolInstance(US); BtcFormat fb = BtcFormat.getSymbolInstance(US); assertEquals(fa, fb); assertEquals(fa.hashCode(), fb.hashCode()); fa.formatToCharacterIterator(COIN.multiply(1000000)); assertEquals(fa, fb); assertEquals(fa.hashCode(), fb.hashCode()); fb.formatToCharacterIterator(COIN.divide(1000000)); assertEquals(fa, fb); assertEquals(fa.hashCode(), fb.hashCode()); } @Ignore("non-determinism between OpenJDK versions") @Test public void parseTest() throws java.text.ParseException { BtcFormat us = BtcFormat.getSymbolInstance(Locale.US); BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US); // Coins assertEquals(valueOf(200000000), us.parseObject("BTC2")); assertEquals(valueOf(200000000), us.parseObject("XBT2")); assertEquals(valueOf(200000000), us.parseObject("฿2")); assertEquals(valueOf(200000000), us.parseObject("Ƀ2")); assertEquals(valueOf(200000000), us.parseObject("2")); assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2")); assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2")); assertEquals(valueOf(200000000), us.parseObject("฿2.0")); assertEquals(valueOf(200000000), us.parseObject("Ƀ2.0")); assertEquals(valueOf(200000000), us.parseObject("2.0")); assertEquals(valueOf(200000000), us.parseObject("BTC2.0")); assertEquals(valueOf(200000000), us.parseObject("XBT2.0")); assertEquals(valueOf(200000000), usCoded.parseObject("฿ 2")); assertEquals(valueOf(200000000), usCoded.parseObject("Ƀ 2")); assertEquals(valueOf(200000000), usCoded.parseObject(" 2")); assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2")); assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2")); assertEquals(valueOf(202222420000000L), us.parseObject("2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("฿2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("Ƀ2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("BTC2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("XBT2,022,224.20")); assertEquals(valueOf(220200000000L), us.parseObject("2,202.0")); assertEquals(valueOf(2100000000000000L), us.parseObject("21000000.00000000")); // MilliCoins assertEquals(valueOf(200000), usCoded.parseObject("mBTC 2")); assertEquals(valueOf(200000), usCoded.parseObject("mXBT 2")); assertEquals(valueOf(200000), usCoded.parseObject("m฿ 2")); assertEquals(valueOf(200000), usCoded.parseObject("mɃ 2")); assertEquals(valueOf(200000), us.parseObject("mBTC2")); assertEquals(valueOf(200000), us.parseObject("mXBT2")); assertEquals(valueOf(200000), us.parseObject("₥฿2")); assertEquals(valueOf(200000), us.parseObject("₥Ƀ2")); assertEquals(valueOf(200000), us.parseObject("₥2")); assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2.00")); assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2.00")); assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥฿ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥Ƀ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥ 2")); assertEquals(valueOf(202222400000L), us.parseObject("₥฿2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("₥Ƀ2,022,224.20")); assertEquals(valueOf(202222400000L), us.parseObject("m฿2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("mɃ2,022,224.20")); assertEquals(valueOf(202222400000L), us.parseObject("₥BTC2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("₥XBT2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("mBTC2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("mXBT2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("₥2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥฿ 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("₥Ƀ 2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("m฿ 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("mɃ 2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥BTC 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XBT 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("mBTC 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("mXBT 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("₥ 2,022,224.20")); // Microcoins assertEquals(valueOf(435), us.parseObject("µ฿4.35")); assertEquals(valueOf(435), us.parseObject("uɃ4.35")); assertEquals(valueOf(435), us.parseObject("u฿4.35")); assertEquals(valueOf(435), us.parseObject("µɃ4.35")); assertEquals(valueOf(435), us.parseObject("uBTC4.35")); assertEquals(valueOf(435), us.parseObject("uXBT4.35")); assertEquals(valueOf(435), us.parseObject("µBTC4.35")); assertEquals(valueOf(435), us.parseObject("µXBT4.35")); assertEquals(valueOf(435), usCoded.parseObject("uBTC 4.35")); assertEquals(valueOf(435), usCoded.parseObject("uXBT 4.35")); assertEquals(valueOf(435), usCoded.parseObject("µBTC 4.35")); assertEquals(valueOf(435), usCoded.parseObject("µXBT 4.35")); // fractional satoshi; round up assertEquals(valueOf(435), us.parseObject("uBTC4.345")); assertEquals(valueOf(435), us.parseObject("uXBT4.345")); // negative with mu symbol assertEquals(valueOf(-1), usCoded.parseObject("(µ฿ 0.01)")); assertEquals(valueOf(-10), us.parseObject("(µBTC0.100)")); assertEquals(valueOf(-10), us.parseObject("(µXBT0.100)")); // Same thing with addition of custom code, symbol us = BtcFormat.builder().locale(US).style(SYMBOL).symbol("£").code("XYZ").build(); usCoded = BtcFormat.builder().locale(US).scale(0).symbol("£").code("XYZ"). pattern("¤ #,##0.00").build(); // Coins assertEquals(valueOf(200000000), us.parseObject("XYZ2")); assertEquals(valueOf(200000000), us.parseObject("BTC2")); assertEquals(valueOf(200000000), us.parseObject("XBT2")); assertEquals(valueOf(200000000), us.parseObject("£2")); assertEquals(valueOf(200000000), us.parseObject("฿2")); assertEquals(valueOf(200000000), us.parseObject("Ƀ2")); assertEquals(valueOf(200000000), us.parseObject("2")); assertEquals(valueOf(200000000), usCoded.parseObject("XYZ 2")); assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2")); assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2")); assertEquals(valueOf(200000000), us.parseObject("£2.0")); assertEquals(valueOf(200000000), us.parseObject("฿2.0")); assertEquals(valueOf(200000000), us.parseObject("Ƀ2.0")); assertEquals(valueOf(200000000), us.parseObject("2.0")); assertEquals(valueOf(200000000), us.parseObject("XYZ2.0")); assertEquals(valueOf(200000000), us.parseObject("BTC2.0")); assertEquals(valueOf(200000000), us.parseObject("XBT2.0")); assertEquals(valueOf(200000000), usCoded.parseObject("£ 2")); assertEquals(valueOf(200000000), usCoded.parseObject("฿ 2")); assertEquals(valueOf(200000000), usCoded.parseObject("Ƀ 2")); assertEquals(valueOf(200000000), usCoded.parseObject(" 2")); assertEquals(valueOf(200000000), usCoded.parseObject("XYZ 2")); assertEquals(valueOf(200000000), usCoded.parseObject("BTC 2")); assertEquals(valueOf(200000000), usCoded.parseObject("XBT 2")); assertEquals(valueOf(202222420000000L), us.parseObject("2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("£2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("฿2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("Ƀ2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("XYZ2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("BTC2,022,224.20")); assertEquals(valueOf(202222420000000L), us.parseObject("XBT2,022,224.20")); assertEquals(valueOf(220200000000L), us.parseObject("2,202.0")); assertEquals(valueOf(2100000000000000L), us.parseObject("21000000.00000000")); // MilliCoins assertEquals(valueOf(200000), usCoded.parseObject("mXYZ 2")); assertEquals(valueOf(200000), usCoded.parseObject("mBTC 2")); assertEquals(valueOf(200000), usCoded.parseObject("mXBT 2")); assertEquals(valueOf(200000), usCoded.parseObject("m£ 2")); assertEquals(valueOf(200000), usCoded.parseObject("m฿ 2")); assertEquals(valueOf(200000), usCoded.parseObject("mɃ 2")); assertEquals(valueOf(200000), us.parseObject("mXYZ2")); assertEquals(valueOf(200000), us.parseObject("mBTC2")); assertEquals(valueOf(200000), us.parseObject("mXBT2")); assertEquals(valueOf(200000), us.parseObject("₥£2")); assertEquals(valueOf(200000), us.parseObject("₥฿2")); assertEquals(valueOf(200000), us.parseObject("₥Ƀ2")); assertEquals(valueOf(200000), us.parseObject("₥2")); assertEquals(valueOf(200000), usCoded.parseObject("₥XYZ 2.00")); assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2.00")); assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2.00")); assertEquals(valueOf(200000), usCoded.parseObject("₥XYZ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥BTC 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥XBT 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥£ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥฿ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥Ƀ 2")); assertEquals(valueOf(200000), usCoded.parseObject("₥ 2")); assertEquals(valueOf(202222400000L), us.parseObject("₥£2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("₥฿2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("₥Ƀ2,022,224.20")); assertEquals(valueOf(202222400000L), us.parseObject("m£2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("m฿2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("mɃ2,022,224.20")); assertEquals(valueOf(202222400000L), us.parseObject("₥XYZ2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("₥BTC2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("₥XBT2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("mXYZ2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("mBTC2,022,224")); assertEquals(valueOf(202222400000L), us.parseObject("mXBT2,022,224")); assertEquals(valueOf(202222420000L), us.parseObject("₥2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥£ 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥฿ 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("₥Ƀ 2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("m£ 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("m฿ 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("mɃ 2,022,224.20")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XYZ 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥BTC 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("₥XBT 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("mXYZ 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("mBTC 2,022,224")); assertEquals(valueOf(202222400000L), usCoded.parseObject("mXBT 2,022,224")); assertEquals(valueOf(202222420000L), usCoded.parseObject("₥ 2,022,224.20")); // Microcoins assertEquals(valueOf(435), us.parseObject("µ£4.35")); assertEquals(valueOf(435), us.parseObject("µ฿4.35")); assertEquals(valueOf(435), us.parseObject("uɃ4.35")); assertEquals(valueOf(435), us.parseObject("u£4.35")); assertEquals(valueOf(435), us.parseObject("u฿4.35")); assertEquals(valueOf(435), us.parseObject("µɃ4.35")); assertEquals(valueOf(435), us.parseObject("uXYZ4.35")); assertEquals(valueOf(435), us.parseObject("uBTC4.35")); assertEquals(valueOf(435), us.parseObject("uXBT4.35")); assertEquals(valueOf(435), us.parseObject("µXYZ4.35")); assertEquals(valueOf(435), us.parseObject("µBTC4.35")); assertEquals(valueOf(435), us.parseObject("µXBT4.35")); assertEquals(valueOf(435), usCoded.parseObject("uXYZ 4.35")); assertEquals(valueOf(435), usCoded.parseObject("uBTC 4.35")); assertEquals(valueOf(435), usCoded.parseObject("uXBT 4.35")); assertEquals(valueOf(435), usCoded.parseObject("µXYZ 4.35")); assertEquals(valueOf(435), usCoded.parseObject("µBTC 4.35")); assertEquals(valueOf(435), usCoded.parseObject("µXBT 4.35")); // fractional satoshi; round up assertEquals(valueOf(435), us.parseObject("uXYZ4.345")); assertEquals(valueOf(435), us.parseObject("uBTC4.345")); assertEquals(valueOf(435), us.parseObject("uXBT4.345")); // negative with mu symbol assertEquals(valueOf(-1), usCoded.parseObject("µ£ -0.01")); assertEquals(valueOf(-1), usCoded.parseObject("µ฿ -0.01")); assertEquals(valueOf(-10), us.parseObject("(µXYZ0.100)")); assertEquals(valueOf(-10), us.parseObject("(µBTC0.100)")); assertEquals(valueOf(-10), us.parseObject("(µXBT0.100)")); // parse() method as opposed to parseObject try { BtcFormat.getInstance().parse("abc"); fail("bad parse must raise exception"); } catch (ParseException e) {} } @Test public void parseMetricTest() throws ParseException { BtcFormat cp = BtcFormat.getCodeInstance(Locale.US); BtcFormat sp = BtcFormat.getSymbolInstance(Locale.US); // coin assertEquals(parseCoin("1"), cp.parseObject("BTC 1.00")); assertEquals(parseCoin("1"), sp.parseObject("BTC1.00")); assertEquals(parseCoin("1"), cp.parseObject("฿ 1.00")); assertEquals(parseCoin("1"), sp.parseObject("฿1.00")); assertEquals(parseCoin("1"), cp.parseObject("B⃦ 1.00")); assertEquals(parseCoin("1"), sp.parseObject("B⃦1.00")); assertEquals(parseCoin("1"), cp.parseObject("Ƀ 1.00")); assertEquals(parseCoin("1"), sp.parseObject("Ƀ1.00")); // milli assertEquals(parseCoin("0.001"), cp.parseObject("mBTC 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("mBTC1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("m฿ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("m฿1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("mB⃦ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("mB⃦1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("mɃ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("mɃ1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("₥BTC 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("₥BTC1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("₥฿ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("₥฿1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("₥B⃦ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("₥B⃦1.00")); assertEquals(parseCoin("0.001"), cp.parseObject("₥Ƀ 1.00")); assertEquals(parseCoin("0.001"), sp.parseObject("₥Ƀ1.00")); // micro assertEquals(parseCoin("0.000001"), cp.parseObject("uBTC 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("uBTC1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("u฿ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("u฿1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("uB⃦ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("uB⃦1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("uɃ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("uɃ1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("µBTC 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("µBTC1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("µ฿ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("µ฿1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("µB⃦ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("µB⃦1.00")); assertEquals(parseCoin("0.000001"), cp.parseObject("µɃ 1.00")); assertEquals(parseCoin("0.000001"), sp.parseObject("µɃ1.00")); // satoshi assertEquals(parseCoin("0.00000001"), cp.parseObject("uBTC 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("uBTC0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("u฿ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("u฿0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("uB⃦ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("uB⃦0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("uɃ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("uɃ0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("µBTC 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("µBTC0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("µ฿ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("µ฿0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("µB⃦ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("µB⃦0.01")); assertEquals(parseCoin("0.00000001"), cp.parseObject("µɃ 0.01")); assertEquals(parseCoin("0.00000001"), sp.parseObject("µɃ0.01")); // cents assertEquals(parseCoin("0.01234567"), cp.parseObject("cBTC 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("cBTC1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("c฿ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("c฿1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("cB⃦ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("cB⃦1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("cɃ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("cɃ1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("¢BTC 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("¢BTC1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("¢฿ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("¢฿1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("¢B⃦ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("¢B⃦1.234567")); assertEquals(parseCoin("0.01234567"), cp.parseObject("¢Ƀ 1.234567")); assertEquals(parseCoin("0.01234567"), sp.parseObject("¢Ƀ1.234567")); // dekacoins assertEquals(parseCoin("12.34567"), cp.parseObject("daBTC 1.234567")); assertEquals(parseCoin("12.34567"), sp.parseObject("daBTC1.234567")); assertEquals(parseCoin("12.34567"), cp.parseObject("da฿ 1.234567")); assertEquals(parseCoin("12.34567"), sp.parseObject("da฿1.234567")); assertEquals(parseCoin("12.34567"), cp.parseObject("daB⃦ 1.234567")); assertEquals(parseCoin("12.34567"), sp.parseObject("daB⃦1.234567")); assertEquals(parseCoin("12.34567"), cp.parseObject("daɃ 1.234567")); assertEquals(parseCoin("12.34567"), sp.parseObject("daɃ1.234567")); // hectocoins assertEquals(parseCoin("123.4567"), cp.parseObject("hBTC 1.234567")); assertEquals(parseCoin("123.4567"), sp.parseObject("hBTC1.234567")); assertEquals(parseCoin("123.4567"), cp.parseObject("h฿ 1.234567")); assertEquals(parseCoin("123.4567"), sp.parseObject("h฿1.234567")); assertEquals(parseCoin("123.4567"), cp.parseObject("hB⃦ 1.234567")); assertEquals(parseCoin("123.4567"), sp.parseObject("hB⃦1.234567")); assertEquals(parseCoin("123.4567"), cp.parseObject("hɃ 1.234567")); assertEquals(parseCoin("123.4567"), sp.parseObject("hɃ1.234567")); // kilocoins assertEquals(parseCoin("1234.567"), cp.parseObject("kBTC 1.234567")); assertEquals(parseCoin("1234.567"), sp.parseObject("kBTC1.234567")); assertEquals(parseCoin("1234.567"), cp.parseObject("k฿ 1.234567")); assertEquals(parseCoin("1234.567"), sp.parseObject("k฿1.234567")); assertEquals(parseCoin("1234.567"), cp.parseObject("kB⃦ 1.234567")); assertEquals(parseCoin("1234.567"), sp.parseObject("kB⃦1.234567")); assertEquals(parseCoin("1234.567"), cp.parseObject("kɃ 1.234567")); assertEquals(parseCoin("1234.567"), sp.parseObject("kɃ1.234567")); // megacoins assertEquals(parseCoin("1234567"), cp.parseObject("MBTC 1.234567")); assertEquals(parseCoin("1234567"), sp.parseObject("MBTC1.234567")); assertEquals(parseCoin("1234567"), cp.parseObject("M฿ 1.234567")); assertEquals(parseCoin("1234567"), sp.parseObject("M฿1.234567")); assertEquals(parseCoin("1234567"), cp.parseObject("MB⃦ 1.234567")); assertEquals(parseCoin("1234567"), sp.parseObject("MB⃦1.234567")); assertEquals(parseCoin("1234567"), cp.parseObject("MɃ 1.234567")); assertEquals(parseCoin("1234567"), sp.parseObject("MɃ1.234567")); } @Test public void parsePositionTest() { BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US); // Test the field constants FieldPosition intField = new FieldPosition(NumberFormat.Field.INTEGER); assertEquals( "987,654,321", usCoded.format(valueOf(98765432123L), new StringBuffer(), intField). substring(intField.getBeginIndex(), intField.getEndIndex()) ); FieldPosition fracField = new FieldPosition(NumberFormat.Field.FRACTION); assertEquals( "23", usCoded.format(valueOf(98765432123L), new StringBuffer(), fracField). substring(fracField.getBeginIndex(), fracField.getEndIndex()) ); // for currency we use a locale that puts the units at the end BtcFormat de = BtcFormat.getSymbolInstance(Locale.GERMANY); BtcFormat deCoded = BtcFormat.getCodeInstance(Locale.GERMANY); FieldPosition currField = new FieldPosition(NumberFormat.Field.CURRENCY); assertEquals( "µ฿", de.format(valueOf(98765432123L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); assertEquals( "µBTC", deCoded.format(valueOf(98765432123L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); assertEquals( "₥฿", de.format(valueOf(98765432000L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); assertEquals( "mBTC", deCoded.format(valueOf(98765432000L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); assertEquals( "฿", de.format(valueOf(98765000000L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); assertEquals( "BTC", deCoded.format(valueOf(98765000000L), new StringBuffer(), currField). substring(currField.getBeginIndex(), currField.getEndIndex()) ); } @Ignore("non-determinism between OpenJDK versions") @Test public void currencyCodeTest() { /* Insert needed space AFTER currency-code */ BtcFormat usCoded = BtcFormat.getCodeInstance(Locale.US); assertEquals("µBTC 0.01", usCoded.format(1)); assertEquals("BTC 1.00", usCoded.format(COIN)); /* Do not insert unneeded space BEFORE currency-code */ BtcFormat frCoded = BtcFormat.getCodeInstance(Locale.FRANCE); assertEquals("0,01 µBTC", frCoded.format(1)); assertEquals("1,00 BTC", frCoded.format(COIN)); /* Insert needed space BEFORE currency-code: no known currency pattern does this? */ /* Do not insert unneeded space AFTER currency-code */ BtcFormat deCoded = BtcFormat.getCodeInstance(Locale.ITALY); assertEquals("µBTC 0,01", deCoded.format(1)); assertEquals("BTC 1,00", deCoded.format(COIN)); } @Test public void coinScaleTest() throws Exception { BtcFormat coinFormat = BtcFormat.getCoinInstance(Locale.US); assertEquals("1.00", coinFormat.format(Coin.COIN)); assertEquals("-1.00", coinFormat.format(Coin.COIN.negate())); assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1.00")); assertEquals(valueOf(1000000), coinFormat.parseObject("0.01")); assertEquals(Coin.parseCoin("1000"), coinFormat.parseObject("1,000.00")); assertEquals(Coin.parseCoin("1000"), coinFormat.parseObject("1000")); } @Test public void millicoinScaleTest() throws Exception { BtcFormat coinFormat = BtcFormat.getMilliInstance(Locale.US); assertEquals("1,000.00", coinFormat.format(Coin.COIN)); assertEquals("-1,000.00", coinFormat.format(Coin.COIN.negate())); assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1.00")); assertEquals(valueOf(1000), coinFormat.parseObject("0.01")); assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1,000.00")); assertEquals(Coin.parseCoin("1"), coinFormat.parseObject("1000")); } @Test public void microcoinScaleTest() throws Exception { BtcFormat coinFormat = BtcFormat.getMicroInstance(Locale.US); assertEquals("1,000,000.00", coinFormat.format(Coin.COIN)); assertEquals("-1,000,000.00", coinFormat.format(Coin.COIN.negate())); assertEquals("1,000,000.10", coinFormat.format(Coin.COIN.add(valueOf(10)))); assertEquals(Coin.parseCoin("0.000001"), coinFormat.parseObject("1.00")); assertEquals(valueOf(1), coinFormat.parseObject("0.01")); assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1,000.00")); assertEquals(Coin.parseCoin("0.001"), coinFormat.parseObject("1000")); } @Test public void testGrouping() throws Exception { BtcFormat usCoin = BtcFormat.getInstance(0, Locale.US, 1, 2, 3); assertEquals("0.1", usCoin.format(Coin.parseCoin("0.1"))); assertEquals("0.010", usCoin.format(Coin.parseCoin("0.01"))); assertEquals("0.001", usCoin.format(Coin.parseCoin("0.001"))); assertEquals("0.000100", usCoin.format(Coin.parseCoin("0.0001"))); assertEquals("0.000010", usCoin.format(Coin.parseCoin("0.00001"))); assertEquals("0.000001", usCoin.format(Coin.parseCoin("0.000001"))); // no more than two fractional decimal places for the default coin-denomination assertEquals("0.01", BtcFormat.getCoinInstance(Locale.US).format(Coin.parseCoin("0.005"))); BtcFormat usMilli = BtcFormat.getInstance(3, Locale.US, 1, 2, 3); assertEquals("0.1", usMilli.format(Coin.parseCoin("0.0001"))); assertEquals("0.010", usMilli.format(Coin.parseCoin("0.00001"))); assertEquals("0.001", usMilli.format(Coin.parseCoin("0.000001"))); // even though last group is 3, that would result in fractional satoshis, which we don't do assertEquals("0.00010", usMilli.format(Coin.valueOf(10))); assertEquals("0.00001", usMilli.format(Coin.valueOf(1))); BtcFormat usMicro = BtcFormat.getInstance(6, Locale.US, 1, 2, 3); assertEquals("0.1", usMicro.format(Coin.valueOf(10))); // even though second group is 2, that would result in fractional satoshis, which we don't do assertEquals("0.01", usMicro.format(Coin.valueOf(1))); } /* These just make sure factory methods don't raise exceptions. * Other tests inspect their return values. */ @Test public void factoryTest() { BtcFormat coded = BtcFormat.getInstance(0, 1, 2, 3); BtcFormat.getInstance(BtcAutoFormat.Style.CODE); BtcAutoFormat symbolic = (BtcAutoFormat)BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL); assertEquals(2, symbolic.fractionPlaces()); BtcFormat.getInstance(BtcAutoFormat.Style.CODE, 3); assertEquals(3, ((BtcAutoFormat)BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, 3)).fractionPlaces()); BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, Locale.US, 3); BtcFormat.getInstance(BtcAutoFormat.Style.CODE, Locale.US); BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL, Locale.US); BtcFormat.getCoinInstance(2, BtcFixedFormat.REPEATING_PLACES); BtcFormat.getMilliInstance(1, 2, 3); BtcFormat.getInstance(2); BtcFormat.getInstance(2, Locale.US); BtcFormat.getCodeInstance(3); BtcFormat.getSymbolInstance(3); BtcFormat.getCodeInstance(Locale.US, 3); BtcFormat.getSymbolInstance(Locale.US, 3); try { BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT + 1); fail("should not have constructed an instance with denomination less than satoshi"); } catch (IllegalArgumentException e) {} } @Test public void factoryArgumentsTest() { Locale locale; if (Locale.getDefault().equals(GERMANY)) locale = FRANCE; else locale = GERMANY; assertEquals(BtcFormat.getInstance(), BtcFormat.getCodeInstance()); assertEquals(BtcFormat.getInstance(locale), BtcFormat.getCodeInstance(locale)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE), BtcFormat.getCodeInstance()); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL), BtcFormat.getSymbolInstance()); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,3), BtcFormat.getCodeInstance(3)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,3), BtcFormat.getSymbolInstance(3)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,locale), BtcFormat.getCodeInstance(locale)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,locale), BtcFormat.getSymbolInstance(locale)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.CODE,locale,3), BtcFormat.getCodeInstance(locale,3)); assertEquals(BtcFormat.getInstance(BtcAutoFormat.Style.SYMBOL,locale,3), BtcFormat.getSymbolInstance(locale,3)); assertEquals(BtcFormat.getCoinInstance(), BtcFormat.getInstance(0)); assertEquals(BtcFormat.getMilliInstance(), BtcFormat.getInstance(3)); assertEquals(BtcFormat.getMicroInstance(), BtcFormat.getInstance(6)); assertEquals(BtcFormat.getCoinInstance(3), BtcFormat.getInstance(0,3)); assertEquals(BtcFormat.getMilliInstance(3), BtcFormat.getInstance(3,3)); assertEquals(BtcFormat.getMicroInstance(3), BtcFormat.getInstance(6,3)); assertEquals(BtcFormat.getCoinInstance(3,4,5), BtcFormat.getInstance(0,3,4,5)); assertEquals(BtcFormat.getMilliInstance(3,4,5), BtcFormat.getInstance(3,3,4,5)); assertEquals(BtcFormat.getMicroInstance(3,4,5), BtcFormat.getInstance(6,3,4,5)); assertEquals(BtcFormat.getCoinInstance(locale), BtcFormat.getInstance(0,locale)); assertEquals(BtcFormat.getMilliInstance(locale), BtcFormat.getInstance(3,locale)); assertEquals(BtcFormat.getMicroInstance(locale), BtcFormat.getInstance(6,locale)); assertEquals(BtcFormat.getCoinInstance(locale,4,5), BtcFormat.getInstance(0,locale,4,5)); assertEquals(BtcFormat.getMilliInstance(locale,4,5), BtcFormat.getInstance(3,locale,4,5)); assertEquals(BtcFormat.getMicroInstance(locale,4,5), BtcFormat.getInstance(6,locale,4,5)); } @Test public void autoDecimalTest() { BtcFormat codedZero = BtcFormat.getCodeInstance(Locale.US, 0); BtcFormat symbolZero = BtcFormat.getSymbolInstance(Locale.US, 0); assertEquals("฿1", symbolZero.format(COIN)); assertEquals("BTC 1", codedZero.format(COIN)); assertEquals("µ฿1,000,000", symbolZero.format(COIN.subtract(SATOSHI))); assertEquals("µBTC 1,000,000", codedZero.format(COIN.subtract(SATOSHI))); assertEquals("µ฿1,000,000", symbolZero.format(COIN.subtract(Coin.valueOf(50)))); assertEquals("µBTC 1,000,000", codedZero.format(COIN.subtract(Coin.valueOf(50)))); assertEquals("µ฿999,999", symbolZero.format(COIN.subtract(Coin.valueOf(51)))); assertEquals("µBTC 999,999", codedZero.format(COIN.subtract(Coin.valueOf(51)))); assertEquals("฿1,000", symbolZero.format(COIN.multiply(1000))); assertEquals("BTC 1,000", codedZero.format(COIN.multiply(1000))); assertEquals("µ฿1", symbolZero.format(Coin.valueOf(100))); assertEquals("µBTC 1", codedZero.format(Coin.valueOf(100))); assertEquals("µ฿1", symbolZero.format(Coin.valueOf(50))); assertEquals("µBTC 1", codedZero.format(Coin.valueOf(50))); assertEquals("µ฿0", symbolZero.format(Coin.valueOf(49))); assertEquals("µBTC 0", codedZero.format(Coin.valueOf(49))); assertEquals("µ฿0", symbolZero.format(Coin.valueOf(1))); assertEquals("µBTC 0", codedZero.format(Coin.valueOf(1))); assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(49999999))); assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(49999999))); assertEquals("µ฿499,500", symbolZero.format(Coin.valueOf(49950000))); assertEquals("µBTC 499,500", codedZero.format(Coin.valueOf(49950000))); assertEquals("µ฿499,500", symbolZero.format(Coin.valueOf(49949999))); assertEquals("µBTC 499,500", codedZero.format(Coin.valueOf(49949999))); assertEquals("µ฿500,490", symbolZero.format(Coin.valueOf(50049000))); assertEquals("µBTC 500,490", codedZero.format(Coin.valueOf(50049000))); assertEquals("µ฿500,490", symbolZero.format(Coin.valueOf(50049001))); assertEquals("µBTC 500,490", codedZero.format(Coin.valueOf(50049001))); assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(49999950))); assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(49999950))); assertEquals("µ฿499,999", symbolZero.format(Coin.valueOf(49999949))); assertEquals("µBTC 499,999", codedZero.format(Coin.valueOf(49999949))); assertEquals("µ฿500,000", symbolZero.format(Coin.valueOf(50000049))); assertEquals("µBTC 500,000", codedZero.format(Coin.valueOf(50000049))); assertEquals("µ฿500,001", symbolZero.format(Coin.valueOf(50000050))); assertEquals("µBTC 500,001", codedZero.format(Coin.valueOf(50000050))); BtcFormat codedTwo = BtcFormat.getCodeInstance(Locale.US, 2); BtcFormat symbolTwo = BtcFormat.getSymbolInstance(Locale.US, 2); assertEquals("฿1.00", symbolTwo.format(COIN)); assertEquals("BTC 1.00", codedTwo.format(COIN)); assertEquals("µ฿999,999.99", symbolTwo.format(COIN.subtract(SATOSHI))); assertEquals("µBTC 999,999.99", codedTwo.format(COIN.subtract(SATOSHI))); assertEquals("฿1,000.00", symbolTwo.format(COIN.multiply(1000))); assertEquals("BTC 1,000.00", codedTwo.format(COIN.multiply(1000))); assertEquals("µ฿1.00", symbolTwo.format(Coin.valueOf(100))); assertEquals("µBTC 1.00", codedTwo.format(Coin.valueOf(100))); assertEquals("µ฿0.50", symbolTwo.format(Coin.valueOf(50))); assertEquals("µBTC 0.50", codedTwo.format(Coin.valueOf(50))); assertEquals("µ฿0.49", symbolTwo.format(Coin.valueOf(49))); assertEquals("µBTC 0.49", codedTwo.format(Coin.valueOf(49))); assertEquals("µ฿0.01", symbolTwo.format(Coin.valueOf(1))); assertEquals("µBTC 0.01", codedTwo.format(Coin.valueOf(1))); BtcFormat codedThree = BtcFormat.getCodeInstance(Locale.US, 3); BtcFormat symbolThree = BtcFormat.getSymbolInstance(Locale.US, 3); assertEquals("฿1.000", symbolThree.format(COIN)); assertEquals("BTC 1.000", codedThree.format(COIN)); assertEquals("µ฿999,999.99", symbolThree.format(COIN.subtract(SATOSHI))); assertEquals("µBTC 999,999.99", codedThree.format(COIN.subtract(SATOSHI))); assertEquals("฿1,000.000", symbolThree.format(COIN.multiply(1000))); assertEquals("BTC 1,000.000", codedThree.format(COIN.multiply(1000))); assertEquals("₥฿0.001", symbolThree.format(Coin.valueOf(100))); assertEquals("mBTC 0.001", codedThree.format(Coin.valueOf(100))); assertEquals("µ฿0.50", symbolThree.format(Coin.valueOf(50))); assertEquals("µBTC 0.50", codedThree.format(Coin.valueOf(50))); assertEquals("µ฿0.49", symbolThree.format(Coin.valueOf(49))); assertEquals("µBTC 0.49", codedThree.format(Coin.valueOf(49))); assertEquals("µ฿0.01", symbolThree.format(Coin.valueOf(1))); assertEquals("µBTC 0.01", codedThree.format(Coin.valueOf(1))); } @Test public void symbolsCodesTest() { BtcFixedFormat coin = (BtcFixedFormat)BtcFormat.getCoinInstance(US); assertEquals("BTC", coin.code()); assertEquals("฿", coin.symbol()); BtcFixedFormat cent = (BtcFixedFormat)BtcFormat.getInstance(2, US); assertEquals("cBTC", cent.code()); assertEquals("¢฿", cent.symbol()); BtcFixedFormat milli = (BtcFixedFormat)BtcFormat.getInstance(3, US); assertEquals("mBTC", milli.code()); assertEquals("₥฿", milli.symbol()); BtcFixedFormat micro = (BtcFixedFormat)BtcFormat.getInstance(6, US); assertEquals("µBTC", micro.code()); assertEquals("µ฿", micro.symbol()); BtcFixedFormat deka = (BtcFixedFormat)BtcFormat.getInstance(-1, US); assertEquals("daBTC", deka.code()); assertEquals("da฿", deka.symbol()); BtcFixedFormat hecto = (BtcFixedFormat)BtcFormat.getInstance(-2, US); assertEquals("hBTC", hecto.code()); assertEquals("h฿", hecto.symbol()); BtcFixedFormat kilo = (BtcFixedFormat)BtcFormat.getInstance(-3, US); assertEquals("kBTC", kilo.code()); assertEquals("k฿", kilo.symbol()); BtcFixedFormat mega = (BtcFixedFormat)BtcFormat.getInstance(-6, US); assertEquals("MBTC", mega.code()); assertEquals("M฿", mega.symbol()); BtcFixedFormat noSymbol = (BtcFixedFormat)BtcFormat.getInstance(4, US); try { noSymbol.symbol(); fail("non-standard denomination has no symbol()"); } catch (IllegalStateException e) {} try { noSymbol.code(); fail("non-standard denomination has no code()"); } catch (IllegalStateException e) {} BtcFixedFormat symbolCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0). symbol("B\u20e6").build(); assertEquals("BTC", symbolCoin.code()); assertEquals("B⃦", symbolCoin.symbol()); BtcFixedFormat symbolCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2). symbol("B\u20e6").build(); assertEquals("cBTC", symbolCent.code()); assertEquals("¢B⃦", symbolCent.symbol()); BtcFixedFormat symbolMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3). symbol("B\u20e6").build(); assertEquals("mBTC", symbolMilli.code()); assertEquals("₥B⃦", symbolMilli.symbol()); BtcFixedFormat symbolMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6). symbol("B\u20e6").build(); assertEquals("µBTC", symbolMicro.code()); assertEquals("µB⃦", symbolMicro.symbol()); BtcFixedFormat symbolDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1). symbol("B\u20e6").build(); assertEquals("daBTC", symbolDeka.code()); assertEquals("daB⃦", symbolDeka.symbol()); BtcFixedFormat symbolHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2). symbol("B\u20e6").build(); assertEquals("hBTC", symbolHecto.code()); assertEquals("hB⃦", symbolHecto.symbol()); BtcFixedFormat symbolKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3). symbol("B\u20e6").build(); assertEquals("kBTC", symbolKilo.code()); assertEquals("kB⃦", symbolKilo.symbol()); BtcFixedFormat symbolMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6). symbol("B\u20e6").build(); assertEquals("MBTC", symbolMega.code()); assertEquals("MB⃦", symbolMega.symbol()); BtcFixedFormat codeCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0). code("XBT").build(); assertEquals("XBT", codeCoin.code()); assertEquals("฿", codeCoin.symbol()); BtcFixedFormat codeCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2). code("XBT").build(); assertEquals("cXBT", codeCent.code()); assertEquals("¢฿", codeCent.symbol()); BtcFixedFormat codeMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3). code("XBT").build(); assertEquals("mXBT", codeMilli.code()); assertEquals("₥฿", codeMilli.symbol()); BtcFixedFormat codeMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6). code("XBT").build(); assertEquals("µXBT", codeMicro.code()); assertEquals("µ฿", codeMicro.symbol()); BtcFixedFormat codeDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1). code("XBT").build(); assertEquals("daXBT", codeDeka.code()); assertEquals("da฿", codeDeka.symbol()); BtcFixedFormat codeHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2). code("XBT").build(); assertEquals("hXBT", codeHecto.code()); assertEquals("h฿", codeHecto.symbol()); BtcFixedFormat codeKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3). code("XBT").build(); assertEquals("kXBT", codeKilo.code()); assertEquals("k฿", codeKilo.symbol()); BtcFixedFormat codeMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6). code("XBT").build(); assertEquals("MXBT", codeMega.code()); assertEquals("M฿", codeMega.symbol()); BtcFixedFormat symbolCodeCoin = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(0). symbol("B\u20e6").code("XBT").build(); assertEquals("XBT", symbolCodeCoin.code()); assertEquals("B⃦", symbolCodeCoin.symbol()); BtcFixedFormat symbolCodeCent = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(2). symbol("B\u20e6").code("XBT").build(); assertEquals("cXBT", symbolCodeCent.code()); assertEquals("¢B⃦", symbolCodeCent.symbol()); BtcFixedFormat symbolCodeMilli = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(3). symbol("B\u20e6").code("XBT").build(); assertEquals("mXBT", symbolCodeMilli.code()); assertEquals("₥B⃦", symbolCodeMilli.symbol()); BtcFixedFormat symbolCodeMicro = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(6). symbol("B\u20e6").code("XBT").build(); assertEquals("µXBT", symbolCodeMicro.code()); assertEquals("µB⃦", symbolCodeMicro.symbol()); BtcFixedFormat symbolCodeDeka = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-1). symbol("B\u20e6").code("XBT").build(); assertEquals("daXBT", symbolCodeDeka.code()); assertEquals("daB⃦", symbolCodeDeka.symbol()); BtcFixedFormat symbolCodeHecto = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-2). symbol("B\u20e6").code("XBT").build(); assertEquals("hXBT", symbolCodeHecto.code()); assertEquals("hB⃦", symbolCodeHecto.symbol()); BtcFixedFormat symbolCodeKilo = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-3). symbol("B\u20e6").code("XBT").build(); assertEquals("kXBT", symbolCodeKilo.code()); assertEquals("kB⃦", symbolCodeKilo.symbol()); BtcFixedFormat symbolCodeMega = (BtcFixedFormat)BtcFormat.builder().locale(US).scale(-6). symbol("B\u20e6").code("XBT").build(); assertEquals("MXBT", symbolCodeMega.code()); assertEquals("MB⃦", symbolCodeMega.symbol()); } /* copied from CoinFormatTest.java and modified */ @Test public void parse() throws Exception { BtcFormat coin = BtcFormat.getCoinInstance(Locale.US); assertEquals(Coin.COIN, coin.parseObject("1")); assertEquals(Coin.COIN, coin.parseObject("1.")); assertEquals(Coin.COIN, coin.parseObject("1.0")); assertEquals(Coin.COIN, BtcFormat.getCoinInstance(Locale.GERMANY).parseObject("1,0")); assertEquals(Coin.COIN, coin.parseObject("01.0000000000")); // TODO work with express positive sign // assertEquals(Coin.COIN, coin.parseObject("+1.0")); assertEquals(Coin.COIN.negate(), coin.parseObject("-1")); assertEquals(Coin.COIN.negate(), coin.parseObject("-1.0")); assertEquals(Coin.CENT, coin.parseObject(".01")); BtcFormat milli = BtcFormat.getMilliInstance(Locale.US); assertEquals(Coin.MILLICOIN, milli.parseObject("1")); assertEquals(Coin.MILLICOIN, milli.parseObject("1.0")); assertEquals(Coin.MILLICOIN, milli.parseObject("01.0000000000")); // TODO work with express positive sign //assertEquals(Coin.MILLICOIN, milli.parseObject("+1.0")); assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1")); assertEquals(Coin.MILLICOIN.negate(), milli.parseObject("-1.0")); BtcFormat micro = BtcFormat.getMicroInstance(Locale.US); assertEquals(Coin.MICROCOIN, micro.parseObject("1")); assertEquals(Coin.MICROCOIN, micro.parseObject("1.0")); assertEquals(Coin.MICROCOIN, micro.parseObject("01.0000000000")); // TODO work with express positive sign // assertEquals(Coin.MICROCOIN, micro.parseObject("+1.0")); assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1")); assertEquals(Coin.MICROCOIN.negate(), micro.parseObject("-1.0")); } /* Copied (and modified) from CoinFormatTest.java */ @Test public void btcRounding() throws Exception { BtcFormat coinFormat = BtcFormat.getCoinInstance(Locale.US); assertEquals("0", BtcFormat.getCoinInstance(Locale.US, 0).format(ZERO)); assertEquals("0", coinFormat.format(ZERO, 0)); assertEquals("0.00", BtcFormat.getCoinInstance(Locale.US, 2).format(ZERO)); assertEquals("0.00", coinFormat.format(ZERO, 2)); assertEquals("1", BtcFormat.getCoinInstance(Locale.US, 0).format(COIN)); assertEquals("1", coinFormat.format(COIN, 0)); assertEquals("1.0", BtcFormat.getCoinInstance(Locale.US, 1).format(COIN)); assertEquals("1.0", coinFormat.format(COIN, 1)); assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2).format(COIN)); assertEquals("1.00", coinFormat.format(COIN, 2, 2)); assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2, 2).format(COIN)); assertEquals("1.00", coinFormat.format(COIN, 2, 2, 2)); assertEquals("1.00", BtcFormat.getCoinInstance(Locale.US, 2, 2, 2, 2).format(COIN)); assertEquals("1.00", coinFormat.format(COIN, 2, 2, 2, 2)); assertEquals("1.000", BtcFormat.getCoinInstance(Locale.US, 3).format(COIN)); assertEquals("1.000", coinFormat.format(COIN, 3)); assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(COIN)); assertEquals("1.0000", coinFormat.format(COIN, 4)); final Coin justNot = COIN.subtract(SATOSHI); assertEquals("1", BtcFormat.getCoinInstance(US, 0).format(justNot)); assertEquals("1", coinFormat.format(justNot, 0)); assertEquals("1.0", BtcFormat.getCoinInstance(US, 1).format(justNot)); assertEquals("1.0", coinFormat.format(justNot, 1)); final Coin justNotUnder = Coin.valueOf(99995000); assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(justNot)); assertEquals("1.00", coinFormat.format(justNot, 2, 2)); assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(justNotUnder)); assertEquals("1.00", coinFormat.format(justNotUnder, 2, 2)); assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2, 2).format(justNot)); assertEquals("1.00", coinFormat.format(justNot, 2, 2, 2)); assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, 2, 2).format(justNotUnder)); assertEquals("0.999950", coinFormat.format(justNotUnder, 2, 2, 2)); assertEquals("0.99999999", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(justNot)); assertEquals("0.99999999", coinFormat.format(justNot, 2, 2, 2, 2)); assertEquals("0.99999999", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(justNot)); assertEquals("0.99999999", coinFormat.format(justNot, 2, REPEATING_DOUBLETS)); assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(justNotUnder)); assertEquals("0.999950", coinFormat.format(justNotUnder, 2, 2, 2, 2)); assertEquals("0.999950", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(justNotUnder)); assertEquals("0.999950", coinFormat.format(justNotUnder, 2, REPEATING_DOUBLETS)); assertEquals("1.000", BtcFormat.getCoinInstance(US, 3).format(justNot)); assertEquals("1.000", coinFormat.format(justNot, 3)); assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(justNot)); assertEquals("1.0000", coinFormat.format(justNot, 4)); final Coin slightlyMore = COIN.add(SATOSHI); assertEquals("1", BtcFormat.getCoinInstance(US, 0).format(slightlyMore)); assertEquals("1", coinFormat.format(slightlyMore, 0)); assertEquals("1.0", BtcFormat.getCoinInstance(US, 1).format(slightlyMore)); assertEquals("1.0", coinFormat.format(slightlyMore, 1)); assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2).format(slightlyMore)); assertEquals("1.00", coinFormat.format(slightlyMore, 2, 2)); assertEquals("1.00", BtcFormat.getCoinInstance(US, 2, 2, 2).format(slightlyMore)); assertEquals("1.00", coinFormat.format(slightlyMore, 2, 2, 2)); assertEquals("1.00000001", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(slightlyMore)); assertEquals("1.00000001", coinFormat.format(slightlyMore, 2, 2, 2, 2)); assertEquals("1.00000001", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(slightlyMore)); assertEquals("1.00000001", coinFormat.format(slightlyMore, 2, REPEATING_DOUBLETS)); assertEquals("1.000", BtcFormat.getCoinInstance(US, 3).format(slightlyMore)); assertEquals("1.000", coinFormat.format(slightlyMore, 3)); assertEquals("1.0000", BtcFormat.getCoinInstance(US, 4).format(slightlyMore)); assertEquals("1.0000", coinFormat.format(slightlyMore, 4)); final Coin pivot = COIN.add(SATOSHI.multiply(5)); assertEquals("1.00000005", BtcFormat.getCoinInstance(US, 8).format(pivot)); assertEquals("1.00000005", coinFormat.format(pivot, 8)); assertEquals("1.00000005", BtcFormat.getCoinInstance(US, 7, 1).format(pivot)); assertEquals("1.00000005", coinFormat.format(pivot, 7, 1)); assertEquals("1.0000001", BtcFormat.getCoinInstance(US, 7).format(pivot)); assertEquals("1.0000001", coinFormat.format(pivot, 7)); final Coin value = Coin.valueOf(1122334455667788l); assertEquals("11,223,345", BtcFormat.getCoinInstance(US, 0).format(value)); assertEquals("11,223,345", coinFormat.format(value, 0)); assertEquals("11,223,344.6", BtcFormat.getCoinInstance(US, 1).format(value)); assertEquals("11,223,344.6", coinFormat.format(value, 1)); assertEquals("11,223,344.5567", BtcFormat.getCoinInstance(US, 2, 2).format(value)); assertEquals("11,223,344.5567", coinFormat.format(value, 2, 2)); assertEquals("11,223,344.556678", BtcFormat.getCoinInstance(US, 2, 2, 2).format(value)); assertEquals("11,223,344.556678", coinFormat.format(value, 2, 2, 2)); assertEquals("11,223,344.55667788", BtcFormat.getCoinInstance(US, 2, 2, 2, 2).format(value)); assertEquals("11,223,344.55667788", coinFormat.format(value, 2, 2, 2, 2)); assertEquals("11,223,344.55667788", BtcFormat.getCoinInstance(US, 2, REPEATING_DOUBLETS).format(value)); assertEquals("11,223,344.55667788", coinFormat.format(value, 2, REPEATING_DOUBLETS)); assertEquals("11,223,344.557", BtcFormat.getCoinInstance(US, 3).format(value)); assertEquals("11,223,344.557", coinFormat.format(value, 3)); assertEquals("11,223,344.5567", BtcFormat.getCoinInstance(US, 4).format(value)); assertEquals("11,223,344.5567", coinFormat.format(value, 4)); BtcFormat megaFormat = BtcFormat.getInstance(-6, US); assertEquals("21.00", megaFormat.format(MAX_MONEY)); assertEquals("21", megaFormat.format(MAX_MONEY, 0)); assertEquals("11.22334455667788", megaFormat.format(value, 0, REPEATING_DOUBLETS)); assertEquals("11.223344556677", megaFormat.format(Coin.valueOf(1122334455667700l), 0, REPEATING_DOUBLETS)); assertEquals("11.22334455667788", megaFormat.format(value, 0, REPEATING_TRIPLETS)); assertEquals("11.223344556677", megaFormat.format(Coin.valueOf(1122334455667700l), 0, REPEATING_TRIPLETS)); } @Ignore("non-determinism between OpenJDK versions") @Test public void negativeTest() throws Exception { assertEquals("-1,00 BTC", BtcFormat.getInstance(FRANCE).format(COIN.multiply(-1))); assertEquals("BTC -1,00", BtcFormat.getInstance(ITALY).format(COIN.multiply(-1))); assertEquals("฿ -1,00", BtcFormat.getSymbolInstance(ITALY).format(COIN.multiply(-1))); assertEquals("BTC -1.00", BtcFormat.getInstance(JAPAN).format(COIN.multiply(-1))); assertEquals("฿-1.00", BtcFormat.getSymbolInstance(JAPAN).format(COIN.multiply(-1))); assertEquals("(BTC 1.00)", BtcFormat.getInstance(US).format(COIN.multiply(-1))); assertEquals("(฿1.00)", BtcFormat.getSymbolInstance(US).format(COIN.multiply(-1))); // assertEquals("BTC -१.००", BtcFormat.getInstance(Locale.forLanguageTag("hi-IN")).format(COIN.multiply(-1))); assertEquals("BTC -๑.๐๐", BtcFormat.getInstance(new Locale("th","TH","TH")).format(COIN.multiply(-1))); assertEquals("Ƀ-๑.๐๐", BtcFormat.getSymbolInstance(new Locale("th","TH","TH")).format(COIN.multiply(-1))); } /* Warning: these tests assume the state of Locale data extant on the platform on which * they were written: openjdk 7u21-2.3.9-5 */ @Test public void equalityTest() throws Exception { // First, autodenominator assertEquals(BtcFormat.getInstance(), BtcFormat.getInstance()); assertEquals(BtcFormat.getInstance().hashCode(), BtcFormat.getInstance().hashCode()); assertNotEquals(BtcFormat.getCodeInstance(), BtcFormat.getSymbolInstance()); assertNotEquals(BtcFormat.getCodeInstance().hashCode(), BtcFormat.getSymbolInstance().hashCode()); assertEquals(BtcFormat.getSymbolInstance(5), BtcFormat.getSymbolInstance(5)); assertEquals(BtcFormat.getSymbolInstance(5).hashCode(), BtcFormat.getSymbolInstance(5).hashCode()); assertNotEquals(BtcFormat.getSymbolInstance(5), BtcFormat.getSymbolInstance(4)); assertNotEquals(BtcFormat.getSymbolInstance(5).hashCode(), BtcFormat.getSymbolInstance(4).hashCode()); /* The underlying formatter is mutable, and its currency code * and symbol may be reset each time a number is * formatted or parsed. Here we check to make sure that state is * ignored when comparing for equality */ // when formatting BtcAutoFormat a = (BtcAutoFormat)BtcFormat.getSymbolInstance(US); BtcAutoFormat b = (BtcAutoFormat)BtcFormat.getSymbolInstance(US); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); a.format(COIN.multiply(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); b.format(COIN.divide(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); // when parsing a = (BtcAutoFormat)BtcFormat.getSymbolInstance(US); b = (BtcAutoFormat)BtcFormat.getSymbolInstance(US); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); a.parseObject("mBTC2"); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); b.parseObject("µ฿4.35"); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); // FRANCE and GERMANY have different pattterns assertNotEquals(BtcFormat.getInstance(FRANCE).hashCode(), BtcFormat.getInstance(GERMANY).hashCode()); // TAIWAN and CHINA differ only in the Locale and Currency, i.e. the patterns and symbols are // all the same (after setting the currency symbols to bitcoins) assertNotEquals(BtcFormat.getInstance(TAIWAN), BtcFormat.getInstance(CHINA)); // but they hash the same because of the DecimalFormatSymbols.hashCode() implementation assertEquals(BtcFormat.getSymbolInstance(4), BtcFormat.getSymbolInstance(4)); assertEquals(BtcFormat.getSymbolInstance(4).hashCode(), BtcFormat.getSymbolInstance(4).hashCode()); assertNotEquals(BtcFormat.getSymbolInstance(4), BtcFormat.getSymbolInstance(5)); assertNotEquals(BtcFormat.getSymbolInstance(4).hashCode(), BtcFormat.getSymbolInstance(5).hashCode()); // Fixed-denomination assertEquals(BtcFormat.getCoinInstance(), BtcFormat.getCoinInstance()); assertEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getCoinInstance().hashCode()); assertEquals(BtcFormat.getMilliInstance(), BtcFormat.getMilliInstance()); assertEquals(BtcFormat.getMilliInstance().hashCode(), BtcFormat.getMilliInstance().hashCode()); assertEquals(BtcFormat.getMicroInstance(), BtcFormat.getMicroInstance()); assertEquals(BtcFormat.getMicroInstance().hashCode(), BtcFormat.getMicroInstance().hashCode()); assertEquals(BtcFormat.getInstance(-6), BtcFormat.getInstance(-6)); assertEquals(BtcFormat.getInstance(-6).hashCode(), BtcFormat.getInstance(-6).hashCode()); assertNotEquals(BtcFormat.getCoinInstance(), BtcFormat.getMilliInstance()); assertNotEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getMilliInstance().hashCode()); assertNotEquals(BtcFormat.getCoinInstance(), BtcFormat.getMicroInstance()); assertNotEquals(BtcFormat.getCoinInstance().hashCode(), BtcFormat.getMicroInstance().hashCode()); assertNotEquals(BtcFormat.getMilliInstance(), BtcFormat.getMicroInstance()); assertNotEquals(BtcFormat.getMilliInstance().hashCode(), BtcFormat.getMicroInstance().hashCode()); assertNotEquals(BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT), BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT - 1)); assertNotEquals(BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT).hashCode(), BtcFormat.getInstance(SMALLEST_UNIT_EXPONENT - 1).hashCode()); assertNotEquals(BtcFormat.getCoinInstance(TAIWAN), BtcFormat.getCoinInstance(CHINA)); assertNotEquals(BtcFormat.getCoinInstance(2,3), BtcFormat.getCoinInstance(2,4)); assertNotEquals(BtcFormat.getCoinInstance(2,3).hashCode(), BtcFormat.getCoinInstance(2,4).hashCode()); assertNotEquals(BtcFormat.getCoinInstance(2,3), BtcFormat.getCoinInstance(2,3,3)); assertNotEquals(BtcFormat.getCoinInstance(2,3).hashCode(), BtcFormat.getCoinInstance(2,3,3).hashCode()); } @Ignore("non-determinism between OpenJDK versions") @Test public void attributeTest() throws Exception { String codePat = BtcFormat.getCodeInstance(Locale.US).pattern(); assertTrue(codePat.contains("BTC") && ! codePat.contains("(^|[^฿])฿([^฿]|$)") && ! codePat.contains("(^|[^¤])¤([^¤]|$)")); String symPat = BtcFormat.getSymbolInstance(Locale.US).pattern(); assertTrue(symPat.contains("฿") && !symPat.contains("BTC") && !symPat.contains("¤¤")); assertEquals("BTC #,##0.00;(BTC #,##0.00)", BtcFormat.getCodeInstance(Locale.US).pattern()); assertEquals("฿#,##0.00;(฿#,##0.00)", BtcFormat.getSymbolInstance(Locale.US).pattern()); assertEquals('0', BtcFormat.getInstance(Locale.US).symbols().getZeroDigit()); // assertEquals('०', BtcFormat.getInstance(Locale.forLanguageTag("hi-IN")).symbols().getZeroDigit()); // TODO will this next line work with other JREs? assertEquals('๐', BtcFormat.getInstance(new Locale("th","TH","TH")).symbols().getZeroDigit()); } @Ignore("non-determinism between OpenJDK versions") @Test public void toStringTest() { assertEquals("Auto-format ฿#,##0.00;(฿#,##0.00)", BtcFormat.getSymbolInstance(Locale.US).toString()); assertEquals("Auto-format ฿#,##0.0000;(฿#,##0.0000)", BtcFormat.getSymbolInstance(Locale.US, 4).toString()); assertEquals("Auto-format BTC #,##0.00;(BTC #,##0.00)", BtcFormat.getCodeInstance(Locale.US).toString()); assertEquals("Auto-format BTC #,##0.0000;(BTC #,##0.0000)", BtcFormat.getCodeInstance(Locale.US, 4).toString()); assertEquals("Coin-format #,##0.00", BtcFormat.getCoinInstance(Locale.US).toString()); assertEquals("Millicoin-format #,##0.00", BtcFormat.getMilliInstance(Locale.US).toString()); assertEquals("Microcoin-format #,##0.00", BtcFormat.getMicroInstance(Locale.US).toString()); assertEquals("Coin-format #,##0.000", BtcFormat.getCoinInstance(Locale.US,3).toString()); assertEquals("Coin-format #,##0.000(####)(#######)", BtcFormat.getCoinInstance(Locale.US,3,4,7).toString()); assertEquals("Kilocoin-format #,##0.000", BtcFormat.getInstance(-3,Locale.US,3).toString()); assertEquals("Kilocoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-3,Locale.US,3,4,7).toString()); assertEquals("Decicoin-format #,##0.000", BtcFormat.getInstance(1,Locale.US,3).toString()); assertEquals("Decicoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(1,Locale.US,3,4,7).toString()); assertEquals("Dekacoin-format #,##0.000", BtcFormat.getInstance(-1,Locale.US,3).toString()); assertEquals("Dekacoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-1,Locale.US,3,4,7).toString()); assertEquals("Hectocoin-format #,##0.000", BtcFormat.getInstance(-2,Locale.US,3).toString()); assertEquals("Hectocoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-2,Locale.US,3,4,7).toString()); assertEquals("Megacoin-format #,##0.000", BtcFormat.getInstance(-6,Locale.US,3).toString()); assertEquals("Megacoin-format #,##0.000(####)(#######)", BtcFormat.getInstance(-6,Locale.US,3,4,7).toString()); assertEquals("Fixed (-4) format #,##0.000", BtcFormat.getInstance(-4,Locale.US,3).toString()); assertEquals("Fixed (-4) format #,##0.000(####)", BtcFormat.getInstance(-4,Locale.US,3,4).toString()); assertEquals("Fixed (-4) format #,##0.000(####)(#######)", BtcFormat.getInstance(-4, Locale.US, 3, 4, 7).toString()); assertEquals("Auto-format ฿#,##0.00;(฿#,##0.00)", BtcFormat.builder().style(SYMBOL).code("USD").locale(US).build().toString()); assertEquals("Auto-format #.##0,00 $", BtcFormat.builder().style(SYMBOL).symbol("$").locale(GERMANY).build().toString()); assertEquals("Auto-format #.##0,0000 $", BtcFormat.builder().style(SYMBOL).symbol("$").fractionDigits(4).locale(GERMANY).build().toString()); assertEquals("Auto-format BTC#,00฿;BTC-#,00฿", BtcFormat.builder().style(SYMBOL).locale(GERMANY).pattern("¤¤#¤").build().toString()); assertEquals("Coin-format BTC#,00฿;BTC-#,00฿", BtcFormat.builder().scale(0).locale(GERMANY).pattern("¤¤#¤").build().toString()); assertEquals("Millicoin-format BTC#.00฿;BTC-#.00฿", BtcFormat.builder().scale(3).locale(US).pattern("¤¤#¤").build().toString()); } @Test public void patternDecimalPlaces() { /* The pattern format provided by DecimalFormat includes specification of fractional digits, * but we ignore that because we have alternative mechanism for specifying that.. */ BtcFormat f = BtcFormat.builder().locale(US).scale(3).pattern("¤¤ #.0").fractionDigits(3).build(); assertEquals("Millicoin-format BTC #.000;BTC -#.000", f.toString()); assertEquals("mBTC 1000.000", f.format(COIN)); } @Ignore("non-determinism between OpenJDK versions") @Test public void builderTest() { Locale locale; if (Locale.getDefault().equals(GERMANY)) locale = FRANCE; else locale = GERMANY; assertEquals(BtcFormat.builder().build(), BtcFormat.getCoinInstance()); try { BtcFormat.builder().scale(0).style(CODE); fail("Invoking both scale() and style() on a Builder should raise exception"); } catch (IllegalStateException e) {} try { BtcFormat.builder().style(CODE).scale(0); fail("Invoking both style() and scale() on a Builder should raise exception"); } catch (IllegalStateException e) {} BtcFormat built = BtcFormat.builder().style(BtcAutoFormat.Style.CODE).fractionDigits(4).build(); assertEquals(built, BtcFormat.getCodeInstance(4)); built = BtcFormat.builder().style(BtcAutoFormat.Style.SYMBOL).fractionDigits(4).build(); assertEquals(built, BtcFormat.getSymbolInstance(4)); built = BtcFormat.builder().scale(0).build(); assertEquals(built, BtcFormat.getCoinInstance()); built = BtcFormat.builder().scale(3).build(); assertEquals(built, BtcFormat.getMilliInstance()); built = BtcFormat.builder().scale(6).build(); assertEquals(built, BtcFormat.getMicroInstance()); built = BtcFormat.builder().locale(locale).scale(0).build(); assertEquals(built, BtcFormat.getCoinInstance(locale)); built = BtcFormat.builder().locale(locale).scale(3).build(); assertEquals(built, BtcFormat.getMilliInstance(locale)); built = BtcFormat.builder().locale(locale).scale(6).build(); assertEquals(built, BtcFormat.getMicroInstance(locale)); built = BtcFormat.builder().minimumFractionDigits(3).scale(0).build(); assertEquals(built, BtcFormat.getCoinInstance(3)); built = BtcFormat.builder().minimumFractionDigits(3).scale(3).build(); assertEquals(built, BtcFormat.getMilliInstance(3)); built = BtcFormat.builder().minimumFractionDigits(3).scale(6).build(); assertEquals(built, BtcFormat.getMicroInstance(3)); built = BtcFormat.builder().fractionGroups(3,4).scale(0).build(); assertEquals(built, BtcFormat.getCoinInstance(2,3,4)); built = BtcFormat.builder().fractionGroups(3,4).scale(3).build(); assertEquals(built, BtcFormat.getMilliInstance(2,3,4)); built = BtcFormat.builder().fractionGroups(3,4).scale(6).build(); assertEquals(built, BtcFormat.getMicroInstance(2,3,4)); built = BtcFormat.builder().pattern("#,####.#").scale(6).locale(GERMANY).build(); assertEquals("100.0000,00", built.format(COIN)); built = BtcFormat.builder().pattern("#,####.#").scale(6).locale(GERMANY).build(); assertEquals("-100.0000,00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().localizedPattern("#.####,#").scale(6).locale(GERMANY).build(); assertEquals("100.0000,00", built.format(COIN)); built = BtcFormat.builder().pattern("¤#,####.#").style(CODE).locale(GERMANY).build(); assertEquals("฿-1,00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("¤¤ #,####.#").style(SYMBOL).locale(GERMANY).build(); assertEquals("BTC -1,00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("¤¤##,###.#").scale(3).locale(US).build(); assertEquals("mBTC1,000.00", built.format(COIN)); built = BtcFormat.builder().pattern("¤ ##,###.#").scale(3).locale(US).build(); assertEquals("₥฿ 1,000.00", built.format(COIN)); try { BtcFormat.builder().pattern("¤¤##,###.#").scale(4).locale(US).build().format(COIN); fail("Pattern with currency sign and non-standard denomination should raise exception"); } catch (IllegalStateException e) {} try { BtcFormat.builder().localizedPattern("¤¤##,###.#").scale(4).locale(US).build().format(COIN); fail("Localized pattern with currency sign and non-standard denomination should raise exception"); } catch (IllegalStateException e) {} built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build(); assertEquals("B⃦1.00", built.format(COIN)); built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build(); assertEquals("XBT 1.00", built.format(COIN)); built = BtcFormat.builder().style(SYMBOL).symbol("$").locale(GERMANY).build(); assertEquals("1,00 $", built.format(COIN)); // Setting the currency code on a DecimalFormatSymbols object can affect the currency symbol. built = BtcFormat.builder().style(SYMBOL).code("USD").locale(US).build(); assertEquals("฿1.00", built.format(COIN)); built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build(); assertEquals("₥B⃦1.00", built.format(COIN.divide(1000))); built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build(); assertEquals("mXBT 1.00", built.format(COIN.divide(1000))); built = BtcFormat.builder().style(SYMBOL).symbol("B\u20e6").locale(US).build(); assertEquals("µB⃦1.00", built.format(valueOf(100))); built = BtcFormat.builder().style(CODE).code("XBT").locale(US).build(); assertEquals("µXBT 1.00", built.format(valueOf(100))); /* The prefix of a pattern can have number symbols in quotes. * Make sure our custom negative-subpattern creator handles this. */ built = BtcFormat.builder().pattern("'#'¤#0").scale(0).locale(US).build(); assertEquals("#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("'#0'¤#0").scale(0).locale(US).build(); assertEquals("#0฿-1.00", built.format(COIN.multiply(-1))); // this is an escaped quote between two hash marks in one set of quotes, not // two adjacent quote-enclosed hash-marks: built = BtcFormat.builder().pattern("'#''#'¤#0").scale(0).locale(US).build(); assertEquals("#'#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("'#0''#'¤#0").scale(0).locale(US).build(); assertEquals("#0'#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("'#0#'¤#0").scale(0).locale(US).build(); assertEquals("#0#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("'#0'E'#'¤#0").scale(0).locale(US).build(); assertEquals("#0E#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("E'#0''#'¤#0").scale(0).locale(US).build(); assertEquals("E#0'#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("E'#0#'¤#0").scale(0).locale(US).build(); assertEquals("E#0#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("E'#0''''#'¤#0").scale(0).locale(US).build(); assertEquals("E#0''#฿-1.00", built.format(COIN.multiply(-1))); built = BtcFormat.builder().pattern("''#0").scale(0).locale(US).build(); assertEquals("'-1.00", built.format(COIN.multiply(-1))); // immutability check for fixed-denomination formatters, w/ & w/o custom pattern BtcFormat a = BtcFormat.builder().scale(3).build(); BtcFormat b = BtcFormat.builder().scale(3).build(); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); a.format(COIN.multiply(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); b.format(COIN.divide(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); a = BtcFormat.builder().scale(3).pattern("¤#.#").build(); b = BtcFormat.builder().scale(3).pattern("¤#.#").build(); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); a.format(COIN.multiply(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); b.format(COIN.divide(1000000)); assertEquals(a, b); assertEquals(a.hashCode(), b.hashCode()); } }
kmels/bitcoinj
core/src/test/java/org/bitcoinj/utils/BtcFormatTest.java
Java
apache-2.0
90,631
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch 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.elasticsearch.ttl; import org.elasticsearch.Version; import org.elasticsearch.action.DocWriteResponse; import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse; import org.elasticsearch.action.admin.indices.mapping.put.PutMappingResponse; import org.elasticsearch.action.admin.indices.stats.IndicesStatsResponse; import org.elasticsearch.action.get.GetResponse; import org.elasticsearch.action.index.IndexResponse; import org.elasticsearch.action.update.UpdateRequestBuilder; import org.elasticsearch.action.update.UpdateResponse; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.test.ESIntegTestCase; import org.elasticsearch.test.InternalSettingsPlugin; import org.elasticsearch.test.ESIntegTestCase.ClusterScope; import org.elasticsearch.test.ESIntegTestCase.Scope; import java.io.IOException; import java.util.Collection; import java.util.Collections; import java.util.Locale; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.elasticsearch.action.support.WriteRequest.RefreshPolicy.IMMEDIATE; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.both; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.greaterThan; import static org.hamcrest.Matchers.hasKey; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.lessThanOrEqualTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; @ClusterScope(scope= Scope.SUITE, supportsDedicatedMasters = false, numDataNodes = 1) public class SimpleTTLIT extends ESIntegTestCase { private static final long PURGE_INTERVAL = 200; @Override protected int numberOfShards() { return 2; } @Override protected Collection<Class<? extends Plugin>> nodePlugins() { return Collections.singleton(InternalSettingsPlugin.class); } @Override protected Settings nodeSettings(int nodeOrdinal) { return Settings.builder() .put(super.nodeSettings(nodeOrdinal)) .put("indices.ttl.interval", PURGE_INTERVAL, TimeUnit.MILLISECONDS) .build(); } public void testSimpleTTL() throws Exception { assertAcked(prepareCreate("test") .setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id) .addMapping("type1", XContentFactory.jsonBuilder() .startObject() .startObject("type1") .startObject("_timestamp").field("enabled", true).endObject() .startObject("_ttl").field("enabled", true).endObject() .endObject() .endObject()) .addMapping("type2", XContentFactory.jsonBuilder() .startObject() .startObject("type2") .startObject("_timestamp").field("enabled", true).endObject() .startObject("_ttl").field("enabled", true).field("default", "1d").endObject() .endObject() .endObject())); final NumShards test = getNumShards("test"); long providedTTLValue = 3000; logger.info("--> checking ttl"); // Index one doc without routing, one doc with routing, one doc with not TTL and no default and one doc with default TTL long now = System.currentTimeMillis(); IndexResponse indexResponse = client().prepareIndex("test", "type1", "1").setSource("field1", "value1") .setTimestamp(String.valueOf(now)).setTTL(providedTTLValue).setRefreshPolicy(IMMEDIATE).get(); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); indexResponse = client().prepareIndex("test", "type1", "with_routing").setSource("field1", "value1") .setTimestamp(String.valueOf(now)).setTTL(providedTTLValue).setRouting("routing").setRefreshPolicy(IMMEDIATE).get(); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); indexResponse = client().prepareIndex("test", "type1", "no_ttl").setSource("field1", "value1").get(); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); indexResponse = client().prepareIndex("test", "type2", "default_ttl").setSource("field1", "value1").get(); assertEquals(DocWriteResponse.Result.CREATED, indexResponse.getResult()); // realtime get check long currentTime = System.currentTimeMillis(); GetResponse getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").get(); long ttl0; if (getResponse.isExists()) { ttl0 = ((Number) getResponse.getField("_ttl").getValue()).longValue(); assertThat(ttl0, lessThanOrEqualTo(providedTTLValue - (currentTime - now))); } else { assertThat(providedTTLValue - (currentTime - now), lessThanOrEqualTo(0L)); } // verify the ttl is still decreasing when going to the replica currentTime = System.currentTimeMillis(); getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").get(); if (getResponse.isExists()) { ttl0 = ((Number) getResponse.getField("_ttl").getValue()).longValue(); assertThat(ttl0, lessThanOrEqualTo(providedTTLValue - (currentTime - now))); } else { assertThat(providedTTLValue - (currentTime - now), lessThanOrEqualTo(0L)); } // non realtime get (stored) currentTime = System.currentTimeMillis(); getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(false).get(); if (getResponse.isExists()) { ttl0 = ((Number) getResponse.getField("_ttl").getValue()).longValue(); assertThat(ttl0, lessThanOrEqualTo(providedTTLValue - (currentTime - now))); } else { assertThat(providedTTLValue - (currentTime - now), lessThanOrEqualTo(0L)); } // non realtime get going the replica currentTime = System.currentTimeMillis(); getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(false).get(); if (getResponse.isExists()) { ttl0 = ((Number) getResponse.getField("_ttl").getValue()).longValue(); assertThat(ttl0, lessThanOrEqualTo(providedTTLValue - (currentTime - now))); } else { assertThat(providedTTLValue - (currentTime - now), lessThanOrEqualTo(0L)); } // no TTL provided so no TTL fetched getResponse = client().prepareGet("test", "type1", "no_ttl").setFields("_ttl").setRealtime(true).execute().actionGet(); assertThat(getResponse.getField("_ttl"), nullValue()); // no TTL provided make sure it has default TTL getResponse = client().prepareGet("test", "type2", "default_ttl").setFields("_ttl").setRealtime(true).execute().actionGet(); ttl0 = ((Number) getResponse.getField("_ttl").getValue()).longValue(); assertThat(ttl0, greaterThan(0L)); IndicesStatsResponse response = client().admin().indices().prepareStats("test").clear().setIndexing(true).get(); assertThat(response.getIndices().get("test").getTotal().getIndexing().getTotal().getDeleteCount(), equalTo(0L)); // make sure the purger has done its job for all indexed docs that are expired long shouldBeExpiredDate = now + providedTTLValue + PURGE_INTERVAL + 2000; currentTime = System.currentTimeMillis(); if (shouldBeExpiredDate - currentTime > 0) { Thread.sleep(shouldBeExpiredDate - currentTime); } // We can't assume that after waiting for ttl + purgeInterval (waitTime) that the document have actually been deleted. // The ttl purging happens in the background in a different thread, and might not have been completed after waiting for waitTime. // But we can use index statistics' delete count to be sure that deletes have been executed, that must be incremented before // ttl purging has finished. logger.info("--> checking purger"); assertTrue(awaitBusy(() -> { if (rarely()) { client().admin().indices().prepareFlush("test").get(); } else if (rarely()) { client().admin().indices().prepareForceMerge("test").setMaxNumSegments(1).get(); } IndicesStatsResponse indicesStatsResponse = client().admin().indices().prepareStats("test").clear().setIndexing(true).get(); // TTL deletes two docs, but it is indexed in the primary shard and replica shard. return indicesStatsResponse.getIndices().get("test").getTotal().getIndexing().getTotal().getDeleteCount() == 2L * test.dataCopies; }, 5, TimeUnit.SECONDS )); // realtime get check getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(true).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); getResponse = client().prepareGet("test", "type1", "with_routing").setRouting("routing").setFields("_ttl").setRealtime(true).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); // replica realtime get check getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(true).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); getResponse = client().prepareGet("test", "type1", "with_routing").setRouting("routing").setFields("_ttl").setRealtime(true).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); // Need to run a refresh, in order for the non realtime get to work. client().admin().indices().prepareRefresh("test").execute().actionGet(); // non realtime get (stored) check getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(false).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); getResponse = client().prepareGet("test", "type1", "with_routing").setRouting("routing").setFields("_ttl").setRealtime(false).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); // non realtime get going the replica check getResponse = client().prepareGet("test", "type1", "1").setFields("_ttl").setRealtime(false).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); getResponse = client().prepareGet("test", "type1", "with_routing").setRouting("routing").setFields("_ttl").setRealtime(false).execute().actionGet(); assertThat(getResponse.isExists(), equalTo(false)); } // issue 5053 public void testThatUpdatingMappingShouldNotRemoveTTLConfiguration() throws Exception { String index = "foo"; String type = "mytype"; XContentBuilder builder = jsonBuilder().startObject().startObject("_ttl").field("enabled", true).endObject().endObject(); assertAcked(client().admin().indices().prepareCreate(index).setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id).addMapping(type, builder)); // check mapping again assertTTLMappingEnabled(index, type); // update some field in the mapping XContentBuilder updateMappingBuilder = jsonBuilder().startObject().startObject("properties").startObject("otherField").field("type", "text").endObject().endObject().endObject(); PutMappingResponse putMappingResponse = client().admin().indices().preparePutMapping(index).setType(type).setSource(updateMappingBuilder).get(); assertAcked(putMappingResponse); // make sure timestamp field is still in mapping assertTTLMappingEnabled(index, type); } /** * Test that updates with detect_noop set to true (the default) that don't * change the source don't change the ttl. This is unexpected behavior and * documented in ttl-field.asciidoc. If this behavior changes it is safe to * rewrite this test to reflect the new behavior and to change the * documentation. */ public void testNoopUpdate() throws IOException { assertAcked(prepareCreate("test") .setSettings(IndexMetaData.SETTING_VERSION_CREATED, Version.V_2_3_0.id) .addMapping("type1", XContentFactory.jsonBuilder() .startObject() .startObject("type1") .startObject("_timestamp").field("enabled", true).endObject() .startObject("_ttl").field("enabled", true).endObject() .endObject() .endObject())); long aLongTime = 10000000; long firstTtl = aLongTime * 3; long secondTtl = aLongTime * 2; long thirdTtl = aLongTime * 1; IndexResponse indexResponse = client().prepareIndex("test", "type1", "1").setSource("field1", "value1") .setTTL(firstTtl).setRefreshPolicy(IMMEDIATE).get(); assertTrue(indexResponse.getResult() == DocWriteResponse.Result.CREATED); assertThat(getTtl("type1", 1), both(lessThanOrEqualTo(firstTtl)).and(greaterThan(secondTtl))); // Updating with the default detect_noop without a change to the document doesn't change the ttl. UpdateRequestBuilder update = client().prepareUpdate("test", "type1", "1").setDoc("field1", "value1").setTtl(secondTtl); assertThat(updateAndGetTtl(update), both(lessThanOrEqualTo(firstTtl)).and(greaterThan(secondTtl))); // Updating with the default detect_noop with a change to the document does change the ttl. update = client().prepareUpdate("test", "type1", "1").setDoc("field1", "value2").setTtl(secondTtl); assertThat(updateAndGetTtl(update), both(lessThanOrEqualTo(secondTtl)).and(greaterThan(thirdTtl))); // Updating with detect_noop=true without a change to the document doesn't change the ttl. update = client().prepareUpdate("test", "type1", "1").setDoc("field1", "value2").setTtl(secondTtl).setDetectNoop(true); assertThat(updateAndGetTtl(update), both(lessThanOrEqualTo(secondTtl)).and(greaterThan(thirdTtl))); // Updating with detect_noop=false without a change to the document does change the ttl. update = client().prepareUpdate("test", "type1", "1").setDoc("field1", "value2").setTtl(thirdTtl).setDetectNoop(false); assertThat(updateAndGetTtl(update), lessThanOrEqualTo(thirdTtl)); } private long updateAndGetTtl(UpdateRequestBuilder update) { UpdateResponse updateResponse = update.setFields("_ttl").get(); assertThat(updateResponse.getShardInfo().getFailed(), equalTo(0)); // You can't actually fetch _ttl from an update so we use a get. return getTtl(updateResponse.getType(), updateResponse.getId()); } private long getTtl(String type, Object id) { GetResponse getResponse = client().prepareGet("test", type, id.toString()).setFields("_ttl").setRealtime(true).execute() .actionGet(); return ((Number) getResponse.getField("_ttl").getValue()).longValue(); } private void assertTTLMappingEnabled(String index, String type) throws IOException { String errMsg = String.format(Locale.ROOT, "Expected ttl field mapping to be enabled for %s/%s", index, type); GetMappingsResponse getMappingsResponse = client().admin().indices().prepareGetMappings(index).addTypes(type).get(); Map<String, Object> mappingSource = getMappingsResponse.getMappings().get(index).get(type).getSourceAsMap(); assertThat(errMsg, mappingSource, hasKey("_ttl")); String ttlAsString = mappingSource.get("_ttl").toString(); assertThat(ttlAsString, is(notNullValue())); assertThat(errMsg, ttlAsString, is("{enabled=true}")); } }
dpursehouse/elasticsearch
core/src/test/java/org/elasticsearch/ttl/SimpleTTLIT.java
Java
apache-2.0
17,283
<?php /** * The original PHP version of this code was written by Geoffrey T. Dairiki * <[email protected]>, and is used/adapted with his permission. * * Copyright 2004 Geoffrey T. Dairiki <[email protected]> * Copyright 2004-2011 Horde LLC (http://www.horde.org/) * * See the enclosed file COPYING for license information (LGPL). If you did * not receive this file, see http://www.horde.org/licenses/lgpl21. * * @package Text_Diff * @author Geoffrey T. Dairiki <[email protected]> */ // Disallow direct access to this file for security reasons if(!defined("IN_MYBB")) { die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined."); } class Horde_Text_Diff_Op_Delete extends Horde_Text_Diff_Op_Base { public function __construct($lines) { $this->orig = $lines; $this->final = false; } public function reverse() { return new Horde_Text_Diff_Op_Add($this->orig); } }
Flauschbaellchen/florensia-base
forum/inc/3rdparty/diff/Diff/Op/Delete.php
PHP
apache-2.0
1,014
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // 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 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; namespace Microsoft.PythonTools.Parsing { public sealed class ParserOptions { internal static ParserOptions Default = new ParserOptions(); public ParserOptions() { ErrorSink = ErrorSink.Null; } public ErrorSink ErrorSink { get; set; } public Severity IndentationInconsistencySeverity { set; get; } public bool Verbatim { get; set; } /// <summary> /// True if references to variables should be bound in the AST. The root node must be /// held onto to access the references via GetReference/GetReferences APIs on various /// nodes which reference variables. /// </summary> public bool BindReferences { get; set; } /// <summary> /// Specifies the class name the parser starts off with for name mangling name expressions. /// /// For example __fob would turn into _C__fob if PrivatePrefix is set to C. /// </summary> public string PrivatePrefix { get; set; } /// <summary> /// An event that is raised for every comment in the source as it is parsed. /// </summary> public event EventHandler<CommentEventArgs> ProcessComment; internal void RaiseProcessComment(object sender, CommentEventArgs e) { var handler = ProcessComment; if (handler != null) { handler(sender, e); } } } public class CommentEventArgs : EventArgs { public SourceSpan Span { get; private set; } public string Text { get; private set; } public CommentEventArgs(SourceSpan span, string text) { Span = span; Text = text; } } }
DinoV/PTVS
Python/Product/Analysis/Parsing/ParserOptions.cs
C#
apache-2.0
2,464
/* * Copyright (C) 2017 Yusuke Suzuki <[email protected]> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS'' * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "CallLinkInfo.h" #include "StructureStubInfo.h" #include <wtf/StringPrintStream.h> namespace JSC { struct Instruction; template<class Block> class BytecodeDumper { public: typedef typename Block::Instruction Instruction; static void dumpBytecode(Block*, PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap()); static void dumpBlock(Block*, const typename Block::UnpackedInstructions&, PrintStream& out, const StubInfoMap& = StubInfoMap(), const CallLinkInfoMap& = CallLinkInfoMap()); private: BytecodeDumper(Block* block, const Instruction* instructionsBegin) : m_block(block) , m_instructionsBegin(instructionsBegin) { } Block* block() const { return m_block; } const Instruction* instructionsBegin() const { return m_instructionsBegin; } ALWAYS_INLINE VM* vm() const; CString registerName(int r) const; CString constantName(int index) const; const Identifier& identifier(int index) const; void dumpIdentifiers(PrintStream& out); void dumpConstants(PrintStream& out); void dumpRegExps(PrintStream& out); void dumpExceptionHandlers(PrintStream& out); void dumpSwitchJumpTables(PrintStream& out); void dumpStringSwitchJumpTables(PrintStream& out); void printUnaryOp(PrintStream& out, int location, const Instruction*& it, const char* op); void printBinaryOp(PrintStream& out, int location, const Instruction*& it, const char* op); void printConditionalJump(PrintStream& out, const Instruction*, const Instruction*& it, int location, const char* op); void printGetByIdOp(PrintStream& out, int location, const Instruction*& it); void printGetByIdCacheStatus(PrintStream& out, int location, const StubInfoMap&); void printPutByIdCacheStatus(PrintStream& out, int location, const StubInfoMap&); enum CacheDumpMode { DumpCaches, DontDumpCaches }; void printCallOp(PrintStream& out, int location, const Instruction*& it, const char* op, CacheDumpMode, bool& hasPrintedProfiling, const CallLinkInfoMap&); void printPutByIdOp(PrintStream& out, int location, const Instruction*& it, const char* op); void printLocationOpAndRegisterOperand(PrintStream& out, int location, const Instruction*& it, const char* op, int operand); void dumpBytecode(PrintStream& out, const Instruction* begin, const Instruction*& it, const StubInfoMap&, const CallLinkInfoMap&); void dumpValueProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling); void dumpArrayProfiling(PrintStream&, const Instruction*&, bool& hasPrintedProfiling); void dumpProfilesForBytecodeOffset(PrintStream&, unsigned location, bool& hasPrintedProfiling); void* actualPointerFor(Special::Pointer) const; #if ENABLE(JIT) void dumpCallLinkStatus(PrintStream&, unsigned location, const CallLinkInfoMap&); #endif Block* m_block; const Instruction* m_instructionsBegin; }; }
alibaba/weex
weex_core/Source/include/JavaScriptCore/bytecode/BytecodeDumper.h
C
apache-2.0
4,384
(function() { var author, quote, sentence; author = "Wittgenstein"; quote = "A picture is a fact. -- " + author; sentence = (22 / 7) + " is a decent approximation of π"; }).call(this);
UAK-35/wro4j
wro4j-extensions/src/test/resources/ro/isdc/wro/extensions/processor/coffeeScript/advanced/expected/interpolation.js
JavaScript
apache-2.0
197
// // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // * Neither the name of NVIDIA CORPORATION nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY // OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008-2019 NVIDIA Corporation. All rights reserved. // Copyright (c) 2004-2008 AGEIA Technologies, Inc. All rights reserved. // Copyright (c) 2001-2004 NovodeX AG. All rights reserved. #ifndef PX_PHYSICS_EXTENSIONS_TRIANGLE_MESH_H #define PX_PHYSICS_EXTENSIONS_TRIANGLE_MESH_H /** \addtogroup extensions @{ */ #include "PxPhysXConfig.h" #include "common/PxPhysXCommonConfig.h" #if !PX_DOXYGEN namespace physx { #endif class PxGeometry; class PxTriangleMeshGeometry; class PxHeightFieldGeometry; /** \brief Utility class to find mesh triangles touched by a specified geometry object. This class is a helper calling PxMeshQuery::findOverlapTriangleMesh or PxMeshQuery::findOverlapHeightField under the hood, while taking care of necessary memory management issues. PxMeshQuery::findOverlapTriangleMesh and PxMeshQuery::findOverlapHeightField are the "raw" functions operating on user-provided fixed-size buffers. These functions abort with an error code in case of buffer overflow. PxMeshOverlapUtil is a convenient helper function checking this error code, and resizing buffers appropriately, until the desired call succeeds. Returned triangle indices are stored within the class, and can be used with PxMeshQuery::getTriangle() to retrieve the triangle properties. */ class PxMeshOverlapUtil { public: PxMeshOverlapUtil(); ~PxMeshOverlapUtil(); /** \brief Find the mesh triangles which touch the specified geometry object. \param[in] geom The geometry object to test for mesh triangle overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry \param[in] geomPose Pose of the geometry object \param[in] meshGeom The triangle mesh geometry to check overlap against \param[in] meshPose Pose of the triangle mesh \return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function. @see PxGeometry PxTransform PxTriangleMeshGeometry PxMeshQuery::findOverlapTriangleMesh */ PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose); /** \brief Find the height field triangles which touch the specified geometry object. \param[in] geom The geometry object to test for height field overlaps. Supported geometries are #PxSphereGeometry, #PxCapsuleGeometry and #PxBoxGeometry. The sphere and capsule queries are currently conservative estimates. \param[in] geomPose Pose of the geometry object \param[in] hfGeom The height field geometry to check overlap against \param[in] hfPose Pose of the height field \return Number of overlaps found. Triangle indices can then be accessed through the #getResults() function. @see PxGeometry PxTransform PxHeightFieldGeometry PxMeshQuery::findOverlapHeightField */ PxU32 findOverlap(const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& hfGeom, const PxTransform& hfPose); /** \brief Retrieves array of triangle indices after a findOverlap call. \return Indices of touched triangles */ PX_FORCE_INLINE const PxU32* getResults() const { return mResultsMemory; } /** \brief Retrieves number of triangle indices after a findOverlap call. \return Number of touched triangles */ PX_FORCE_INLINE PxU32 getNbResults() const { return mNbResults; } private: PxU32* mResultsMemory; PxU32 mResults[256]; PxU32 mNbResults; PxU32 mMaxNbResults; }; /** \brief Computes an approximate minimum translational distance (MTD) between a geometry object and a mesh. This iterative function computes an approximate vector that can be used to depenetrate a geom object from a triangle mesh. Returned depenetration vector should be applied to 'geom', to get out of the mesh. The function works best when the amount of overlap between the geom object and the mesh is small. If the geom object's center goes inside the mesh, backface culling usually kicks in, no overlap is detected, and the function does not compute an MTD vector. The function early exits if no overlap is detected after a depenetration attempt. This means that if maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has been successful. Usually N = 4 gives good results. \param[out] direction Computed MTD unit direction \param[out] depth Penetration depth. Always positive or zero. \param[in] geom The geometry object \param[in] geomPose Pose for the geometry object \param[in] meshGeom The mesh geometry \param[in] meshPose Pose for the mesh \param[in] maxIter Max number of iterations before returning. \param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL. \return True if the MTD has successfully been computed, i.e. if objects do overlap. @see PxGeometry PxTransform PxTriangleMeshGeometry */ bool PxComputeTriangleMeshPenetration(PxVec3& direction, PxReal& depth, const PxGeometry& geom, const PxTransform& geomPose, const PxTriangleMeshGeometry& meshGeom, const PxTransform& meshPose, PxU32 maxIter, PxU32* usedIter = NULL); /** \brief Computes an approximate minimum translational distance (MTD) between a geometry object and a heightfield. This iterative function computes an approximate vector that can be used to depenetrate a geom object from a heightfield. Returned depenetration vector should be applied to 'geom', to get out of the heightfield. The function works best when the amount of overlap between the geom object and the mesh is small. If the geom object's center goes inside the heightfield, backface culling usually kicks in, no overlap is detected, and the function does not compute an MTD vector. The function early exits if no overlap is detected after a depenetration attempt. This means that if maxIter = N, the code will attempt at most N iterations but it might exit earlier if depenetration has been successful. Usually N = 4 gives good results. \param[out] direction Computed MTD unit direction \param[out] depth Penetration depth. Always positive or zero. \param[in] geom The geometry object \param[in] geomPose Pose for the geometry object \param[in] heightFieldGeom The heightfield geometry \param[in] heightFieldPose Pose for the heightfield \param[in] maxIter Max number of iterations before returning. \param[out] usedIter Number of depenetrations attempts performed during the call. Will not be returned if the pointer is NULL. \return True if the MTD has successfully been computed, i.e. if objects do overlap. @see PxGeometry PxTransform PxHeightFieldGeometry */ bool PxComputeHeightFieldPenetration(PxVec3& direction, PxReal& depth, const PxGeometry& geom, const PxTransform& geomPose, const PxHeightFieldGeometry& heightFieldGeom, const PxTransform& heightFieldPose, PxU32 maxIter, PxU32* usedIter = NULL); #if !PX_DOXYGEN } // namespace physx #endif /** @} */ #endif
Mephostopilis/lua
physx/3rd/PhysX-4.1/physx/include/extensions/PxTriangleMeshExt.h
C
apache-2.0
8,674
package com.google.api.ads.dfp.jaxws.v201508; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * * Ad rule slot with optimized podding. Optimized pods are defined by a * {@link BaseAdRuleSlot#maxPodDuration} and a {@link BaseAdRuleSlot#maxAdsInPod}, and the ad * server chooses the best ads for the alloted duration. * * * <p>Java class for OptimizedPoddingAdRuleSlot complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="OptimizedPoddingAdRuleSlot"> * &lt;complexContent> * &lt;extension base="{https://www.google.com/apis/ads/publisher/v201508}BaseAdRuleSlot"> * &lt;sequence> * &lt;/sequence> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "OptimizedPoddingAdRuleSlot") public class OptimizedPoddingAdRuleSlot extends BaseAdRuleSlot { }
raja15792/googleads-java-lib
modules/dfp_appengine/src/main/java/com/google/api/ads/dfp/jaxws/v201508/OptimizedPoddingAdRuleSlot.java
Java
apache-2.0
1,120
/* Copyright 2012 - 2014 Jerome Leleu 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.pac4j.core.profile; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; /** * This class represents a formatted date. * * @author Jerome Leleu * @since 1.1.0 */ public final class FormattedDate extends Date { private static final long serialVersionUID = 7721389956184262608L; private String format; private Locale locale; public FormattedDate() { } public FormattedDate(final Date date, final String format, final Locale locale) { super(date.getTime()); this.format = format; this.locale = locale; } public String getFormat() { return this.format; } public void setFormat(final String format) { this.format = format; } public void setLocale(final Locale locale) { this.locale = locale; } public Locale getLocale() { return this.locale; } @Override public String toString() { SimpleDateFormat simpleDateFormat; if (this.locale == null) { simpleDateFormat = new SimpleDateFormat(this.format); } else { simpleDateFormat = new SimpleDateFormat(this.format, this.locale); } return simpleDateFormat.format(this); } }
F0REacH/pac4j-1.5.1
pac4j-core/src/main/java/org/pac4j/core/profile/FormattedDate.java
Java
apache-2.0
1,900
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/medialive/model/RawSettings.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace MediaLive { namespace Model { RawSettings::RawSettings() { } RawSettings::RawSettings(JsonView jsonValue) { *this = jsonValue; } RawSettings& RawSettings::operator =(JsonView jsonValue) { AWS_UNREFERENCED_PARAM(jsonValue); return *this; } JsonValue RawSettings::Jsonize() const { JsonValue payload; return payload; } } // namespace Model } // namespace MediaLive } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-medialive/source/model/RawSettings.cpp
C++
apache-2.0
723
{% extends "registration_base_template.html" %} {% block content %} <h1>{{ email_verified_title }}</h1> <p>{{ email_verified_content }}</p> {% endblock %}
beeldengeluid/AVResearcherXL
avresearcher/templates/verify_email.html
HTML
apache-2.0
162
/* Copyright 2007 Brian Tanner [email protected] http://brian.tannerpages.com 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.rlcommunity.rlviz.app.gluestepper; import org.rlcommunity.rlviz.app.RLGlueLogic; public class GlueStepper{ int timeStepDelay=100; boolean running=false; RLGlueLogic theGlueLogic=null; GlueRunner theGlueRunner=null; public GlueStepper(RLGlueLogic theGlueLogic){ this.theGlueLogic=theGlueLogic; } public void setNewStepDelay(int stepDelay) { this.timeStepDelay=stepDelay; if(running)start(); } public void start() { if(running) stop(); running=true; //If time is the minimum we want to do something different // if(timeStepDelay==1) // theGlueRunner=new NoDelayGlueRunner(theGlueLogic); // else theGlueRunner=new FixedIntervalGlueRunner(theGlueLogic,timeStepDelay); theGlueRunner.start(); } public void stop() { if(theGlueRunner!=null)theGlueRunner.stop(); theGlueRunner=null; running=false; } }
cosmoharrigan/rl-viz
projects/rlVizApp/src/org/rlcommunity/rlviz/app/gluestepper/GlueStepper.java
Java
apache-2.0
1,478
"""Class to hold all thermostat accessories.""" import logging from pyhap.const import CATEGORY_THERMOSTAT from homeassistant.components.climate.const import ( ATTR_CURRENT_TEMPERATURE, ATTR_HVAC_ACTION, ATTR_HVAC_MODE, ATTR_HVAC_MODES, ATTR_MAX_TEMP, ATTR_MIN_TEMP, ATTR_TARGET_TEMP_HIGH, ATTR_TARGET_TEMP_LOW, ATTR_TARGET_TEMP_STEP, CURRENT_HVAC_COOL, CURRENT_HVAC_HEAT, CURRENT_HVAC_IDLE, CURRENT_HVAC_OFF, DEFAULT_MAX_TEMP, DEFAULT_MIN_TEMP, DOMAIN as DOMAIN_CLIMATE, HVAC_MODE_AUTO, HVAC_MODE_COOL, HVAC_MODE_FAN_ONLY, HVAC_MODE_HEAT, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, SERVICE_SET_HVAC_MODE as SERVICE_SET_HVAC_MODE_THERMOSTAT, SERVICE_SET_TEMPERATURE as SERVICE_SET_TEMPERATURE_THERMOSTAT, SUPPORT_TARGET_TEMPERATURE_RANGE, ) from homeassistant.components.water_heater import ( DOMAIN as DOMAIN_WATER_HEATER, SERVICE_SET_TEMPERATURE as SERVICE_SET_TEMPERATURE_WATER_HEATER, ) from homeassistant.const import ( ATTR_ENTITY_ID, ATTR_SUPPORTED_FEATURES, ATTR_TEMPERATURE, TEMP_CELSIUS, TEMP_FAHRENHEIT, ) from . import TYPES from .accessories import HomeAccessory, debounce from .const import ( CHAR_COOLING_THRESHOLD_TEMPERATURE, CHAR_CURRENT_HEATING_COOLING, CHAR_CURRENT_TEMPERATURE, CHAR_HEATING_THRESHOLD_TEMPERATURE, CHAR_TARGET_HEATING_COOLING, CHAR_TARGET_TEMPERATURE, CHAR_TEMP_DISPLAY_UNITS, DEFAULT_MAX_TEMP_WATER_HEATER, DEFAULT_MIN_TEMP_WATER_HEATER, PROP_MAX_VALUE, PROP_MIN_STEP, PROP_MIN_VALUE, SERV_THERMOSTAT, ) from .util import temperature_to_homekit, temperature_to_states _LOGGER = logging.getLogger(__name__) HC_HOMEKIT_VALID_MODES_WATER_HEATER = { "Heat": 1, } UNIT_HASS_TO_HOMEKIT = {TEMP_CELSIUS: 0, TEMP_FAHRENHEIT: 1} UNIT_HOMEKIT_TO_HASS = {c: s for s, c in UNIT_HASS_TO_HOMEKIT.items()} HC_HASS_TO_HOMEKIT = { HVAC_MODE_OFF: 0, HVAC_MODE_HEAT: 1, HVAC_MODE_COOL: 2, HVAC_MODE_AUTO: 3, HVAC_MODE_HEAT_COOL: 3, HVAC_MODE_FAN_ONLY: 2, } HC_HOMEKIT_TO_HASS = {c: s for s, c in HC_HASS_TO_HOMEKIT.items()} HC_HASS_TO_HOMEKIT_ACTION = { CURRENT_HVAC_OFF: 0, CURRENT_HVAC_IDLE: 0, CURRENT_HVAC_HEAT: 1, CURRENT_HVAC_COOL: 2, } @TYPES.register("Thermostat") class Thermostat(HomeAccessory): """Generate a Thermostat accessory for a climate.""" def __init__(self, *args): """Initialize a Thermostat accessory object.""" super().__init__(*args, category=CATEGORY_THERMOSTAT) self._unit = self.hass.config.units.temperature_unit self._flag_heat_cool = False self._flag_temperature = False self._flag_coolingthresh = False self._flag_heatingthresh = False min_temp, max_temp = self.get_temperature_range() temp_step = self.hass.states.get(self.entity_id).attributes.get( ATTR_TARGET_TEMP_STEP, 0.5 ) # Add additional characteristics if auto mode is supported self.chars = [] state = self.hass.states.get(self.entity_id) features = state.attributes.get(ATTR_SUPPORTED_FEATURES, 0) if features & SUPPORT_TARGET_TEMPERATURE_RANGE: self.chars.extend( (CHAR_COOLING_THRESHOLD_TEMPERATURE, CHAR_HEATING_THRESHOLD_TEMPERATURE) ) serv_thermostat = self.add_preload_service(SERV_THERMOSTAT, self.chars) # Current mode characteristics self.char_current_heat_cool = serv_thermostat.configure_char( CHAR_CURRENT_HEATING_COOLING, value=0 ) # Target mode characteristics hc_modes = state.attributes.get(ATTR_HVAC_MODES, None) if hc_modes is None: _LOGGER.error( "%s: HVAC modes not yet available. Please disable auto start for homekit.", self.entity_id, ) hc_modes = ( HVAC_MODE_HEAT, HVAC_MODE_COOL, HVAC_MODE_HEAT_COOL, HVAC_MODE_OFF, ) # determine available modes for this entity, prefer AUTO over HEAT_COOL and COOL over FAN_ONLY self.hc_homekit_to_hass = { c: s for s, c in HC_HASS_TO_HOMEKIT.items() if ( s in hc_modes and not ( (s == HVAC_MODE_HEAT_COOL and HVAC_MODE_AUTO in hc_modes) or (s == HVAC_MODE_FAN_ONLY and HVAC_MODE_COOL in hc_modes) ) ) } hc_valid_values = {k: v for v, k in self.hc_homekit_to_hass.items()} self.char_target_heat_cool = serv_thermostat.configure_char( CHAR_TARGET_HEATING_COOLING, value=0, setter_callback=self.set_heat_cool, valid_values=hc_valid_values, ) # Current and target temperature characteristics self.char_current_temp = serv_thermostat.configure_char( CHAR_CURRENT_TEMPERATURE, value=21.0 ) self.char_target_temp = serv_thermostat.configure_char( CHAR_TARGET_TEMPERATURE, value=21.0, properties={ PROP_MIN_VALUE: min_temp, PROP_MAX_VALUE: max_temp, PROP_MIN_STEP: temp_step, }, setter_callback=self.set_target_temperature, ) # Display units characteristic self.char_display_units = serv_thermostat.configure_char( CHAR_TEMP_DISPLAY_UNITS, value=0 ) # If the device supports it: high and low temperature characteristics self.char_cooling_thresh_temp = None self.char_heating_thresh_temp = None if CHAR_COOLING_THRESHOLD_TEMPERATURE in self.chars: self.char_cooling_thresh_temp = serv_thermostat.configure_char( CHAR_COOLING_THRESHOLD_TEMPERATURE, value=23.0, properties={ PROP_MIN_VALUE: min_temp, PROP_MAX_VALUE: max_temp, PROP_MIN_STEP: temp_step, }, setter_callback=self.set_cooling_threshold, ) if CHAR_HEATING_THRESHOLD_TEMPERATURE in self.chars: self.char_heating_thresh_temp = serv_thermostat.configure_char( CHAR_HEATING_THRESHOLD_TEMPERATURE, value=19.0, properties={ PROP_MIN_VALUE: min_temp, PROP_MAX_VALUE: max_temp, PROP_MIN_STEP: temp_step, }, setter_callback=self.set_heating_threshold, ) def get_temperature_range(self): """Return min and max temperature range.""" max_temp = self.hass.states.get(self.entity_id).attributes.get(ATTR_MAX_TEMP) max_temp = ( temperature_to_homekit(max_temp, self._unit) if max_temp else DEFAULT_MAX_TEMP ) max_temp = round(max_temp * 2) / 2 min_temp = self.hass.states.get(self.entity_id).attributes.get(ATTR_MIN_TEMP) min_temp = ( temperature_to_homekit(min_temp, self._unit) if min_temp else DEFAULT_MIN_TEMP ) min_temp = round(min_temp * 2) / 2 return min_temp, max_temp def set_heat_cool(self, value): """Change operation mode to value if call came from HomeKit.""" _LOGGER.debug("%s: Set heat-cool to %d", self.entity_id, value) self._flag_heat_cool = True hass_value = self.hc_homekit_to_hass[value] params = {ATTR_ENTITY_ID: self.entity_id, ATTR_HVAC_MODE: hass_value} self.call_service( DOMAIN_CLIMATE, SERVICE_SET_HVAC_MODE_THERMOSTAT, params, hass_value ) @debounce def set_cooling_threshold(self, value): """Set cooling threshold temp to value if call came from HomeKit.""" _LOGGER.debug( "%s: Set cooling threshold temperature to %.1f°C", self.entity_id, value ) self._flag_coolingthresh = True low = self.char_heating_thresh_temp.value temperature = temperature_to_states(value, self._unit) params = { ATTR_ENTITY_ID: self.entity_id, ATTR_TARGET_TEMP_HIGH: temperature, ATTR_TARGET_TEMP_LOW: temperature_to_states(low, self._unit), } self.call_service( DOMAIN_CLIMATE, SERVICE_SET_TEMPERATURE_THERMOSTAT, params, f"cooling threshold {temperature}{self._unit}", ) @debounce def set_heating_threshold(self, value): """Set heating threshold temp to value if call came from HomeKit.""" _LOGGER.debug( "%s: Set heating threshold temperature to %.1f°C", self.entity_id, value ) self._flag_heatingthresh = True high = self.char_cooling_thresh_temp.value temperature = temperature_to_states(value, self._unit) params = { ATTR_ENTITY_ID: self.entity_id, ATTR_TARGET_TEMP_HIGH: temperature_to_states(high, self._unit), ATTR_TARGET_TEMP_LOW: temperature, } self.call_service( DOMAIN_CLIMATE, SERVICE_SET_TEMPERATURE_THERMOSTAT, params, f"heating threshold {temperature}{self._unit}", ) @debounce def set_target_temperature(self, value): """Set target temperature to value if call came from HomeKit.""" _LOGGER.debug("%s: Set target temperature to %.1f°C", self.entity_id, value) self._flag_temperature = True temperature = temperature_to_states(value, self._unit) params = {ATTR_ENTITY_ID: self.entity_id, ATTR_TEMPERATURE: temperature} self.call_service( DOMAIN_CLIMATE, SERVICE_SET_TEMPERATURE_THERMOSTAT, params, f"{temperature}{self._unit}", ) def update_state(self, new_state): """Update thermostat state after state changed.""" # Update current temperature current_temp = new_state.attributes.get(ATTR_CURRENT_TEMPERATURE) if isinstance(current_temp, (int, float)): current_temp = temperature_to_homekit(current_temp, self._unit) self.char_current_temp.set_value(current_temp) # Update target temperature target_temp = new_state.attributes.get(ATTR_TEMPERATURE) if isinstance(target_temp, (int, float)): target_temp = temperature_to_homekit(target_temp, self._unit) if not self._flag_temperature: self.char_target_temp.set_value(target_temp) self._flag_temperature = False # Update cooling threshold temperature if characteristic exists if self.char_cooling_thresh_temp: cooling_thresh = new_state.attributes.get(ATTR_TARGET_TEMP_HIGH) if isinstance(cooling_thresh, (int, float)): cooling_thresh = temperature_to_homekit(cooling_thresh, self._unit) if not self._flag_coolingthresh: self.char_cooling_thresh_temp.set_value(cooling_thresh) self._flag_coolingthresh = False # Update heating threshold temperature if characteristic exists if self.char_heating_thresh_temp: heating_thresh = new_state.attributes.get(ATTR_TARGET_TEMP_LOW) if isinstance(heating_thresh, (int, float)): heating_thresh = temperature_to_homekit(heating_thresh, self._unit) if not self._flag_heatingthresh: self.char_heating_thresh_temp.set_value(heating_thresh) self._flag_heatingthresh = False # Update display units if self._unit and self._unit in UNIT_HASS_TO_HOMEKIT: self.char_display_units.set_value(UNIT_HASS_TO_HOMEKIT[self._unit]) # Update target operation mode hvac_mode = new_state.state if hvac_mode and hvac_mode in HC_HASS_TO_HOMEKIT: if not self._flag_heat_cool: self.char_target_heat_cool.set_value(HC_HASS_TO_HOMEKIT[hvac_mode]) self._flag_heat_cool = False # Set current operation mode for supported thermostats hvac_action = new_state.attributes.get(ATTR_HVAC_ACTION) if hvac_action: self.char_current_heat_cool.set_value( HC_HASS_TO_HOMEKIT_ACTION[hvac_action] ) @TYPES.register("WaterHeater") class WaterHeater(HomeAccessory): """Generate a WaterHeater accessory for a water_heater.""" def __init__(self, *args): """Initialize a WaterHeater accessory object.""" super().__init__(*args, category=CATEGORY_THERMOSTAT) self._unit = self.hass.config.units.temperature_unit self._flag_heat_cool = False self._flag_temperature = False min_temp, max_temp = self.get_temperature_range() serv_thermostat = self.add_preload_service(SERV_THERMOSTAT) self.char_current_heat_cool = serv_thermostat.configure_char( CHAR_CURRENT_HEATING_COOLING, value=1 ) self.char_target_heat_cool = serv_thermostat.configure_char( CHAR_TARGET_HEATING_COOLING, value=1, setter_callback=self.set_heat_cool, valid_values=HC_HOMEKIT_VALID_MODES_WATER_HEATER, ) self.char_current_temp = serv_thermostat.configure_char( CHAR_CURRENT_TEMPERATURE, value=50.0 ) self.char_target_temp = serv_thermostat.configure_char( CHAR_TARGET_TEMPERATURE, value=50.0, properties={ PROP_MIN_VALUE: min_temp, PROP_MAX_VALUE: max_temp, PROP_MIN_STEP: 0.5, }, setter_callback=self.set_target_temperature, ) self.char_display_units = serv_thermostat.configure_char( CHAR_TEMP_DISPLAY_UNITS, value=0 ) def get_temperature_range(self): """Return min and max temperature range.""" max_temp = self.hass.states.get(self.entity_id).attributes.get(ATTR_MAX_TEMP) max_temp = ( temperature_to_homekit(max_temp, self._unit) if max_temp else DEFAULT_MAX_TEMP_WATER_HEATER ) max_temp = round(max_temp * 2) / 2 min_temp = self.hass.states.get(self.entity_id).attributes.get(ATTR_MIN_TEMP) min_temp = ( temperature_to_homekit(min_temp, self._unit) if min_temp else DEFAULT_MIN_TEMP_WATER_HEATER ) min_temp = round(min_temp * 2) / 2 return min_temp, max_temp def set_heat_cool(self, value): """Change operation mode to value if call came from HomeKit.""" _LOGGER.debug("%s: Set heat-cool to %d", self.entity_id, value) self._flag_heat_cool = True hass_value = HC_HOMEKIT_TO_HASS[value] if hass_value != HVAC_MODE_HEAT: self.char_target_heat_cool.set_value(1) # Heat @debounce def set_target_temperature(self, value): """Set target temperature to value if call came from HomeKit.""" _LOGGER.debug("%s: Set target temperature to %.1f°C", self.entity_id, value) self._flag_temperature = True temperature = temperature_to_states(value, self._unit) params = {ATTR_ENTITY_ID: self.entity_id, ATTR_TEMPERATURE: temperature} self.call_service( DOMAIN_WATER_HEATER, SERVICE_SET_TEMPERATURE_WATER_HEATER, params, f"{temperature}{self._unit}", ) def update_state(self, new_state): """Update water_heater state after state change.""" # Update current and target temperature temperature = new_state.attributes.get(ATTR_TEMPERATURE) if isinstance(temperature, (int, float)): temperature = temperature_to_homekit(temperature, self._unit) self.char_current_temp.set_value(temperature) if not self._flag_temperature: self.char_target_temp.set_value(temperature) self._flag_temperature = False # Update display units if self._unit and self._unit in UNIT_HASS_TO_HOMEKIT: self.char_display_units.set_value(UNIT_HASS_TO_HOMEKIT[self._unit]) # Update target operation mode operation_mode = new_state.state if operation_mode and not self._flag_heat_cool: self.char_target_heat_cool.set_value(1) # Heat self._flag_heat_cool = False
leppa/home-assistant
homeassistant/components/homekit/type_thermostats.py
Python
apache-2.0
16,630
/* * Copyright 2007 BBN Technologies Corporation * * 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. */ /* * $Id$ */ #ifdef HAVE_CONFIG_H # include <dtn-config.h> #endif #ifdef BSP_ENABLED #include <cstring> #include <string> #include <oasys/compat/inttypes.h> #include <oasys/util/StringBuffer.h> #include "KeyDB.h" #include "Ciphersuite.h" namespace dtn { template <> KeyDB* oasys::Singleton<KeyDB, false>::instance_ = NULL; static const char * log = "/dtn/bundle/security"; KeyDB::KeyDB() { } KeyDB::~KeyDB() { } void KeyDB::init() { if (instance_ != NULL) { PANIC("KeyDB already initialized"); } instance_ = new KeyDB(); log_debug_p(log, "KeyDB::init() done"); } void KeyDB::shutdown() { if(instance_ != NULL) { delete instance_; log_debug_p(log, "KeyDB::shutdown() completed"); } } void KeyDB::set_key(Entry& entry) { EntryList& keys = instance()->keys_; EntryList::iterator iter; for (iter = keys.begin(); iter != keys.end(); iter++) { if (iter->match(entry)) { *iter = entry; return; } } // if we get here then there was no existing matching entry; // insert the new entry just before any existing wildcard entries for (iter = keys.begin(); iter != keys.end() && iter->host() != std::string("*"); iter++) { } keys.insert(iter, entry); log_debug_p(log, "KeyDB::set_key() done"); } const KeyDB::Entry* KeyDB::find_key(const char* host, u_int16_t cs_num) { EntryList& keys = instance()->keys_; EntryList::iterator iter; log_debug_p(log, "KeyDB::find_key()"); for (iter = keys.begin(); iter != keys.end(); iter++) { if (iter->match_wildcard(host, cs_num)) return &(*iter); } // not found return NULL; } void KeyDB::del_key(const char* host, u_int16_t cs_num) { EntryList& keys = instance()->keys_; EntryList::iterator iter; log_debug_p(log, "KeyDB::del_key()"); for (iter = keys.begin(); iter != keys.end(); iter++) { if (iter->match(host, cs_num)) { keys.erase(iter); return; } } // if not found, then nothing to do } void KeyDB::flush_keys() { log_debug_p(log, "KeyDB::flush_keys()"); instance()->keys_.clear(); } /// Dump the current contents of the KeyDB in human-readable form. void KeyDB::dump(oasys::StringBuffer* buf) { EntryList& keys = instance()->keys_; EntryList::iterator iter; for (iter = keys.begin(); iter != keys.end(); iter++) iter->dump(buf); } /// Dump a human-readable header for the output of dump(). void KeyDB::dump_header(oasys::StringBuffer* buf) { KeyDB::Entry::dump_header(buf); } /// Validate the specified ciphersuite number (see if it corresponds /// to a registered ciphersuite). bool KeyDB::validate_cs_num(u_int16_t cs_num) { return (Ciphersuite::find_suite(cs_num) != NULL); } bool KeyDB::validate_key_len(u_int16_t cs_num, size_t* key_len) { Ciphersuite* cs = dynamic_cast<Ciphersuite*>(Ciphersuite::find_suite(cs_num)); if (cs == NULL) return false; if (*key_len != cs->result_len()) { *key_len = cs->result_len(); return false; } return true; } /// Detailed constructor. KeyDB::Entry::Entry(const char* host, u_int16_t cs_num, const u_char* key, size_t key_len) : host_(host), cs_num_(cs_num), key_len_(key_len) { ASSERT(key != NULL); ASSERT(key_len != 0); key_ = new u_char[key_len]; memcpy(key_, key, key_len); } /// Default constructor. KeyDB::Entry::Entry() : host_(""), cs_num_(0), key_(NULL), key_len_(0) { } /// Copy constructor. KeyDB::Entry::Entry(const Entry& other) : host_(other.host_), cs_num_(other.cs_num_), key_len_(other.key_len_) { if (other.key_ == NULL) key_ = NULL; else { key_ = new u_char[other.key_len_]; memcpy(key_, other.key_, other.key_len_); } } /// Destructor. KeyDB::Entry::~Entry() { if (key_ != NULL) { memset(key_, 0, key_len_); delete[] key_; key_len_ = 0; } else ASSERT(key_len_ == 0); } /// Assignment operator. void KeyDB::Entry::operator=(const Entry& other) { if (key_ != NULL) { memset(key_, 0, key_len_); delete[] key_; } host_ = other.host_; cs_num_ = other.cs_num_; if (other.key_ == NULL) key_ = NULL; else { key_ = new u_char[other.key_len_]; memcpy(key_, other.key_, other.key_len_); } key_len_ = other.key_len_; } /// Determine if two entries have the same host and ciphersuite /// number. bool KeyDB::Entry::match(const Entry& other) const { return (host_ == other.host_ && cs_num_ == other.cs_num_); } /// Determine if this entry matches the given host and ciphersuite /// number. bool KeyDB::Entry::match(const char* host, u_int16_t cs_num) const { return (host_ == std::string(host) && cs_num_ == cs_num); } /// Same as match(), but also matches wildcard entries (where host /// is "*"). bool KeyDB::Entry::match_wildcard(const char* host, u_int16_t cs_num) const { return ((host_ == std::string(host) || host_ == std::string("*")) && cs_num_ == cs_num); } /// Dump this entry to a StringBuffer in human-readable form. void KeyDB::Entry::dump(oasys::StringBuffer* buf) const { buf->appendf("%15s 0x%03x ", host_.c_str(), cs_num_); //buf->appendf("(-- not shown --)"); for (int i = 0; i < (int)key_len_; i++) buf->appendf("%02x", (int)key_[i]); buf->appendf("\n"); } /// Dump a human-readable header for the output of dump(). void KeyDB::Entry::dump_header(oasys::StringBuffer* buf) { buf->appendf("host cs_num key\n" ); buf->appendf("--------------- ------ -------------------\n"); } } // namespace dtn #endif /* BSP_ENABLED */
ltartarini90/DTN2-BP-Metadata
servlib/security/KeyDB.cc
C++
apache-2.0
6,378
# Copyright (c) 2014 OpenStack Foundation. # 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. import re import shutil import tempfile import netaddr from oslo_config import cfg from oslo_log import log as logging from oslo_utils import uuidutils import six from neutron.agent.common import ovs_lib from neutron.agent.l3 import ha_router from neutron.agent.l3 import namespaces from neutron.agent.linux import external_process from neutron.agent.linux import ip_lib from neutron.agent.linux import ip_link_support from neutron.agent.linux import keepalived from neutron.agent.linux import utils as agent_utils from neutron.common import constants as n_consts from neutron.common import utils from neutron.i18n import _LE from neutron.plugins.common import constants as const from neutron.plugins.ml2.drivers.openvswitch.agent.common \ import constants as ovs_const LOG = logging.getLogger(__name__) MINIMUM_DNSMASQ_VERSION = 2.67 def ovs_vxlan_supported(from_ip='192.0.2.1', to_ip='192.0.2.2'): name = "vxlantest-" + utils.get_random_string(6) with ovs_lib.OVSBridge(name) as br: port = br.add_tunnel_port(from_ip, to_ip, const.TYPE_VXLAN) return port != ovs_lib.INVALID_OFPORT def iproute2_vxlan_supported(): ip = ip_lib.IPWrapper() name = "vxlantest-" + utils.get_random_string(4) port = ip.add_vxlan(name, 3000) ip.del_veth(name) return name == port.name def patch_supported(): seed = utils.get_random_string(6) name = "patchtest-" + seed peer_name = "peertest0-" + seed patch_name = "peertest1-" + seed with ovs_lib.OVSBridge(name) as br: port = br.add_patch_port(patch_name, peer_name) return port != ovs_lib.INVALID_OFPORT def nova_notify_supported(): try: import neutron.notifiers.nova # noqa since unused return True except ImportError: return False def ofctl_arg_supported(cmd, **kwargs): """Verify if ovs-ofctl binary supports cmd with **kwargs. :param cmd: ovs-ofctl command to use for test. :param **kwargs: arguments to test with the command. :returns: a boolean if the supplied arguments are supported. """ br_name = 'br-test-%s' % utils.get_random_string(6) with ovs_lib.OVSBridge(br_name) as test_br: full_args = ["ovs-ofctl", cmd, test_br.br_name, ovs_lib._build_flow_expr_str(kwargs, cmd.split('-')[0])] try: agent_utils.execute(full_args, run_as_root=True) except RuntimeError as e: LOG.debug("Exception while checking supported feature via " "command %s. Exception: %s", full_args, e) return False except Exception: LOG.exception(_LE("Unexpected exception while checking supported" " feature via command: %s"), full_args) return False else: return True def arp_responder_supported(): mac = netaddr.EUI('dead:1234:beef', dialect=netaddr.mac_unix) ip = netaddr.IPAddress('240.0.0.1') actions = ovs_const.ARP_RESPONDER_ACTIONS % {'mac': mac, 'ip': ip} return ofctl_arg_supported(cmd='add-flow', table=21, priority=1, proto='arp', dl_vlan=42, nw_dst='%s' % ip, actions=actions) def arp_header_match_supported(): return ofctl_arg_supported(cmd='add-flow', table=24, priority=1, proto='arp', arp_op='0x2', arp_spa='1.1.1.1', actions="NORMAL") def vf_management_supported(): try: vf_section = ip_link_support.IpLinkSupport.get_vf_mgmt_section() if not ip_link_support.IpLinkSupport.vf_mgmt_capability_supported( vf_section, ip_link_support.IpLinkConstants.IP_LINK_CAPABILITY_STATE): LOG.debug("ip link command does not support vf capability") return False except ip_link_support.UnsupportedIpLinkCommand: LOG.exception(_LE("Unexpected exception while checking supported " "ip link command")) return False return True def netns_read_requires_helper(): ipw = ip_lib.IPWrapper() nsname = "netnsreadtest-" + uuidutils.generate_uuid() ipw.netns.add(nsname) try: # read without root_helper. if exists, not required. ipw_nohelp = ip_lib.IPWrapper() exists = ipw_nohelp.netns.exists(nsname) finally: ipw.netns.delete(nsname) return not exists def get_minimal_dnsmasq_version_supported(): return MINIMUM_DNSMASQ_VERSION def dnsmasq_version_supported(): try: cmd = ['dnsmasq', '--version'] env = {'LC_ALL': 'C'} out = agent_utils.execute(cmd, addl_env=env) m = re.search(r"version (\d+\.\d+)", out) ver = float(m.group(1)) if m else 0 if ver < MINIMUM_DNSMASQ_VERSION: return False except (OSError, RuntimeError, IndexError, ValueError) as e: LOG.debug("Exception while checking minimal dnsmasq version. " "Exception: %s", e) return False return True class KeepalivedIPv6Test(object): def __init__(self, ha_port, gw_port, gw_vip, default_gw): self.ha_port = ha_port self.gw_port = gw_port self.gw_vip = gw_vip self.default_gw = default_gw self.manager = None self.config = None self.config_path = None self.nsname = "keepalivedtest-" + uuidutils.generate_uuid() self.pm = external_process.ProcessMonitor(cfg.CONF, 'router') self.orig_interval = cfg.CONF.AGENT.check_child_processes_interval def configure(self): config = keepalived.KeepalivedConf() instance1 = keepalived.KeepalivedInstance('MASTER', self.ha_port, 1, ['169.254.192.0/18'], advert_int=5) instance1.track_interfaces.append(self.ha_port) # Configure keepalived with an IPv6 address (gw_vip) on gw_port. vip_addr1 = keepalived.KeepalivedVipAddress(self.gw_vip, self.gw_port) instance1.vips.append(vip_addr1) # Configure keepalived with an IPv6 default route on gw_port. gateway_route = keepalived.KeepalivedVirtualRoute(n_consts.IPv6_ANY, self.default_gw, self.gw_port) instance1.virtual_routes.gateway_routes = [gateway_route] config.add_instance(instance1) self.config = config def start_keepalived_process(self): # Disable process monitoring for Keepalived process. cfg.CONF.set_override('check_child_processes_interval', 0, 'AGENT') # Create a temp directory to store keepalived configuration. self.config_path = tempfile.mkdtemp() # Instantiate keepalived manager with the IPv6 configuration. self.manager = keepalived.KeepalivedManager('router1', self.config, namespace=self.nsname, process_monitor=self.pm, conf_path=self.config_path) self.manager.spawn() def verify_ipv6_address_assignment(self, gw_dev): process = self.manager.get_process() agent_utils.wait_until_true(lambda: process.active) def _gw_vip_assigned(): iface_ip = gw_dev.addr.list(ip_version=6, scope='global') if iface_ip: return self.gw_vip == iface_ip[0]['cidr'] agent_utils.wait_until_true(_gw_vip_assigned) def __enter__(self): ip_lib.IPWrapper().netns.add(self.nsname) return self def __exit__(self, exc_type, exc_value, exc_tb): self.pm.stop() if self.manager: self.manager.disable() if self.config_path: shutil.rmtree(self.config_path, ignore_errors=True) ip_lib.IPWrapper().netns.delete(self.nsname) cfg.CONF.set_override('check_child_processes_interval', self.orig_interval, 'AGENT') def keepalived_ipv6_supported(): """Check if keepalived supports IPv6 functionality. Validation is done as follows. 1. Create a namespace. 2. Create OVS bridge with two ports (ha_port and gw_port) 3. Move the ovs ports to the namespace. 4. Spawn keepalived process inside the namespace with IPv6 configuration. 5. Verify if IPv6 address is assigned to gw_port. 6. Verify if IPv6 default route is configured by keepalived. """ random_str = utils.get_random_string(6) br_name = "ka-test-" + random_str ha_port = ha_router.HA_DEV_PREFIX + random_str gw_port = namespaces.INTERNAL_DEV_PREFIX + random_str gw_vip = 'fdf8:f53b:82e4::10/64' expected_default_gw = 'fe80:f816::1' with ovs_lib.OVSBridge(br_name) as br: with KeepalivedIPv6Test(ha_port, gw_port, gw_vip, expected_default_gw) as ka: br.add_port(ha_port, ('type', 'internal')) br.add_port(gw_port, ('type', 'internal')) ha_dev = ip_lib.IPDevice(ha_port) gw_dev = ip_lib.IPDevice(gw_port) ha_dev.link.set_netns(ka.nsname) gw_dev.link.set_netns(ka.nsname) ha_dev.link.set_up() gw_dev.link.set_up() ka.configure() ka.start_keepalived_process() ka.verify_ipv6_address_assignment(gw_dev) default_gw = gw_dev.route.get_gateway(ip_version=6) if default_gw: default_gw = default_gw['gateway'] return expected_default_gw == default_gw def ovsdb_native_supported(): # Running the test should ensure we are configured for OVSDB native try: ovs = ovs_lib.BaseOVS() ovs.get_bridges() return True except ImportError as ex: LOG.error(_LE("Failed to import required modules. Ensure that the " "python-openvswitch package is installed. Error: %s"), ex) except Exception as ex: LOG.exception(six.text_type(ex)) return False def ebtables_supported(): try: cmd = ['ebtables', '--version'] agent_utils.execute(cmd) return True except (OSError, RuntimeError, IndexError, ValueError) as e: LOG.debug("Exception while checking for installed ebtables. " "Exception: %s", e) return False
eonpatapon/neutron
neutron/cmd/sanity/checks.py
Python
apache-2.0
11,285
/** * * 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.ipc; import org.apache.hadoop.hbase.metrics.BaseSourceImpl; import org.apache.hadoop.metrics2.MetricsBuilder; import org.apache.hadoop.metrics2.MetricsRecordBuilder; import org.apache.hadoop.metrics2.lib.MetricMutableCounterLong; import org.apache.hadoop.metrics2.lib.MetricMutableHistogram; public class MetricsHBaseServerSourceImpl extends BaseSourceImpl implements MetricsHBaseServerSource { private final MetricsHBaseServerWrapper wrapper; private final MetricMutableCounterLong authorizationSuccesses; private final MetricMutableCounterLong authorizationFailures; private final MetricMutableCounterLong authenticationSuccesses; private final MetricMutableCounterLong authenticationFailures; private final MetricMutableCounterLong sentBytes; private final MetricMutableCounterLong receivedBytes; private MetricMutableHistogram queueCallTime; private MetricMutableHistogram processCallTime; public MetricsHBaseServerSourceImpl(String metricsName, String metricsDescription, String metricsContext, String metricsJmxContext, MetricsHBaseServerWrapper wrapper) { super(metricsName, metricsDescription, metricsContext, metricsJmxContext); this.wrapper = wrapper; this.authorizationSuccesses = this.getMetricsRegistry().newCounter(AUTHORIZATION_SUCCESSES_NAME, AUTHORIZATION_SUCCESSES_DESC, 0l); this.authorizationFailures = this.getMetricsRegistry().newCounter(AUTHORIZATION_FAILURES_NAME, AUTHORIZATION_FAILURES_DESC, 0l); this.authenticationSuccesses = this.getMetricsRegistry().newCounter( AUTHENTICATION_SUCCESSES_NAME, AUTHENTICATION_SUCCESSES_DESC, 0l); this.authenticationFailures = this.getMetricsRegistry().newCounter(AUTHENTICATION_FAILURES_NAME, AUTHENTICATION_FAILURES_DESC, 0l); this.sentBytes = this.getMetricsRegistry().newCounter(SENT_BYTES_NAME, SENT_BYTES_DESC, 0l); this.receivedBytes = this.getMetricsRegistry().newCounter(RECEIVED_BYTES_NAME, RECEIVED_BYTES_DESC, 0l); this.queueCallTime = this.getMetricsRegistry().newHistogram(QUEUE_CALL_TIME_NAME, QUEUE_CALL_TIME_DESC); this.processCallTime = this.getMetricsRegistry().newHistogram(PROCESS_CALL_TIME_NAME, PROCESS_CALL_TIME_DESC); } @Override public void authorizationSuccess() { authorizationSuccesses.incr(); } @Override public void authorizationFailure() { authorizationFailures.incr(); } @Override public void authenticationFailure() { authenticationFailures.incr(); } @Override public void authenticationSuccess() { authenticationSuccesses.incr(); } @Override public void sentBytes(int count) { this.sentBytes.incr(count); } @Override public void receivedBytes(int count) { this.receivedBytes.incr(count); } @Override public void dequeuedCall(int qTime) { queueCallTime.add(qTime); } @Override public void processedCall(int processingTime) { processCallTime.add(processingTime); } @Override public void getMetrics(MetricsBuilder metricsBuilder, boolean all) { MetricsRecordBuilder mrb = metricsBuilder.addRecord(metricsName) .setContext(metricsContext); if (wrapper != null) { mrb.addGauge(QUEUE_SIZE_NAME, QUEUE_SIZE_DESC, wrapper.getTotalQueueSize()) .addGauge(GENERAL_QUEUE_NAME, GENERAL_QUEUE_DESC, wrapper.getGeneralQueueLength()) .addGauge(REPLICATION_QUEUE_NAME, REPLICATION_QUEUE_DESC, wrapper.getReplicationQueueLength()) .addGauge(PRIORITY_QUEUE_NAME, PRIORITY_QUEUE_DESC, wrapper.getPriorityQueueLength()) .addGauge(NUM_OPEN_CONNECTIONS_NAME, NUM_OPEN_CONNECTIONS_DESC, wrapper.getNumOpenConnections()); } metricsRegistry.snapshot(mrb, all); } }
jyates/hbase
hbase-hadoop1-compat/src/main/java/org/apache/hadoop/hbase/ipc/MetricsHBaseServerSourceImpl.java
Java
apache-2.0
4,761
/* * This file is part of the swblocks-baselib library. * * 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 <baselib/loader/Cookie.h> #include <baselib/core/OS.h> #include <baselib/core/BaseIncludes.h> #include <utests/baselib/UtfDirectoryFixture.h> #include <utests/baselib/Utf.h> UTF_AUTO_TEST_CASE( TestCookie ) { using namespace bl; using namespace bl::loader; using namespace utest; utest::TestDirectory dir; const auto file = dir.testFile( "cookie" ); /* * Check exception thrown when cookie does not exist */ UTF_CHECK_THROW( CookieFactory::getCookie( file, false ), UnexpectedException ); /* * Check cookie can be created from file */ { bl::fs::SafeOutputFileStreamWrapper outputFile( file ); auto& os = outputFile.stream(); os << "4f082035-e301-4cce-94f0-68f1c99f9223" << std::endl; } const auto cookie = CookieFactory::getCookie( file, false ); UTF_CHECK_EQUAL( cookie -> getId(), uuids::string2uuid( "4f082035-e301-4cce-94f0-68f1c99f9223" ) ); /* * Check new cookie creation */ const auto newFile = dir.testFile( "new_cookie" ); CookieFactory::getCookie( newFile, true ); UTF_CHECK( fs::exists( newFile ) ); }
jpmorganchase/swblocks-baselib
src/utests/utf_baselib_loader/TestCookie.h
C
apache-2.0
1,774
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/workmail/WorkMail_EXPORTS.h> namespace Aws { template<typename RESULT_TYPE> class AmazonWebServiceResult; namespace Utils { namespace Json { class JsonValue; } // namespace Json } // namespace Utils namespace WorkMail { namespace Model { class AWS_WORKMAIL_API DeleteRetentionPolicyResult { public: DeleteRetentionPolicyResult(); DeleteRetentionPolicyResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); DeleteRetentionPolicyResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result); }; } // namespace Model } // namespace WorkMail } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-workmail/include/aws/workmail/model/DeleteRetentionPolicyResult.h
C
apache-2.0
785
/* * Copyright Camunda Services GmbH and/or licensed to Camunda Services GmbH * under one or more contributor license agreements. See the NOTICE file * distributed with this work for additional information regarding copyright * ownership. Camunda licenses this file to you under the Apache License, * Version 2.0; 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.camunda.bpm.integrationtest.functional.scriptengine; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.shrinkwrap.api.spec.WebArchive; /** * @author Sebastian Menski */ public class GroovyScriptEngineSupportTest extends AbstractScriptEngineSupportTest { @Deployment public static WebArchive createProcessApplication() { return initWebArchiveDeployment() .addClass(AbstractScriptEngineSupportTest.class) .addAsResource(createScriptTaskProcess("groovy", EXAMPLE_SCRIPT, EXAMPLE_SPIN_SCRIPT), "process.bpmn20.xml"); } }
camunda/camunda-bpm-platform
qa/integration-tests-engine/src/test/java/org/camunda/bpm/integrationtest/functional/scriptengine/GroovyScriptEngineSupportTest.java
Java
apache-2.0
1,391
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.eas.designer.application.query.nodes; import com.eas.client.model.gui.DatamodelDesignUtils; import com.eas.client.model.query.QueryEntity; import com.eas.designer.datamodel.nodes.EntityNode; import org.openide.ErrorManager; import org.openide.awt.UndoRedo; import org.openide.nodes.PropertySupport; import org.openide.nodes.Sheet; import static org.openide.nodes.Sheet.PROPERTIES; import org.openide.util.Lookup; /** * * @author mg */ public class QueryEntityNode extends EntityNode<QueryEntity> { public static final String ALIAS_PROP_NAME = "alias"; public QueryEntityNode(QueryEntity aEntity, UndoRedo.Manager aUndoReciever, Lookup aLookup) throws Exception { super(aEntity, aUndoReciever, new QueryEntityNodeChildren(aEntity, aUndoReciever, aLookup), aLookup); } @Override public String getName() { String schemaName = entity.getTableSchemaName(); String tableName = entity.getTableName(); String res = (schemaName != null && !schemaName.isEmpty()) ? schemaName + "." + tableName : tableName; return res != null ? res : ""; } @Override public String getDisplayName() { String text = super.getDisplayName(); if (text == null || text.isEmpty()) { text = DatamodelDesignUtils.getLocalizedString("noName"); } return text; } @Override public boolean canRename() { return false; } @Override protected Sheet createSheet() { try { Sheet sheet = super.createSheet(); nameToProperty.remove(NAME_PROP_NAME); Sheet.Set defaultSet = sheet.get(PROPERTIES); defaultSet.remove(PROP_NAME); PropertySupport.Reflection<String> aliasProp = new PropertySupport.Reflection<>(entity, String.class, ALIAS_PROP_NAME); aliasProp.setName(ALIAS_PROP_NAME); defaultSet.put(aliasProp); nameToProperty.put(ALIAS_PROP_NAME, aliasProp); return sheet; } catch (NoSuchMethodException ex) { ErrorManager.getDefault().notify(ex); return super.createSheet(); } } }
jskonst/PlatypusJS
designer/PlatypusQueries/src/com/eas/designer/application/query/nodes/QueryEntityNode.java
Java
apache-2.0
2,262
<?php namespace PHPExcel\Reader; /** * PHPExcel_Reader_SYLK * * Copyright (c) 2006 - 2015 PHPExcel * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * @category PHPExcel * @package PHPExcel_Reader * @copyright Copyright (c) 2006 - 2015 PHPExcel (http://www.codeplex.com/PHPExcel) * @license http://www.gnu.org/licenses/old-licenses/lgpl-2.1.txt LGPL * @version ##VERSION##, ##DATE## */ class SYLK extends BaseReader implements IReader { /** * Input encoding * * @var string */ private $inputEncoding = 'ANSI'; /** * Sheet index to read * * @var int */ private $sheetIndex = 0; /** * Formats * * @var array */ private $formats = array(); /** * Format Count * * @var int */ private $format = 0; /** * Create a new SYLK Reader instance */ public function __construct() { $this->readFilter = new DefaultReadFilter(); } /** * Validate that the current file is a SYLK file * * @return boolean */ protected function isValidFormat() { // Read sample data (first 2 KB will do) $data = fread($this->fileHandle, 2048); // Count delimiters in file $delimiterCount = substr_count($data, ';'); if ($delimiterCount < 1) { return false; } // Analyze first line looking for ID; signature $lines = explode("\n", $data); if (substr($lines[0], 0, 4) != 'ID;P') { return false; } return true; } /** * Set input encoding * * @param string $pValue Input encoding */ public function setInputEncoding($pValue = 'ANSI') { $this->inputEncoding = $pValue; return $this; } /** * Get input encoding * * @return string */ public function getInputEncoding() { return $this->inputEncoding; } /** * Return worksheet info (Name, Last Column Letter, Last Column Index, Total Rows, Total Columns) * * @param string $pFilename * @throws Exception */ public function listWorksheetInfo($pFilename) { // Open file $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); throw new Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->fileHandle; rewind($fileHandle); $worksheetInfo = array(); $worksheetInfo[0]['worksheetName'] = 'Worksheet'; $worksheetInfo[0]['lastColumnLetter'] = 'A'; $worksheetInfo[0]['lastColumnIndex'] = 0; $worksheetInfo[0]['totalRows'] = 0; $worksheetInfo[0]['totalColumns'] = 0; // Loop through file $rowData = array(); // loop through one row (line) at a time in the file $rowIndex = 0; while (($rowData = fgets($fileHandle)) !== false) { $columnIndex = 0; // convert SYLK encoded $rowData to UTF-8 $rowData = \PHPExcel\Shared\StringHelper::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); $dataType = array_shift($rowData); if ($dataType == 'C') { // Read cell value data foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'C': case 'X': $columnIndex = substr($rowDatum, 1) - 1; break; case 'R': case 'Y': $rowIndex = substr($rowDatum, 1); break; } $worksheetInfo[0]['totalRows'] = max($worksheetInfo[0]['totalRows'], $rowIndex); $worksheetInfo[0]['lastColumnIndex'] = max($worksheetInfo[0]['lastColumnIndex'], $columnIndex); } } } $worksheetInfo[0]['lastColumnLetter'] = \PHPExcel\Cell::stringFromColumnIndex($worksheetInfo[0]['lastColumnIndex']); $worksheetInfo[0]['totalColumns'] = $worksheetInfo[0]['lastColumnIndex'] + 1; // Close file fclose($fileHandle); return $worksheetInfo; } /** * Loads PHPExcel from file * * @param string $pFilename * @return \PHPExcel\Spreadsheet * @throws Exception */ public function load($pFilename) { // Create new Spreadsheet $objPHPExcel = new \PHPExcel\Spreadsheet(); // Load into this instance return $this->loadIntoExisting($pFilename, $objPHPExcel); } /** * Loads PHPExcel from file into PHPExcel instance * * @param string $pFilename * @param \PHPExcel\Spreadsheet $objPHPExcel * @return \PHPExcel\Spreadsheet * @throws Exception */ public function loadIntoExisting($pFilename, \PHPExcel\Spreadsheet $objPHPExcel) { // Open file $this->openFile($pFilename); if (!$this->isValidFormat()) { fclose($this->fileHandle); throw new Exception($pFilename . " is an Invalid Spreadsheet file."); } $fileHandle = $this->fileHandle; rewind($fileHandle); // Create new Worksheets while ($objPHPExcel->getSheetCount() <= $this->sheetIndex) { $objPHPExcel->createSheet(); } $objPHPExcel->setActiveSheetIndex($this->sheetIndex); $fromFormats = array('\-', '\ '); $toFormats = array('-', ' '); // Loop through file $rowData = array(); $column = $row = ''; // loop through one row (line) at a time in the file while (($rowData = fgets($fileHandle)) !== false) { // convert SYLK encoded $rowData to UTF-8 $rowData = \PHPExcel\Shared\StringHelper::SYLKtoUTF8($rowData); // explode each row at semicolons while taking into account that literal semicolon (;) // is escaped like this (;;) $rowData = explode("\t", str_replace('¤', ';', str_replace(';', "\t", str_replace(';;', '¤', rtrim($rowData))))); $dataType = array_shift($rowData); // Read shared styles if ($dataType == 'P') { $formatArray = array(); foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'P': $formatArray['numberformat']['code'] = str_replace($fromFormats, $toFormats, substr($rowDatum, 1)); break; case 'E': case 'F': $formatArray['font']['name'] = substr($rowDatum, 1); break; case 'L': $formatArray['font']['size'] = substr($rowDatum, 1); break; case 'S': $styleSettings = substr($rowDatum, 1); for ($i=0; $i<strlen($styleSettings); ++$i) { switch ($styleSettings{$i}) { case 'I': $formatArray['font']['italic'] = true; break; case 'D': $formatArray['font']['bold'] = true; break; case 'T': $formatArray['borders']['top']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'B': $formatArray['borders']['bottom']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'L': $formatArray['borders']['left']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'R': $formatArray['borders']['right']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; } } break; } } $this->formats['P'.$this->format++] = $formatArray; // Read cell value data } elseif ($dataType == 'C') { $hasCalculatedValue = false; $cellData = $cellDataFormula = ''; foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'C': case 'X': $column = substr($rowDatum, 1); break; case 'R': case 'Y': $row = substr($rowDatum, 1); break; case 'K': $cellData = substr($rowDatum, 1); break; case 'E': $cellDataFormula = '='.substr($rowDatum, 1); // Convert R1C1 style references to A1 style references (but only when not quoted) $temp = explode('"', $cellDataFormula); $key = false; foreach ($temp as &$value) { // Only count/replace in alternate array entries if ($key = !$key) { preg_match_all('/(R(\[?-?\d*\]?))(C(\[?-?\d*\]?))/', $value, $cellReferences, PREG_SET_ORDER+PREG_OFFSET_CAPTURE); // Reverse the matches array, otherwise all our offsets will become incorrect if we modify our way // through the formula from left to right. Reversing means that we work right to left.through // the formula $cellReferences = array_reverse($cellReferences); // Loop through each R1C1 style reference in turn, converting it to its A1 style equivalent, // then modify the formula to use that new reference foreach ($cellReferences as $cellReference) { $rowReference = $cellReference[2][0]; // Empty R reference is the current row if ($rowReference == '') { $rowReference = $row; } // Bracketed R references are relative to the current row if ($rowReference{0} == '[') { $rowReference = $row + trim($rowReference, '[]'); } $columnReference = $cellReference[4][0]; // Empty C reference is the current column if ($columnReference == '') { $columnReference = $column; } // Bracketed C references are relative to the current column if ($columnReference{0} == '[') { $columnReference = $column + trim($columnReference, '[]'); } $A1CellReference = \PHPExcel\Cell::stringFromColumnIndex($columnReference-1).$rowReference; $value = substr_replace($value, $A1CellReference, $cellReference[0][1], strlen($cellReference[0][0])); } } } unset($value); // Then rebuild the formula string $cellDataFormula = implode('"', $temp); $hasCalculatedValue = true; break; } } $columnLetter = \PHPExcel\Cell::stringFromColumnIndex($column-1); $cellData = \PHPExcel\Calculation::unwrapResult($cellData); // Set cell value $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setValue(($hasCalculatedValue) ? $cellDataFormula : $cellData); if ($hasCalculatedValue) { $cellData = \PHPExcel\Calculation::unwrapResult($cellData); $objPHPExcel->getActiveSheet()->getCell($columnLetter.$row)->setCalculatedValue($cellData); } // Read cell formatting } elseif ($dataType == 'F') { $formatStyle = $columnWidth = $styleSettings = ''; $styleData = array(); foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'C': case 'X': $column = substr($rowDatum, 1); break; case 'R': case 'Y': $row = substr($rowDatum, 1); break; case 'P': $formatStyle = $rowDatum; break; case 'W': list($startCol, $endCol, $columnWidth) = explode(' ', substr($rowDatum, 1)); break; case 'S': $styleSettings = substr($rowDatum, 1); for ($i=0; $i<strlen($styleSettings); ++$i) { switch ($styleSettings{$i}) { case 'I': $styleData['font']['italic'] = true; break; case 'D': $styleData['font']['bold'] = true; break; case 'T': $styleData['borders']['top']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'B': $styleData['borders']['bottom']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'L': $styleData['borders']['left']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; case 'R': $styleData['borders']['right']['style'] = \PHPExcel\Style\Border::BORDER_THIN; break; } } break; } } if (($formatStyle > '') && ($column > '') && ($row > '')) { $columnLetter = \PHPExcel\Cell::stringFromColumnIndex($column-1); if (isset($this->formats[$formatStyle])) { $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($this->formats[$formatStyle]); } } if ((!empty($styleData)) && ($column > '') && ($row > '')) { $columnLetter = \PHPExcel\Cell::stringFromColumnIndex($column-1); $objPHPExcel->getActiveSheet()->getStyle($columnLetter.$row)->applyFromArray($styleData); } if ($columnWidth > '') { if ($startCol == $endCol) { $startCol = \PHPExcel\Cell::stringFromColumnIndex($startCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); } else { $startCol = \PHPExcel\Cell::stringFromColumnIndex($startCol-1); $endCol = \PHPExcel\Cell::stringFromColumnIndex($endCol-1); $objPHPExcel->getActiveSheet()->getColumnDimension($startCol)->setWidth($columnWidth); do { $objPHPExcel->getActiveSheet()->getColumnDimension(++$startCol)->setWidth($columnWidth); } while ($startCol != $endCol); } } } else { foreach ($rowData as $rowDatum) { switch ($rowDatum{0}) { case 'C': case 'X': $column = substr($rowDatum, 1); break; case 'R': case 'Y': $row = substr($rowDatum, 1); break; } } } } // Close file fclose($fileHandle); // Return return $objPHPExcel; } /** * Get sheet index * * @return int */ public function getSheetIndex() { return $this->sheetIndex; } /** * Set sheet index * * @param int $pValue Sheet index * @return SYLK */ public function setSheetIndex($pValue = 0) { $this->sheetIndex = $pValue; return $this; } }
winerQin/yesnophp
library/PHPExcel/Reader/SYLK.php
PHP
apache-2.0
19,386
"""Device tracker helpers.""" import asyncio from types import ModuleType from typing import Any, Callable, Dict, Optional import attr from homeassistant.const import ATTR_LATITUDE, ATTR_LONGITUDE from homeassistant.core import callback from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers import config_per_platform from homeassistant.helpers.event import async_track_time_interval from homeassistant.helpers.typing import ConfigType, HomeAssistantType from homeassistant.setup import async_prepare_setup_platform from homeassistant.util import dt as dt_util from .const import ( CONF_SCAN_INTERVAL, DOMAIN, LOGGER, PLATFORM_TYPE_LEGACY, SCAN_INTERVAL, SOURCE_TYPE_ROUTER, ) @attr.s class DeviceTrackerPlatform: """Class to hold platform information.""" LEGACY_SETUP = ( "async_get_scanner", "get_scanner", "async_setup_scanner", "setup_scanner", ) name = attr.ib(type=str) platform = attr.ib(type=ModuleType) config = attr.ib(type=Dict) @property def type(self): """Return platform type.""" for methods, platform_type in ((self.LEGACY_SETUP, PLATFORM_TYPE_LEGACY),): for meth in methods: if hasattr(self.platform, meth): return platform_type return None async def async_setup_legacy(self, hass, tracker, discovery_info=None): """Set up a legacy platform.""" LOGGER.info("Setting up %s.%s", DOMAIN, self.type) try: scanner = None setup = None if hasattr(self.platform, "async_get_scanner"): scanner = await self.platform.async_get_scanner( hass, {DOMAIN: self.config} ) elif hasattr(self.platform, "get_scanner"): scanner = await hass.async_add_job( self.platform.get_scanner, hass, {DOMAIN: self.config} ) elif hasattr(self.platform, "async_setup_scanner"): setup = await self.platform.async_setup_scanner( hass, self.config, tracker.async_see, discovery_info ) elif hasattr(self.platform, "setup_scanner"): setup = await hass.async_add_job( self.platform.setup_scanner, hass, self.config, tracker.see, discovery_info, ) else: raise HomeAssistantError("Invalid legacy device_tracker platform.") if scanner: async_setup_scanner_platform( hass, self.config, scanner, tracker.async_see, self.type ) return if not setup: LOGGER.error("Error setting up platform %s", self.type) return except Exception: # pylint: disable=broad-except LOGGER.exception("Error setting up platform %s", self.type) async def async_extract_config(hass, config): """Extract device tracker config and split between legacy and modern.""" legacy = [] for platform in await asyncio.gather( *( async_create_platform_type(hass, config, p_type, p_config) for p_type, p_config in config_per_platform(config, DOMAIN) ) ): if platform is None: continue if platform.type == PLATFORM_TYPE_LEGACY: legacy.append(platform) else: raise ValueError( f"Unable to determine type for {platform.name}: {platform.type}" ) return legacy async def async_create_platform_type( hass, config, p_type, p_config ) -> Optional[DeviceTrackerPlatform]: """Determine type of platform.""" platform = await async_prepare_setup_platform(hass, config, DOMAIN, p_type) if platform is None: return None return DeviceTrackerPlatform(p_type, platform, p_config) @callback def async_setup_scanner_platform( hass: HomeAssistantType, config: ConfigType, scanner: Any, async_see_device: Callable, platform: str, ): """Set up the connect scanner-based platform to device tracker. This method must be run in the event loop. """ interval = config.get(CONF_SCAN_INTERVAL, SCAN_INTERVAL) update_lock = asyncio.Lock() scanner.hass = hass # Initial scan of each mac we also tell about host name for config seen: Any = set() async def async_device_tracker_scan(now: dt_util.dt.datetime): """Handle interval matches.""" if update_lock.locked(): LOGGER.warning( "Updating device list from %s took longer than the scheduled " "scan interval %s", platform, interval, ) return async with update_lock: found_devices = await scanner.async_scan_devices() for mac in found_devices: if mac in seen: host_name = None else: host_name = await scanner.async_get_device_name(mac) seen.add(mac) try: extra_attributes = await scanner.async_get_extra_attributes(mac) except NotImplementedError: extra_attributes = {} kwargs = { "mac": mac, "host_name": host_name, "source_type": SOURCE_TYPE_ROUTER, "attributes": { "scanner": scanner.__class__.__name__, **extra_attributes, }, } zone_home = hass.states.get(hass.components.zone.ENTITY_ID_HOME) if zone_home: kwargs["gps"] = [ zone_home.attributes[ATTR_LATITUDE], zone_home.attributes[ATTR_LONGITUDE], ] kwargs["gps_accuracy"] = 0 hass.async_create_task(async_see_device(**kwargs)) async_track_time_interval(hass, async_device_tracker_scan, interval) hass.async_create_task(async_device_tracker_scan(None))
nkgilley/home-assistant
homeassistant/components/device_tracker/setup.py
Python
apache-2.0
6,224
<?php /** * LICENSE: 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. * * PHP version 5 * * @category Microsoft * * @author Azure PHP SDK <[email protected]> * @copyright Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * * @link https://github.com/windowsazure/azure-sdk-for-php */ namespace Tests\unit\WindowsAzure\MediaServices\Models; use WindowsAzure\MediaServices\Models\ErrorDetail; /** * Represents access policy object used in media services. * * @category Microsoft * * @author Azure PHP SDK <[email protected]> * @copyright Microsoft Corporation * @license http://www.apache.org/licenses/LICENSE-2.0 Apache License 2.0 * * @version Release: 0.5.0_2016-11 * * @link https://github.com/windowsazure/azure-sdk-for-php */ class ErrorDetailTest extends \PHPUnit_Framework_TestCase { /** * @covers \WindowsAzure\MediaServices\Models\ErrorDetail::createFromOptions * @covers \WindowsAzure\MediaServices\Models\ErrorDetail::fromArray */ public function testCreateFromOptions() { // Setup $options = [ 'Code' => 404, 'Message' => 'Not found', ]; // Test $error = ErrorDetail::createFromOptions($options); //Assert $this->assertEquals($options['Code'], $error->getCode()); $this->assertEquals($options['Message'], $error->getMessage()); } /** * @covers \WindowsAzure\MediaServices\Models\ErrorDetail::getCode */ public function testGetCode() { // Setup $options = [ 'Code' => 404, 'Message' => 'Not found', ]; $error = ErrorDetail::createFromOptions($options); // Test $result = $error->getCode(); // Assert $this->assertEquals($options['Code'], $result); } /** * @covers \WindowsAzure\MediaServices\Models\ErrorDetail::getMessage */ public function testGetMessage() { // Setup $options = [ 'Code' => 404, 'Message' => 'Not found', ]; $error = ErrorDetail::createFromOptions($options); // Test $result = $error->getMessage(); // Assert $this->assertEquals($options['Message'], $result); } }
chewbaccateam/hackfest
vendor/microsoft/windowsazure/tests/unit/WindowsAzure/MediaServices/Models/ErrorDetailTest.php
PHP
apache-2.0
2,886
/* Copyright 2017 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. ==============================================================================*/ // This abstracts command line arguments in toco. // Arg<T> is a parseable type that can register a default value, be able to // parse itself, and keep track of whether it was specified. #ifndef THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_ARGS_H_ #define THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_ARGS_H_ #include <functional> #include <unordered_map> #include <vector> #include "absl/strings/numbers.h" #include "absl/strings/str_split.h" #include "tensorflow/contrib/lite/toco/toco_port.h" #include "tensorflow/contrib/lite/toco/toco_types.h" namespace toco { // Since std::vector<int32> is in the std namespace, and we are not allowed // to add ParseFlag/UnparseFlag to std, we introduce a simple wrapper type // to use as the flag type: struct IntList { std::vector<int32> elements; }; struct StringMapList { std::vector<std::unordered_map<string, string>> elements; }; // command_line_flags.h don't track whether or not a flag is specified. Arg // contains the value (which will be default if not specified) and also // whether the flag is specified. // TODO(aselle): consider putting doc string and ability to construct the // tensorflow argument into this, so declaration of parameters can be less // distributed. // Every template specialization of Arg is required to implement // default_value(), specified(), value(), parse(), bind(). template <class T> class Arg final { public: explicit Arg(T default_ = T()) : value_(default_) {} virtual ~Arg() {} // Provide default_value() to arg list T default_value() const { return value_; } // Return true if the command line argument was specified on the command line. bool specified() const { return specified_; } // Const reference to parsed value. const T& value() const { return value_; } // Parsing callback for the tensorflow::Flags code bool parse(T value_in) { value_ = value_in; specified_ = true; return true; } // Bind the parse member function so tensorflow::Flags can call it. std::function<bool(T)> bind() { return std::bind(&Arg::parse, this, std::placeholders::_1); } private: // Becomes true after parsing if the value was specified bool specified_ = false; // Value of the argument (initialized to the default in the constructor). T value_; }; template <> class Arg<toco::IntList> final { public: // Provide default_value() to arg list string default_value() const { return ""; } // Return true if the command line argument was specified on the command line. bool specified() const { return specified_; } // Bind the parse member function so tensorflow::Flags can call it. bool parse(string text) { parsed_value_.elements.clear(); specified_ = true; // strings::Split("") produces {""}, but we need {} on empty input. // TODO(aselle): Moved this from elsewhere, but ahentz recommends we could // use absl::SplitLeadingDec32Values(text.c_str(), &parsed_values_.elements) if (!text.empty()) { int32 element; for (absl::string_view part : absl::StrSplit(text, ',')) { if (!SimpleAtoi(part, &element)) return false; parsed_value_.elements.push_back(element); } } return true; } std::function<bool(string)> bind() { return std::bind(&Arg::parse, this, std::placeholders::_1); } const toco::IntList& value() const { return parsed_value_; } private: toco::IntList parsed_value_; bool specified_ = false; }; template <> class Arg<toco::StringMapList> final { public: // Provide default_value() to StringMapList string default_value() const { return ""; } // Return true if the command line argument was specified on the command line. bool specified() const { return specified_; } // Bind the parse member function so tensorflow::Flags can call it. bool parse(string text) { parsed_value_.elements.clear(); specified_ = true; if (text.empty()) { return true; } #if defined(PLATFORM_GOOGLE) std::vector<absl::string_view> outer_vector; absl::string_view text_disposable_copy = text; SplitStructuredLine(text_disposable_copy, ',', "{}", &outer_vector); for (const absl::string_view& outer_member_stringpiece : outer_vector) { string outer_member(outer_member_stringpiece); if (outer_member.empty()) { continue; } string outer_member_copy = outer_member; absl::StripAsciiWhitespace(&outer_member); if (!TryStripPrefixString(outer_member, "{", &outer_member)) return false; if (!TryStripSuffixString(outer_member, "}", &outer_member)) return false; const std::vector<string> inner_fields_vector = strings::Split(outer_member, ','); std::unordered_map<string, string> element; for (const string& member_field : inner_fields_vector) { std::vector<string> outer_member_key_value = strings::Split(member_field, ':'); if (outer_member_key_value.size() != 2) return false; string& key = outer_member_key_value[0]; string& value = outer_member_key_value[1]; absl::StripAsciiWhitespace(&key); absl::StripAsciiWhitespace(&value); if (element.count(key) != 0) return false; element[key] = value; } parsed_value_.elements.push_back(element); } return true; #else // TODO(aselle): Fix argument parsing when absl supports structuredline fprintf(stderr, "%s:%d StringMapList arguments not supported\n", __FILE__, __LINE__); abort(); #endif } std::function<bool(string)> bind() { return std::bind(&Arg::parse, this, std::placeholders::_1); } const toco::StringMapList& value() const { return parsed_value_; } private: toco::StringMapList parsed_value_; bool specified_ = false; }; // Flags that describe a model. See model_cmdline_flags.cc for details. struct ParsedModelFlags { Arg<string> input_array; Arg<string> input_arrays; Arg<string> output_array; Arg<string> output_arrays; Arg<string> input_shapes; Arg<float> mean_value = Arg<float>(0.f); Arg<string> mean_values; Arg<float> std_value = Arg<float>(1.f); Arg<string> std_values; Arg<string> input_data_type; Arg<string> input_data_types; Arg<bool> variable_batch = Arg<bool>(false); Arg<toco::IntList> input_shape; Arg<toco::StringMapList> rnn_states; Arg<toco::StringMapList> model_checks; // Debugging output options. // TODO(benoitjacob): these shouldn't be ModelFlags. Arg<string> graphviz_first_array; Arg<string> graphviz_last_array; Arg<string> dump_graphviz; Arg<bool> dump_graphviz_video = Arg<bool>(false); }; // Flags that describe the operation you would like to do (what conversion // you want). See toco_cmdline_flags.cc for details. struct ParsedTocoFlags { Arg<string> input_file; Arg<string> output_file; Arg<string> input_format; Arg<string> output_format; // TODO(aselle): command_line_flags doesn't support doubles Arg<float> default_ranges_min = Arg<float>(0.); Arg<float> default_ranges_max = Arg<float>(0.); Arg<string> inference_type; Arg<string> inference_input_type; Arg<bool> drop_fake_quant = Arg<bool>(false); Arg<bool> reorder_across_fake_quant = Arg<bool>(false); Arg<bool> allow_custom_ops = Arg<bool>(false); // Deprecated flags Arg<string> input_type; Arg<string> input_types; Arg<bool> drop_control_dependency = Arg<bool>(false); }; } // namespace toco #endif // THIRD_PARTY_TENSORFLOW_CONTRIB_LITE_TOCO_ARGS_H_
Kongsea/tensorflow
tensorflow/contrib/lite/toco/args.h
C
apache-2.0
8,135
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/appmesh/AppMesh_EXPORTS.h> #include <aws/appmesh/AppMeshRequest.h> #include <aws/core/utils/memory/stl/AWSString.h> #include <aws/appmesh/model/VirtualNodeSpec.h> #include <utility> #include <aws/core/utils/UUID.h> namespace Aws { namespace Http { class URI; } //namespace Http namespace AppMesh { namespace Model { /** * <zonbook></zonbook><xhtml></xhtml><p><h3>See Also:</h3> <a * href="http://docs.aws.amazon.com/goto/WebAPI/appmesh-2019-01-25/UpdateVirtualNodeInput">AWS * API Reference</a></p> */ class AWS_APPMESH_API UpdateVirtualNodeRequest : public AppMeshRequest { public: UpdateVirtualNodeRequest(); // Service request name is the Operation name which will send this request out, // each operation should has unique request name, so that we can get operation's name from this request. // Note: this is not true for response, multiple operations may have the same response name, // so we can not get operation's name from response. inline virtual const char* GetServiceRequestName() const override { return "UpdateVirtualNode"; } Aws::String SerializePayload() const override; void AddQueryStringParameters(Aws::Http::URI& uri) const override; /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline const Aws::String& GetClientToken() const{ return m_clientToken; } /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline bool ClientTokenHasBeenSet() const { return m_clientTokenHasBeenSet; } /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline void SetClientToken(const Aws::String& value) { m_clientTokenHasBeenSet = true; m_clientToken = value; } /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline void SetClientToken(Aws::String&& value) { m_clientTokenHasBeenSet = true; m_clientToken = std::move(value); } /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline void SetClientToken(const char* value) { m_clientTokenHasBeenSet = true; m_clientToken.assign(value); } /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline UpdateVirtualNodeRequest& WithClientToken(const Aws::String& value) { SetClientToken(value); return *this;} /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline UpdateVirtualNodeRequest& WithClientToken(Aws::String&& value) { SetClientToken(std::move(value)); return *this;} /** * <p>Unique, case-sensitive identifier that you provide to ensure the idempotency * of the request. Up to 36 letters, numbers, hyphens, and underscores are * allowed.</p> */ inline UpdateVirtualNodeRequest& WithClientToken(const char* value) { SetClientToken(value); return *this;} /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline const Aws::String& GetMeshName() const{ return m_meshName; } /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline bool MeshNameHasBeenSet() const { return m_meshNameHasBeenSet; } /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline void SetMeshName(const Aws::String& value) { m_meshNameHasBeenSet = true; m_meshName = value; } /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline void SetMeshName(Aws::String&& value) { m_meshNameHasBeenSet = true; m_meshName = std::move(value); } /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline void SetMeshName(const char* value) { m_meshNameHasBeenSet = true; m_meshName.assign(value); } /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline UpdateVirtualNodeRequest& WithMeshName(const Aws::String& value) { SetMeshName(value); return *this;} /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline UpdateVirtualNodeRequest& WithMeshName(Aws::String&& value) { SetMeshName(std::move(value)); return *this;} /** * <p>The name of the service mesh that the virtual node resides in.</p> */ inline UpdateVirtualNodeRequest& WithMeshName(const char* value) { SetMeshName(value); return *this;} /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline const Aws::String& GetMeshOwner() const{ return m_meshOwner; } /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline bool MeshOwnerHasBeenSet() const { return m_meshOwnerHasBeenSet; } /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline void SetMeshOwner(const Aws::String& value) { m_meshOwnerHasBeenSet = true; m_meshOwner = value; } /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline void SetMeshOwner(Aws::String&& value) { m_meshOwnerHasBeenSet = true; m_meshOwner = std::move(value); } /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline void SetMeshOwner(const char* value) { m_meshOwnerHasBeenSet = true; m_meshOwner.assign(value); } /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline UpdateVirtualNodeRequest& WithMeshOwner(const Aws::String& value) { SetMeshOwner(value); return *this;} /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline UpdateVirtualNodeRequest& WithMeshOwner(Aws::String&& value) { SetMeshOwner(std::move(value)); return *this;} /** * <p>The AWS IAM account ID of the service mesh owner. If the account ID is not * your own, then it's the ID of the account that shared the mesh with your * account. For more information about mesh sharing, see <a * href="https://docs.aws.amazon.com/app-mesh/latest/userguide/sharing.html">Working * with shared meshes</a>.</p> */ inline UpdateVirtualNodeRequest& WithMeshOwner(const char* value) { SetMeshOwner(value); return *this;} /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline const VirtualNodeSpec& GetSpec() const{ return m_spec; } /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline bool SpecHasBeenSet() const { return m_specHasBeenSet; } /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline void SetSpec(const VirtualNodeSpec& value) { m_specHasBeenSet = true; m_spec = value; } /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline void SetSpec(VirtualNodeSpec&& value) { m_specHasBeenSet = true; m_spec = std::move(value); } /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline UpdateVirtualNodeRequest& WithSpec(const VirtualNodeSpec& value) { SetSpec(value); return *this;} /** * <p>The new virtual node specification to apply. This overwrites the existing * data.</p> */ inline UpdateVirtualNodeRequest& WithSpec(VirtualNodeSpec&& value) { SetSpec(std::move(value)); return *this;} /** * <p>The name of the virtual node to update.</p> */ inline const Aws::String& GetVirtualNodeName() const{ return m_virtualNodeName; } /** * <p>The name of the virtual node to update.</p> */ inline bool VirtualNodeNameHasBeenSet() const { return m_virtualNodeNameHasBeenSet; } /** * <p>The name of the virtual node to update.</p> */ inline void SetVirtualNodeName(const Aws::String& value) { m_virtualNodeNameHasBeenSet = true; m_virtualNodeName = value; } /** * <p>The name of the virtual node to update.</p> */ inline void SetVirtualNodeName(Aws::String&& value) { m_virtualNodeNameHasBeenSet = true; m_virtualNodeName = std::move(value); } /** * <p>The name of the virtual node to update.</p> */ inline void SetVirtualNodeName(const char* value) { m_virtualNodeNameHasBeenSet = true; m_virtualNodeName.assign(value); } /** * <p>The name of the virtual node to update.</p> */ inline UpdateVirtualNodeRequest& WithVirtualNodeName(const Aws::String& value) { SetVirtualNodeName(value); return *this;} /** * <p>The name of the virtual node to update.</p> */ inline UpdateVirtualNodeRequest& WithVirtualNodeName(Aws::String&& value) { SetVirtualNodeName(std::move(value)); return *this;} /** * <p>The name of the virtual node to update.</p> */ inline UpdateVirtualNodeRequest& WithVirtualNodeName(const char* value) { SetVirtualNodeName(value); return *this;} private: Aws::String m_clientToken; bool m_clientTokenHasBeenSet; Aws::String m_meshName; bool m_meshNameHasBeenSet; Aws::String m_meshOwner; bool m_meshOwnerHasBeenSet; VirtualNodeSpec m_spec; bool m_specHasBeenSet; Aws::String m_virtualNodeName; bool m_virtualNodeNameHasBeenSet; }; } // namespace Model } // namespace AppMesh } // namespace Aws
awslabs/aws-sdk-cpp
aws-cpp-sdk-appmesh/include/aws/appmesh/model/UpdateVirtualNodeRequest.h
C
apache-2.0
12,403
# Copyright 2011 OpenStack LLC. # 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. from webob import exc from nova import exception from nova import flags from nova import log as logging from nova.api.openstack import common from nova.api.openstack import wsgi from nova.auth import manager FLAGS = flags.FLAGS LOG = logging.getLogger('nova.api.openstack') def _translate_keys(user): return dict(id=user.id, name=user.name, access=user.access, secret=user.secret, admin=user.admin) class Controller(object): def __init__(self): self.manager = manager.AuthManager() def _check_admin(self, context): """We cannot depend on the db layer to check for admin access for the auth manager, so we do it here""" if not context.is_admin: raise exception.AdminRequired() def index(self, req): """Return all users in brief""" users = self.manager.get_users() users = common.limited(users, req) users = [_translate_keys(user) for user in users] return dict(users=users) def detail(self, req): """Return all users in detail""" return self.index(req) def show(self, req, id): """Return data about the given user id""" #NOTE(justinsb): The drivers are a little inconsistent in how they # deal with "NotFound" - some throw, some return None. try: user = self.manager.get_user(id) except exception.NotFound: user = None if user is None: raise exc.HTTPNotFound() return dict(user=_translate_keys(user)) def delete(self, req, id): self._check_admin(req.environ['nova.context']) self.manager.delete_user(id) return {} def create(self, req, body): self._check_admin(req.environ['nova.context']) is_admin = body['user'].get('admin') in ('T', 'True', True) name = body['user'].get('name') access = body['user'].get('access') secret = body['user'].get('secret') user = self.manager.create_user(name, access, secret, is_admin) return dict(user=_translate_keys(user)) def update(self, req, id, body): self._check_admin(req.environ['nova.context']) is_admin = body['user'].get('admin') if is_admin is not None: is_admin = is_admin in ('T', 'True', True) access = body['user'].get('access') secret = body['user'].get('secret') self.manager.modify_user(id, access, secret, is_admin) return dict(user=_translate_keys(self.manager.get_user(id))) def create_resource(): metadata = { "attributes": { "user": ["id", "name", "access", "secret", "admin"], }, } body_serializers = { 'application/xml': wsgi.XMLDictSerializer(metadata=metadata), } serializer = wsgi.ResponseSerializer(body_serializers) return wsgi.Resource(Controller(), serializer=serializer)
nii-cloud/dodai-compute
nova/api/openstack/users.py
Python
apache-2.0
3,595
# Applier target inferencing Composition produces a tree of nodes and uses an applier to build and make changes to the tree implied by composition. If a composable function directly or indirectly calls `ComposeNode` then it is tied to an applier that can handle the type of node being emitted by the `ComposeNode`. `ComposeNode` contains a runtime check to ensure that the applier is of the expected type. However, currently, there is no warning or error generated when a composition function is called that expects a different applier than is provided. For Compose UI 1.0 this was not as important as there are only two appliers used by Compose UI, the `UIApplier` and the `VectorApplier` and vector composable are rarely used so calling the incorrect composable function is rare. However, as appliers proliferate, such as Wear projections, or menu trees for Compose Desktop, the likelihood of calling an incorrect composable grows larger and detecting these statically is more important. Requiring to specify the applier seems clumsy and inappropriate since, in 1.0, it wasn't necessary, and especially since the inference rules are fairly simple. There is only one parameter that needs to be determined, the type of the applier of the implied `$composer` parameter. From now on I will be referring to this as the type of the applier when it technically is the type of the applier instance used by the composer. In most cases the applier type is simply the applier type required by composition functions it calls. For example, if a composable function calls `Text` it must be a `UiApplier` composable because `Text` requires a `UIApplier`. ## Sketch of the algorithm The following Prolog program demonstrates how type type of the applier can be inferred from the content of the function (https://swish.swi-prolog.org/p/Composer%20Inference.swinb): ``` % An empty list can have any applier. applier([], _). % A list elements must have identical appliers. applier([H|T], A) :- applier(H, A), applier(T, A). % A layout has a uiApplier applier(layout, uiApplier). % A layout with content has a uiApplier and its content must have a uiApplier. applier(layout(C), uiApplier) :- applier(C, uiApplier). % A vector has a vector Applier. applier(vector, vectorApplier). % A vector with content has a vector applier and its content must have a vector applier applier(vector(C), vectorApplier) :- applier(C, vectorApplier). ``` The above corresponds to calling `ComposeNode` (from Layout.kt and Vector.kt) and can easily be derived from the body of the call. Taking advantage of of Prolog's unification algorithm, this can also express open composition functions like the `CompositionLocalProvider`, ``` % provider provides information to its content for all appliers. applier(provider(C), A) :- applier(C, A). ``` This predicate binds `A` to whatever applier the content `C` requires. In other words, `A` is an open applier bound by the lambda passed into `provider`. The above allows the validation that the composition function represented by, for example, ``` program( row([ drawing([ provider([ circle, square ]) ]) ]) ). ``` will not generate an applier runtime error (demonstrated in the link above). ## Declarations Inferring the applier type is translated into inferring one of two attributes for every composable function or composable lambda type, `ComposableTarget` and `ComposableOpenTarget`. ``` @Retention(AnnotationRetention.BINARY) @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER, ) annotation class ComposableTarget(val applier: String) ``` ``` @Retention(AnnotationRetention.BINARY) @Target( AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.TYPE, AnnotationTarget.TYPE_PARAMETER, ) annotation class ComposableOpenTarget(val index: Int) ``` ## Inferring appliers Every composable function has an applier scheme determined by the composable functions it calls or by explicit declarations. The scheme for a function is the applier token or open token variable for each `@Composable` function type in the description including the description itself and corresponds to the applier required by the respective composable function. For the purposes of this document, the scheme is represented by a Prolog-like list with identifier symbols being bound and [deBruijn](https://en.wikipedia.org/wiki/De_Bruijn_index) indices (written as a backslash followed by the index such as `\1`) are unbound variables and unbound variables with the same index bind together. A scheme is a list where the first element is the variable or token for the `$composer` of the function followed by the schemes for each composable parameter (which might also contain schemes for its parameters). For example, a composable function declared as, ``` @Composable @ComposableTarget("UI") fun Text(value: String) { … } ``` has the scheme `[UI]`. Open appliers, such as, ``` @Composable @ComposableOpenTarget(0) fun Providers( providers: vararg values: ProvidedValue<*>, content: @ComposableOpenTarget(0) @Composable () -> Unit ) { … content() … } ``` Has the scheme `[\0, [\0]]` meaning the applier for `Providers` and the `content` lambda must be the same but they can be any applier. Using these schemes an algorithm similar to the Prolog algorithm can be implemented. That is, when type variables are bound, the variables are unified using a normal unify algorithm. As backtracking is not needed so a simple mutating unify algorithm can be used as once unification fails the failure is reported, the requested binding is ignored, and the algorithm continues without backtracking. When inferring an applier scheme, 1. The applier schemes are determined for each composable call directly in the body of the composable function. If the function is inferred recursively while its scheme is being inferred then a scheme with all unique deBruijn indices matching the shape of the expected scheme is used instead. 2. A scheme is recursively inferred for all nested lambdas literals. 3. Applier variables are created for the function and each composable lambda parameter of the function. 4. For each call, fresh applier variables are created and are bound as defined by the scheme of the call; the symbols are bound and type variables with the same index in the scheme are bound together. Then, 1. the first fresh variable is bound to the function's variable 2. the composable lambda parameters are bound to the lambda literals or variable references 3. if a lambda expression is passed as a parameter it is treated as if it was called at the point of the parameter expression evaluation using the scheme declared or inferred for the type of the formal lambda parameter. If the expression is a lambda literal the variables are bound to both the scheme inferred for the lambda literal and the scheme of the type. 5. The scheme is created by resolving each applier variable for the function. If it is bound to a token then the token is placed in the scheme. If it is bound to a still open variable then the variable group is given a number (if it doesn't have one already) and the corresponding deBruijn index is produced. A variable's group is the set of type variables that are bound together with the type variable. An open type parameter can only be a member of one group as, once it is bound to another variable, it either is bound to a token or the variable groups are merged together. For each function or type with an inferred scheme the declaration is augmented with attributes where `CompositionTarget` is produced for tokens and `CompositionOpenTarget` is produced with the deBruijn index. This records the information necessary to infer appliers across module boundaries. If any of the bindings fails (that is if it tries to unify to two different tokens) a diagnostic is produced and the binding is ignored. Each variable can contain the location (e.g. PsiElement) that it was created for. When the binding fails, the locations associated with each variable in the binding group can be reported as being in error. # Implementation Notes ## `ComposableInferredTarget` Due to a limitation in how annotations are currentl handled in the Kotlin compiler, a plugin cannot add annotation to types, specifically the lambda types in a composable function. To work around this the plugin will infer a `ComposableInferredTarget` on the composable function which contains the scheme, as described above, instead of adding annotations to the composable lambda types in the function. For the target type checking described here `ComposableInferredTarget` takes presedence over any other attriutes present on the function. The implementation dropped the leading `\` from the deBruijn indexes, to save space, as they were unnecessary. ## Unification Because backtracking is not required, the unify algorithm implemented takes advantage of this by using a circular-linked-list to track the binding variables (two circular-linked lists can be concatenated together in `O(1)` time by swapping next pointer of just one element in each). The bindings can be reversed (e.g. swapping the next pointers back), but the code is not included to do so, so if backtracking is later required, `Bindings` would need to be updated accordingly. Details are provided in the class.
AndroidX/androidx
compose/compiler/design/target-inference.md
Markdown
apache-2.0
9,641
from __future__ import unicode_literals from .helpers import ( compose, non_string, format_tags, single_result, language_codes, element_to_dict, oai_process_uris, build_properties, datetime_formatter, doe_process_contributors, oai_process_contributors, dif_process_contributors ) DOESCHEMA = { "description": ('//dc:description/node()', compose(lambda x: x.strip(), single_result)), "contributors": ('//dc:creator/node()', compose(doe_process_contributors, lambda x: x.split(';'), single_result)), "title": ('//dc:title/node()', compose(lambda x: x.strip(), single_result)), "providerUpdatedDateTime": ('//dc:dateEntry/node()', compose(datetime_formatter, single_result)), "uris": { "canonicalUri": ('//dcq:identifier-citation/node()', compose(lambda x: x.strip(), single_result)), "objectUris": [('//dc:doi/node()', compose(lambda x: 'http://dx.doi.org/' + x, single_result))] }, "languages": ("//dc:language/text()", language_codes), "publisher": { "name": ("//dcq:publisher/node()", single_result) }, "sponsorships": [{ "sponsor": { "sponsorName": ("//dcq:publisherSponsor/node()", single_result) } }], "otherProperties": build_properties( ('coverage', '//dc:coverage/node()'), ('date', '//dc:date/node()'), ('format', '//dc:format/node()'), ('identifier', '//dc:identifier/node()'), ('identifierDOEcontract', '//dcq:identifierDOEcontract/node()'), ('identifierOther', '//dc:identifierOther/node()'), ('identifier-purl', '//dc:identifier-purl/node()'), ('identifierReport', '//dc:identifierReport/node()'), ('publisherAvailability', '//dcq:publisherAvailability/node()'), ('publisherCountry', '//dcq:publisherCountry/node()'), ('publisherResearch', '//dcq:publisherResearch/node()'), ('relation', '//dc:relation/node()'), ('rights', '//dc:rights/node()'), ('type', '//dc:type/node()'), ('typeQualifier', '//dc:typeQualifier/node()') ) } OAISCHEMA = { "contributors": ('//dc:creator/node()', '//dc:contributor/node()', oai_process_contributors), "uris": ('//dc:doi/node()', '//dc:identifier/node()', oai_process_uris), 'providerUpdatedDateTime': ('//ns0:header/ns0:datestamp/node()', compose(datetime_formatter, single_result)), 'title': ('//dc:title/node()', single_result), 'description': ('//dc:description/node()', single_result), 'subjects': ('//dc:subject/node()', format_tags), 'publisher': { 'name': ('//dc:publisher/node()', single_result) }, 'languages': ('//dc:language/text()', language_codes) } DIFSCHEMA = { "abstract": ('//dif:Summary/dif:Abstract/node()', single_result), "uris": ('//dif:URL/node()', oai_process_uris), "title": ('//dif:Entry_Title/node()', single_result), 'providerUpdatedDateTime': ('//OAI-PMH:header/OAI-PMH:datestamp/node()', compose(datetime_formatter, single_result)), "contributors": ('//dif:Personnel/dif:First_Name/node()', '//dif:Personnel/dif:Last_Name/node()', dif_process_contributors), "otherProperties": build_properties( ('metadataName', '//dif:Metadata_Name/node()'), ('metadataVersion', '//dif:Metadata_Version/node()'), ('lastDIFRevisionDate', '//dif:Last_DIF_Revision_Date/node()'), ('dataCenter', ('//dif:Data_Center/node()', compose( list, lambda x: map(element_to_dict, x), lambda x: filter(non_string, x) ))), ('relatedUrl', ('//dif:Related_URL/node()', compose( list, lambda x: map(element_to_dict, x), lambda x: filter(non_string, x) ))), ) }
CenterForOpenScience/scrapi
scrapi/base/schemas.py
Python
apache-2.0
3,782