text:
Zencoin Core version 0.16.3 is now available from:

  <https://download.zencoin.io/zencoin-0.16.3/>

This is a new minor version release, with various bugfixes
as well as updated translations.

Please report bugs using the issue tracker at GitHub:

  <https://github.com/ledvina/zencoin/issues>

To receive security and update notifications, please subscribe to:

  <https://groups.google.com/forum/#!forum/zencoin-dev>

How to Upgrade
==============

If you are running an older version, shut it down. Wait until it has completely
shut down (which might take a few minutes for older versions), then run the
installer (on Windows) or just copy over `/Applications/Zencoin-Qt` (on Mac)
or `zencoind`/`zencoin-qt` (on Linux).

The first time you run version 0.15.0 or newer, your chainstate database will be converted to a
new format, which will take anywhere from a few minutes to half an hour,
depending on the speed of your machine.

Note that the block database format also changed in version 0.8.0 and there is no
automatic upgrade code from before version 0.8 to version 0.15.0 or higher. Upgrading
directly from 0.7.x and earlier without re-downloading the blockchain is not supported.
However, as usual, old wallet versions are still supported.

Downgrading warning
-------------------

Wallets created in 0.16 and later are not compatible with versions prior to 0.16
and will not work if you try to use newly created wallets in older versions. Existing
wallets that were created with older versions are not affected by this.

Compatibility
==============

Zencoin Core is extensively tested on multiple operating systems using
the Linux kernel, macOS 10.8+, and Windows Vista and later. Windows XP is not supported.

Zencoin Core should also work on most other Unix-like systems but is not
frequently tested on them.

Notable changes
===============

Denial-of-Service vulnerability
-------------------------------

A denial-of-service vulnerability exploitable by miners has been discovered in
Zencoin Core versions 0.14.0 up to 0.16.2. It is recommended to upgrade any of
the vulnerable versions to 0.16.3 as soon as possible.

0.16.3 change log
------------------

### Consensus
- #14249 `696b936` Fix crash bug with duplicate inputs within a transaction (TheBlueMatt, sdaftuar)

Credits
=======

Thanks to everyone who directly contributed to this release:

- [The Bitcoin Core Developers](/doc/release-notes)
- Adrian Gallagher
- aunyks
- coblee
- cryptonexii
- gabrieldov
- jmutkawoa
- Martin Smith
- NeMO84
- ppm0
- romanornr
- shaolinfry
- spl0i7
- stedwms
- ultragtx
- VKoskiv
- voidmain
- wbsmolen
- xinxi

And to those that reported security issues:

- beardnboobies


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/sync_users"
        android:icon="@drawable/ic_sync_details"
        android:title="@string/sync_users"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/sync_visitors"
        android:icon="@drawable/ic_sync_visitors"
        android:title="@string/sync_visitors"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/signout"
        android:icon="@drawable/ic_sync_visitors"
        android:title="@string/sign_out"
        app:showAsAction="never" />
</menu>

redpajama_set_name: RedPajamaGithub


text:
package com.wii.vmail.db.dao;

import java.util.List;

import android.content.ContentValues;
import android.database.Cursor;
import com.wii.vmail.net.json.obj.MailInfo;
import com.wii.vmail.net.json.obj.MailItem;

import static com.wii.vmail.db.DbConstants.*;

public class MailItemDao extends AbstractDao<MailItem> {

    private static MailItemDao sDao = null;
    final static String TAG       = "MailItemDao";
    private MailItemDao() {}

    public static MailItemDao getDao() {
        if (sDao == null) sDao = new MailItemDao();
        return sDao;
    }

    public synchronized List<MailItem> loadTopMails(int isMain,
            String orderField, String order,int limit) {

        String statement = String.format(SQL_WHERECAUSE_TOP,
                isMain, orderField, order, limit);

        return loadWithQualification(statement);
    }

    @Override
    protected String getTableName() {
        return TABLE_SUBJECT;
    }

    public synchronized List<MailItem> loadTopMails(){

        List<MailItem> list = loadTopMails(1, "id", "DESC", 4);

        for (MailItem item : list) {
            //for subject mail, the id == main_id
            MailInfo mail_info = MailInfoDao.getDao().queryById(item.getId());
            item.setMailInfo(mail_info);

            MailItem last_info = MailItemDao.getDao().queryById(item.getLastId());
            item.setLastInfo(last_info);

            MailInfo last_mail_info = MailInfoDao.getDao().queryById(last_info.getId());
            item.getLastInfo().setMailInfo(last_mail_info);
        }

        return list;
    }

    public synchronized List<MailItem> queryLimitMails(long id, long start, int offset){
        String sqlStr = String.format(SQL_WHERECAUSE_LIMIT, id, start, offset);
        return loadWithQualification(sqlStr);
    }

    public synchronized List<MailItem> queryLimit(long id, long start, int offset) {
        List<MailItem> list = queryLimitMails(id,start,offset);//Query Subject Mail [is_main = 1]

        for (MailItem item : list) {
            //for subject mail, the id == main_id
            MailInfo mail_info = MailInfoDao.getDao().queryById(item.getId());
            item.setMailInfo(mail_info);

            MailItem last_info = MailItemDao.getDao().queryById(item.getLastId());
            item.setLastInfo(last_info);

            MailInfo last_mail_info = MailInfoDao.getDao().queryById(last_info.getId());
            item.getLastInfo().setMailInfo(last_mail_info);
        }

        return list;
    }

    @Override
    protected synchronized MailItem buildObject(Cursor c) {

        int type                = getInt(c, FIELD_TYPE);
        int is_main             = getInt(c, FIELD_IS_MAIN);
        int total_num           = getInt(c, FIELD_TOTAL_NUM);
        int new_num             = getInt(c, FIELD_NEW_NUM);
        int star                = getInt(c, FIELD_STAR_NUM);
        int status              = getInt(c, FIELD_STATUS);
        long id                 = getLng(c,FIELD_ID);
        long last_id            = getLng(c,FIELD_LAST_ID);
        long main_id            = getLng(c,FIELD_MAIN_ID);
        long create_time        = getLng(c,FIELD_CREATE_TIME);
        long uid                = getLng(c,FIELD_UID);
        long from_uid           = getLng(c,FIELD_FROM_UID);
        long last_update_time   = getLng(c,FIELD_LAST_UPDATE_TIME);
        long modify_time        = getLng(c,FIELD_MODIFY_TIME);
        String modify_ip        = getStr(c,FIELD_MODIFY_IP);
        String create_ip        = getStr(c,FIELD_CREATE_IP);

        MailItem item = new MailItem(type, status,
                    new_num, total_num, is_main, star,
                    id, uid, from_uid,main_id, last_id,
                    last_update_time,create_time,
                    modify_time, create_ip,
                    modify_ip,null, null);
        return item;
    }

    public synchronized List<MailItem> queryWithMainId(long main_id) {

        List<MailItem> list = loadWithQualification("WHERE main_id=" + main_id);

        for (MailItem item : list) {

            MailInfo mail_info = MailInfoDao.getDao().queryById(item.getId());
            item.setMailInfo(mail_info);

            if (item.isMainMail() == 1) {
                MailItem last_info = MailItemDao.getDao().queryById(item.getId());
                item.setLastInfo(last_info);

                MailInfo last_mail_info = MailInfoDao.getDao().queryById(last_info.getId());
                item.getLastInfo().setMailInfo(last_mail_info);

            } else {

                MailItem last_info = MailItemDao.getDao().queryById(item.getLastId());
                item.setLastInfo(last_info);

                MailInfo last_mail_info = MailInfoDao.getDao().queryById(last_info.getId());
                item.getLastInfo().setMailInfo(last_mail_info);
            }
        }

        return list;
    }

    public synchronized List<MailItem> queryMailItems(long mailId){

        List<MailItem> list = loadWithQualification("WHERE is_main=1 and last_id>=" + mailId);

        for (MailItem item : list) {

            MailInfo mail_info = MailInfoDao.getDao().queryById(item.getId());
            item.setMailInfo(mail_info);

            MailItem last_info = MailItemDao.getDao().queryById(item.getLastId());
            item.setLastInfo(last_info);

            MailInfo last_mail_info = MailInfoDao.getDao().queryById(last_info.getId());
            item.getLastInfo().setMailInfo(last_mail_info);
        }

        return list;
    }

    public synchronized MailItem queryById(long id) {
        MailItem item =  loadFirstWithQualification("WHERE id=?", new String[] {
            String.valueOf(id)
        });
        return item;
    }

    public synchronized void removeById(long id) {
        removeWithQualification("WHERE id=" + id);
    }

    @Override
    protected synchronized void fillContent(ContentValues content, MailItem data) {
        content.put(FIELD_TYPE,               String.valueOf(data.getMailType()));
        content.put(FIELD_IS_MAIN,            String.valueOf(data.isMainMail()));
        content.put(FIELD_TOTAL_NUM,          String.valueOf(data.getTotalNum()));
        content.put(FIELD_NEW_NUM,            String.valueOf(data.getNewNum()));
        content.put(FIELD_STAR_NUM,           String.valueOf(data.getStar()));
        content.put(FIELD_STATUS,             String.valueOf(data.getStatus()));
        content.put(FIELD_ID,                 String.valueOf(data.getId()));
        content.put(FIELD_LAST_ID,            String.valueOf(data.getLastId()));
        content.put(FIELD_MAIN_ID,            String.valueOf(data.getMainId()));
        content.put(FIELD_CREATE_TIME,        String.valueOf(data.getCreateTime()));
        content.put(FIELD_UID,                String.valueOf(data.getUid()));
        content.put(FIELD_FROM_UID,           String.valueOf(data.getFromUid()));
        content.put(FIELD_LAST_UPDATE_TIME,   String.valueOf(data.getLasUpdateTime()));
        content.put(FIELD_MODIFY_TIME,        String.valueOf(data.getModifyTime()));
        content.put(FIELD_MODIFY_IP,                         data.getModifyIp());
        content.put(FIELD_CREATE_IP,                         data.getCreateIp());
    }

    @Override
    protected String getTag() {
        return TAG;
    }
}


text:
//===- SCCP.cpp - Sparse Conditional Constant Propagation -----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This transformation pass performs a sparse conditional constant propagation
// in MLIR. It identifies values known to be constant, propagates that
// information throughout the IR, and replaces them. This is done with an
// optimisitic dataflow analysis that assumes that all values are constant until
// proven otherwise.
//
//===----------------------------------------------------------------------===//

#include "PassDetail.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/Dialect.h"
#include "mlir/Interfaces/ControlFlowInterfaces.h"
#include "mlir/Interfaces/SideEffects.h"
#include "mlir/Pass/Pass.h"
#include "mlir/Transforms/FoldUtils.h"
#include "mlir/Transforms/Passes.h"

using namespace mlir;

namespace {
/// This class represents a single lattice value. A lattive value corresponds to
/// the various different states that a value in the SCCP dataflow anaylsis can
/// take. See 'Kind' below for more details on the different states a value can
/// take.
class LatticeValue {
  enum Kind {
    /// A value with a yet to be determined value. This state may be changed to
    /// anything.
    Unknown,

    /// A value that is known to be a constant. This state may be changed to
    /// overdefined.
    Constant,

    /// A value that cannot statically be determined to be a constant. This
    /// state cannot be changed.
    Overdefined
  };

public:
  /// Initialize a lattice value with "Unknown".
  LatticeValue()
      : constantAndTag(nullptr, Kind::Unknown), constantDialect(nullptr) {}
  /// Initialize a lattice value with a constant.
  LatticeValue(Attribute attr, Dialect *dialect)
      : constantAndTag(attr, Kind::Constant), constantDialect(dialect) {}

  /// Returns true if this lattice value is unknown.
  bool isUnknown() const { return constantAndTag.getInt() == Kind::Unknown; }

  /// Mark the lattice value as overdefined.
  void markOverdefined() {
    constantAndTag.setPointerAndInt(nullptr, Kind::Overdefined);
    constantDialect = nullptr;
  }

  /// Returns true if the lattice is overdefined.
  bool isOverdefined() const {
    return constantAndTag.getInt() == Kind::Overdefined;
  }

  /// Mark the lattice value as constant.
  void markConstant(Attribute value, Dialect *dialect) {
    constantAndTag.setPointerAndInt(value, Kind::Constant);
    constantDialect = dialect;
  }

  /// If this lattice is constant, return the constant. Returns nullptr
  /// otherwise.
  Attribute getConstant() const { return constantAndTag.getPointer(); }

  /// If this lattice is constant, return the dialect to use when materializing
  /// the constant.
  Dialect *getConstantDialect() const {
    assert(getConstant() && "expected valid constant");
    return constantDialect;
  }

  /// Merge in the value of the 'rhs' lattice into this one. Returns true if the
  /// lattice value changed.
  bool meet(const LatticeValue &rhs) {
    // If we are already overdefined, or rhs is unknown, there is nothing to do.
    if (isOverdefined() || rhs.isUnknown())
      return false;
    // If we are unknown, just take the value of rhs.
    if (isUnknown()) {
      constantAndTag = rhs.constantAndTag;
      constantDialect = rhs.constantDialect;
      return true;
    }

    // Otherwise, if this value doesn't match rhs go straight to overdefined.
    if (constantAndTag != rhs.constantAndTag) {
      markOverdefined();
      return true;
    }
    return false;
  }

private:
  /// The attribute value if this is a constant and the tag for the element
  /// kind.
  llvm::PointerIntPair<Attribute, 2, Kind> constantAndTag;

  /// The dialect the constant originated from. This is only valid if the
  /// lattice is a constant. This is not used as part of the key, and is only
  /// needed to materialize the held constant if necessary.
  Dialect *constantDialect;
};

/// This class contains various state used when computing the lattice of a
/// callable operation.
class CallableLatticeState {
public:
  /// Build a lattice state with a given callable region, and a specified number
  /// of results to be initialized to the default lattice value (Unknown).
  CallableLatticeState(Region *callableRegion, unsigned numResults)
      : callableArguments(callableRegion->front().getArguments()),
        resultLatticeValues(numResults) {}

  /// Returns the arguments to the callable region.
  Block::BlockArgListType getCallableArguments() const {
    return callableArguments;
  }

  /// Returns the lattice value for the results of the callable region.
  MutableArrayRef<LatticeValue> getResultLatticeValues() {
    return resultLatticeValues;
  }

  /// Add a call to this callable. This is only used if the callable defines a
  /// symbol.
  void addSymbolCall(Operation *op) { symbolCalls.push_back(op); }

  /// Return the calls that reference this callable. This is only used
  /// if the callable defines a symbol.
  ArrayRef<Operation *> getSymbolCalls() const { return symbolCalls; }

private:
  /// The arguments of the callable region.
  Block::BlockArgListType callableArguments;

  /// The lattice state for each of the results of this region. The return
  /// values of the callable aren't SSA values, so we need to track them
  /// separately.
  SmallVector<LatticeValue, 4> resultLatticeValues;

  /// The calls referencing this callable if this callable defines a symbol.
  /// This removes the need to recompute symbol references during propagation.
  /// Value based references are trivial to resolve, so they can be done
  /// in-place.
  SmallVector<Operation *, 4> symbolCalls;
};

/// This class represents the solver for the SCCP analysis. This class acts as
/// the propagation engine for computing which values form constants.
class SCCPSolver {
public:
  /// Initialize the solver with the given top-level operation.
  SCCPSolver(Operation *op);

  /// Run the solver until it converges.
  void solve();

  /// Rewrite the given regions using the computing analysis. This replaces the
  /// uses of all values that have been computed to be constant, and erases as
  /// many newly dead operations.
  void rewrite(MLIRContext *context, MutableArrayRef<Region> regions);

private:
  /// Initialize the set of symbol defining callables that can have their
  /// arguments and results tracked. 'op' is the top-level operation that SCCP
  /// is operating on.
  void initializeSymbolCallables(Operation *op);

  /// Replace the given value with a constant if the corresponding lattice
  /// represents a constant. Returns success if the value was replaced, failure
  /// otherwise.
  LogicalResult replaceWithConstant(OpBuilder &builder, OperationFolder &folder,
                                    Value value);

  /// Visit the users of the given IR that reside within executable blocks.
  template <typename T>
  void visitUsers(T &value) {
    for (Operation *user : value.getUsers())
      if (isBlockExecutable(user->getBlock()))
        visitOperation(user);
  }

  /// Visit the given operation and compute any necessary lattice state.
  void visitOperation(Operation *op);

  /// Visit the given call operation and compute any necessary lattice state.
  void visitCallOperation(CallOpInterface op);

  /// Visit the given callable operation and compute any necessary lattice
  /// state.
  void visitCallableOperation(Operation *op);

  /// Visit the given operation, which defines regions, and compute any
  /// necessary lattice state. This also resolves the lattice state of both the
  /// operation results and any nested regions.
  void visitRegionOperation(Operation *op,
                            ArrayRef<Attribute> constantOperands);

  /// Visit the given set of region successors, computing any necessary lattice
  /// state. The provided function returns the input operands to the region at
  /// the given index. If the index is 'None', the input operands correspond to
  /// the parent operation results.
  void visitRegionSuccessors(
      Operation *parentOp, ArrayRef<RegionSuccessor> regionSuccessors,
      function_ref<OperandRange(Optional<unsigned>)> getInputsForRegion);

  /// Visit the given terminator operation and compute any necessary lattice
  /// state.
  void visitTerminatorOperation(Operation *op,
                                ArrayRef<Attribute> constantOperands);

  /// Visit the given terminator operation that exits a callable region. These
  /// are terminators with no CFG successors.
  void visitCallableTerminatorOperation(Operation *callable,
                                        Operation *terminator);

  /// Visit the given block and compute any necessary lattice state.
  void visitBlock(Block *block);

  /// Visit argument #'i' of the given block and compute any necessary lattice
  /// state.
  void visitBlockArgument(Block *block, int i);

  /// Mark the given block as executable. Returns false if the block was already
  /// marked executable.
  bool markBlockExecutable(Block *block);

  /// Returns true if the given block is executable.
  bool isBlockExecutable(Block *block) const;

  /// Mark the edge between 'from' and 'to' as executable.
  void markEdgeExecutable(Block *from, Block *to);

  /// Return true if the edge between 'from' and 'to' is executable.
  bool isEdgeExecutable(Block *from, Block *to) const;

  /// Mark the given value as overdefined. This means that we cannot refine a
  /// specific constant for this value.
  void markOverdefined(Value value);

  /// Mark all of the given values as overdefined.
  template <typename ValuesT>
  void markAllOverdefined(ValuesT values) {
    for (auto value : values)
      markOverdefined(value);
  }
  template <typename ValuesT>
  void markAllOverdefined(Operation *op, ValuesT values) {
    markAllOverdefined(values);
    opWorklist.push_back(op);
  }
  template <typename ValuesT>
  void markAllOverdefinedAndVisitUsers(ValuesT values) {
    for (auto value : values) {
      auto &lattice = latticeValues[value];
      if (!lattice.isOverdefined()) {
        lattice.markOverdefined();
        visitUsers(value);
      }
    }
  }

  /// Returns true if the given value was marked as overdefined.
  bool isOverdefined(Value value) const;

  /// Merge in the given lattice 'from' into the lattice 'to'. 'owner'
  /// corresponds to the parent operation of 'to'.
  void meet(Operation *owner, LatticeValue &to, const LatticeValue &from);

  /// The lattice for each SSA value.
  DenseMap<Value, LatticeValue> latticeValues;

  /// The set of blocks that are known to execute, or are intrinsically live.
  SmallPtrSet<Block *, 16> executableBlocks;

  /// The set of control flow edges that are known to execute.
  DenseSet<std::pair<Block *, Block *>> executableEdges;

  /// A worklist containing blocks that need to be processed.
  SmallVector<Block *, 64> blockWorklist;

  /// A worklist of operations that need to be processed.
  SmallVector<Operation *, 64> opWorklist;

  /// The callable operations that have their argument/result state tracked.
  DenseMap<Operation *, CallableLatticeState> callableLatticeState;

  /// A map between a call operation and the resolved symbol callable. This
  /// avoids re-resolving symbol references during propagation. Value based
  /// callables are trivial to resolve, so they can be done in-place.
  DenseMap<Operation *, Operation *> callToSymbolCallable;
};
} // end anonymous namespace

SCCPSolver::SCCPSolver(Operation *op) {
  /// Initialize the solver with the regions within this operation.
  for (Region &region : op->getRegions()) {
    if (region.empty())
      continue;
    Block *entryBlock = &region.front();

    // Mark the entry block as executable.
    markBlockExecutable(entryBlock);

    // The values passed to these regions are invisible, so mark any arguments
    // as overdefined.
    markAllOverdefined(entryBlock->getArguments());
  }
  initializeSymbolCallables(op);
}

void SCCPSolver::solve() {
  while (!blockWorklist.empty() || !opWorklist.empty()) {
    // Process any operations in the op worklist.
    while (!opWorklist.empty())
      visitUsers(*opWorklist.pop_back_val());

    // Process any blocks in the block worklist.
    while (!blockWorklist.empty())
      visitBlock(blockWorklist.pop_back_val());
  }
}

void SCCPSolver::rewrite(MLIRContext *context,
                         MutableArrayRef<Region> initialRegions) {
  SmallVector<Block *, 8> worklist;
  auto addToWorklist = [&](MutableArrayRef<Region> regions) {
    for (Region &region : regions)
      for (Block &block : region)
        if (isBlockExecutable(&block))
          worklist.push_back(&block);
  };

  // An operation folder used to create and unique constants.
  OperationFolder folder(context);
  OpBuilder builder(context);

  addToWorklist(initialRegions);
  while (!worklist.empty()) {
    Block *block = worklist.pop_back_val();

    // Replace any block arguments with constants.
    builder.setInsertionPointToStart(block);
    for (BlockArgument arg : block->getArguments())
      replaceWithConstant(builder, folder, arg);

    for (Operation &op : llvm::make_early_inc_range(*block)) {
      builder.setInsertionPoint(&op);

      // Replace any result with constants.
      bool replacedAll = op.getNumResults() != 0;
      for (Value res : op.getResults())
        replacedAll &= succeeded(replaceWithConstant(builder, folder, res));

      // If all of the results of the operation were replaced, try to erase
      // the operation completely.
      if (replacedAll && wouldOpBeTriviallyDead(&op)) {
        assert(op.use_empty() && "expected all uses to be replaced");
        op.erase();
        continue;
      }

      // Add any the regions of this operation to the worklist.
      addToWorklist(op.getRegions());
    }
  }
}

void SCCPSolver::initializeSymbolCallables(Operation *op) {
  // Initialize the set of symbol callables that can have their state tracked.
  // This tracks which symbol callable operations we can propagate within and
  // out of.
  auto walkFn = [&](Operation *symTable, bool allUsesVisible) {
    Region &symbolTableRegion = symTable->getRegion(0);
    Block *symbolTableBlock = &symbolTableRegion.front();
    for (auto callable : symbolTableBlock->getOps<CallableOpInterface>()) {
      // We won't be able to track external callables.
      Region *callableRegion = callable.getCallableRegion();
      if (!callableRegion)
        continue;
      // We only care about symbol defining callables here.
      auto symbol = dyn_cast<SymbolOpInterface>(callable.getOperation());
      if (!symbol)
        continue;
      callableLatticeState.try_emplace(callable, callableRegion,
                                       callable.getCallableResults().size());

      // If not all of the uses of this symbol are visible, we can't track the
      // state of the arguments.
      if (symbol.isPublic() || (!allUsesVisible && symbol.isNested()))
        markAllOverdefined(callableRegion->front().getArguments());
    }
    if (callableLatticeState.empty())
      return;

    // After computing the valid callables, walk any symbol uses to check
    // for non-call references. We won't be able to track the lattice state
    // for arguments to these callables, as we can't guarantee that we can see
    // all of its calls.
    Optional<SymbolTable::UseRange> uses =
        SymbolTable::getSymbolUses(&symbolTableRegion);
    if (!uses) {
      // If we couldn't gather the symbol uses, conservatively assume that
      // we can't track information for any nested symbols.
      op->walk([&](CallableOpInterface op) { callableLatticeState.erase(op); });
      return;
    }

    for (const SymbolTable::SymbolUse &use : *uses) {
      // If the use is a call, track it to avoid the need to recompute the
      // reference later.
      if (auto callOp = dyn_cast<CallOpInterface>(use.getUser())) {
        Operation *symCallable = callOp.resolveCallable();
        auto callableLatticeIt = callableLatticeState.find(symCallable);
        if (callableLatticeIt != callableLatticeState.end()) {
          callToSymbolCallable.try_emplace(callOp, symCallable);

          // We only need to record the call in the lattice if it produces any
          // values.
          if (callOp.getOperation()->getNumResults())
            callableLatticeIt->second.addSymbolCall(callOp);
        }
        continue;
      }
      // This use isn't a call, so don't we know all of the callers.
      auto *symbol = SymbolTable::lookupSymbolIn(op, use.getSymbolRef());
      auto it = callableLatticeState.find(symbol);
      if (it != callableLatticeState.end())
        markAllOverdefined(it->second.getCallableArguments());
    }
  };
  SymbolTable::walkSymbolTables(op, /*allSymUsesVisible=*/!op->getBlock(),
                                walkFn);
}

LogicalResult SCCPSolver::replaceWithConstant(OpBuilder &builder,
                                              OperationFolder &folder,
                                              Value value) {
  auto it = latticeValues.find(value);
  auto attr = it == latticeValues.end() ? nullptr : it->second.getConstant();
  if (!attr)
    return failure();

  // Attempt to materialize a constant for the given value.
  Dialect *dialect = it->second.getConstantDialect();
  Value constant = folder.getOrCreateConstant(builder, dialect, attr,
                                              value.getType(), value.getLoc());
  if (!constant)
    return failure();

  value.replaceAllUsesWith(constant);
  latticeValues.erase(it);
  return success();
}

void SCCPSolver::visitOperation(Operation *op) {
  // Collect all of the constant operands feeding into this operation. If any
  // are not ready to be resolved, bail out and wait for them to resolve.
  SmallVector<Attribute, 8> operandConstants;
  operandConstants.reserve(op->getNumOperands());
  for (Value operand : op->getOperands()) {
    // Make sure all of the operands are resolved first.
    auto &operandLattice = latticeValues[operand];
    if (operandLattice.isUnknown())
      return;
    operandConstants.push_back(operandLattice.getConstant());
  }

  // If this is a terminator operation, process any control flow lattice state.
  if (op->isKnownTerminator())
    visitTerminatorOperation(op, operandConstants);

  // Process call operations. The call visitor processes result values, so we
  // can exit afterwards.
  if (CallOpInterface call = dyn_cast<CallOpInterface>(op))
    return visitCallOperation(call);

  // Process callable operations. These are specially handled region operations
  // that track dataflow via calls.
  if (isa<CallableOpInterface>(op))
    return visitCallableOperation(op);

  // Process region holding operations. The region visitor processes result
  // values, so we can exit afterwards.
  if (op->getNumRegions())
    return visitRegionOperation(op, operandConstants);

  // If this op produces no results, it can't produce any constants.
  if (op->getNumResults() == 0)
    return;

  // If all of the results of this operation are already overdefined, bail out
  // early.
  auto isOverdefinedFn = [&](Value value) { return isOverdefined(value); };
  if (llvm::all_of(op->getResults(), isOverdefinedFn))
    return;

  // Save the original operands and attributes just in case the operation folds
  // in-place. The constant passed in may not correspond to the real runtime
  // value, so in-place updates are not allowed.
  SmallVector<Value, 8> originalOperands(op->getOperands());
  MutableDictionaryAttr originalAttrs = op->getMutableAttrDict();

  // Simulate the result of folding this operation to a constant. If folding
  // fails or was an in-place fold, mark the results as overdefined.
  SmallVector<OpFoldResult, 8> foldResults;
  foldResults.reserve(op->getNumResults());
  if (failed(op->fold(operandConstants, foldResults)))
    return markAllOverdefined(op, op->getResults());

  // If the folding was in-place, mark the results as overdefined and reset the
  // operation. We don't allow in-place folds as the desire here is for
  // simulated execution, and not general folding.
  if (foldResults.empty()) {
    op->setOperands(originalOperands);
    op->setAttrs(originalAttrs);
    return markAllOverdefined(op, op->getResults());
  }

  // Merge the fold results into the lattice for this operation.
  assert(foldResults.size() == op->getNumResults() && "invalid result size");
  Dialect *opDialect = op->getDialect();
  for (unsigned i = 0, e = foldResults.size(); i != e; ++i) {
    LatticeValue &resultLattice = latticeValues[op->getResult(i)];

    // Merge in the result of the fold, either a constant or a value.
    OpFoldResult foldResult = foldResults[i];
    if (Attribute foldAttr = foldResult.dyn_cast<Attribute>())
      meet(op, resultLattice, LatticeValue(foldAttr, opDialect));
    else
      meet(op, resultLattice, latticeValues[foldResult.get<Value>()]);
  }
}

void SCCPSolver::visitCallableOperation(Operation *op) {
  // Mark the regions as executable.
  bool isTrackingLatticeState = callableLatticeState.count(op);
  for (Region &region : op->getRegions()) {
    if (region.empty())
      continue;
    Block *entryBlock = &region.front();
    markBlockExecutable(entryBlock);

    // If we aren't tracking lattice state for this callable, mark all of the
    // region arguments as overdefined.
    if (!isTrackingLatticeState)
      markAllOverdefined(entryBlock->getArguments());
  }

  // TODO: Add support for non-symbol callables when necessary. If the callable
  // has non-call uses we would mark overdefined, otherwise allow for
  // propagating the return values out.
  markAllOverdefined(op, op->getResults());
}

void SCCPSolver::visitCallOperation(CallOpInterface op) {
  ResultRange callResults = op.getOperation()->getResults();

  // Resolve the callable operation for this call.
  Operation *callableOp = nullptr;
  if (Value callableValue = op.getCallableForCallee().dyn_cast<Value>())
    callableOp = callableValue.getDefiningOp();
  else
    callableOp = callToSymbolCallable.lookup(op);

  // The callable of this call can't be resolved, mark any results overdefined.
  if (!callableOp)
    return markAllOverdefined(op, callResults);

  // If this callable is tracking state, merge the argument operands with the
  // arguments of the callable.
  auto callableLatticeIt = callableLatticeState.find(callableOp);
  if (callableLatticeIt == callableLatticeState.end())
    return markAllOverdefined(op, callResults);

  OperandRange callOperands = op.getArgOperands();
  auto callableArgs = callableLatticeIt->second.getCallableArguments();
  for (auto it : llvm::zip(callOperands, callableArgs)) {
    BlockArgument callableArg = std::get<1>(it);
    if (latticeValues[callableArg].meet(latticeValues[std::get<0>(it)]))
      visitUsers(callableArg);
  }

  // Merge in the lattice state for the callable results as well.
  auto callableResults = callableLatticeIt->second.getResultLatticeValues();
  for (auto it : llvm::zip(callResults, callableResults))
    meet(/*owner=*/op, /*to=*/latticeValues[std::get<0>(it)],
         /*from=*/std::get<1>(it));
}

void SCCPSolver::visitRegionOperation(Operation *op,
                                      ArrayRef<Attribute> constantOperands) {
  // Check to see if we can reason about the internal control flow of this
  // region operation.
  auto regionInterface = dyn_cast<RegionBranchOpInterface>(op);
  if (!regionInterface) {
    // If we can't, conservatively mark all regions as executable.
    for (Region &region : op->getRegions()) {
      if (region.empty())
        continue;
      Block *entryBlock = &region.front();
      markBlockExecutable(entryBlock);
      markAllOverdefined(entryBlock->getArguments());
    }

    // Don't try to simulate the results of a region operation as we can't
    // guarantee that folding will be out-of-place. We don't allow in-place
    // folds as the desire here is for simulated execution, and not general
    // folding.
    return markAllOverdefined(op, op->getResults());
  }

  // Check to see which regions are executable.
  SmallVector<RegionSuccessor, 1> successors;
  regionInterface.getSuccessorRegions(/*index=*/llvm::None, constantOperands,
                                      successors);

  // If the interface identified that no region will be executed. Mark
  // any results of this operation as overdefined, as we can't reason about
  // them.
  // TODO: If we had an interface to detect pass through operands, we could
  // resolve some results based on the lattice state of the operands. We could
  // also allow for the parent operation to have itself as a region successor.
  if (successors.empty())
    return markAllOverdefined(op, op->getResults());
  return visitRegionSuccessors(op, successors, [&](Optional<unsigned> index) {
    assert(index && "expected valid region index");
    return regionInterface.getSuccessorEntryOperands(*index);
  });
}

void SCCPSolver::visitRegionSuccessors(
    Operation *parentOp, ArrayRef<RegionSuccessor> regionSuccessors,
    function_ref<OperandRange(Optional<unsigned>)> getInputsForRegion) {
  for (const RegionSuccessor &it : regionSuccessors) {
    Region *region = it.getSuccessor();
    ValueRange succArgs = it.getSuccessorInputs();

    // Check to see if this is the parent operation.
    if (!region) {
      ResultRange results = parentOp->getResults();
      if (llvm::all_of(results, [&](Value res) { return isOverdefined(res); }))
        continue;

      // Mark the results outside of the input range as overdefined.
      if (succArgs.size() != results.size()) {
        opWorklist.push_back(parentOp);
        if (succArgs.empty())
          return markAllOverdefined(results);

        unsigned firstResIdx = succArgs[0].cast<OpResult>().getResultNumber();
        markAllOverdefined(results.take_front(firstResIdx));
        markAllOverdefined(results.drop_front(firstResIdx + succArgs.size()));
      }

      // Update the lattice for any operation results.
      OperandRange operands = getInputsForRegion(/*index=*/llvm::None);
      for (auto it : llvm::zip(succArgs, operands))
        meet(parentOp, latticeValues[std::get<0>(it)],
             latticeValues[std::get<1>(it)]);
      return;
    }
    assert(!region->empty() && "expected region to be non-empty");
    Block *entryBlock = &region->front();
    markBlockExecutable(entryBlock);

    // If all of the arguments are already overdefined, the arguments have
    // already been fully resolved.
    auto arguments = entryBlock->getArguments();
    if (llvm::all_of(arguments, [&](Value arg) { return isOverdefined(arg); }))
      continue;

    // Mark any arguments that do not receive inputs as overdefined, we won't be
    // able to discern if they are constant.
    if (succArgs.size() != arguments.size()) {
      if (succArgs.empty()) {
        markAllOverdefined(arguments);
        continue;
      }

      unsigned firstArgIdx = succArgs[0].cast<BlockArgument>().getArgNumber();
      markAllOverdefinedAndVisitUsers(arguments.take_front(firstArgIdx));
      markAllOverdefinedAndVisitUsers(
          arguments.drop_front(firstArgIdx + succArgs.size()));
    }

    // Update the lattice for arguments that have inputs from the predecessor.
    OperandRange succOperands = getInputsForRegion(region->getRegionNumber());
    for (auto it : llvm::zip(succArgs, succOperands)) {
      LatticeValue &argLattice = latticeValues[std::get<0>(it)];
      if (argLattice.meet(latticeValues[std::get<1>(it)]))
        visitUsers(std::get<0>(it));
    }
  }
}

void SCCPSolver::visitTerminatorOperation(
    Operation *op, ArrayRef<Attribute> constantOperands) {
  // If this operation has no successors, we treat it as an exiting terminator.
  if (op->getNumSuccessors() == 0) {
    Region *parentRegion = op->getParentRegion();
    Operation *parentOp = parentRegion->getParentOp();

    // Check to see if this is a terminator for a callable region.
    if (isa<CallableOpInterface>(parentOp))
      return visitCallableTerminatorOperation(parentOp, op);

    // Otherwise, check to see if the parent tracks region control flow.
    auto regionInterface = dyn_cast<RegionBranchOpInterface>(parentOp);
    if (!regionInterface || !isBlockExecutable(parentOp->getBlock()))
      return;

    // Query the set of successors from the current region.
    SmallVector<RegionSuccessor, 1> regionSuccessors;
    regionInterface.getSuccessorRegions(parentRegion->getRegionNumber(),
                                        constantOperands, regionSuccessors);
    if (regionSuccessors.empty())
      return;

    // If this terminator is not "region-like", conservatively mark all of the
    // successor values as overdefined.
    if (!op->hasTrait<OpTrait::ReturnLike>()) {
      for (auto &it : regionSuccessors)
        markAllOverdefinedAndVisitUsers(it.getSuccessorInputs());
      return;
    }

    // Otherwise, propagate the operand lattice states to each of the
    // successors.
    OperandRange operands = op->getOperands();
    return visitRegionSuccessors(parentOp, regionSuccessors,
                                 [&](Optional<unsigned>) { return operands; });
  }

  // Try to resolve to a specific successor with the constant operands.
  if (auto branch = dyn_cast<BranchOpInterface>(op)) {
    if (Block *singleSucc = branch.getSuccessorForOperands(constantOperands)) {
      markEdgeExecutable(op->getBlock(), singleSucc);
      return;
    }
  }

  // Otherwise, conservatively treat all edges as executable.
  Block *block = op->getBlock();
  for (Block *succ : op->getSuccessors())
    markEdgeExecutable(block, succ);
}

void SCCPSolver::visitCallableTerminatorOperation(Operation *callable,
                                                  Operation *terminator) {
  // If there are no exiting values, we have nothing to track.
  if (terminator->getNumOperands() == 0)
    return;

  // If this callable isn't tracking any lattice state there is nothing to do.
  auto latticeIt = callableLatticeState.find(callable);
  if (latticeIt == callableLatticeState.end())
    return;
  assert(callable->getNumResults() == 0 && "expected symbol callable");

  // If this terminator is not "return-like", conservatively mark all of the
  // call-site results as overdefined.
  auto callableResultLattices = latticeIt->second.getResultLatticeValues();
  if (!terminator->hasTrait<OpTrait::ReturnLike>()) {
    for (auto &it : callableResultLattices)
      it.markOverdefined();
    for (Operation *call : latticeIt->second.getSymbolCalls())
      markAllOverdefined(call, call->getResults());
    return;
  }

  // Merge the terminator operands into the results.
  bool anyChanged = false;
  for (auto it : llvm::zip(terminator->getOperands(), callableResultLattices))
    anyChanged |= std::get<1>(it).meet(latticeValues[std::get<0>(it)]);
  if (!anyChanged)
    return;

  // If any of the result lattices changed, update the callers.
  for (Operation *call : latticeIt->second.getSymbolCalls())
    for (auto it : llvm::zip(call->getResults(), callableResultLattices))
      meet(call, latticeValues[std::get<0>(it)], std::get<1>(it));
}

void SCCPSolver::visitBlock(Block *block) {
  // If the block is not the entry block we need to compute the lattice state
  // for the block arguments. Entry block argument lattices are computed
  // elsewhere, such as when visiting the parent operation.
  if (!block->isEntryBlock()) {
    for (int i : llvm::seq<int>(0, block->getNumArguments()))
      visitBlockArgument(block, i);
  }

  // Visit all of the operations within the block.
  for (Operation &op : *block)
    visitOperation(&op);
}

void SCCPSolver::visitBlockArgument(Block *block, int i) {
  BlockArgument arg = block->getArgument(i);
  LatticeValue &argLattice = latticeValues[arg];
  if (argLattice.isOverdefined())
    return;

  bool updatedLattice = false;
  for (auto it = block->pred_begin(), e = block->pred_end(); it != e; ++it) {
    Block *pred = *it;

    // We only care about this predecessor if it is going to execute.
    if (!isEdgeExecutable(pred, block))
      continue;

    // Try to get the operand forwarded by the predecessor. If we can't reason
    // about the terminator of the predecessor, mark overdefined.
    Optional<OperandRange> branchOperands;
    if (auto branch = dyn_cast<BranchOpInterface>(pred->getTerminator()))
      branchOperands = branch.getSuccessorOperands(it.getSuccessorIndex());
    if (!branchOperands) {
      updatedLattice = true;
      argLattice.markOverdefined();
      break;
    }

    // If the operand hasn't been resolved, it is unknown which can merge with
    // anything.
    auto operandLattice = latticeValues.find((*branchOperands)[i]);
    if (operandLattice == latticeValues.end())
      continue;

    // Otherwise, meet the two lattice values.
    updatedLattice |= argLattice.meet(operandLattice->second);
    if (argLattice.isOverdefined())
      break;
  }

  // If the lattice was updated, visit any executable users of the argument.
  if (updatedLattice)
    visitUsers(arg);
}

bool SCCPSolver::markBlockExecutable(Block *block) {
  bool marked = executableBlocks.insert(block).second;
  if (marked)
    blockWorklist.push_back(block);
  return marked;
}

bool SCCPSolver::isBlockExecutable(Block *block) const {
  return executableBlocks.count(block);
}

void SCCPSolver::markEdgeExecutable(Block *from, Block *to) {
  if (!executableEdges.insert(std::make_pair(from, to)).second)
    return;
  // Mark the destination as executable, and reprocess its arguments if it was
  // already executable.
  if (!markBlockExecutable(to)) {
    for (int i : llvm::seq<int>(0, to->getNumArguments()))
      visitBlockArgument(to, i);
  }
}

bool SCCPSolver::isEdgeExecutable(Block *from, Block *to) const {
  return executableEdges.count(std::make_pair(from, to));
}

void SCCPSolver::markOverdefined(Value value) {
  latticeValues[value].markOverdefined();
}

bool SCCPSolver::isOverdefined(Value value) const {
  auto it = latticeValues.find(value);
  return it != latticeValues.end() && it->second.isOverdefined();
}

void SCCPSolver::meet(Operation *owner, LatticeValue &to,
                      const LatticeValue &from) {
  if (to.meet(from))
    opWorklist.push_back(owner);
}

//===----------------------------------------------------------------------===//
// SCCP Pass
//===----------------------------------------------------------------------===//

namespace {
struct SCCP : public SCCPBase<SCCP> {
  void runOnOperation() override;
};
} // end anonymous namespace

void SCCP::runOnOperation() {
  Operation *op = getOperation();

  // Solve for SCCP constraints within nested regions.
  SCCPSolver solver(op);
  solver.solve();

  // Cleanup any operations using the solver analysis.
  solver.rewrite(&getContext(), op->getRegions());
}

std::unique_ptr<Pass> mlir::createSCCPPass() {
  return std::make_unique<SCCP>();
}


text:
layout: post
title: RVM Cannot Compile on Ubuntu 22.04
author: FrozenFOXX
tags:
 - linux
 - ruby
---

Since upgrading to Ubuntu 22.04 the popular [RVM](https://rvm.io) tool has stopped being able to install or use Ruby:

```
➜  ~ rvm install 3.0
Searching for binary rubies, this might take some time.
No binary rubies available for: ubuntu/22.04/x86_64/ruby-3.0.0.
Continuing with compilation. Please read 'rvm help mount' to get more information on binary rubies.
Checking requirements for ubuntu.
Requirements installation successful.
Installing Ruby from source to: /home/frozenfoxx/.rvm/rubies/ruby-3.0.0, this may take a while depending on your cpu(s)...
ruby-3.0.0 - #downloading ruby-3.0.0, this may take a while depending on your connection...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 18.6M  100 18.6M    0     0  14.7M      0  0:00:01  0:00:01 --:--:-- 14.7M
ruby-3.0.0 - #extracting ruby-3.0.0 to /home/frozenfoxx/.rvm/src/ruby-3.0.0 - please wait
ruby-3.0.0 - #configuring - please wait
ruby-3.0.0 - #post-configuration - please wait
ruby-3.0.0 - #compiling - please wait
Error running '__rvm_make -j12',
please read /home/frozenfoxx/.rvm/log/1653505265_ruby-3.0.0/make.log

There has been an error while running make. Halting the installation.
```

Looking in the `/home/frozenfoxx/.rvm/log/1653505265_ruby-3.0.0/make.log` it looks like it's having a problem with OpenSSL:

```
[...]
make[2]: Leaving directory '/home/frozenfoxx/.rvm/src/ruby-3.0.0/ext/openssl'
make[1]: *** [exts.mk:260: ext/openssl/all] Error 2
[...]
```

Turns out this is an incompatibility introduced by Ubuntu's switch to OpenSSL 3.0. Previously many Rubies shipped with OpenSSL 1.1 and many Gems relied on it. Supposing you don't want to downgrade the system OpenSSL to 3.0 which would have its own issues, what are you supposed to do?

While a little cumbersome there's a way to get everything you need still contained in the RVM installation. First, use the RVM `pkg` command to install a local build of a compatible OpenSSL:

```
rvm pkg install openssl
```

This will create a compatible OpenSSL build for those Rubies that need it. Now when installing Rubies that have a problem with OpenSSL (pretty much any that are older than 3.1) you can redirect them to use the locally supplied OpenSSL library:

```
rvm install [version] --with-openssl-dir=$HOME/.rvm/usr
```

Here's a sample involving Ruby 2.4:

```
➜  ~ rvm install 2.4 --with-openssl-dir=$HOME/.rvm/usr
Checking requirements for ubuntu.
Requirements installation successful.
Installing Ruby from source to: /home/frozenfoxx/.rvm/rubies/ruby-2.4.10, this may take a while depending on your cpu(s)...
ruby-2.4.10 - #downloading ruby-2.4.10, this may take a while depending on your connection...
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100 11.9M  100 11.9M    0     0  17.4M      0 --:--:-- --:--:-- --:--:-- 17.4M
ruby-2.4.10 - #extracting ruby-2.4.10 to /home/frozenfoxx/.rvm/src/ruby-2.4.10 - please wait
ruby-2.4.10 - #configuring - please wait
ruby-2.4.10 - #post-configuration - please wait
ruby-2.4.10 - #compiling - please wait
ruby-2.4.10 - #installing - please wait
ruby-2.4.10 - #making binaries executable - please wait
ruby-2.4.10 - #downloading rubygems-3.0.9
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  865k  100  865k    0     0  5337k      0 --:--:-- --:--:-- --:--:-- 5309k
No checksum for downloaded archive, recording checksum in user configuration.
ruby-2.4.10 - #extracting rubygems-3.0.9 - please wait
ruby-2.4.10 - #removing old rubygems - please wait
ruby-2.4.10 - #installing rubygems-3.0.9 - please wait
ruby-2.4.10 - #gemset created /home/frozenfoxx/.rvm/gems/ruby-2.4.10@global
ruby-2.4.10 - #importing gemset /home/frozenfoxx/.rvm/gemsets/global.gems - please wait
ruby-2.4.10 - #generating global wrappers - please wait
ruby-2.4.10 - #gemset created /home/frozenfoxx/.rvm/gems/ruby-2.4.10
ruby-2.4.10 - #importing gemsetfile /home/frozenfoxx/.rvm/gemsets/default.gems evaluated to empty gem list
ruby-2.4.10 - #generating default wrappers - please wait
ruby-2.4.10 - #adjusting #shebangs for (gem irb erb ri rdoc testrb rake).
Install of ruby-2.4.10 - #complete
Ruby was built without documentation, to build it run: rvm docs generate-ri
```


text:
/**
 * @ngdoc function
 * @name starter.controllers.LoginController
 * @description Dash controller
 * @author nthusitha
 * @requires [$scope, $http, $state, $ionicLoading, $ionicPopup, $rootScope, $window, loginService, platformSubscriberService,
		Alerts, $injector]
 * @since 0.0.1
 */
angular.module('starter.controllers').controller('LoginController', ['$scope', '$http', '$state', '$ionicLoading', '$ionicPopup', '$rootScope', '$window', '$q', 'loginService', 'platformSubscriberService', 'Alerts', '$injector', function($scope, $http, $state, $ionicLoading, $ionicPopup, $rootScope, $window, $q, loginService, platformSubscriberService, Alerts, $injector) {

    // get username password from config

    var notificationService_ = null;
    $scope.userName = localStorage.getItem("username");
    $scope.password = localStorage.getItem("password");
    $scope.loginError = false;

    // signIn Function
    $scope.signIn = function(username, password) {
        console.log(username);
        $scope.loginError = false;
        if (username == "" || password == "") {
            $scope.loginError = true;
            $scope.errorMessage = "Username / Password cannot be empty.";
            weather_config.gtnx_user = "";
            weather_config.gtnx_pw = "";

            localStorage.setItem("username", weather_config.gtnx_user);
            localStorage.setItem("password", weather_config.gtnx_pw);
        } else {

            $ionicLoading.show({
                content: 'Loading!',
                animation: 'fade-in',
                showBackdrop: true,
                maxWidth: 400,
                showDelay: 0
            });
            $scope.userName = username;
            $scope.password = password;
            $scope.loginError = false;
            console.log("START CALLED");

            weather_config.gtnx_user = $scope.userName;
            weather_config.gtnx_pw = $scope.password;

            localStorage.setItem("username", weather_config.gtnx_user);
            localStorage.setItem("password", weather_config.gtnx_pw);

            // localStorage.getItem("username")
            // Code for Select the production Environment

            console.log(localStorage.getItem("username"));
            // TODO : Your login logic here

            console.log($scope.userName);
            console.log($scope.password);

            var loginServiceCall = loginService.login({
                userName: $scope.userName,
                password: $scope.password,
                eid: null
            });

            loginServiceCall.success(function(data, status, headers, config) {
                var header = headers();
                var authResponse = header.authorization;
                if (authResponse != null) {
                    console.log("AuthToken (in Response): " + authResponse);
                    var authToken = encodeHeader($scope.userName, $scope.password, null);
                    weather_config.authToken = authToken;
                    // weather_config.authToken = authResponse;// overwrite
                    // existing
                    // token
                    // localStorage.setItem("authToken", authResponse);
                    localStorage.setItem(weather_config.local_storage_auth_token_key, authToken);
                    // code for fetch the users information
                    $scope.getUserIdByName($scope.userName);

                    $state.go('tab.alerts');
                    $ionicLoading.hide();

                }

            }).error(function(data, status, headers, config) {
                console.log(data);
                console.log(status);
                console.log(headers());
                if (status == 401) {
                    $scope.loginError = true;
                    $scope.errorMessage = "Incorrect username and/or password";
                }

                $ionicLoading.hide();
            });

        }
    };

    // function to get userId by name
    $scope.getUserIdByName = function(userName) {
        var authToken = localStorage.getItem(weather_config.local_storage_auth_token_key);
        var platformSubscriberServiceCall = platformSubscriberService.findUser(userName, authToken);
        platformSubscriberServiceCall.success(function(data, status, headers, config) {

            console.log(data);
            console.log(status);
            // console.log(headers());

            var resultObj = data.resultInfo;
            if (data.result) {
                console.log(data.result[0]);
            }

            if (resultObj.count == 0) {

                $scope.createNewPlatformSubscriber(userName);
            } else {
                // storing the platform subscriber object into local
                // storage
                var jsonString = JSON.stringify(data.result[0]);
                console.log(data.result[0]["uid"]);
                localStorage.setItem(weather_config.local_storage_platform_susbscirber_json_key, jsonString);
                localStorage.setItem(weather_config.local_storage_platform_subscriber_id_key, data.result[0]["uid"]);
                syncWithPush();
            }

        }).error(function(data, status, headers, config) {
            console.log(data);
            console.log(status);
            console.log(headers());
            if (status == 401) {

                $scope.errorMessage = "Incorrect username and/or password";
            }

        });

    };

    // function to create a new user object if there no user obj found
    // in platform
    // subscriber
    // module.
    $scope.createNewPlatformSubscriber = function(userName) {

        // time stamp for the UIdentifier.
        var timeStamp = Date.now();

        var platformSubscriberObj = new Object();
        platformSubscriberObj.type = weather_config.platform_subscription_design;
        platformSubscriberObj.uIdentifier = timeStamp.toString();
        platformSubscriberObj.username = userName.toLowerCase();
        platformSubscriberObj.status = "active";

        // create a owner object ,Currently its hard coded .This should
        // be ORG object of the
        // logged user.
        $scope.getOwnerByUserName(userName).then(function(response) {
            if (response != 'error') {

                var ownerObj = response;
                platformSubscriberObj.owner = ownerObj;
                // End of owner object code.
                var authToken = localStorage.getItem(weather_config.local_storage_auth_token_key);
                var platformSubscriberServiceCall = platformSubscriberService.createUser(platformSubscriberObj, authToken);
                platformSubscriberServiceCall.success(function(data, status, headers, config) {

                    console.log(data);
                    console.log(status);
                    console.log(headers()); // common method to get all success

                    var resultObj = data.create.result;
                    if (resultObj) {
                        console.log(resultObj);
                        // storing the platform subscriber object into local
                        // storage
                        var jsonString = JSON.stringify(resultObj);
                       // console.log(data.result[0]["uid"]);
                        localStorage.setItem(weather_config.local_storage_platform_susbscirber_json_key, jsonString);
                        localStorage.setItem(weather_config.local_storage_platform_subscriber_id_key, resultObj.uid);
                        syncWithPush();
                    }

                }).error(function(data, status, headers, config) {
                    console.log(data);
                    console.log(status);
                    console.log(headers());
                    if (status == 401) {

                    }
                    // It's a common method to handle all responses.

                });

            }

        });

    };

    /*
     * platformSubscriberId and authToken must be persisted before call this.
     *
     */
    var syncWithPush = function() {
        //TODO: ADD CONFIRMATION DIALOG FOR PUSH NOTIFICATIONS
        // UTC
        var date = new Date();
        var now = date.getTime();

        if (notificationService_ == null) {
            notificationService_ = $injector.get('NotificationService');
        }

        var lastSyncedTime = localStorage.getItem(weather_config.local_storage_last_device_token_sync_time_key);
        var cachedPlatformSubscriberId = localStorage.getItem(weather_config.local_storage_platform_subscriber_id_key);
        var cachedAuthToken = localStorage.getItem(weather_config.local_storage_auth_token_key);

        if (lastSyncedTime && lastSyncedTime != '') {
            if ((now - lastSyncedTime) >= weather_config.apns_device_token_refresh_interval_ms) {
                // if time stamp is not updated previously
                // do if token expires after given time
                notificationService_.registerForPushNotifications($http, Alerts, cachedPlatformSubscriberId, cachedAuthToken);
                localStorage.setItem(weather_config.local_storage_last_device_token_sync_time_key, now);
                if (weather_config.debug) {
                    console.log("synced apns/gcm device token, token expiry time reached");
                }
            }
        } else {

            if (weather_config.debug) {
                console.log("synced apns/gcm device token for the first time");
            }
            // do for the first time.
            notificationService_.registerForPushNotifications($http, Alerts, cachedPlatformSubscriberId, cachedAuthToken);
            localStorage.setItem(weather_config.local_storage_last_device_token_sync_time_key, now);
        }
    }

    // function to get owner object by username
    $scope.getOwnerByUserNameDeprecated = function(userName) {
        // create a owner object ,Currently its hard coded .This should
        // be ORG object of the
        // logged user.
        var ownerObj = new Object();
        ownerObj.partyRoleCode = "Buyer";

        var addressObj = new Object();
        addressObj.countryCode = "US";
        addressObj.stateOrProvince = "New York";
        addressObj.addressLine2 = "31st Floor";
        addressObj.postalCodeNumber = "NY 10041";
        addressObj.addressLine1 = "55 Water Street";
        addressObj.city = "New York";

        ownerObj.address = addressObj;
        ownerObj.name = "Scout Buyer";
        ownerObj.memberId = "3717989018024131";
        ownerObj.contact = new Object();

        return ownerObj;
        // End of owner object code.
    };

    // function to get owner object by username
    $scope.getOwnerByUserName = function(userName) {

        var authToken = localStorage.getItem(weather_config.local_storage_auth_token_key);
        var defer = $q.defer();

        if (authToken) {
            loginService.getUserDetails(authToken).success(function(data, status, headers, config) {

                if (data.organizationUid) {
                    var ownerParty = new Object();
                    ownerParty.memberId = data.organizationUid;
                    defer.resolve(ownerParty);

                } else {
                    defer.reject('error');
                }

            }).error(function(data, status, headers, config) {
                defer.reject('error');

            });
        } else {

            if (weather_config.debug) {
                console.log("error occured while getting owner org, cause: can't find authtoken the local storage");
            }
        }

        return defer.promise;
    }

    // function for logout
    $scope.logout = function() {

        // to pop up the logout confirmation
        var confirmPopup = $ionicPopup.confirm({
            title: 'Logout',
            template: 'Are you sure you want to logout ?'
        });
        confirmPopup.then(function(res) {
            if (res) {

                localStorage.removeItem(weather_config.local_storage_auth_token_key);
                localStorage.removeItem(weather_config.local_storage_platform_susbscirber_json_key);
                localStorage.removeItem(weather_config.local_storage_platform_subscriber_id_key);

                // localStorage.removeItem("username");
                weather_config.authToken = null;
                // reset login fields

            } else {
                // nothing to do
            }
        });

    };

}]);


text:
using System;

namespace Banshee.MediaEngine
{
    public interface ISupportClutter
    {
        void EnableClutterVideoSink (IntPtr videoTexture);
        void DisableClutterVideoSink ();
        bool IsClutterVideoSinkInitialized { get; }
    }
}


text:
package com.streamsets.datacollector.client.model;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.streamsets.datacollector.client.StringUtil;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;

import java.util.ArrayList;
import java.util.List;

@ApiModel(description = "")
public class RuleDefinitionsJson   {

  private List<MetricsRuleDefinitionJson> metricsRuleDefinitions = new ArrayList<MetricsRuleDefinitionJson>();
  private List<DataRuleDefinitionJson> dataRuleDefinitions = new ArrayList<DataRuleDefinitionJson>();
  private List<String> emailIds = new ArrayList<String>();
  private String uuid = null;
  private List<RuleIssueJson> ruleIssues = new ArrayList<RuleIssueJson>();
  List<ConfigConfigurationJson> configuration = new ArrayList<>();
  private List<IssueJson> configIssues = new ArrayList<IssueJson>();

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("metricsRuleDefinitions")
  public List<MetricsRuleDefinitionJson> getMetricsRuleDefinitions() {
    return metricsRuleDefinitions;
  }
  public void setMetricsRuleDefinitions(List<MetricsRuleDefinitionJson> metricsRuleDefinitions) {
    this.metricsRuleDefinitions = metricsRuleDefinitions;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("dataRuleDefinitions")
  public List<DataRuleDefinitionJson> getDataRuleDefinitions() {
    return dataRuleDefinitions;
  }
  public void setDataRuleDefinitions(List<DataRuleDefinitionJson> dataRuleDefinitions) {
    this.dataRuleDefinitions = dataRuleDefinitions;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("emailIds")
  public List<String> getEmailIds() {
    return emailIds;
  }
  public void setEmailIds(List<String> emailIds) {
    this.emailIds = emailIds;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("uuid")
  public String getUuid() {
    return uuid;
  }
  public void setUuid(String uuid) {
    this.uuid = uuid;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("ruleIssues")
  public List<RuleIssueJson> getRuleIssues() {
    return ruleIssues;
  }
  public void setRuleIssues(List<RuleIssueJson> ruleIssues) {
    this.ruleIssues = ruleIssues;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("configuration")
  public List<ConfigConfigurationJson> getConfiguration() {
    return configuration;
  }
  public void setConfiguration(List<ConfigConfigurationJson> configuration) {
    this.configuration = configuration;
  }

  /**
   **/
  @ApiModelProperty(value = "")
  @JsonProperty("configIssues")
  public List<IssueJson> getConfigIssues() {
    return configIssues;
  }
  public void setConfigIssues(List<IssueJson> configIssues) {
    this.configIssues = configIssues;
  }

  @Override
  public String toString()  {
    StringBuilder sb = new StringBuilder();
    sb.append("class RuleDefinitionsJson {\n");

    sb.append("    metricsRuleDefinitions: ").append(StringUtil.toIndentedString(metricsRuleDefinitions)).append("\n");
    sb.append("    dataRuleDefinitions: ").append(StringUtil.toIndentedString(dataRuleDefinitions)).append("\n");
    sb.append("    emailIds: ").append(StringUtil.toIndentedString(emailIds)).append("\n");
    sb.append("    uuid: ").append(StringUtil.toIndentedString(uuid)).append("\n");
    sb.append("    ruleIssues: ").append(StringUtil.toIndentedString(ruleIssues)).append("\n");
    sb.append("    configuration: ").append(StringUtil.toIndentedString(configuration)).append("\n");
    sb.append("    configIssues: ").append(StringUtil.toIndentedString(configIssues)).append("\n");
    sb.append("}");
    return sb.toString();
  }
}


text:
var models = require('../models');
var response = require('../utils/response');
var wmiCrypto = require("../utils/wmi-crypto");

var authController = {};

authController.postDeveloperToken = function(req, res){
    var developerId = req.body.id;
    var developerKey = req.body.key;
    if(developerId && developerKey){
        models.Developer.findOne({
            where: {
                id: developerId
            }
        }).then(function(developer){
            if(developer && wmiCrypto.compareAccessKeyHash(developerKey, developer.key)){
                var token = wmiCrypto.createToken();
                models.DeveloperToken.create({
                    token: wmiCrypto.createTokenHash(token),
                    DeveloperId: developer.id
                }).then(function (developerToken) {
                    developerToken.token = token;
                    res.json(developerToken);
                });
            }else{
                res.json(response.error.developerKeyNotFound);
            }
        });
    }else{
        res.json(response.error.developerKeyMissingCredentials);
    }
};

authController.postUserToken = function(req, res){
    var developer = req.authenticated.entity;
    var userId = req.body.id;
    if(developer && userId && req.authenticated.type === 'developer'){
        models.User.findOne({
            where: {
                id: userId,
                DeveloperId: developer.id
            }
        }).then(function(user){
            if(user){
                var token = wmiCrypto.createToken();
                models.UserToken.create({
                    token: wmiCrypto.createTokenHash(token),
                    UserId: user.id
                }).then(function(userToken){
                    userToken.token = token;
                    res.json(userToken);
                });
            }else{
                res.json(response.error.userTokenAuthenticationFailed);
            }
        });
    }else{
        res.json(response.error.userTokenNotAuthenticated);
    }
};

authController.getAuthStatus = function (req, res) {
    var entity = req.authenticated.entity;

    if(entity){
        var ret = response.success.authenticated;
        ret.id = entity.id;
        ret.type = entity.type;
        res.json(ret);
    }else{
        res.json(response.success.notAuthenticated);
    }
};

module.exports = authController;


text:
// Copyright (C) 2014, Panagiotis Christopoulos Charitos.
// All rights reserved.
// Code licensed under the BSD License.
// http://www.anki3d.org/LICENSE

#include "anki/event/MainRendererPpsHdrEvent.h"
#include "anki/renderer/MainRenderer.h"

namespace anki {

#if 0

//==============================================================================
MainRendererPpsHdrEvent::MainRendererPpsHdrEvent(float startTime,
	float duration,
	float exposure_,
	uint blurringIterationsNum_,
	float blurringDist_)
	: Event(ET_MAIN_RENDERER_PPS_HDR, startTime, duration)
{
	finalData.exposure = exposure_;
	finalData.blurringIterationsNum = blurringIterationsNum_;
	finalData.blurringDist = blurringDist_;

	const Hdr& hdr =
		MainRendererSingleton::get().getPps().getHdr();
	originalData.exposure = hdr.getExposure();
	originalData.blurringIterationsNum = hdr.getBlurringIterationsCount();
	//originalData.blurringDist = hdr.getBlurringDistance();
}

//==============================================================================
MainRendererPpsHdrEvent::MainRendererPpsHdrEvent(
	const MainRendererPpsHdrEvent& b)
	: Event(ET_MAIN_RENDERER_PPS_HDR, 0.0, 0.0)
{
	*this = b;
}

//==============================================================================
MainRendererPpsHdrEvent& MainRendererPpsHdrEvent::operator=(
	const MainRendererPpsHdrEvent& b)
{
	Event::operator=(b);
	finalData = b.finalData;
	originalData = b.originalData;
	return *this;
}

//==============================================================================
void MainRendererPpsHdrEvent::updateSp(float /*prevUpdateTime*/, float crntTime)
{
	float d = crntTime - getStartTime(); // delta
	float dp = d / getDuration(); // delta as percentage

	Hdr& hdr = MainRendererSingleton::get().getPps().getHdr();

	hdr.setExposure(interpolate(originalData.exposure, finalData.exposure, dp));

	hdr.setBlurringIterationsCount(
		interpolate(originalData.blurringIterationsNum,
		finalData.blurringIterationsNum, dp));

	/*hdr.setBlurringDistance(interpolate(originalData.blurringDist,
		finalData.blurringDist, dp));*/
}

#endif

} // end namespace


text:
<?php

namespace SSD\Backup\Contracts;

interface Directory extends Job
{
}


text:
package com.moomeen.views.workouts.details;

import java.util.ArrayList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.moomeen.bests.BestDistanceTimeCalculator;
import com.moomeen.bests.model.DistanceTime;
import com.moomeen.endo2java.model.DetailedWorkout;
import com.moomeen.endo2java.model.Point;
import com.moomeen.utils.LocaleHelper;
import com.moomeen.views.workouts.details.timelapse.JsStreetView;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Resource;
import com.vaadin.tapio.googlemaps.GoogleMap;
import com.vaadin.tapio.googlemaps.client.LatLon;
import com.vaadin.tapio.googlemaps.client.overlays.GoogleMapInfoWindow;
import com.vaadin.tapio.googlemaps.client.overlays.GoogleMapPolyline;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Panel;
import com.vaadin.ui.ProgressBar;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;

public class WorkoutDetails extends HorizontalLayout {

	/**
	 *
	 */
	private static final long serialVersionUID = 9203596511419142742L;

	private final static Logger LOG = LoggerFactory.getLogger(WorkoutDetails.class);

	private final static String GOOGLE_MAPS_KEY = "AIzaSyDnDtkT3abR20ajxVlbYhI6uYKTXMgNJG4";

	private static final String ROUTE_COLOR = "#0072c6";
	private static final String BEST_COLOR = "#FF0E0E";

	private LatLon boundsNE;
	private LatLon boundsSW;

	private Button routeBtn;
	private Button streetViewBtn;
	private Button bestsBtn;

	public WorkoutDetails(final DetailedWorkout workout) {
		setSizeFull();
		addStyleName("workout-details");

		VerticalLayout menu = createMenu();
		final Panel contentPanel = createContentPanel();
		final GoogleMap route = createRouteContent(workout);
		final VerticalLayout streetView = createStreetViewContent(workout);
		final VerticalLayout bests = createBestsContent(workout);

		setMenuClickAction(routeBtn, contentPanel, route);
		setMenuClickAction(streetViewBtn, contentPanel, streetView);
		setMenuClickAction(bestsBtn, contentPanel, bests);
		contentPanel.setContent(route);

		addComponent(menu);
		addComponent(contentPanel);
		setComponentAlignment(menu, Alignment.TOP_LEFT);
		setComponentAlignment(contentPanel, Alignment.MIDDLE_RIGHT);
		setExpandRatio(menu, 0.3f);
		setExpandRatio(contentPanel, 1.2f);
	}

	private void setMenuClickAction(Button button, final Panel contentPanel, final Component content){
		button.addClickListener(new ClickListener() {
			private static final long serialVersionUID = 4276024325003572024L;

			@Override
			public void buttonClick(ClickEvent event) {
				contentPanel.setContent(content);
			}
		});
	}

	private VerticalLayout createMenu() {
		routeBtn = menuButton(FontAwesome.GLOBE, "Route");
		streetViewBtn = menuButton(FontAwesome.PHOTO, "Street view");
		bestsBtn = menuButton(FontAwesome.TACHOMETER, "Bests");

		VerticalLayout menu = new VerticalLayout();
		menu.addComponent(routeBtn);
		menu.addComponent(streetViewBtn);
		menu.addComponent(bestsBtn);
		return menu;
	}

	private Button menuButton(Resource icon, String caption) {
		Button btn = new Button(caption);
		btn.setIcon(icon);
		btn.addStyleName("details-button");
		return btn;
	}

	private Panel createContentPanel() {
		final Panel contentPanel = new Panel();
		contentPanel.setSizeFull();
		return contentPanel;
	}

	private GoogleMap createRouteContent(final DetailedWorkout workout) {
		final GoogleMap googleMap = new GoogleMap(GOOGLE_MAPS_KEY, null, null);
		googleMap.setMinZoom(4);
		googleMap.setMaxZoom(16);
		googleMap.setSizeFull();

		drawWorkoutRoute(googleMap, workout);
		googleMap.fitToBounds(boundsNE, boundsSW);
		return googleMap;
	}

	private VerticalLayout createStreetViewContent(final DetailedWorkout workout) {
		final VerticalLayout streetView = new VerticalLayout();
		ProgressBar loadProgressBar = new ProgressBar();
		loadProgressBar.setId("street-view-progress");
		loadProgressBar.setStyleName("street-view-progress-bar");

		final JsStreetView streetViewAnimation = new JsStreetView(workout);
		streetView.addComponent(loadProgressBar);
		streetView.addComponent(streetViewAnimation);
		streetView.setExpandRatio(streetViewAnimation, 1f);
		streetView.setSizeFull();
		return streetView;
	}

	@SuppressWarnings("serial")
	private VerticalLayout createBestsContent(final DetailedWorkout workout) {
		final VerticalLayout bests = new VerticalLayout();
		bests.setSpacing(true);
		final GoogleMap map = createRouteContent(workout);

		CssLayout controls = new CssLayout();
		controls.addStyleName("v-component-group");
		final TextField tf = new TextField();
		tf.setInputPrompt("Distance in km");
		tf.addStyleName("inline-icon");
		tf.setIcon(FontAwesome.TROPHY);
		tf.setWidth("260px");
		controls.addComponent(tf);
		Button button = new Button("Calculate");
		button.addStyleName("friendly");
		controls.addComponent(button);

		HorizontalLayout bottom = new HorizontalLayout();
		bottom.setWidth("100%");
		bottom.addComponent(controls);
		bottom.setComponentAlignment(controls, Alignment.BOTTOM_LEFT);

		class BestContent {
			GoogleMapPolyline line;
			GoogleMapInfoWindow info;
		}

		final BestContent best = new BestContent();

		button.addClickListener(new ClickListener() {
			@Override
			public void buttonClick(ClickEvent event) {
				if (best.line != null){
					map.removePolyline(best.line);
					map.closeInfoWindow(best.info);
				}

				Double distanceToCalculate = Double.parseDouble(tf.getValue());
				DistanceTime bestDistance = new BestDistanceTimeCalculator(workout).calculate(distanceToCalculate);
				if (bestDistance.getPoints() == null){
					LOG.warn("Couldn't calculate best {} for workout with length {}", bestDistance.getDistance(), workout.getDistance());
					return;
				}
				best.line = drawLine(map, bestDistance.getPoints(), BEST_COLOR);

				if (bestDistance.getTime() != null) {
					Point firstPoint = bestDistance.getPoints().get(0);
					Point lastPoint = bestDistance.getPoints().get(bestDistance.getPoints().size()-1);
					String time = LocaleHelper.getPeriodFormatter().print(bestDistance.getTime().toPeriod());
					String bestTimePoints = firstPoint.getDistance() + " km - " + lastPoint.getDistance() + " km";
					GoogleMapInfoWindow infoWindow = new GoogleMapInfoWindow(distanceToCalculate + " km in " + time + "<br>" + bestTimePoints);
					best.info = infoWindow;
					infoWindow.setPosition(new LatLon(lastPoint.getLatitude(), lastPoint.getLongitude()));
					map.openInfoWindow(infoWindow);
				}
			}
		});

		bests.addComponent(map);
		bests.addComponent(bottom);
		bests.setSizeFull();
		bests.setExpandRatio(map, 0.9f);
		bests.setExpandRatio(bottom, 0.1f);
		return bests;
	}

	private void drawWorkoutRoute(GoogleMap map, DetailedWorkout workout) {
		if (workout.getPoints() == null || workout.getPoints().isEmpty()){
			return;
		}

		drawLine(map, workout.getPoints(), ROUTE_COLOR);
		findMapBounds(workout.getPoints());
	}

	private void findMapBounds(List<Point> workoutPoints){
		for (Point point : workoutPoints) {
			adjustBoundsIfNeeded(point);
		}
	}

	private GoogleMapPolyline drawLine(GoogleMap map, List<Point> workoutPoints, String color){
		List<LatLon> points = new ArrayList<LatLon>();

		for (Point workoutPoint : workoutPoints) {
			LatLon point = vaadinPoint(workoutPoint);
			points.add(point);
		}

		GoogleMapPolyline overlay = new GoogleMapPolyline(points, color, 0.8, 5);
		map.addPolyline(overlay);
		return overlay;
	}

	private void adjustBoundsIfNeeded(Point point) {
		initBoundsIfNeeded(point);
		adjustNEBoundIfNeeded(point);
		adjustSWBoundIfNeeded(point);
	}

	private void adjustSWBoundIfNeeded(Point point) {
		if (point.getLatitude() < boundsSW.getLat()){
			boundsSW.setLat(point.getLatitude());
		}
		if (point.getLongitude() < boundsSW.getLon()){
			boundsSW.setLon(point.getLongitude());
		}
	}

	private void adjustNEBoundIfNeeded(Point point) {
		if (point.getLatitude() > boundsNE.getLat()){
			boundsNE.setLat(point.getLatitude());
		}
		if (point.getLongitude() > boundsNE.getLon()){
			boundsNE.setLon(point.getLongitude());
		}
	}

	private void initBoundsIfNeeded(Point point) {
		if (boundsNE == null || boundsSW == null){
			boundsNE = new LatLon(point.getLatitude(), point.getLongitude());
			boundsSW = new LatLon(point.getLatitude(), point.getLongitude());
		}
	}

	private LatLon vaadinPoint(Point point){
		return new LatLon(point.getLatitude(), point.getLongitude());
	}

}


text:
package pt.up.fe.specs.deps;

import org.suikasoft.SharedLibrary.Interfaces.ResourceProvider;

/**
 * @author Joao Bispo
 *
 */
public enum DepsResource implements ResourceProvider {

    SFTP_TEMPLATE("sftp.xml.template");

    private final String resource;

    private DepsResource(String resource) {
        this.resource = resource;
    }

    /* (non-Javadoc)
     * @see org.suikasoft.SharedLibrary.Interfaces.ResourceProvider#getResource()
     */
    @Override
    public String getResource() {
        return resource;
    }

}


text:
<?php

namespace Uci\Bundle\SeguridadBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class UciSeguridadBundle extends Bundle
{
}


text:
layout: model
title: BERT Embeddings (Large Uncased)
author: John Snow Labs
name: bert_large_uncased
date: 2020-08-25
task: Embeddings
language: en
edition: Spark NLP 2.6.0
spark_version: 2.4
tags: [open_source, embeddings, en]
supported: true
annotator: BertEmbeddings
article_header:
type: cover
use_language_switcher: "Python-Scala-Java"
---

## Description
This model contains a deep bidirectional transformer trained on Wikipedia and the BookCorpus. The details are described in the paper "[BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding](https://arxiv.org/abs/1810.04805)".

{:.btn-box}
<button class="button button-orange" disabled>Live Demo</button>
<button class="button button-orange" disabled>Open in Colab</button>
[Download](https://s3.amazonaws.com/auxdata.johnsnowlabs.com/public/models/bert_large_uncased_en_2.6.0_2.4_1598341287005.zip){:.button.button-orange.button-orange-trans.arr.button-icon}

## How to use

<div class="tabs-box" markdown="1">

{% include programmingLanguageSelectScalaPythonNLU.html %}

```python
...
embeddings = BertEmbeddings.pretrained("bert_large_uncased", "en") \
.setInputCols("sentence", "token") \
.setOutputCol("embeddings")
nlp_pipeline = Pipeline(stages=[document_assembler, sentence_detector, tokenizer, embeddings])
pipeline_model = nlp_pipeline.fit(spark.createDataFrame([[""]]).toDF("text"))
result = pipeline_model.transform(spark.createDataFrame([['I love NLP']], ["text"]))
```

```scala
...
val embeddings = BertEmbeddings.pretrained("bert_large_uncased", "en")
.setInputCols("sentence", "token")
.setOutputCol("embeddings")
val pipeline = new Pipeline().setStages(Array(document_assembler, sentence_detector, tokenizer, embeddings))
val data = Seq("I love NLP").toDF("text")
val result = pipeline.fit(data).transform(data)
```

{:.nlu-block}
```python
import nlu

text = ["I love NLP"]
embeddings_df = nlu.load('en.embed.bert.large_uncased').predict(text, output_level='token')
embeddings_df
```

</div>

{:.h2_title}
## Results
```bash
	en_embed_bert_large_uncased_embeddings	token

	[-0.07447264343500137, -0.337308406829834, -0....	I
	[-0.5735481977462769, -0.3580206632614136, -0....	love
	[-0.3929762840270996, -0.4147087037563324, 0.2...	NLP
```

{:.model-param}
## Model Information

{:.table-model}
|---|---|
|Model Name:|bert_large_uncased|
|Type:|embeddings|
|Compatibility:|Spark NLP 2.6.0+|
|License:|Open Source|
|Edition:|Official|
|Input Labels:|[sentence, token]|
|Output Labels:|[word_embeddings]|
|Language:|[en]|
|Dimension:|1024|
|Case sensitive:|false|

{:.h2_title}
## Data Source
The model is imported from [https://tfhub.dev/google/bert_uncased_L-24_H-1024_A-16/1](https://tfhub.dev/google/bert_uncased_L-24_H-1024_A-16/1)


text:
<?php
namespace Ctct\Components\Contacts;

use Ctct\Components\Component;

/**
 * Represents a single Custom Field for a Contact
 *
 * @package        Components
 * @subpackage     Contacts
 * @author         Constant Contact
 */
class CustomField extends Component {
    /**
     * Name of the custom field
     * @var string
     */
    public $name;

    /**
     * Value of the custom field
     * @var string
     */
    public $value;

    /**
     * Factory method to create a CustomField object from an array
     * @param array $props - Associative array of initial properties to set
     * @return CustomField
     */
    public static function create(array $props) {
        $custom_field = new CustomField();
        $custom_field->name = parent::getValue($props, "name");
        $custom_field->value = parent::getValue($props, "value");
        return $custom_field;
    }
}


text:
import matplotlib.mlab as mlab
from matplotlib.pyplot import figure, show
import numpy as np

x = np.arange(0.0, 2, 0.01)
y1 = np.sin(2*np.pi*x)
y2 = 1.2*np.sin(4*np.pi*x)

fig = figure()
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312, sharex=ax1)
ax3 = fig.add_subplot(313, sharex=ax1)

ax1.fill_between(x, 0, y1)
ax1.set_ylabel('between y1 and 0')

ax2.fill_between(x, y1, 1)
ax2.set_ylabel('between y1 and 1')

ax3.fill_between(x, y1, y2)
ax3.set_ylabel('between y1 and y2')
ax3.set_xlabel('x')

# now fill between y1 and y2 where a logical condition is met.  Note
# this is different than calling
#   fill_between(x[where], y1[where],y2[where]
# because of edge effects over multiple contiguous regions.
fig = figure()
ax = fig.add_subplot(211)
ax.plot(x, y1, x, y2, color='black')
ax.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True)
ax.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True)
ax.set_title('fill between where')

# Test support for masked arrays.
y2 = np.ma.masked_greater(y2, 1.0)
ax1 = fig.add_subplot(212, sharex=ax)
ax1.plot(x, y1, x, y2, color='black')
ax1.fill_between(x, y1, y2, where=y2>=y1, facecolor='green', interpolate=True)
ax1.fill_between(x, y1, y2, where=y2<=y1, facecolor='red', interpolate=True)
ax1.set_title('Now regions with y2>1 are masked')

# This example illustrates a problem; because of the data
# gridding, there are undesired unfilled triangles at the crossover
# points.  A brute-force solution would be to interpolate all
# arrays to a very fine grid before plotting.

# show how to use transforms to create axes spans where a certain condition is satisfied
fig = figure()
ax = fig.add_subplot(111)
y = np.sin(4*np.pi*x)
ax.plot(x, y, color='black')

# use the data coordinates for the x-axis and the axes coordinates for the y-axis
import matplotlib.transforms as mtransforms
trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
theta = 0.9
ax.axhline(theta, color='green', lw=2, alpha=0.5)
ax.axhline(-theta, color='red', lw=2, alpha=0.5)
ax.fill_between(x, 0, 1, where=y>theta, facecolor='green', alpha=0.5, transform=trans)
ax.fill_between(x, 0, 1, where=y<-theta, facecolor='red', alpha=0.5, transform=trans)

show()


text:
package paymentgateway.dds.com.webservice.paymentservice;

import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.Service;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceException;
import javax.xml.ws.WebServiceFeature;

/**
 * This class was generated by the JAX-WS RI.
 * JAX-WS RI 2.2.4-b01
 * Generated source version: 2.2
 *
 */
@WebServiceClient(name = "PaymentGatewayService", targetNamespace = "http://com.dds.paymentgateway/webservice/paymentservice", wsdlLocation = "file:/C:/stm/tmp/aaa/asi.wsdl")
public class PaymentGatewayService
    extends Service
{

    private final static URL PAYMENTGATEWAYSERVICE_WSDL_LOCATION;
    private final static WebServiceException PAYMENTGATEWAYSERVICE_EXCEPTION;
    private final static QName PAYMENTGATEWAYSERVICE_QNAME = new QName("http://com.dds.paymentgateway/webservice/paymentservice", "PaymentGatewayService");

    static {
        URL url = null;
        WebServiceException e = null;
        try {
            url = new URL("file:/C:/stm/tmp/aaa/asi.wsdl");
        } catch (MalformedURLException ex) {
            e = new WebServiceException(ex);
        }
        PAYMENTGATEWAYSERVICE_WSDL_LOCATION = url;
        PAYMENTGATEWAYSERVICE_EXCEPTION = e;
    }

    public PaymentGatewayService() {
        super(__getWsdlLocation(), PAYMENTGATEWAYSERVICE_QNAME);
    }

    public PaymentGatewayService(WebServiceFeature... features) {
        super(__getWsdlLocation(), PAYMENTGATEWAYSERVICE_QNAME, features);
    }

    public PaymentGatewayService(URL wsdlLocation) {
        super(wsdlLocation, PAYMENTGATEWAYSERVICE_QNAME);
    }

    public PaymentGatewayService(URL wsdlLocation, WebServiceFeature... features) {
        super(wsdlLocation, PAYMENTGATEWAYSERVICE_QNAME, features);
    }

    public PaymentGatewayService(URL wsdlLocation, QName serviceName) {
        super(wsdlLocation, serviceName);
    }

    public PaymentGatewayService(URL wsdlLocation, QName serviceName, WebServiceFeature... features) {
        super(wsdlLocation, serviceName, features);
    }

    /**
     *
     * @return
     *     returns PaymentGatewayServiceInterface
     */
    @WebEndpoint(name = "PaymentGatewayServiceInterfacePort")
    public PaymentGatewayServiceInterface getPaymentGatewayServiceInterfacePort() {
        return super.getPort(new QName("http://com.dds.paymentgateway/webservice/paymentservice", "PaymentGatewayServiceInterfacePort"), PaymentGatewayServiceInterface.class);
    }

    /**
     *
     * @param features
     *     A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy.  Supported features not in the features parameter will have their default values.
     * @return
     *     returns PaymentGatewayServiceInterface
     */
    @WebEndpoint(name = "PaymentGatewayServiceInterfacePort")
    public PaymentGatewayServiceInterface getPaymentGatewayServiceInterfacePort(WebServiceFeature... features) {
        return super.getPort(new QName("http://com.dds.paymentgateway/webservice/paymentservice", "PaymentGatewayServiceInterfacePort"), PaymentGatewayServiceInterface.class, features);
    }

    private static URL __getWsdlLocation() {
        if (PAYMENTGATEWAYSERVICE_EXCEPTION!= null) {
            throw PAYMENTGATEWAYSERVICE_EXCEPTION;
        }
        return PAYMENTGATEWAYSERVICE_WSDL_LOCATION;
    }

}


text:
import ContainerInterface from './../container/container-interface';
import BootInterface from './boot-interface';
import ChainedDefinitionInterface from './../definition/chained-definition-interface';
import AnnotationInterface from './../annotation/annotation-interface';

/**
 * A kernel is a simple container boot. It allows you to launch initial
 * container member as you wish.
 */
interface KernelInterface
{
    container: ContainerInterface;

    annotations: AnnotationInterface;

    /**
     * Register a new boot.
     */
    initialize(boot: BootInterface): KernelInterface;

    /**
     * Boot a container
     */
    boot(): void;

    /**
     * Embed an other kernel inside.
     */
    embed(kernel: KernelInterface, alias?: string): KernelInterface;

    /**
     * Register definitions as a simple JSON object.
     */
    register<T>(definitions: ChainedDefinitionInterface<T>): KernelInterface;
}

export default KernelInterface;


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 50: 317 (1967)

#### Original name
Dactylella acrochaeta Drechsler, 1952

### Remarks
null


text:
package com.google.cloud.pubsublite.flink.internal.sink;

import com.google.api.core.ApiService.Listener;
import com.google.api.core.ApiService.State;
import com.google.api.gax.rpc.ApiException;
import com.google.cloud.pubsublite.MessageMetadata;
import com.google.cloud.pubsublite.internal.Publisher;
import com.google.cloud.pubsublite.internal.wire.SystemExecutors;
import com.google.common.annotations.VisibleForTesting;
import com.google.errorprone.annotations.concurrent.GuardedBy;
import java.util.HashMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/** A map of working publishers by PublisherOptions. */
public class PublisherCache<T> implements AutoCloseable {
  private static final Logger LOG = LoggerFactory.getLogger(PublisherCache.class);

  interface PublisherFactory<T> {
    Publisher<MessageMetadata> New(T options);
  }

  @GuardedBy("this")
  private final HashMap<T, Publisher<MessageMetadata>> livePublishers = new HashMap<>();

  private final PublisherFactory<T> factory;

  public PublisherCache(PublisherFactory<T> factory) {
    this.factory = factory;
  }

  private synchronized void evict(T options) {
    livePublishers.remove(options);
  }

  public synchronized Publisher<MessageMetadata> get(T options) throws ApiException {
    LOG.info("Requesting a publisher for options {}", options);
    Publisher<MessageMetadata> publisher = livePublishers.get(options);
    if (publisher != null) {
      return publisher;
    }
    publisher = factory.New(options);
    publisher.addListener(
        new Listener() {
          @Override
          public void failed(State s, Throwable t) {
            LOG.error("Publisher for options {} failed with exception", options, t);
            evict(options);
          }
        },
        SystemExecutors.getAlarmExecutor());
    publisher.startAsync().awaitRunning();
    LOG.info("Successfully started publisher for options {}", options);
    livePublishers.put(options, publisher);
    return publisher;
  }

  @VisibleForTesting
  public synchronized void set(T options, Publisher<MessageMetadata> toCache) {
    livePublishers.put(options, toCache);
    toCache.addListener(
        new Listener() {
          @Override
          public void failed(State s, Throwable t) {
            LOG.error("Publisher for options {} failed with exception", options, t);
            evict(options);
          }
        },
        SystemExecutors.getAlarmExecutor());
  }

  @Override
  public synchronized void close() {
    livePublishers.forEach(((options, publisher) -> publisher.stopAsync()));
    livePublishers.clear();
  }
}