text:
/**
 * 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;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileLock;
import java.nio.channels.OverlappingFileLockException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.hadoop.classification.InterfaceAudience;
import org.apache.hadoop.classification.InterfaceStability;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.HardLink;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.hdfs.DFSConfigKeys;
import org.apache.hadoop.hdfs.HdfsConfiguration;
import org.apache.hadoop.hdfs.protocol.Block;
import org.apache.hadoop.hdfs.protocol.LayoutVersion;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.NodeType;
import org.apache.hadoop.hdfs.server.common.HdfsServerConstants.StartupOption;
import org.apache.hadoop.hdfs.server.common.InconsistentFSStateException;
import org.apache.hadoop.hdfs.server.common.Storage;
import org.apache.hadoop.hdfs.server.common.StorageInfo;
import org.apache.hadoop.hdfs.server.protocol.DatanodeStorage;
import org.apache.hadoop.hdfs.server.protocol.NamespaceInfo;
import org.apache.hadoop.util.Daemon;
import org.apache.hadoop.util.DiskChecker;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ComparisonChain;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.util.concurrent.Futures;

/**
 * Data storage information file.
 *

 * @see Storage
 */
@InterfaceAudience.Private
public class DataStorage extends Storage {

  public final static String BLOCK_SUBDIR_PREFIX = "subdir";
  final static String STORAGE_DIR_DETACHED = "detach";
  public final static String STORAGE_DIR_RBW = "rbw";
  public final static String STORAGE_DIR_FINALIZED = "finalized";
  public final static String STORAGE_DIR_LAZY_PERSIST = "lazypersist";
  public final static String STORAGE_DIR_TMP = "tmp";

  /**
   * Set of bpids for which 'trash' is currently enabled.
   * When trash is enabled block files are moved under a separate
   * 'trash' folder instead of being deleted right away. This can
   * be useful during rolling upgrades, for example.
   * The set is backed by a concurrent HashMap.
   *
   * Even if trash is enabled, it is not used if a layout upgrade
   * is in progress for a storage directory i.e. if the previous
   * directory exists.
   */
  private Set<String> trashEnabledBpids;

  /**
   * Datanode UUID that this storage is currently attached to. This
   *  is the same as the legacy StorageID for datanodes that were
   *  upgraded from a pre-UUID version. For compatibility with prior
   *  versions of Datanodes we cannot make this field a UUID.
   */
  private volatile String datanodeUuid = null;

  // Maps block pool IDs to block pool storage
  private final Map<String, BlockPoolSliceStorage> bpStorageMap
      = Collections.synchronizedMap(new HashMap<String, BlockPoolSliceStorage>());

  DataStorage() {
    super(NodeType.DATA_NODE);
    trashEnabledBpids = Collections.newSetFromMap(
        new ConcurrentHashMap<String, Boolean>());
  }

  public BlockPoolSliceStorage getBPStorage(String bpid) {
    return bpStorageMap.get(bpid);
  }

  public DataStorage(StorageInfo storageInfo) {
    super(storageInfo);
  }

  public String getDatanodeUuid() {
    return datanodeUuid;
  }

  public void setDatanodeUuid(String newDatanodeUuid) {
    this.datanodeUuid = newDatanodeUuid;
  }

  private static boolean createStorageID(StorageDirectory sd, int lv) {
    // Clusters previously upgraded from layout versions earlier than
    // ADD_DATANODE_AND_STORAGE_UUIDS failed to correctly generate a
    // new storage ID. We check for that and fix it now.
    final boolean haveValidStorageId = DataNodeLayoutVersion.supports(
        LayoutVersion.Feature.ADD_DATANODE_AND_STORAGE_UUIDS, lv)
        && DatanodeStorage.isValidStorageId(sd.getStorageUuid());
    return createStorageID(sd, !haveValidStorageId);
  }

  /** Create an ID for this storage.
   * @return true if a new storage ID was generated.
   * */
  public static boolean createStorageID(
      StorageDirectory sd, boolean regenerateStorageIds) {
    final String oldStorageID = sd.getStorageUuid();
    if (oldStorageID == null || regenerateStorageIds) {
      sd.setStorageUuid(DatanodeStorage.generateUuid());
      LOG.info("Generated new storageID " + sd.getStorageUuid() +
          " for directory " + sd.getRoot() +
          (oldStorageID == null ? "" : (" to replace " + oldStorageID)));
      return true;
    }
    return false;
  }

  /**
   * Enable trash for the specified block pool storage. Even if trash is
   * enabled by the caller, it is superseded by the 'previous' directory
   * if a layout upgrade is in progress.
   */
  public void enableTrash(String bpid) {
    if (trashEnabledBpids.add(bpid)) {
      getBPStorage(bpid).stopTrashCleaner();
      LOG.info("Enabled trash for bpid " + bpid);
    }
  }

  public void clearTrash(String bpid) {
    if (trashEnabledBpids.contains(bpid)) {
      getBPStorage(bpid).clearTrash();
      trashEnabledBpids.remove(bpid);
      LOG.info("Cleared trash for bpid " + bpid);
    }
  }

  public boolean trashEnabled(String bpid) {
    return trashEnabledBpids.contains(bpid);
  }

  public void setRollingUpgradeMarker(String bpid) throws IOException {
    getBPStorage(bpid).setRollingUpgradeMarkers(storageDirs);
  }

  public void clearRollingUpgradeMarker(String bpid) throws IOException {
    getBPStorage(bpid).clearRollingUpgradeMarkers(storageDirs);
  }

  /**
   * If rolling upgrades are in progress then do not delete block files
   * immediately. Instead we move the block files to an intermediate
   * 'trash' directory. If there is a subsequent rollback, then the block
   * files will be restored from trash.
   *
   * @return trash directory if rolling upgrade is in progress, null
   *         otherwise.
   */
  public String getTrashDirectoryForBlockFile(String bpid, File blockFile) {
    if (trashEnabledBpids.contains(bpid)) {
      return getBPStorage(bpid).getTrashDirectory(blockFile);
    }
    return null;
  }

  /**
   * VolumeBuilder holds the metadata (e.g., the storage directories) of the
   * prepared volume returned from {@link prepareVolume()}. Calling {@link build()}
   * to add the metadata to {@link DataStorage} so that this prepared volume can
   * be active.
   */
  @InterfaceAudience.Private
  @InterfaceStability.Unstable
  static public class VolumeBuilder {
    private DataStorage storage;
    /** Volume level storage directory. */
    private StorageDirectory sd;
    /** Mapping from block pool ID to an array of storage directories. */
    private Map<String, List<StorageDirectory>> bpStorageDirMap =
        Maps.newHashMap();

    @VisibleForTesting
    public VolumeBuilder(DataStorage storage, StorageDirectory sd) {
      this.storage = storage;
      this.sd = sd;
    }

    public final StorageDirectory getStorageDirectory() {
      return this.sd;
    }

    private void addBpStorageDirectories(String bpid,
        List<StorageDirectory> dirs) {
      bpStorageDirMap.put(bpid, dirs);
    }

    /**
     * Add loaded metadata of a data volume to {@link DataStorage}.
     */
    public void build() {
      assert this.sd != null;
      synchronized (storage) {
        for (Map.Entry<String, List<StorageDirectory>> e :
            bpStorageDirMap.entrySet()) {
          final String bpid = e.getKey();
          BlockPoolSliceStorage bpStorage = this.storage.bpStorageMap.get(bpid);
          assert bpStorage != null;
          for (StorageDirectory bpSd : e.getValue()) {
            bpStorage.addStorageDir(bpSd);
          }
        }
        storage.addStorageDir(sd);
      }
    }
  }

  private StorageDirectory loadStorageDirectory(DataNode datanode,
      NamespaceInfo nsInfo, File dataDir, StartupOption startOpt)
          throws IOException {
    StorageDirectory sd = new StorageDirectory(dataDir, null, false);
    try {
      StorageState curState = sd.analyzeStorage(startOpt, this);
      // sd is locked but not opened
      switch (curState) {
      case NORMAL:
        break;
      case NON_EXISTENT:
        LOG.info("Storage directory " + dataDir + " does not exist");
        throw new IOException("Storage directory " + dataDir
            + " does not exist");
      case NOT_FORMATTED: // format
        LOG.info("Storage directory " + dataDir
            + " is not formatted for namespace " + nsInfo.getNamespaceID()
            + ". Formatting...");
        format(sd, nsInfo, datanode.getDatanodeUuid());
        break;
      default:  // recovery part is common
        sd.doRecover(curState);
      }

      // 2. Do transitions
      // Each storage directory is treated individually.
      // During startup some of them can upgrade or roll back
      // while others could be up-to-date for the regular startup.
      if (doTransition(sd, nsInfo, startOpt, datanode.getConf())) {
        return sd;
      }

      // 3. Update successfully loaded storage.
      setServiceLayoutVersion(getServiceLayoutVersion());
      writeProperties(sd);

      return sd;
    } catch (IOException ioe) {
      sd.unlock();
      throw ioe;
    }
  }

  /**
   * Prepare a storage directory. It creates a builder which can be used to add
   * to the volume. If the volume cannot be added, it is OK to discard the
   * builder later.
   *
   * @param datanode DataNode object.
   * @param volume the root path of a storage directory.
   * @param nsInfos an array of namespace infos.
   * @return a VolumeBuilder that holds the metadata of this storage directory
   * and can be added to DataStorage later.
   * @throws IOException if encounters I/O errors.
   *
   * Note that if there is IOException, the state of DataStorage is not modified.
   */
  public VolumeBuilder prepareVolume(DataNode datanode, File volume,
      List<NamespaceInfo> nsInfos) throws IOException {
    if (containsStorageDir(volume)) {
      final String errorMessage = "Storage directory is in use";
      LOG.warn(errorMessage + ".");
      throw new IOException(errorMessage);
    }

    StorageDirectory sd = loadStorageDirectory(
        datanode, nsInfos.get(0), volume, StartupOption.HOTSWAP);
    VolumeBuilder builder =
        new VolumeBuilder(this, sd);
    for (NamespaceInfo nsInfo : nsInfos) {
      List<File> bpDataDirs = Lists.newArrayList();
      bpDataDirs.add(BlockPoolSliceStorage.getBpRoot(
          nsInfo.getBlockPoolID(), new File(volume, STORAGE_DIR_CURRENT)));
      makeBlockPoolDataDir(bpDataDirs, null);

      final BlockPoolSliceStorage bpStorage = getBlockPoolSliceStorage(nsInfo);
      final List<StorageDirectory> dirs = bpStorage.loadBpStorageDirectories(
          nsInfo, bpDataDirs, StartupOption.HOTSWAP, datanode.getConf());
      builder.addBpStorageDirectories(nsInfo.getBlockPoolID(), dirs);
    }
    return builder;
  }

  /**
   * Add a list of volumes to be managed by DataStorage. If the volume is empty,
   * format it, otherwise recover it from previous transitions if required.
   *
   * @param datanode the reference to DataNode.
   * @param nsInfo namespace information
   * @param dataDirs array of data storage directories
   * @param startOpt startup option
   * @return a list of successfully loaded storage directories.
   */
  @VisibleForTesting
  synchronized List<StorageDirectory> addStorageLocations(DataNode datanode,
      NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
      StartupOption startOpt) throws IOException {
    final List<StorageLocation> successLocations = loadDataStorage(
        datanode, nsInfo, dataDirs, startOpt);
    return loadBlockPoolSliceStorage(
        datanode, nsInfo, successLocations, startOpt);
  }

  private List<StorageLocation> loadDataStorage(DataNode datanode,
      NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
      StartupOption startOpt) throws IOException {
    final List<StorageLocation> success = Lists.newArrayList();
    for (StorageLocation dataDir : dataDirs) {
      File root = dataDir.getFile();
      if (!containsStorageDir(root)) {
        try {
          // It first ensures the datanode level format is completed.
          final StorageDirectory sd = loadStorageDirectory(
              datanode, nsInfo, root, startOpt);
          addStorageDir(sd);
        } catch (IOException e) {
          LOG.warn("Failed to add storage directory " + dataDir, e);
          continue;
        }
      } else {
        LOG.info("Storage directory " + dataDir + " has already been used.");
      }
      success.add(dataDir);
    }

    return success;
  }

  private List<StorageDirectory> loadBlockPoolSliceStorage(DataNode datanode,
      NamespaceInfo nsInfo, Collection<StorageLocation> dataDirs,
      StartupOption startOpt) throws IOException {
    final String bpid = nsInfo.getBlockPoolID();
    final BlockPoolSliceStorage bpStorage = getBlockPoolSliceStorage(nsInfo);
    final List<StorageDirectory> success = Lists.newArrayList();
    for (StorageLocation dataDir : dataDirs) {
      final File curDir = new File(dataDir.getFile(), STORAGE_DIR_CURRENT);
      List<File> bpDataDirs = new ArrayList<File>();
      bpDataDirs.add(BlockPoolSliceStorage.getBpRoot(bpid, curDir));
      try {
        makeBlockPoolDataDir(bpDataDirs, null);

        final List<StorageDirectory> dirs = bpStorage.recoverTransitionRead(
            nsInfo, bpDataDirs, startOpt, datanode.getConf());
        for(StorageDirectory sd : dirs) {
          success.add(sd);
        }
      } catch (IOException e) {
        LOG.warn("Failed to add storage directory " + dataDir
            + " for block pool " + bpid, e);
      }
    }

    return success;
  }

  /**
   * Remove storage dirs from DataStorage. All storage dirs are removed even when the
   * IOException is thrown.
   *
   * @param dirsToRemove a set of storage directories to be removed.
   * @throws IOException if I/O error when unlocking storage directory.
   */
  synchronized void removeVolumes(final Set<File> dirsToRemove)
      throws IOException {
    if (dirsToRemove.isEmpty()) {
      return;
    }

    StringBuilder errorMsgBuilder = new StringBuilder();
    for (Iterator<StorageDirectory> it = this.storageDirs.iterator();
         it.hasNext(); ) {
      StorageDirectory sd = it.next();
      if (dirsToRemove.contains(sd.getRoot())) {
        // Remove the block pool level storage first.
        for (Map.Entry<String, BlockPoolSliceStorage> entry :
            this.bpStorageMap.entrySet()) {
          String bpid = entry.getKey();
          BlockPoolSliceStorage bpsStorage = entry.getValue();
          File bpRoot =
              BlockPoolSliceStorage.getBpRoot(bpid, sd.getCurrentDir());
          bpsStorage.remove(bpRoot.getAbsoluteFile());
        }

        it.remove();
        try {
          sd.unlock();
        } catch (IOException e) {
          LOG.warn(String.format(
            "I/O error attempting to unlock storage directory %s.",
            sd.getRoot()), e);
          errorMsgBuilder.append(String.format("Failed to remove %s: %s%n",
              sd.getRoot(), e.getMessage()));
        }
      }
    }
    if (errorMsgBuilder.length() > 0) {
      throw new IOException(errorMsgBuilder.toString());
    }
  }

  /**
   * Analyze storage directories for a specific block pool.
   * Recover from previous transitions if required.
   * Perform fs state transition if necessary depending on the namespace info.
   * Read storage info.
   *

   * This method should be synchronized between multiple DN threads.  Only the
   * first DN thread does DN level storage dir recoverTransitionRead.
   *
   * @param datanode DataNode
   * @param nsInfo Namespace info of namenode corresponding to the block pool
   * @param dataDirs Storage directories
   * @param startOpt startup option
   * @throws IOException on error
   */
  void recoverTransitionRead(DataNode datanode, NamespaceInfo nsInfo,
      Collection<StorageLocation> dataDirs, StartupOption startOpt) throws IOException {
    if (addStorageLocations(datanode, nsInfo, dataDirs, startOpt).isEmpty()) {
      throw new IOException("All specified directories are failed to load.");
    }
  }

  /**
   * Create physical directory for block pools on the data node
   *
   * @param dataDirs
   *          List of data directories
   * @param conf
   *          Configuration instance to use.
   * @throws IOException on errors
   */
  static void makeBlockPoolDataDir(Collection<File> dataDirs,
      Configuration conf) throws IOException {
    if (conf == null)
      conf = new HdfsConfiguration();

    LocalFileSystem localFS = FileSystem.getLocal(conf);
    FsPermission permission = new FsPermission(conf.get(
        DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_KEY,
        DFSConfigKeys.DFS_DATANODE_DATA_DIR_PERMISSION_DEFAULT));
    for (File data : dataDirs) {
      try {
        DiskChecker.checkDir(localFS, new Path(data.toURI()), permission);
      } catch ( IOException e ) {
        LOG.warn("Invalid directory in: " + data.getCanonicalPath() + ": "
            + e.getMessage());
      }
    }
  }

  void format(StorageDirectory sd, NamespaceInfo nsInfo,
              String datanodeUuid) throws IOException {
    sd.clearDirectory(); // create directory
    this.layoutVersion = HdfsServerConstants.DATANODE_LAYOUT_VERSION;
    this.clusterID = nsInfo.getClusterID();
    this.namespaceID = nsInfo.getNamespaceID();
    this.cTime = 0;
    setDatanodeUuid(datanodeUuid);

    createStorageID(sd, false);
    writeProperties(sd);
  }

  /*
   * Set ClusterID, StorageID, StorageType, CTime into
   * DataStorage VERSION file.
   * Always called just before writing the properties to
   * the VERSION file.
  */
  @Override
  protected void setPropertiesFromFields(Properties props,
                           StorageDirectory sd
                           ) throws IOException {
    props.setProperty("storageType", storageType.toString());
    props.setProperty("clusterID", clusterID);
    props.setProperty("cTime", String.valueOf(cTime));
    props.setProperty("layoutVersion", String.valueOf(layoutVersion));
    props.setProperty("storageID", sd.getStorageUuid());

    String datanodeUuid = getDatanodeUuid();
    if (datanodeUuid != null) {
      props.setProperty("datanodeUuid", datanodeUuid);
    }

    // Set NamespaceID in version before federation


text:
package io.github.frame.cache.redis;

import io.github.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.core.RedisTemplate;

/**
 * 重写Redis 缓存
 *
 * @author Created by 思伟 on 2020/4/27
 * @see RedisCache,MyRedisCacheManager
 */
public class MyRedisCache extends RedisCache {
    protected Logger log = LoggerFactory.getLogger(this.getClass());

    private RedisTemplate<? extends Object, ? extends Object> redisTemplate;

    private String name;

    private int expire = 0;

    public MyRedisCache(RedisTemplate redisTemplate, String name, RedisCacheWriter cacheWriter, RedisCacheConfiguration cacheConfig) {
        super(name, cacheWriter, cacheConfig);
        this.redisTemplate = redisTemplate;
        this.name = name;
    }

    public RedisTemplate<? extends Object, ? extends Object> getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate<? extends Object, ? extends Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public ValueWrapper get(Object key) {
        final String keyStr = toString(key);
        ValueWrapper wrapper = super.get(key);
        if (null != wrapper) {
            log.debug("获取Redis缓存 key ：{}, value : {}",
                    keyStr, toString(wrapper.get()));
        }
        return wrapper;
    }

    @Override
    public void put(Object key, Object value) {
        ValueWrapper waWrapper = super.get(key);
        if (null != waWrapper) {
            log.warn("重复添加Redis缓存 key ：{}, old-value : {}", key, toString(waWrapper.get()));
        }
        log.debug("设置Redis缓存 key ：{}", toString(key));
        super.put(key, value);
    }

    @Override
    public void evict(Object key) {
        log.debug("删除Redis缓存 key ：{}", toString(key));
        super.evict(key);
    }

    /**
     * 将对象转换为String
     *
     * @param object Object
     * @return String
     */
    protected String toString(Object object) {
        return StringUtils.toString(object);
    }

}

domain: java


text:
// Copyright 2014 The Bazel 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.

package com.google.devtools.build.lib.packages;

import com.google.common.base.Predicate;
import com.google.common.base.Predicates;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.LinkedListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.cmdline.LabelSyntaxException;
import com.google.devtools.build.lib.cmdline.RepositoryName;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.events.EventHandler;
import com.google.devtools.build.lib.events.Location;
import com.google.devtools.build.lib.packages.License.DistributionType;
import com.google.devtools.build.lib.syntax.EvalException;
import com.google.devtools.build.lib.syntax.GlobList;
import com.google.devtools.build.lib.syntax.Type;
import com.google.devtools.build.lib.util.BinaryPredicate;
import com.google.devtools.build.lib.util.Preconditions;
import java.util.Collection;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * An instance of a build rule in the build language.  A rule has a name, a
 * package to which it belongs, a class such as cc_library, and
 * set of typed attributes.  The set of attribute names and types is a property
 * of the rule's class.  The use of the term "class" here has nothing to do
 * with Java classes.  All rules are implemented by the same Java classes, Rule
 * and RuleClass.
 *
 *
Here is a typical rule as it appears in a BUILD file:
 *

 * cc_library(name = 'foo',
 *            defines = ['-Dkey=value'],
 *            srcs = ['foo.cc'],
 *            deps = ['bar'])
 *

 */
public final class Rule implements Target, DependencyFilter.AttributeInfoProvider {

  /** Label predicate that allows every label. */
  public static final Predicate ALL_LABELS = Predicates.alwaysTrue();

  private final Label label;

  private final Package pkg;

  private final RuleClass ruleClass;

  private final AttributeContainer attributes;

  private RuleVisibility visibility;

  private boolean containsErrors;

  private final Location location;

  private final ImplicitOutputsFunction implicitOutputsFunction;

  // Initialized in the call to populateOutputFiles.
  private List<OutputFile> outputFiles;
  private ListMultimap<String, OutputFile> outputFileMap;

  Rule(
      Package pkg,
      Label label,
      RuleClass ruleClass,
      Location location,
      AttributeContainer attributeContainer) {
    this(
        pkg,
        label,
        ruleClass,
        location,
        attributeContainer,
        ruleClass.getDefaultImplicitOutputsFunction());
  }

  Rule(
      Package pkg,
      Label label,
      RuleClass ruleClass,
      Location location,
      AttributeContainer attributeContainer,
      ImplicitOutputsFunction implicitOutputsFunction) {
    this.pkg = Preconditions.checkNotNull(pkg);
    this.label = label;
    this.ruleClass = Preconditions.checkNotNull(ruleClass);
    this.location = Preconditions.checkNotNull(location);
    this.attributes = attributeContainer;
    this.implicitOutputsFunction = implicitOutputsFunction;
    this.containsErrors = false;
  }

  void setVisibility(RuleVisibility visibility) {
    this.visibility = visibility;
  }

  void setAttributeValue(Attribute attribute, Object value, boolean explicit) {
    attributes.setAttributeValue(attribute, value, explicit);
  }

  void setAttributeValueByName(String attrName, Object value) {
    attributes.setAttributeValueByName(attrName, value);
  }

  void setAttributeLocation(int attrIndex, Location location) {
    attributes.setAttributeLocation(attrIndex, location);
  }

  void setContainsErrors() {
    this.containsErrors = true;
  }

  @Override
  public Label getLabel() {
    return label;
  }

  @Override
  public String getName() {
    return label.getName();
  }

  @Override
  public Package getPackage() {
    return pkg;
  }

  public RuleClass getRuleClassObject() {
    return ruleClass;
  }

  @Override
  public String getTargetKind() {
    return ruleClass.getTargetKind();
  }

  /**
   * Returns the class of this rule. (e.g. "cc_library")
   */
  public String getRuleClass() {
    return ruleClass.getName();
  }

  /**
   * Returns the build features that apply to this rule.
   */
  public ImmutableSet<String> getFeatures() {
    return pkg.getFeatures();
  }

  /**
   * Returns true iff the outputs of this rule should be created beneath the
   * bin directory, false if beneath genfiles.  For most rule
   * classes, this is a constant, but for genrule, it is a property of the
   * individual rule instance, derived from the 'output_to_bindir' attribute.
   */
  public boolean hasBinaryOutput() {
    return ruleClass.getName().equals("genrule") // this is unfortunate...
        ? NonconfigurableAttributeMapper.of(this).get("output_to_bindir", Type.BOOLEAN)
        : ruleClass.hasBinaryOutput();
  }

  /**
   * Returns true iff there were errors while constructing this rule, such as
   * attributes with missing values or values of the wrong type.
   */
  public boolean containsErrors() {
    return containsErrors;
  }

  /**
   * Returns an (unmodifiable, unordered) collection containing all the
   * Attribute definitions for this kind of rule.  (Note, this doesn't include
   * the values of the attributes, merely the schema.  Call
   * get[Type]Attr() methods to access the actual values.)
   */
  public Collection<Attribute> getAttributes() {
    return ruleClass.getAttributes();
  }

  /**
   * Returns true if this rule has any attributes that are configurable.
   *
   *
Note this is *not* the same as having attribute *types* that are configurable. For example,
   * "deps" is configurable, in that one can write a rule that sets "deps" to a configuration
   * dictionary. But if *this* rule's instance of "deps" doesn't do that, its instance
   * of "deps" is not considered configurable.
   *
   *
In other words, this method signals which rules might have their attribute values
   * influenced by the configuration.
   */
  public boolean hasConfigurableAttributes() {
    for (Attribute attribute : getAttributes()) {
      if (AbstractAttributeMapper.isConfigurable(this, attribute.getName(), attribute.getType())) {
        return true;
      }
    }
    return false;
  }

  /**
   * Returns true if the given attribute is configurable.
   */
  public boolean isConfigurableAttribute(String attributeName) {
    Attribute attribute = ruleClass.getAttributeByNameMaybe(attributeName);
    return attribute != null
        ? AbstractAttributeMapper.isConfigurable(this, attributeName, attribute.getType())
        : false;
  }

  /**
   * Returns the attribute definition whose name is {@code attrName}, or null
   * if not found.  (Use get[X]Attr for the actual value.)
   *
   * @deprecated use {@link AbstractAttributeMapper#getAttributeDefinition} instead
   */
  @Deprecated
  public Attribute getAttributeDefinition(String attrName) {
    return ruleClass.getAttributeByNameMaybe(attrName);
  }

  /**
   * Returns an (unmodifiable, ordered) collection containing all the declared output files of this
   * rule.
   *
   *
All implicit output files (declared in the {@link RuleClass}) are
   * listed first, followed by any explicit files (declared via the 'outs' attribute). Additionally
   * both implicit and explicit outputs will retain the relative order in which they were declared.
   *
   *
This ordering is useful because it is propagated through to the list of targets returned by
   * getOuts() and allows targets to access their implicit outputs easily via
   * {@code getOuts().get(N)} (providing that N is less than the number of implicit outputs).
   *
   *
The fact that the relative order of the explicit outputs is also retained is less obviously
   * useful but is still well defined.
   */
  public Collection<OutputFile> getOutputFiles() {
    return outputFiles;
  }

  /**
   * Returns an (unmodifiable, ordered) map containing the list of output files for every
   * output type attribute.
   */
  public ListMultimap<String, OutputFile> getOutputFileMap() {
    return outputFileMap;
  }

  @Override
  public Location getLocation() {
    return location;
  }

  public ImplicitOutputsFunction getImplicitOutputsFunction() {
    return implicitOutputsFunction;
  }

  @Override
  public Rule getAssociatedRule() {
    return this;
  }

  /**
   * Returns this rule's raw attribute info, suitable for being fed into an
   * {@link AttributeMap} for user-level attribute access. Don't use this method
   * for direct attribute access.
   */
  public AttributeContainer getAttributeContainer() {
    return attributes;
  }

  /********************************************************************
   * Attribute accessor functions.
   *
   * The below provide access to attribute definitions and other generic
   * metadata.
   *
   * For access to attribute *values* (e.g. "What's the value of attribute
   * X for Rule Y?"), go through {@link RuleContext#attributes}. If no
   * RuleContext is available, create a localized {@link AbstractAttributeMapper}
   * instance instead.
   ********************************************************************/

  /**
   * Returns the default value for the attribute {@code attrName}, which may be
   * of any type, but must exist (an exception is thrown otherwise).
   */
  public Object getAttrDefaultValue(String attrName) {
    Object defaultValue = ruleClass.getAttributeByName(attrName).getDefaultValue(this);
    // Computed defaults not expected here.
    Preconditions.checkState(!(defaultValue instanceof Attribute.ComputedDefault));
    return defaultValue;
  }

  /**
   * Returns true iff the rule class has an attribute with the given name and type.
   */
  public boolean isAttrDefined(String attrName, Type<?> type) {
    return ruleClass.hasAttr(attrName, type);
  }

  @Override
  public boolean isAttributeValueExplicitlySpecified(Attribute attribute) {
    return attributes.isAttributeValueExplicitlySpecified(attribute);
  }

  /**
   * Returns true iff the value of the specified attribute is explicitly set in the BUILD file (as
   * opposed to its default value). This also returns true if the value from the BUILD file is the
   * same as the default value. In addition, this method return false if the rule has no attribute
   * with the given name.
   */
  public boolean isAttributeValueExplicitlySpecified(String attrName) {
    return attributes.isAttributeValueExplicitlySpecified(attrName);
  }

  /**
   * Returns the location of the attribute definition for this rule, if known;
   * or the location of the whole rule otherwise. "attrName" need not be a
   * valid attribute name for this rule.
   *
   *
This method ignores whether the present rule was created by a macro or not.
   */
  public Location getAttributeLocationWithoutMacro(String attrName) {
    return getAttributeLocation(attrName, false /* useBuildLocation */);
  }

  /**
   * Returns the location of the attribute definition for this rule, if known;
   * or the location of the whole rule otherwise. "attrName" need not be a
   * valid attribute name for this rule.
   *
   *
If this rule was created by a macro, this method returns the
   * location of the macro invocation in the BUILD file instead.
   */
  public Location getAttributeLocation(String attrName) {
    return getAttributeLocation(attrName, true /* useBuildLocation */);
  }

  private Location getAttributeLocation(String attrName, boolean useBuildLocation) {
    /*
     * If the rule was created by a macro, we have to deal with two locations: one in the BUILD
     * file where the macro is invoked and one in the bzl file where the rule is created.
     * For error reporting, we are usually more interested in the former one.
     * Different methods in this class refer to different locations, though:
     * - getLocation() points to the location of the macro invocation in the BUILD file (thanks to
     *   RuleFactory).
     * - attributes.getAttributeLocation() points to the location in the bzl file.
     */
    if (wasCreatedByMacro() && useBuildLocation) {
      return getLocation();
    }

    Location attrLocation = null;
    if (!attrName.equals("name")) {
      attrLocation = attributes.getAttributeLocation(attrName);
    }
    return attrLocation != null ? attrLocation : getLocation();
  }

  /**
   * Returns whether this rule was created by a macro.
   */
  public boolean wasCreatedByMacro() {
    return hasStringAttribute("generator_name") || hasStringAttribute("generator_function");
  }

  private boolean hasStringAttribute(String attrName) {
    Object value = attributes.getAttr(attrName);
    if (value != null && value instanceof String) {
      return !((String) value).isEmpty();
    }
    return false;
  }

  /** Returns a new List instance containing all direct dependencies (all types). */
  public Collection getLabels() throws InterruptedException {
    final List labels = Lists.newArrayList();
    AggregatingAttributeMapper.of(this).visitLabels(new AttributeMap.AcceptsLabelAttribute() {
      @Override
      public void acceptLabelAttribute(Label label, Attribute attribute) {
        labels.add(label);
      }
    });
    return labels;
  }

  /**
   * Returns a new Collection containing all Labels that match a given Predicate, not including
   * outputs.
   *
   * @param predicate A binary predicate that determines if a label should be included in the
   *     result. The predicate is evaluated with this rule and the attribute that contains the
   *     label. The label will be contained in the result iff (the predicate returned {@code true}
   *     and the labels are not outputs)
   */
  public Collection getLabels(BinaryPredicate<? super Rule, Attribute> predicate)
      throws InterruptedException {
    return ImmutableSortedSet.copyOf(getTransitions(predicate).values());
  }

  /**
   * Returns a new Multimap containing all attributes that match a given Predicate and corresponding
   * labels, not including outputs.
   *
   * @param predicate A binary predicate that determines if a label should be included in the
   *     result. The predicate is evaluated with this rule and the attribute that contains the
   *     label. The label will be contained in the result iff (the predicate returned {@code true}
   *     and the labels are not outputs)
   */
  public Multimap<Attribute, Label> getTransitions(
      final BinaryPredicate<? super Rule, Attribute> predicate) throws InterruptedException {
    final Multimap<Attribute, Label> transitions = HashMultimap.create();
    // TODO(bazel-team): move this to AttributeMap, too. Just like visitLabels, which labels should
    // be visited may depend on the calling context. We shouldn't implicitly decide this for
    // the caller.
    AggregatingAttributeMapper.of(this).visitLabels(new AttributeMap.AcceptsLabelAttribute() {
      @Override
      public void acceptLabelAttribute(Label label, Attribute attribute) {
        if (predicate.apply(Rule.this, attribute)) {
          transitions.put(attribute, label);
        }
      }
    });
    return transitions;
  }

  /**
   * Check if this rule is valid according to the validityPredicate of its RuleClass.
   */
  void checkValidityPredicate(EventHandler eventHandler) {
    PredicateWithMessage<Rule> predicate = getRuleClassObject().getValidityPredicate();
    if (!predicate.apply(this)) {
      reportError(predicate.getErrorReason(this), eventHandler);
    }
  }

  /**
   * Collects the output files (both implicit and explicit). All the implicit output files are added
   * first, followed by any explicit files. Additionally both implicit and explicit output files
   * will retain the relative order in which they were declared.
   */
  void populateOutputFiles(EventHandler eventHandler, Package.Builder pkgBuilder)
      throws LabelSyntaxException, InterruptedException {
    Preconditions.checkState(outputFiles == null);
    // Order is important here: implicit before explicit
    outputFiles = Lists.newArrayList();
    outputFileMap = LinkedListMultimap.create();
    populateImplicitOutputFiles(eventHandler, pkgBuilder);
    populateExplicitOutputFiles(eventHandler);
    outputFiles = ImmutableList.copyOf(outputFiles);
    outputFileMap = ImmutableListMultimap.copyOf(outputFileMap);
  }

  // Explicit output files are user-specified attributes of type OUTPUT.
  private void populateExplicitOutputFiles(EventHandler eventHandler) throws LabelSyntaxException {
    NonconfigurableAttributeMapper nonConfigurableAttributes =
        NonconfigurableAttributeMapper.of(this);
    for (Attribute attribute : ruleClass.getAttributes()) {
      String name = attribute.getName();
      Type<?> type = attribute.getType();
      if (type == BuildType.OUTPUT) {
        Label outputLabel = nonConfigurableAttributes.get(name, BuildType.OUTPUT);
        if (outputLabel != null) {
          addLabelOutput(attribute, outputLabel, eventHandler);
        }
      } else if (type == BuildType.OUTPUT_LIST) {
        for (Label label : nonConfigurableAttributes.get(name, BuildType.OUTPUT_LIST)) {
          addLabelOutput(attribute, label, eventHandler);
        }
      }
    }
  }

  /**
   * Implicit output files come from rule-specific patterns, and are a function
   * of the rule's "name", "srcs", and other attributes.
   */
  private void populateImplicitOutputFiles(EventHandler eventHandler, Package.Builder pkgBuilder)
      throws InterruptedException {
    try {
      RawAttributeMapper attributeMap = RawAttributeMapper.of(this);
      for (String out : implicitOutputsFunction.getImplicitOutputs(attributeMap)) {
        try {
          addOutputFile(pkgBuilder.createLabel(out), eventHandler);
        } catch (LabelSyntaxException e) {
          reportError(
              "illegal output file name '"
                  + out
                  + "' in rule "
                  + getLabel()
                  + " due to: "
                  + e.getMessage(),
              eventHandler);
        }
      }
    } catch (EvalException e) {
      reportError(e.print(), eventHandler);
    }
  }

  private void addLabelOutput(Attribute attribute, Label label, EventHandler eventHandler)
      throws LabelSyntaxException {
    if (!label.getPackageIdentifier().equals(pkg.getPackageIdentifier())) {
      throw new IllegalStateException("Label for attribute " + attribute
          + " should refer to '" + pkg.getName()
          + "' but instead refers to '" + label.getPackageFragment()
          + "' (label '" + label.getName() + "')");
    }
    if (label.getName().equals(".")) {
      throw new LabelSyntaxException("output file name can't be equal '.'");
    }
    OutputFile outputFile = addOutputFile(label, eventHandler);
    outputFileMap.put(attribute.getName(), outputFile);
  }

  private OutputFile addOutputFile(Label label, EventHandler eventHandler) {


text:
package de.dlyt.yanndroid.oneui.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;

import java.util.HashMap;

import de.dlyt.yanndroid.oneui.R;
import de.dlyt.yanndroid.oneui.widget.OptionButton;

public class OptionGroup extends LinearLayout {

    private HashMap<Integer, Boolean> checkState = new HashMap<>();
    private HashMap<Integer, Integer> idPosition = new HashMap<>();
    private Integer selectedId = -1;

    private OnOptionButtonClickListener mOnOptionButtonClickListener;

    public OptionGroup(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        setOrientation(VERTICAL);

        TypedArray attr = context.getTheme().obtainStyledAttributes(attrs, R.styleable.OptionGroup, 0, 0);
        selectedId = attr.getResourceId(R.styleable.OptionGroup_selectedOptionButton, -1);
        attr.recycle();
    }

    @Override
    public void addView(View child, int index, ViewGroup.LayoutParams params) {
        if (child instanceof OptionButton) {
            final OptionButton optionButton = (OptionButton) child;

            int id = child.getId();
            if (id == View.NO_ID) {
                id = View.generateViewId();
                child.setId(id);
            }

            checkState.put(id, id == selectedId);
            idPosition.put(id, idPosition.size());

            optionButton.setButtonSelected(id == selectedId);

            optionButton.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (selectedId != -1) checkState.put(selectedId, false);
                    selectedId = v.getId();
                    checkState.put(selectedId, true);
                    updateCheckState();
                    if (mOnOptionButtonClickListener != null) {
                        mOnOptionButtonClickListener.onOptionButtonClick(optionButton, selectedId, idPosition.get(selectedId));
                    }
                }
            });

        }
        super.addView(child, index, params);
    }

    private void updateCheckState() {
        for (Integer id : checkState.keySet()) {
            OptionButton optionButton = findViewById(id);
            optionButton.setButtonSelected(checkState.get(id));
        }
    }

    public OptionButton getSelectedOptionButton() {
        return findViewById(selectedId);
    }

    public void setSelectedOptionButton(OptionButton optionButton) {
        if (selectedId != -1) checkState.put(selectedId, false);
        selectedId = optionButton.getId();
        checkState.put(selectedId, true);
        updateCheckState();
    }

    public void setSelectedOptionButton(int position) {
        for (Integer id : idPosition.keySet()) {
            if (idPosition.get(id) == position) {
                if (selectedId != -1) checkState.put(selectedId, false);
                selectedId = idPosition.get(id);
                checkState.put(selectedId, true);
                updateCheckState();
                break;
            }
        }
    }

    public void setSelectedOptionButton(Integer id) {
        if (selectedId != -1) checkState.put(selectedId, false);
        selectedId = id;
        checkState.put(selectedId, true);
        updateCheckState();
    }

    public void setOnOptionButtonClickListener(OnOptionButtonClickListener listener) {
        mOnOptionButtonClickListener = listener;
    }

    public interface OnOptionButtonClickListener {
        public void onOptionButtonClick(OptionButton view, int checkedId, int position);
    }

}


text:
package problems;

import java.util.HashSet;
import java.util.Set;

/**
 * https://leetcode.com/problems/ugly-number-ii/
 *
 * Write a program to find the n-th ugly number.
 *
 * Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
 *
 * Example:
 *
 * Input: n = 10
 * Output: 12
 * Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
 * Note:
 *
 * 1 is typically treated as an ugly number.
 * n does not exceed 1690.
 *
 * Approach:
 *
 * 1. Create an array of size n - this will represent the set of the ugly numbers we are trying to capture
 * 2. One way to think about ugly numbers is that they can be constructed by multiplying some previous ugly number by 2, 3, or 5
 * 3. So by keeping track of the last ugly number that 2, 3, or 5 was multiplied by, we can generate the minimum next ugly
 *    number.
 * 4. Need to keep track of ugly numbers that satisfy multiple prime factors (e.g. 6, which satisfies 2 and 3 as prime factors)
 * 5. When the minimum ugly number matches the value of multiplying the prime factor of 2, 3, 5, increment the ugly number index
 *    associated with that prime factor - this means that the next ugly number times that prime factor is the next
 *    smallest ugly number for that prime factor
 */

public class UglyNumber2 {
    public int nthUglyNumber(int n) {
        int[] uglyNumbers = new int[n];
        uglyNumbers[0] = 1;

        int primeFactor2UglyNumberIndex = 0;
        int primeFactor3UglyNumberIndex = 0;
        int primeFactor5UglyNumberIndex = 0;

        int lastPrimeFactor2UglyNumber = 2;
        int lastPrimeFactor3UglyNumber = 3;
        int lastPrimeFactor5UglyNumber = 5;

        for (int uglyNumberIndex = 1; uglyNumberIndex < n; uglyNumberIndex++) {
            int nextPrimeFactor2UglyNumber = lastPrimeFactor2UglyNumber * uglyNumbers[primeFactor2UglyNumberIndex];
            int nextPrimeFactor3UglyNumber = lastPrimeFactor3UglyNumber * uglyNumbers[primeFactor3UglyNumberIndex];
            int nextPrimeFactor5UglyNumber = lastPrimeFactor5UglyNumber * uglyNumbers[primeFactor5UglyNumberIndex];
            int minimumNextUglyNumber = Math.min(nextPrimeFactor2UglyNumber, Math.min( nextPrimeFactor3UglyNumber, nextPrimeFactor5UglyNumber));

            uglyNumbers[uglyNumberIndex] = minimumNextUglyNumber;

            if (nextPrimeFactor2UglyNumber == minimumNextUglyNumber) {
                primeFactor2UglyNumberIndex++;
            }

            if (nextPrimeFactor3UglyNumber == minimumNextUglyNumber) {
                primeFactor3UglyNumberIndex++;
            }

            if (nextPrimeFactor5UglyNumber == minimumNextUglyNumber) {
                primeFactor5UglyNumberIndex++;
            }
        }

        return uglyNumbers[n - 1];
    }
}


text:
package com.planet_ink.coffee_mud.Abilities.Thief;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

/*
   Copyright 2004-2018 Bo Zimmerman

   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.
*/
public class Thief_CarefulStep extends ThiefSkill
{
	@Override
	public String ID()
	{
		return "Thief_CarefulStep";
	}

	private final static String	localizedName	= CMLib.lang().L("Careful Step");

	@Override
	public String name()
	{
		return localizedName;
	}

	@Override
	protected int canAffectCode()
	{
		return 0;
	}

	@Override
	protected int canTargetCode()
	{
		return 0;
	}

	@Override
	public double castingTime(final MOB mob, final List<String> cmds)
	{
		return CMProps.getSkillActionCost(ID(), CMath.div(CMProps.getIntVar(CMProps.Int.DEFABLETIME), 50.0));
	}

	@Override
	public double combatCastingTime(final MOB mob, final List<String> cmds)
	{
		return CMProps.getSkillCombatActionCost(ID(), CMath.div(CMProps.getIntVar(CMProps.Int.DEFCOMABLETIME), 50.0));
	}

	@Override
	public int abstractQuality()
	{
		return Ability.QUALITY_INDIFFERENT;
	}

	private static final String[]	triggerStrings	= I(new String[] { "CARESTEP", "CAREFULSTEP" });

	@Override
	public String[] triggerStrings()
	{
		return triggerStrings;
	}

	@Override
	public int usageType()
	{
		return USAGE_MOVEMENT;
	}

	@Override
	public int classificationCode()
	{
		return Ability.ACODE_THIEF_SKILL | Ability.DOMAIN_ACROBATIC;
	}

	@Override
	public boolean preInvoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel, int secondsElapsed, double actionsRemaining)
	{
		if(secondsElapsed==0)
		{
			String dir=CMParms.combine(commands,0);
			if(commands.size()>0)
				dir=commands.get(commands.size()-1);
			final int dirCode=CMLib.directions().getGoodDirectionCode(dir);
			if(dirCode<0)
			{
				mob.tell(L("Step where?"));
				return false;
			}
			if(mob.isInCombat())
			{
				mob.tell(L("Not while you are fighting!"));
				return false;
			}

			if((mob.location().getRoomInDir(dirCode)==null)||(mob.location().getExitInDir(dirCode)==null))
			{
				mob.tell(L("Step where?"));
				return false;
			}
			final CMMsg msg=CMClass.getMsg(mob,null,this,auto?CMMsg.MSG_OK_VISUAL:CMMsg.MSG_DELICATE_HANDS_ACT,L("<S-NAME> start(s) walking carefully @x1.",CMLib.directions().getDirectionName(dirCode)));
			if(mob.location().okMessage(mob,msg))
				mob.location().send(mob,msg);
			else
				return false;
		}
		return true;
	}

	@Override
	public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
	{
		String dir=CMParms.combine(commands,0);
		if(commands.size()>0)
			dir=commands.get(commands.size()-1);
		final int dirCode=CMLib.directions().getGoodDirectionCode(dir);
		if(!preInvoke(mob,commands,givenTarget,auto,asLevel,0,0.0))
			return false;

		final MOB highestMOB=getHighestLevelMOB(mob,null);
		int levelDiff=mob.phyStats().level()+(2*getXLEVELLevel(mob))-getMOBLevel(highestMOB);

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		boolean success=false;
		final CMMsg msg=CMClass.getMsg(mob,null,this,auto?CMMsg.MSG_OK_VISUAL:CMMsg.MSG_DELICATE_HANDS_ACT,L("<S-NAME> walk(s) carefully @x1.",CMLib.directions().getDirectionName(dirCode)));
		if(mob.location().okMessage(mob,msg))
		{
			mob.location().send(mob,msg);
			if(levelDiff<0)
				levelDiff=levelDiff*8;
			else
				levelDiff=levelDiff*10;
			success=proficiencyCheck(mob,levelDiff,auto);
			final int oldDex=mob.baseCharStats().getStat(CharStats.STAT_DEXTERITY);
			if(success)
				mob.baseCharStats().setStat(CharStats.STAT_DEXTERITY,oldDex+100);
			mob.recoverCharStats();
			CMLib.tracking().walk(mob,dirCode,false,false);
			if(oldDex!=mob.baseCharStats().getStat(CharStats.STAT_DEXTERITY))
				mob.baseCharStats().setStat(CharStats.STAT_DEXTERITY,oldDex);
			mob.recoverCharStats();
		}
		return success;
	}

}


text:
package assignment;

/**
 * The main function of the assginment
 *
 *
 * @author Tao Xin <taoxin.se@gmail.com>
 * @date 2021-07-28
 */

import common.ConfigLoader;
import common.Location;

import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.HashSet;

public class GetPath {

    private final static String CONFIG_FILE_PATH = "./config_file/assignment_config.txt";

    /**
     * Main function for Assignment basic
     * @param args
     */
    public static void main(String[] args) {
        if (args.length < 2 || args.length > 2) {
            System.out.println("Wrong number of input arguments, please verify and try again.");
            System.exit(0);
        }

        getPathToObj(args[0].toLowerCase(), args[1].toLowerCase(), CONFIG_FILE_PATH);
    }

    /**
     * Get the path from the given location to the input Object
     *
     * @param lo
     * @param obj
     * @param configFilePath
     */
    private static void getPathToObj(String lo, String obj, String configFilePath) {

        ConfigLoader config = new ConfigLoader();

        HashMap<String, Location> locationsMap = config.loadConfigFromFile(configFilePath);
        HashMap<String, ArrayList<Location>> objectsMap = config.getObjectMap();

        if (!locationsMap.containsKey(lo)) {
            System.out.println("The input Location is not available! ");
            System.out.println("Available locations are: " + locationsMap.keySet() + "\nPlease try again!");
            return;
        }

        if (!objectsMap.containsKey(obj)) {
            System.out.println("The input Object (" + obj + ") is not available! Please try again!");
            return;
        }

        Location startLocation = locationsMap.get(lo);
        ArrayList<Location> locationsWithObject = objectsMap.get(obj);

        if (startLocation.getObject().equals(obj)) {
            System.out.println("You are in the " + startLocation.getName() + ". You can get " + obj + " right here.");
            return;
        }

        Location dest = getNode(startLocation, locationsWithObject);
        ArrayList<Location> pathToDest = getPath(startLocation, dest);

        if (pathToDest == null) {
            System.out.println("Sorry, we cant find the path between the two location.");
            return;
        }

        System.out.println("You are in the " + startLocation.getName());
        for (Location p : pathToDest) {
            System.out.print("Go to " + p.getName() + " ");
        }
        System.out.print("get " + obj + ".\n");
    }

    /**
     * Get the shortest destination from a list of available destinations
     *
     * @param start
     * @param destinations
     * @return
     */
    private static Location getNode(Location start, ArrayList<Location> destinations) {
        int count = -1;
        Location dest = null;
        ArrayList<Location> temp = new ArrayList<Location>();

        for (Location l : destinations) {
            temp.clear();
            temp.addAll(l.getPathToRoot());
            temp.addAll(start.getPathToRoot());
            Set<Location> locationSet = new HashSet<Location>(temp);
            if (count > locationSet.size() || count < 0) {
                dest = l;
                count =locationSet.size();
            }
        }

        return dest;
    }

    /**
     * Get the path between two Locations
     *
     * @param from
     * @param dest
     * @return
     */
    private static ArrayList<Location> getPath(Location from, Location dest) {
        Location temp = from;
        ArrayList<Location> from_pathToRoot = from.getPathToRoot();
        ArrayList<Location> dest_pathToRoot = dest.getPathToRoot();
        ArrayList<Location> path = new ArrayList<Location>();

        if (dest_pathToRoot.containsAll(from_pathToRoot)){
            if (dest_pathToRoot.removeAll(from.getPathToRoot())) {
                return dest_pathToRoot;
            }
        }

        while (temp.hasParent()) {
            temp = temp.getParent();
            path.add(temp);

            if (dest_pathToRoot.contains(temp)) {// Find the common ancestor
                if (dest_pathToRoot.removeAll(temp.getPathToRoot())) {
                    path.addAll(dest_pathToRoot);
                }
                return path;
            }
        }
        return null;
    }
}


text:
package crazypants.enderio.machine.spawner;

import java.util.Collections;
import java.util.List;

import net.minecraft.item.ItemStack;
import crazypants.enderio.ModObject;
import crazypants.enderio.machine.IMachineRecipe;
import crazypants.enderio.machine.MachineRecipeInput;
import crazypants.enderio.machine.recipe.RecipeBonusType;

public class DummyRecipe implements IMachineRecipe {

  @Override
  public String getUid() {
    return "PoweredTaskRecipe";
  }

  @Override
  public int getEnergyRequired(MachineRecipeInput... inputs) {
    //NB: This value is not actually used, see createTask in the tile
   return TilePoweredSpawner.POWER_PER_TICK_ONE * 800;
  }

  @Override
  public boolean isRecipe(MachineRecipeInput... inputs) {
    return true;
  }

  @Override
  public ResultStack[] getCompletedResult(float randomChance, MachineRecipeInput... inputs) {
    return new ResultStack[0];
  }

  @Override
  public RecipeBonusType getBonusType(MachineRecipeInput... inputs) {
    return RecipeBonusType.NONE;
  }

  @Override
  public float getExperienceForOutput(ItemStack output) {
    return 0;
  }

  @Override
  public boolean isValidInput(MachineRecipeInput input) {
    return false;
  }

  @Override
  public String getMachineName() {
    return ModObject.blockPoweredSpawner.unlocalisedName;
  }

  @Override
  public List<MachineRecipeInput> getQuantitiesConsumed(MachineRecipeInput[] inputs) {
    return Collections.emptyList();
  }

}


text:
package org.iot.dsa.node;

import org.iot.dsa.util.DSUtil;

/**
 * Combines a boolean with true text and false text.
 *
 * @author Aaron Hansen
 */
public class DSBoolRange extends DSValue implements DSIBoolean, DSIMetadata, DSIStorable {

    ///////////////////////////////////////////////////////////////////////////
    // Class Fields
    ///////////////////////////////////////////////////////////////////////////

    public static final DSBoolRange ACTIVE_INACTIVE = new DSBoolRange(
            DSBool.NULL, DSList.valueOf("Inactive", "Active"));
    public static final DSBoolRange ENABLED_DISABLED = new DSBoolRange(
            DSBool.NULL, DSList.valueOf("Disabled", "Enabled"));
    public static final DSBoolRange NULL = new DSBoolRange(
            DSBool.NULL, DSList.valueOf("false", "true"));
    public static final DSBoolRange ON_OFF = new DSBoolRange(
            DSBool.NULL, DSList.valueOf("Off", "On"));

    ///////////////////////////////////////////////////////////////////////////
    // Instance Fields
    ///////////////////////////////////////////////////////////////////////////

    private DSList range;
    private DSBool val;

    ///////////////////////////////////////////////////////////////////////////
    // Constructors
    ///////////////////////////////////////////////////////////////////////////

    private DSBoolRange(DSBool val, DSList range) {
        if (val == null) {
            throw new NullPointerException("Null value");
        }
        if (range == null) {
            throw new NullPointerException("Null range");
        }
        if (range.size() != 2) {
            throw new NullPointerException("Invalid range: " + range);
        }
        this.val = val;
        this.range = range;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Methods in alphabetical order
    ///////////////////////////////////////////////////////////////////////////

    @Override
    public boolean equals(Object obj) {
        if (obj instanceof DSBoolRange) {
            DSBoolRange dt = (DSBoolRange) obj;
            return val.equals(dt.val) && DSUtil.equal(range, dt.range);
        }
        return false;
    }

    public String getFalseText() {
        return range.getString(0);
    }

    @Override
    public void getMetadata(DSMap bucket) {
        bucket.put(DSMetadata.BOOLEAN_RANGE, range.copy());
    }

    public String getTrueText() {
        return range.getString(1);
    }

    /**
     * Bool.
     */
    @Override
    public DSValueType getValueType() {
        return DSValueType.BOOL;
    }

    @Override
    public int hashCode() {
        return toString().hashCode();
    }

    @Override
    public boolean isNull() {
        return this == NULL;
    }

    /**
     * Restores the value and range from a map created by store()
     */
    @Override
    public DSIValue restore(DSElement map) {
        if (!map.isMap()) {
            throw new IllegalStateException("Not a map");
        }
        DSMap tmp = map.toMap();
        DSBool b = (DSBool) tmp.get("v");
        if (val.isNull()) {
            return NULL;
        }
        DSList r = (DSList) tmp.get("r");
        return new DSBoolRange(b, r);
    }

    /**
     * Stores the value and range in a map.
     */
    @Override
    public DSElement store() {
        return new DSMap().put("v", val).put("r", range);
    }

    @Override
    public boolean toBoolean() {
        return val.toBoolean();
    }

    /**
     * Returns the boolean value.
     */
    @Override
    public DSBool toElement() {
        return val;
    }

    @Override
    public String toString() {
        if (isNull()) {
            return "null";
        }
        if (toBoolean()) {
            return getTrueText();
        }
        return getFalseText();
    }

    public static DSBoolRange valueOf(boolean val, String falseText, String trueText) {
        return valueOf(DSBool.valueOf(val), falseText, trueText);
    }

    public static DSBoolRange valueOf(DSBool val, String falseText, String trueText) {
        if (trueText == null) {
            throw new NullPointerException("trueText cannot be null");
        }
        if (falseText == null) {
            throw new NullPointerException("falseText cannot be null");
        }
        return new DSBoolRange(val, new DSList().add(falseText).add(trueText));
    }

    /**
     * Can handle a boolean or string.
     */
    @Override
    public DSBoolRange valueOf(DSElement element) {
        if (element instanceof DSBool) {
            if (DSUtil.equal(element, val)) {
                return this;
            }
            return valueOf((DSBool) element, range);
        }
        return valueOf(element.toString());
    }

    /**
     * Must equal the true or false text.
     */
    public DSBoolRange valueOf(String text) {
        if (getTrueText().equals(text)) {
            return valueOf(DSBool.TRUE);
        }
        if (getFalseText().equals(text)) {
            return valueOf(DSBool.TRUE);
        }
        throw new IllegalArgumentException("Unknown boolean tag: " + text);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Private Methods
    ///////////////////////////////////////////////////////////////////////////

    public static DSBoolRange valueOf(DSBool val, DSList range) {
        if ((val == null) || val.isNull()) {
            return NULL;
        }
        if (ACTIVE_INACTIVE.equals(val, range)) {
            return ACTIVE_INACTIVE;
        }
        if (ENABLED_DISABLED.equals(val, range)) {
            return ENABLED_DISABLED;
        }
        if (ON_OFF.equals(val, range)) {
            return ON_OFF;
        }
        return new DSBoolRange(val, range);
    }

    private boolean equals(DSBool val, DSList range) {
        return this.val.equals(val) && this.range.equals(range);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Initialization
    ///////////////////////////////////////////////////////////////////////////

    static {
        DSRegistry.registerDecoder(DSBoolRange.class, NULL);
    }

}


text:
package cases.s2_login_and_auth;

import android.app.Activity;
import android.app.Instrumentation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.test.espresso.Espresso;
import android.support.test.espresso.intent.Intents;
import android.support.test.filters.LargeTest;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.support.test.uiautomator.UiObjectNotFoundException;

import com.facebook.FacebookActivity;
import com.facebook.login.LoginClientCreator;
import com.rideaustin.BaseUITest;
import com.rideaustin.DriverMockResponseFactory;
import com.rideaustin.FacebookMocks;
import com.rideaustin.R;
import com.rideaustin.RaActivityRule;
import com.rideaustin.RequestType;
import com.rideaustin.TestCases;
import com.rideaustin.ui.signin.SplashActivity;
import com.rideaustin.utils.FacebookHelper;
import com.rideaustin.utils.NavigationUtils;

import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.clearText;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard;
import static android.support.test.espresso.action.ViewActions.typeText;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.intent.Intents.intending;
import static android.support.test.espresso.intent.matcher.IntentMatchers.hasComponent;
import static android.support.test.espresso.matcher.ViewMatchers.hasErrorText;
import static android.support.test.espresso.matcher.ViewMatchers.isClickable;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static com.rideaustin.DriverMockResponseFactory.INVALID_CREDENTIALS;
import static com.rideaustin.utils.MatcherUtils.hasNoErrorText;
import static com.rideaustin.utils.MatcherUtils.isToast;
import static com.rideaustin.utils.ViewActionUtils.allowPermissionsIfNeeded;
import static com.rideaustin.utils.ViewActionUtils.waitFor;
import static com.rideaustin.utils.ViewActionUtils.waitForDisplayed;
import static com.rideaustin.utils.ViewActionUtils.waitForViewInWindow;
import static org.hamcrest.core.AllOf.allOf;

/**
 * Created by hatak on 26.10.2017.
 */

@LargeTest
@RunWith(AndroidJUnit4.class)
public class SignInSuite extends BaseUITest {

    @Rule
    public ActivityTestRule<SplashActivity> activityRule = new RaActivityRule<>(SplashActivity.class, false, false);

    @Override
    public void setUp() {
        super.setUp();
        initMockResponseFactory(DriverMockResponseFactory.class);
        mockRequests(RequestType.GLOBAL_APP_INFO_200_GET,
                RequestType.LOGIN_SUCCESS_200_POST,
                RequestType.CURRENT_USER_200_GET,
                RequestType.CONFIG_DRIVER_200_GET,
                RequestType.TOKENS_200_POST,
                RequestType.QUEUES_200_GET,
                RequestType.EVENTS_EMPTY_200_GET,
                RequestType.ACCEPT_RIDE_200_POST,
                RequestType.SURGE_AREA_EMPTY_200_GET,
                RequestType.CURRENT_DRIVER_200_GET,
                RequestType.DRIVER_UPDATE_LOCATION_200_PUT,
                RequestType.ACTIVE_DRIVERS_EMPTY_200_GET,
                RequestType.RIDE_ROUTE_DRIVER_ASSIGNED_200_GET,
                RequestType.PENDING_EVENTS_200_POST,
                RequestType.DRIVER_GO_OFFLINE_200_DELETE,
                RequestType.DRIVERS_CARTYPES_200_GET,
                RequestType.DRIVER_TYPES_200_GET,
                RequestType.CONFIG_DRIVER_200_GET);

        Intents.init();
    }

    @Override
    public void tearDown() {
        super.tearDown();
        // for tests using intent mocks
        Intents.release();
    }

    @Test
    @TestCases("C1929184")
    public void testSignInViaEmail() throws UiObjectNotFoundException, PackageManager.NameNotFoundException {
        NavigationUtils.startActivity(activityRule);
        waitForDisplayed(R.id.signIn);
        onView(withId(R.id.signIn)).check(matches(withText(R.string.sign_in))).check(matches(isDisplayed())).perform(click());

        waitForDisplayed(R.id.email);
        waitForDisplayed(R.id.password);
        waitForDisplayed(R.id.facebook);
        waitForDisplayed(R.id.done);
        waitForDisplayed(R.id.forgotPassword);

        // enter arbitrary data as we are mocking server
        onView(withId(R.id.email)).perform(typeText("anyvalid@email.com"));
        onView(withId(R.id.password)).perform(typeText("doesnotmatter"), closeSoftKeyboard());

        // perform login and wait
        onView(withId(R.id.done)).perform(click());

        // allow permission
        allowPermissionsIfNeeded();

        // check map is visible
        waitForDisplayed(R.id.mapContainer);
        waitForDisplayed(R.id.toolbarActionButton);
        onView(allOf(withId(R.id.toolbarActionButton), withText(R.string.action_go_online))).check(matches(isDisplayed()));

    }

    @Test
    @TestCases("C1929185")
    public void testSignInViaEmailValidations() {
        // mock invalid requests
        removeRequests(RequestType.LOGIN_SUCCESS_200_POST);
        mockRequests(RequestType.LOGIN_FAILED_401_POST);

        NavigationUtils.startActivity(activityRule);

        waitForDisplayed(R.id.signIn);

        // go to login
        onView(withId(R.id.signIn)).check(matches(isDisplayed())).perform(click());

        // check title
        onView(withId(R.id.toolbarTitle)).check(matches(withText(R.string.title_sign_in)));

        // perform login
        onView(withId(R.id.done)).perform(click());
        onView(withId(R.id.email)).check(matches(hasErrorText(getString(R.string.email_error))));

        // enter arbitrary data as we are mocking server
        onView(withId(R.id.email)).perform(typeText("notregistered@email.com"));
        onView(withId(R.id.done)).perform(click());
        onView(withId(R.id.password)).check(matches(hasErrorText(getString(R.string.no_password_error))));

        // HACK: suddenly this test stopped working
        // No obvious reason, Espresso/UIAutomator were not updated
        // Maybe its because of support lib?
        // Anyway, removing this block breaks further test execution
        Espresso.pressBack();
        Espresso.pressBack();
        waitForDisplayed(R.id.signIn);
        onView(withId(R.id.signIn)).check(matches(isDisplayed())).perform(click());
        // END HACK

        onView(withId(R.id.email)).perform(clearText());
        onView(withId(R.id.password)).perform(clearText());

        // enter arbitrary data as we are mocking server
        onView(withId(R.id.email)).perform(typeText("notregistered@email.com"));
        onView(withId(R.id.password)).perform(typeText("doesnotmatter"), closeSoftKeyboard());

        // perform login
        onView(withId(R.id.done)).perform(click());

        // check login failed
        onView(withText(INVALID_CREDENTIALS)).check(matches(isDisplayed()));
        onView(withId(com.afollestad.materialdialogs.R.id.md_buttonDefaultPositive)).perform(click());
    }

    @Test
    @TestCases("C1929187")
    public void testSignInForgotPassword() {
        mockRequests(RequestType.RESET_PASSWORD_200_POST);

        NavigationUtils.startActivity(activityRule);

        waitForDisplayed(R.id.signIn);

        // go to login
        onView(withId(R.id.signIn)).check(matches(isDisplayed())).perform(click());

        // go to forgot password
        onView(allOf(withId(R.id.forgotPassword), withText(R.string.forgot_password)))
                .check(matches(isDisplayed())).check(matches(isClickable()))
                .perform(click());

        // click on button
        onView(allOf(withId(R.id.reset), withText(R.string.reset_pass))).perform(click());

        // check error
        onView(withId(R.id.email)).check(matches(hasErrorText(getString(R.string.email_error))));

        // type invalid email
        onView(withId(R.id.email)).perform(typeText("invalidemail"), closeSoftKeyboard());

        // click on button
        onView(allOf(withId(R.id.reset), withText(R.string.reset_pass))).perform(click());

        // check error
        onView(withId(R.id.email)).check(matches(hasErrorText(getString(R.string.invalid_email_error))));

        // type valid email
        onView(withId(R.id.email)).perform(clearText(), typeText("registered@email.com"), closeSoftKeyboard());

        // click on button
        onView(allOf(withId(R.id.reset), withText(R.string.reset_pass))).perform(click());

        // check no error
        onView(withId(R.id.email)).check(matches(hasNoErrorText()));

        // check toast
        waitForViewInWindow(onView(withText(R.string.email_sent)).inRoot(isToast()));
    }

    @Test
    @TestCases("C1929186")
    public void signInViaFacebook() {
        mockRequests(RequestType.FACEBOOK_LOGIN_200_POST);
        // mock facebook intents
        final Intent resultData = new Intent();
        resultData.putExtra("com.facebook.LoginFragment:Result", LoginClientCreator.createSuccess());
        intending(hasComponent(FacebookActivity.class.getName())).respondWith(new Instrumentation.ActivityResult(Activity.RESULT_OK, resultData));

        // mock facebook requests
        FacebookHelper.meRequestCreator = FacebookMocks.getMe("FACEBOOK_ME_VALID");

        NavigationUtils.startActivity(activityRule);

        waitForDisplayed(R.id.signIn);

        // go to login
        onView(withId(R.id.signIn)).check(matches(isDisplayed())).perform(click());

        // go to facebook login
        onView(allOf(withId(R.id.facebook), withText(R.string.fb_login_text))).perform(click());

        // allow permission
        allowPermissionsIfNeeded();

        // check map is visible
        waitForDisplayed(R.id.mapContainer);
        waitForDisplayed(R.id.toolbarActionButton);
        onView(allOf(withId(R.id.toolbarActionButton), withText(R.string.action_go_online))).check(matches(isDisplayed()));
    }
}


text:
/*
 * 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 code was generated by https://github.com/google/apis-client-generator/
 * (build: 2017-11-07 19:12:12 UTC)
 * on 2017-12-21 at 07:37:53 UTC
 * Modify at your own risk.
 */

package challenge.rt.medibus.mani.data.source.remote.myApi.model;

/**
 * Model definition for CollectionResponseSalesRep.
 *
 *
 This is the Java data model class that specifies how to parse/serialize into the JSON that is
 * transmitted over HTTP when working with the myApi. For a detailed explanation see:
 * https://developers.google.com/api-client-library/java/google-http-java-client/json
 *

 *
 * @author Google, Inc.
 */
@SuppressWarnings("javadoc")
public final class CollectionResponseSalesRep extends com.google.api.client.json.GenericJson {

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.util.List<SalesRep> items;

  static {
    // hack to force ProGuard to consider SalesRep used, since otherwise it would be stripped out
    // see https://github.com/google/google-api-java-client/issues/543
    com.google.api.client.util.Data.nullOf(SalesRep.class);
  }

  /**
   * The value may be {@code null}.
   */
  @com.google.api.client.util.Key
  private java.lang.String nextPageToken;

  /**
   * @return value or {@code null} for none
   */
  public java.util.List<SalesRep> getItems() {
    return items;
  }

  /**
   * @param items items or {@code null} for none
   */
  public CollectionResponseSalesRep setItems(java.util.List<SalesRep> items) {
    this.items = items;
    return this;
  }

  /**
   * @return value or {@code null} for none
   */
  public java.lang.String getNextPageToken() {
    return nextPageToken;
  }

  /**
   * @param nextPageToken nextPageToken or {@code null} for none
   */
  public CollectionResponseSalesRep setNextPageToken(java.lang.String nextPageToken) {
    this.nextPageToken = nextPageToken;
    return this;
  }

  @Override
  public CollectionResponseSalesRep set(String fieldName, Object value) {
    return (CollectionResponseSalesRep) super.set(fieldName, value);
  }

  @Override
  public CollectionResponseSalesRep clone() {
    return (CollectionResponseSalesRep) super.clone();
  }

}


text:
/**
 * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
 * Licensed under the terms of the Eclipse Public License (EPL).
 * Please see the license.txt included with this distribution for details.
 * Any modifications to this file must keep this entire header intact.
 */
package org.python.pydev.plugin.nature;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.python.pydev.ast.codecompletion.revisited.SystemASTManager;
import org.python.pydev.core.ICodeCompletionASTManager;
import org.python.pydev.core.IInterpreterInfo;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.core.IModule;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.IPythonPathNature;
import org.python.pydev.core.MisconfigurationException;
import org.python.pydev.core.PropertiesHelper;
import org.python.pydev.core.PythonNatureWithoutProjectException;
import org.python.pydev.core.TokensList;
import org.python.pydev.core.log.Log;
import org.python.pydev.core.nature.AbstractPythonNature;
import org.python.pydev.shared_core.structure.OrderedMap;
import org.python.pydev.shared_core.structure.Tuple;

/**
 * This nature is used only as a 'last resort', if we're unable to link a given resource to
 * a project (and thus, we don't have project-related completions and we don't know with what
 * exactly we're dealing with: it's usually only used for external files)
 */
public class SystemPythonNature extends AbstractPythonNature implements IPythonNature {

    /**
     * @author Fabio
     *
     */
    private final class SystemPythonPathNature implements IPythonPathNature {
        @Override
        public void setVariableSubstitution(Map<String, String> variableSubstitution) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public void setProjectSourcePath(String newSourcePath) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public void setProjectExternalSourcePath(String newExternalSourcePath) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public void setProject(IProject project, IPythonNature nature) {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public Map<String, String> getVariableSubstitution(boolean addInterpreterInfoSubstitutions)
                throws CoreException, MisconfigurationException, PythonNatureWithoutProjectException {
            return getVariableSubstitution();
        }

        @Override
        public Map<String, String> getVariableSubstitution() throws CoreException, MisconfigurationException,
                PythonNatureWithoutProjectException {
            Properties stringSubstitutionVariables = SystemPythonNature.this.info.getStringSubstitutionVariables();
            Map<String, String> variableSubstitution;
            if (stringSubstitutionVariables == null) {
                variableSubstitution = new HashMap<String, String>();
            } else {
                variableSubstitution = PropertiesHelper.createMapFromProperties(stringSubstitutionVariables);
            }
            return variableSubstitution;

        }

        @Override
        public Set<String> getProjectSourcePathSet(boolean replaceVariables) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public String getProjectSourcePath(boolean replaceVariables) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public List<String> getProjectExternalSourcePathAsList(boolean replaceVariables) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public String getProjectExternalSourcePath(boolean replaceVariables) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public String getOnlyProjectPythonPathStr(boolean addExternal) throws CoreException {
            throw new RuntimeException("Not implemented");
        }

        @Override
        public IPythonNature getNature() {
            return SystemPythonNature.this;
        }

        @Override
        public List<String> getCompleteProjectPythonPath(IInterpreterInfo interpreter, IInterpreterManager info) {
            return interpreter.getPythonPath();
        }

        @Override
        public void clearCaches() {
            //No caches anyways
        }

        @Override
        public OrderedMap<String, String> getProjectSourcePathResolvedToUnresolvedMap() throws CoreException {
            throw new RuntimeException(
                    "Not implemented: We should use this only for doing path manipulation, "
                            + "which should not happen for the system python nature.");
        }

        @Override
        public Set<IResource> getProjectSourcePathFolderSet() throws CoreException {
            throw new RuntimeException("not implemented");
        }
    }

    private final IInterpreterManager manager;
    public final IInterpreterInfo info;
    private SystemASTManager systemASTManager;

    public SystemPythonNature(IInterpreterManager manager) throws MisconfigurationException {
        this(manager, manager.getDefaultInterpreterInfo(false));
    }

    public SystemPythonNature(IInterpreterManager manager, IInterpreterInfo info) {
        this.info = info;
        this.manager = manager;
    }

    @Override
    public boolean isResourceInPythonpathProjectSources(IResource resource, boolean addExternal)
            throws MisconfigurationException {
        return super.isResourceInPythonpath(resource); //no source folders in the system nature (just treat it as default)
    }

    @Override
    public boolean isResourceInPythonpathProjectSources(String resource, boolean addExternal)
            throws MisconfigurationException {
        return super.isResourceInPythonpath(resource); //no source folders in the system nature (just treat it as default)
    }

    @Override
    public String resolveModuleOnlyInProjectSources(IResource fileAbsolutePath, boolean addExternal)
            throws CoreException, MisconfigurationException {
        return super.resolveModule(fileAbsolutePath);
    }

    @Override
    public String resolveModuleOnlyInProjectSources(String fileAbsolutePath, boolean addExternal) throws CoreException,
            MisconfigurationException {
        return super.resolveModule(new File(fileAbsolutePath));
    }

    @Override
    public String getVersion(boolean translateIfInterpreter) throws CoreException {
        if (!translateIfInterpreter) {
            switch (this.manager.getInterpreterType()) {
                case IInterpreterManager.INTERPRETER_TYPE_PYTHON:
                    return IPythonNature.PYTHON_VERSION_INTERPRETER;

                case IInterpreterManager.INTERPRETER_TYPE_JYTHON:
                    return IPythonNature.JYTHON_VERSION_INTERPRETER;

                case IInterpreterManager.INTERPRETER_TYPE_IRONPYTHON:
                    return IPythonNature.IRONPYTHON_VERSION_INTERPRETER;

                default:
                    throw new RuntimeException("Not Python nor Jython nor IronPython?");
            }
        }
        if (this.info != null) {
            String version = this.info.getVersion();
            if (version != null) {
                return IPythonNature.Versions.convertToInternalVersion(this.manager.getInterpreterType(), version);
            } else {
                Log.log("Unable to get version from interpreter info: " + this.info.getNameForUI() + " - "
                        + this.info.getExecutableOrJar());
            }
        }

        // Last fallback (we should almost never get here).

        switch (this.manager.getInterpreterType()) {
            case IInterpreterManager.INTERPRETER_TYPE_PYTHON:
                return IPythonNature.Versions.PYTHON_VERSION_LATEST;

            case IInterpreterManager.INTERPRETER_TYPE_JYTHON:
                return IPythonNature.Versions.JYTHON_VERSION_LATEST;

            case IInterpreterManager.INTERPRETER_TYPE_IRONPYTHON:
                return IPythonNature.Versions.IRONPYTHON_VERSION_LATEST;

            default:
                throw new RuntimeException("Not Python nor Jython nor IronPython?");
        }
    }

    @Override
    public AdditionalGrammarVersionsToCheck getAdditionalGrammarVersions() throws MisconfigurationException {
        return null;
    }

    @Override
    public void setVersion(String version, String interpreter) throws CoreException {
        throw new RuntimeException("Not Implemented: the system nature is read-only.");
    }

    @Override
    public int getInterpreterType() throws CoreException {
        return this.manager.getInterpreterType();
    }

    @Override
    public File getCompletionsCacheDir() {
        throw new RuntimeException("Not Implemented");
    }

    @Override
    public void saveAstManager() {
        throw new RuntimeException("Not Implemented: system nature is only transient.");
    }

    @Override
    public IPythonPathNature getPythonPathNature() {
        return new SystemPythonPathNature();
    }

    @Override
    public String resolveModule(String file) throws MisconfigurationException {
        if (info == null) {
            return null;
        }
        return info.getModulesManager().resolveModule(file);
    }

    @Override
    public ICodeCompletionASTManager getAstManager() {
        if (systemASTManager == null) {
            systemASTManager = new SystemASTManager(this.manager, this, this.info);
        }
        return systemASTManager;
    }

    @Override
    public void configure() throws CoreException {
    }

    @Override
    public void deconfigure() throws CoreException {
    }

    @Override
    public IProject getProject() {
        return null;
    }

    @Override
    public void setProject(IProject project) {
    }

    @Override
    public void rebuildPath() {
        throw new RuntimeException("Not Implemented");
    }

    public void rebuildPath(String defaultSelectedInterpreter, IProgressMonitor monitor) {
        throw new RuntimeException("Not Implemented");
    }

    @Override
    public IInterpreterManager getRelatedInterpreterManager() {
        return manager;
    }

    //builtin completions

    @Override
    public TokensList getBuiltinCompletions() {
        if (!this.isOkToUse()) {
            return null;
        }
        return this.manager.getBuiltinCompletions(this.info.getName());
    }

    @Override
    public void clearBuiltinCompletions() {
        this.manager.clearBuiltinCompletions(this.info.getName());
    }

    //builtin mod

    @Override
    public IModule getBuiltinMod() {
        if (!this.isOkToUse()) {
            return null;
        }
        return this.manager.getBuiltinMod(this.info.getName());
    }

    @Override
    public void clearBuiltinMod() {
        this.manager.clearBuiltinMod(this.info.getName());
    }

    @Override
    public int getGrammarVersion() throws MisconfigurationException {
        IInterpreterInfo info = this.info;
        if (info != null) {
            return info.getGrammarVersion();
        } else {
            return IPythonNature.LATEST_GRAMMAR_PY3_VERSION;
        }
    }

    @Override
    public IInterpreterInfo getProjectInterpreter() throws MisconfigurationException {
        return this.info;
    }

    @Override
    public boolean isOkToUse() {
        return this.manager != null && this.info != null;
    }

    @Override
    public <T> T getAdapter(Class<T> adapter) {
        return null;
    }

    @Override
    public Tuple<String, String> getVersionAndError(boolean translateIfInterpreter) throws CoreException {
        throw new RuntimeException("Not implemented (expected only for the PythonNature itself).");
    }
}