text:
package org.apache.geronimo.daytrader.javaee6.web;

import java.math.BigDecimal;
import java.util.Collection;

import javax.naming.InitialContext;

import org.apache.geronimo.daytrader.javaee6.entities.AccountDataBean;
import org.apache.geronimo.daytrader.javaee6.entities.AccountProfileDataBean;
import org.apache.geronimo.daytrader.javaee6.entities.HoldingDataBean;
import org.apache.geronimo.daytrader.javaee6.entities.OrderDataBean;
import org.apache.geronimo.daytrader.javaee6.entities.QuoteDataBean;
import org.apache.geronimo.daytrader.javaee6.core.api.TradeServices;

import org.apache.geronimo.daytrader.javaee6.core.beans.MarketSummaryDataBean;
import org.apache.geronimo.daytrader.javaee6.core.beans.RunStatsDataBean;
import org.apache.geronimo.daytrader.javaee6.core.direct.FinancialUtils;
import org.apache.geronimo.daytrader.javaee6.core.direct.TradeJDBCDirect;
import org.apache.geronimo.daytrader.javaee6.core.direct.TradeJEEDirect;
import org.apache.geronimo.daytrader.javaee6.core.direct.TradeJPADirect;

import org.apache.geronimo.daytrader.javaee6.utils.Log;
import org.apache.geronimo.daytrader.javaee6.utils.TradeConfig;

/**
 * The TradeAction class provides the generic client side access to each of the
 * Trade brokerage user operations. These include login, logout, buy, sell,
 * getQuote, etc. The TradeAction class does not handle user interface
 * processing and should be used by a class that is UI specific. For example,
 * {trade_client.TradeServletAction}manages a web interface to Trade,
 * making calls to TradeAction methods to actually performance each operation.
 */

public class TradeAction implements TradeServices {
    // This lock is used to serialize market summary operations.
    private static final Integer marketSummaryLock = new Integer(0);
    private static long nextMarketSummary = System.currentTimeMillis();
    private static MarketSummaryDataBean cachedMSDB = MarketSummaryDataBean.getRandomInstance();

    // make this static so the trade impl can be cached
    // - ejb3 mode is the only thing that really uses this
    // - can go back and update other modes to take advantage (ie. TradeDirect)
    private static TradeServices trade = null;

    public TradeAction() {
        if (Log.doTrace())
            Log.trace("TradeAction:TradeAction()");
        createTrade();
    }

    public TradeAction(TradeServices trade) {
        if (Log.doActionTrace())
            Log.trace("TradeAction:TradeAction(trade)");
        this.trade = trade;
    }

    private void createTrade() {
        RuntimeException re = null;

        if (TradeConfig.runTimeMode == TradeConfig.EJB3) {
            try {
                Class c = Class.forName("org.apache.geronimo.daytrader.javaee6.web.ejb3.TradeSLSBBean");
                if ((trade == null) ||
                    (!(trade.getClass().isAssignableFrom(c)))) {
                    InitialContext context = new InitialContext();
                    try {
                        trade = (TradeServices) context.lookup("java:global/daytrader/web/TradeSLSBBean!org.apache.geronimo.daytrader.javaee6.web.ejb3.TradeSLSBLocal");
                    } catch (Exception ex) {
                        Log.error("TradeAction:createTrade - Lookup of TradeSLSBRemote failed!!!");
                        trade = (TradeServices) context.lookup("java:global/TradeSLSBBean");
                    }
                }
            }
            catch (Exception e) {
                Log.error("TradeAction:TradeAction() Creation of Trade EJB 3 failed\n" + e);
                re = new RuntimeException(e);
            }
        } else if (TradeConfig.runTimeMode == TradeConfig.SESSION3) {
            try {
                Class c = Class.forName("org.apache.geronimo.daytrader.javaee6.web.ejb3.DirectSLSBBean");
                if ((trade == null) ||
                    (!(trade.getClass().isAssignableFrom(c)))) {
                    InitialContext context = new InitialContext();
                    try {
                        trade = (TradeServices) context.lookup("java:global/daytrader/web/DirectSLSBBean!org.apache.geronimo.daytrader.javaee6.web.ejb3.DirectSLSBLocal");
                    } catch (Exception ex) {
                        Log.error("TradeAction:createTrade - Lookup of DirectSLSBRemote failed!!!");
                        trade = (TradeServices) context.lookup("java:global/DirectSLSBBean");
                    }
                }
            }
            catch (Exception e) {
                Log.error("TradeAction:TradeAction() Creation of Trade SESSION3 failed\n" + e);
                re = new RuntimeException(e);
            }
        } else if (TradeConfig.runTimeMode == TradeConfig.DIRECT) {
            try {
                trade = new TradeJEEDirect();
            }
            catch (Exception e) {
                Log.error("TradeAction:TradeAction() Creation of Trade JDBC Direct failed\n" + e);
                re = new RuntimeException(e);
            }
        } else if (TradeConfig.runTimeMode == TradeConfig.JDBC) {
            try {
                trade = new TradeJDBCDirect();
            }
            catch (Exception e) {
                Log.error("TradeAction:TradeAction() Creation of TradeJDBCDirect failed\n" + e);
                re = new RuntimeException(e);
            }
        } else if (TradeConfig.runTimeMode == TradeConfig.JPA) {
            try {
                trade = new TradeJPADirect();
            }
            catch (Exception e) {
                Log.error("TradeAction:TradeAction() Creation of TradeJPADirect failed\n" + e);
                re = new RuntimeException(e);
            }
        } else {
            Log.error("TradeAction:TradeAction() Unknown Trade runtime mode.");
            re = new IllegalArgumentException("TradeAction:TradeAction() Unknown runTimeMode=" + TradeConfig.runTimeMode);
        }

        if (re != null) {
            throw re;
        }
    }

    /**
     * Market Summary is inherently a heavy database operation.  For servers that have a caching
     * story this is a great place to cache data that is good for a period of time.  In order to
     * provide a flexible framework for this we allow the market summary operation to be
     * invoked on every transaction, time delayed or never.  This is configurable in the
     * configuration panel.
     *
     * @return An instance of the market summary
     */
    public MarketSummaryDataBean getMarketSummary() throws Exception {

        if (Log.doActionTrace()) {
            Log.trace("TradeAction:getMarketSummary()");
        }

        if (TradeConfig.getMarketSummaryInterval() == 0) return getMarketSummaryInternal();
        if (TradeConfig.getMarketSummaryInterval() < 0) return cachedMSDB;

        /**
         * This is a little funky.  If its time to fetch a new Market summary then we'll synchronize
         * access to make sure only one requester does it.  Others will merely return the old copy until
         * the new MarketSummary has been executed.
         */
         long currentTime = System.currentTimeMillis();

         if (currentTime > nextMarketSummary) {
             long oldNextMarketSummary = nextMarketSummary;
             boolean fetch = false;

             synchronized (marketSummaryLock) {
                 /**
                  * Is it still ahead or did we miss lose the race?  If we lost then let's get out
                  * of here as the work has already been done.
                  */
                 if (oldNextMarketSummary == nextMarketSummary) {
                     fetch = true;
                     nextMarketSummary += TradeConfig.getMarketSummaryInterval()*1000;

                     /**
                      * If the server has been idle for a while then its possible that nextMarketSummary
                      * could be way off.  Rather than try and play catch up we'll simply get in sync with the
                      * current time + the interval.
                      */
                     if (nextMarketSummary < currentTime) {
                         nextMarketSummary = currentTime + TradeConfig.getMarketSummaryInterval()*1000;
                     }
                 }
             }

            /**
             * If we're the lucky one then let's update the MarketSummary
             */
            if (fetch) {
                cachedMSDB = getMarketSummaryInternal();
            }
        }

        return cachedMSDB;
    }

    /**
     * Compute and return a snapshot of the current market conditions This
     * includes the TSIA - an index of the price of the top 100 Trade stock
     * quotes The openTSIA ( the index at the open) The volume of shares traded,
     * Top Stocks gain and loss
     *
     * @return A snapshot of the current market summary
     */
    public MarketSummaryDataBean getMarketSummaryInternal() throws Exception {
        if (Log.doActionTrace()) {
            Log.trace("TradeAction:getMarketSummaryInternal()");
        }
        MarketSummaryDataBean marketSummaryData = null;
        marketSummaryData = trade.getMarketSummary();
        return marketSummaryData;
    }

    /**
     * Purchase a stock and create a new holding for the given user. Given a
     * stock symbol and quantity to purchase, retrieve the current quote price,
     * debit the user's account balance, and add holdings to user's portfolio.
     *
     * @param userID   the customer requesting the stock purchase
     * @param symbol   the symbol of the stock being purchased
     * @param quantity the quantity of shares to purchase
     * @return OrderDataBean providing the status of the newly created buy order
     */
    public OrderDataBean buy(String userID, String symbol, double quantity, int orderProcessingMode) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:buy", userID, symbol, new Double(quantity), new Integer(orderProcessingMode));
        OrderDataBean orderData;
        orderData = trade.buy(userID, symbol, quantity, orderProcessingMode);
        //after the purchase or sell of a stock, update the stocks volume and
        // price
        updateQuotePriceVolume(symbol, TradeConfig.getRandomPriceChangeFactor(), quantity);
        return orderData;
    }

    /**
     * Sell(SOAP 2.2 Wrapper converting int to Integer) a stock holding and
     * removed the holding for the given user. Given a Holding, retrieve current
     * quote, credit user's account, and reduce holdings in user's portfolio.
     *
     * @param userID    the customer requesting the sell
     * @param holdingID the users holding to be sold
     * @return OrderDataBean providing the status of the newly created sell
     *         order
     */
    public OrderDataBean sell(String userID, int holdingID, int orderProcessingMode) throws Exception {
        return sell(userID, new Integer(holdingID), orderProcessingMode);
    }

    /**
     * Sell a stock holding and removed the holding for the given user. Given a
     * Holding, retrieve current quote, credit user's account, and reduce
     * holdings in user's portfolio.
     *
     * @param userID    the customer requesting the sell
     * @param holdingID the users holding to be sold
     * @return OrderDataBean providing the status of the newly created sell
     *         order
     */
    public OrderDataBean sell(String userID, Integer holdingID, int orderProcessingMode) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:sell", userID, holdingID, new Integer(orderProcessingMode));
        OrderDataBean orderData;
        orderData = trade.sell(userID, holdingID, orderProcessingMode);
        if (!(orderData.getOrderStatus().equalsIgnoreCase("cancelled")))
            //after the purchase or sell of a stock, update the stocks volume
            // and price
            updateQuotePriceVolume(orderData.getSymbol(), TradeConfig.getRandomPriceChangeFactor(), orderData.getQuantity());
        return orderData;
    }

    /**
     * Queue the Order identified by orderID to be processed
     *

     * Orders are submitted through JMS to a Trading Broker and completed
     * asynchronously. This method queues the order for processing
     *

     * The boolean twoPhase specifies to the server implementation whether or
     * not the method is to participate in a global transaction
     *
     * @param orderID the Order being queued for processing
     */
    public void queueOrder(Integer orderID, boolean twoPhase) {
        throw new UnsupportedOperationException("TradeAction: queueOrder method not supported");
    }

    /**
     * Complete the Order identefied by orderID Orders are submitted through JMS
     * to a Trading agent and completed asynchronously. This method completes
     * the order For a buy, the stock is purchased creating a holding and the
     * users account is debited For a sell, the stock holding is removed and the
     * users account is credited with the proceeds
     *

     * The boolean twoPhase specifies to the server implementation whether or
     * not the method is to participate in a global transaction
     *
     * @param orderID the Order to complete
     * @return OrderDataBean providing the status of the completed order
     */
    public OrderDataBean completeOrder(Integer orderID, boolean twoPhase) {
        throw new UnsupportedOperationException("TradeAction: completeOrder method not supported");
    }

    /**
     * Cancel the Order identified by orderID
     *

     * Orders are submitted through JMS to a Trading Broker and completed
     * asynchronously. This method queues the order for processing
     *

     * The boolean twoPhase specifies to the server implementation whether or
     * not the method is to participate in a global transaction
     *
     * @param orderID the Order being queued for processing
     */
    public void cancelOrder(Integer orderID, boolean twoPhase) {
        throw new UnsupportedOperationException("TradeAction: cancelOrder method not supported");
    }

    public void orderCompleted(String userID, Integer orderID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:orderCompleted", userID, orderID);
        if (Log.doTrace())
            Log.trace("OrderCompleted", userID, orderID);
    }

    /**
     * Get the collection of all orders for a given account
     *
     * @param userID the customer account to retrieve orders for
     * @return Collection OrderDataBeans providing detailed order information
     */
    public Collection getOrders(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getOrders", userID);
        Collection orderDataBeans;
        orderDataBeans = trade.getOrders(userID);
        return orderDataBeans;
    }

    /**
     * Get the collection of completed orders for a given account that need to
     * be alerted to the user
     *
     * @param userID the customer account to retrieve orders for
     * @return Collection OrderDataBeans providing detailed order information
     */
    public Collection getClosedOrders(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getClosedOrders", userID);
        Collection orderDataBeans;
        orderDataBeans = trade.getClosedOrders(userID);
        return orderDataBeans;
    }

    /**
     * Given a market symbol, price, and details, create and return a new
     * {@link QuoteDataBean}
     *
     * @param symbol  the symbol of the stock
     * @param price   the current stock price
     * @return a new QuoteDataBean or null if Quote could not be created
     */
    public QuoteDataBean createQuote(String symbol, String companyName, BigDecimal price) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:createQuote", symbol, companyName, price);
        QuoteDataBean quoteData;
        quoteData = trade.createQuote(symbol, companyName, price);
        return quoteData;
    }

    /**
     * Return a collection of {@link QuoteDataBean}describing all current
     * quotes
     *
     * @return the collection of QuoteDataBean
     */
    public Collection getAllQuotes() throws Exception {
        if (Log.doActionTrace()) {
            Log.trace("TradeAction:getAllQuotes");
        }
        Collection quotes;
        quotes = trade.getAllQuotes();
        return quotes;
    }

    /**
     * Return a {@link QuoteDataBean}describing a current quote for the given
     * stock symbol
     *
     * @param symbol the stock symbol to retrieve the current Quote
     * @return the QuoteDataBean
     */
    public QuoteDataBean getQuote(String symbol) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getQuote", symbol);
        if ((symbol == null) || (symbol.length() == 0) || (symbol.length() > 10)) {
            if (Log.doActionTrace()) {
                Log.trace("TradeAction:getQuote   ---  primitive workload");
            }
            return new QuoteDataBean("Invalid symbol", "", 0.0, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, FinancialUtils.ZERO, 0.0);
        }
        QuoteDataBean quoteData;
        quoteData = trade.getQuote(symbol);
        return quoteData;
    }

    /**
     * Update the stock quote price for the specified stock symbol
     *
     * @param symbol for stock quote to update
     * @return the QuoteDataBean describing the stock
     */
    /* avoid data collision with synch */
    public QuoteDataBean updateQuotePriceVolume(String symbol, BigDecimal changeFactor, double sharesTraded) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:updateQuotePriceVolume", symbol, changeFactor, new Double(sharesTraded));
        QuoteDataBean quoteData = null;
        try {
            quoteData = trade.updateQuotePriceVolume(symbol, changeFactor, sharesTraded);
        }
        catch (Exception e) {
            Log.error("TradeAction:updateQuotePrice -- ", e);
        }
        return quoteData;
    }

    /**
     * Return the portfolio of stock holdings for the specified customer as a
     * collection of HoldingDataBeans
     *
     * @param userID the customer requesting the portfolio
     * @return Collection of the users portfolio of stock holdings
     */
    public Collection getHoldings(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getHoldings", userID);
        Collection holdingDataBeans;
        holdingDataBeans = trade.getHoldings(userID);
        return holdingDataBeans;
    }

    /**
     * Return a specific user stock holding identifed by the holdingID
     *
     * @param holdingID the holdingID to return
     * @return a HoldingDataBean describing the holding
     */
    public HoldingDataBean getHolding(Integer holdingID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getHolding", holdingID);
        HoldingDataBean holdingData;
        holdingData = trade.getHolding(holdingID);
        return holdingData;
    }

    /**
     * Return an AccountDataBean object for userID describing the account
     *
     * @param userID the account userID to lookup
     * @return User account data in AccountDataBean
     */
    public AccountDataBean getAccountData(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getAccountData", userID);
        AccountDataBean accountData;
        accountData = trade.getAccountData(userID);
        return accountData;
    }

    /**
     * Return an AccountProfileDataBean for userID providing the users profile
     *
     * @param userID the account userID to lookup
     */
    public AccountProfileDataBean getAccountProfileData(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:getAccountProfileData", userID);
        AccountProfileDataBean accountProfileData;
        accountProfileData = trade.getAccountProfileData(userID);
        return accountProfileData;
    }

    /**
     * Update userID's account profile information using the provided
     * AccountProfileDataBean object
     *
     * @param accountProfileData   account profile data in AccountProfileDataBean
     */
    public AccountProfileDataBean updateAccountProfile(AccountProfileDataBean accountProfileData) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:updateAccountProfile", accountProfileData);
        accountProfileData = trade.updateAccountProfile(accountProfileData);
        return accountProfileData;
    }

    /**
     * Attempt to authenticate and login a user with the given password
     *
     * @param userID   the customer to login
     * @param password the password entered by the customer for authentication
     * @return User account data in AccountDataBean
     */
    public AccountDataBean login(String userID, String password) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:login", userID, password);
        AccountDataBean accountData;
        accountData = trade.login(userID, password);
        return accountData;
    }

    /**
     * Logout the given user
     *
     * @param userID the customer to logout
     */
    public void logout(String userID) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:logout", userID);
        trade.logout(userID);
    }

    /**
     * Register a new Trade customer. Create a new user profile, user registry
     * entry, account with initial balance, and empty portfolio.
     *
     * @param userID         the new customer to register
     * @param password       the customers password
     * @param fullname       the customers fullname
     * @param address        the customers street address
     * @param email          the customers email address
     * @param creditCard     the customers creditcard number
     * @param openBalance the amount to charge to the customers credit to open the
     *                       account and set the initial balance
     * @return the userID if successful, null otherwise
     */
    public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditCard, BigDecimal openBalance) throws Exception {
        if (Log.doActionTrace())
            Log.trace("TradeAction:register", userID, password, fullname, address, email, creditCard, openBalance);
        AccountDataBean accountData;
        accountData = trade.register(userID, password, fullname, address, email, creditCard, openBalance);
        return accountData;
    }

    public AccountDataBean register(String userID, String password, String fullname, String address, String email, String creditCard, String openBalanceString) throws Exception {
        BigDecimal openBalance = new BigDecimal(openBalanceString);
        return register(userID, password, fullname, address, email, creditCard, openBalance);
    }

    /**
     * Reset the TradeData by - removing all newly registered users by scenario
     * servlet (i.e. users with userID's beginning with "ru:") * - removing all
     * buy/sell order pairs - setting logoutCount = loginCount
     *
     * return statistics for this benchmark run
     */
    public RunStatsDataBean resetTrade(boolean deleteAll) throws Exception {
        RunStatsDataBean runStatsData;
        runStatsData = trade.resetTrade(deleteAll);
        return runStatsData;
    }

}


text:
const config = require('../../config');
const utils = require('../../utils/utils');

const logger = config.logger;

function getFrameWithFrameModel(Frame) {
  return async function getFrame(id, projections = {}, populations = []) {
    const q = Frame.findById(id, projections);
    return populations.reduce((query, p) => query.populate(p), q);
  };
}

async function getByID(context, next) {
  const startTime = utils.getStartTime();
  logger.info(`Querying for Frame with _id = ${context.params.id}`);
  const frameModel = context.valencer.models.Frame;
  context.body = await getFrameWithFrameModel(frameModel)(context.params.id,
                                                          context.valencer.query.projections,
                                                          context.valencer.query.populations);
  logger.verbose(`Frame with _id = ${context.params.id} retrieved from database in ${utils.getElapsedTime(startTime)}ms`);
  return next();
}

module.exports = {
  getByID,
};

redpajama_set_name: RedPajamaGithub


text:
using Eigen::Tensor;

template <typename DataType, typename IndexType>
static void test_simple_swap_sycl(const Eigen::SyclDevice& sycl_device)
{
  IndexType sizeDim1 = 2;
  IndexType sizeDim2 = 3;
  IndexType sizeDim3 = 7;
  array<IndexType, 3> tensorColRange = {{sizeDim1, sizeDim2, sizeDim3}};
  array<IndexType, 3> tensorRowRange = {{sizeDim3, sizeDim2, sizeDim1}};

  Tensor<DataType, 3, ColMajor, IndexType> tensor1(tensorColRange);
  Tensor<DataType, 3, RowMajor, IndexType> tensor2(tensorRowRange);
  tensor1.setRandom();

  DataType* gpu_data1  = static_cast<DataType*>(sycl_device.allocate(tensor1.size()*sizeof(DataType)));
  DataType* gpu_data2  = static_cast<DataType*>(sycl_device.allocate(tensor2.size()*sizeof(DataType)));
  TensorMap<Tensor<DataType, 3, ColMajor, IndexType>> gpu1(gpu_data1, tensorColRange);
  TensorMap<Tensor<DataType, 3, RowMajor, IndexType>> gpu2(gpu_data2, tensorRowRange);

  sycl_device.memcpyHostToDevice(gpu_data1, tensor1.data(),(tensor1.size())*sizeof(DataType));
  gpu2.device(sycl_device)=gpu1.swap_layout();
  sycl_device.memcpyDeviceToHost(tensor2.data(), gpu_data2,(tensor2.size())*sizeof(DataType));

//  Tensor<float, 3, ColMajor> tensor(2,3,7);
  //tensor.setRandom();

//  Tensor<float, 3, RowMajor> tensor2 = tensor.swap_layout();
  VERIFY_IS_EQUAL(tensor1.dimension(0), tensor2.dimension(2));
  VERIFY_IS_EQUAL(tensor1.dimension(1), tensor2.dimension(1));
  VERIFY_IS_EQUAL(tensor1.dimension(2), tensor2.dimension(0));

  for (IndexType i = 0; i < 2; ++i) {
    for (IndexType j = 0; j < 3; ++j) {
      for (IndexType k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(tensor1(i,j,k), tensor2(k,j,i));
      }
    }
  }
  sycl_device.deallocate(gpu_data1);
  sycl_device.deallocate(gpu_data2);
}

template <typename DataType, typename IndexType>
static void test_swap_as_lvalue_sycl(const Eigen::SyclDevice& sycl_device)
{

  IndexType sizeDim1 = 2;
  IndexType sizeDim2 = 3;
  IndexType sizeDim3 = 7;
  array<IndexType, 3> tensorColRange = {{sizeDim1, sizeDim2, sizeDim3}};
  array<IndexType, 3> tensorRowRange = {{sizeDim3, sizeDim2, sizeDim1}};

  Tensor<DataType, 3, ColMajor, IndexType> tensor1(tensorColRange);
  Tensor<DataType, 3, RowMajor, IndexType> tensor2(tensorRowRange);
  tensor1.setRandom();

  DataType* gpu_data1  = static_cast<DataType*>(sycl_device.allocate(tensor1.size()*sizeof(DataType)));
  DataType* gpu_data2  = static_cast<DataType*>(sycl_device.allocate(tensor2.size()*sizeof(DataType)));
  TensorMap<Tensor<DataType, 3, ColMajor, IndexType>> gpu1(gpu_data1, tensorColRange);
  TensorMap<Tensor<DataType, 3, RowMajor, IndexType>> gpu2(gpu_data2, tensorRowRange);

  sycl_device.memcpyHostToDevice(gpu_data1, tensor1.data(),(tensor1.size())*sizeof(DataType));
  gpu2.swap_layout().device(sycl_device)=gpu1;
  sycl_device.memcpyDeviceToHost(tensor2.data(), gpu_data2,(tensor2.size())*sizeof(DataType));

//  Tensor<float, 3, ColMajor> tensor(2,3,7);
//  tensor.setRandom();

  //Tensor<float, 3, RowMajor> tensor2(7,3,2);
//  tensor2.swap_layout() = tensor;
  VERIFY_IS_EQUAL(tensor1.dimension(0), tensor2.dimension(2));
  VERIFY_IS_EQUAL(tensor1.dimension(1), tensor2.dimension(1));
  VERIFY_IS_EQUAL(tensor1.dimension(2), tensor2.dimension(0));

  for (IndexType i = 0; i < 2; ++i) {
    for (IndexType j = 0; j < 3; ++j) {
      for (IndexType k = 0; k < 7; ++k) {
        VERIFY_IS_EQUAL(tensor1(i,j,k), tensor2(k,j,i));
      }
    }
  }
  sycl_device.deallocate(gpu_data1);
  sycl_device.deallocate(gpu_data2);
}

template<typename DataType, typename dev_Selector> void sycl_tensor_layout_swap_test_per_device(dev_Selector s){
  QueueInterface queueInterface(s);
  auto sycl_device = Eigen::SyclDevice(&queueInterface);
  test_simple_swap_sycl<DataType, int64_t>(sycl_device);
  test_swap_as_lvalue_sycl<DataType, int64_t>(sycl_device);
}
EIGEN_DECLARE_TEST(cxx11_tensor_layout_swap_sycl)
{
  for (const auto& device :Eigen::get_sycl_supported_devices()) {
    CALL_SUBTEST(sycl_tensor_layout_swap_test_per_device<float>(device));
  }
}


text:
using System;
using System.Collections.Generic;

namespace InstaKiller.Model
{
    public class Photo
    {
        public Guid Id { get; set; }
        public Guid UserId { get; set; }
        public string ImageUrl { get; set; }
        public DateTime TimeDate { get; set; }
        public List<Person> UsersThatLike { get; set; }
        public List<Comment> AllComments { get; set; }

        public Photo()
        {
            UsersThatLike = new List<Person>();
        }
    }
}


text:
Name | Type | Description | Notes
------------ | ------------- | ------------- | -------------
**id** | **String** | The id of the batch. |  [optional]
**type** | **String** | The type of the batch. |  [optional]
**totalJobs** | **Integer** | The total jobs of a batch is the number of batch execution jobs required to complete the batch. |  [optional]
**jobsCreated** | **Integer** | The number of batch execution jobs already created by the seed job. |  [optional]
**batchJobsPerSeed** | **Integer** | The number of batch execution jobs created per seed job invocation. The batch seed job is invoked until it has created all batch execution jobs required by the batch (see totalJobs property). |  [optional]
**invocationsPerBatchJob** | **Integer** | Every batch execution job invokes the command executed by the batch invocationsPerBatchJob times. E.g., for a process instance migration batch this specifies the number of process instances which are migrated per batch execution job. |  [optional]
**seedJobDefinitionId** | **String** | The job definition id for the seed jobs of this batch. |  [optional]
**monitorJobDefinitionId** | **String** | The job definition id for the monitor jobs of this batch. |  [optional]
**batchJobDefinitionId** | **String** | The job definition id for the batch execution jobs of this batch. |  [optional]
**suspended** | **Boolean** | Indicates whether this batch is suspended or not. |  [optional]
**tenantId** | **String** | The tenant id of the batch. |  [optional]
**createUserId** | **String** | The id of the user that created the batch. |  [optional]


text:
Simple 'chat' application
=======================================================
Application is based on Yii 2 + Angular.js. All communications between the client and server happen through AJAX.

DIRECTORY STRUCTURE
-------------------

      assets/             contains assets definition
      config/             contains application configurations
      controllers/        contains Web controller classes
      data/               contains SQLite database
      models/             contains model classes
      modules/api         contains API module
      modules/auth        contains Authentication module
      vendor/             contains dependent 3rd-party packages
      views/              contains view files for the Web application
      web/                contains the entry script and Web resources
      web/js              contains JavaScript files
      web/views           contains HTML files

REQUIREMENTS
------------

* PHP >= 5.6.0.
* SQLite >= 3.6.19

INSTALLATION
------------

Run the following command in the project directory
```
php composer.phar install
```
Alternatively, copy `vendor` directory from [Yii 2 Basic Project Template](http://www.yiiframework.com/download/).

The web root of application is the `/web` folder.

USAGE
-----
There is no registration. Users are created automatically for each new session. To login as new user just open application in a new private browser window. Messages can be sent to any previously created user. All incoming messages for the current user are showm in a single table. Messages are updated automatically every 1 minute or manually by clicking Refresh button.


text:
package com.intellij.ide.lightEdit;

interface LightEditSaveConfirmationHandler {
  void onSave();
  void onDiscard();
}


text:
title: Destroying My Blog
layout: post
author: anshu.attavar
permalink: captainstar.github.io
source-id: 1XGx8YSEPoPatT60asgnnREyc4KOt6I4wVZEG_TDBwgc
published: true
---
   Hey Guys. Last year I had a blog which I put in a lot of hard work but this year I had to destroy it and create a new one. This lesson we had to fill in a Google form which was not the most fun thing but it had to be done. Then we spent the rest of the lesson trying to re create our blogs after we deleted it which involved a lot of waiting around for other people to figure out what they had to do. That was all the lesson pretty much. See you next time.


text:
<?php

declare(strict_types=1);

namespace BinSoul\Common\I18n;

/**
 * Provides a default implementation of the {@see MutableAddress} interface.
 */
class DefaultAddress implements MutableAddress
{
    /**
     * @var string|null
     */
    private $organization;

    /**
     * @var string|null
     */
    private $namePrefix;

    /**
     * @var string|null
     */
    private $firstName;

    /**
     * @var string|null
     */
    private $lastName;

    /**
     * @var string|null
     */
    private $addressLine1;

    /**
     * @var string|null
     */
    private $addressLine2;

    /**
     * @var string|null
     */
    private $addressLine3;

    /**
     * @var string|null
     */
    private $sortingCode;

    /**
     * @var string|null
     */
    private $postalCode;

    /**
     * @var string|null
     */
    private $locality;

    /**
     * @var string|null
     */
    private $subLocality;

    /**
     * @var string|null
     */
    private $state;

    /**
     * @var string|null
     */
    private $countryCode;

    /**
     * Constructs an instance of this class.
     */
    public function __construct(
        ?string $organization = null,
        ?string $namePrefix = null,
        ?string $firstName = null,
        ?string $lastName = null,
        ?string $addressLine1 = null,
        ?string $addressLine2 = null,
        ?string $addressLine3 = null,
        ?string $sortingCode = null,
        ?string $postalCode = null,
        ?string $locality = null,
        ?string $subLocality = null,
        ?string $state = null,
        ?string $countryCode = null
    ) {
        $this->organization = $organization;
        $this->namePrefix = $namePrefix;
        $this->firstName = $firstName;
        $this->lastName = $lastName;
        $this->addressLine1 = $addressLine1;
        $this->addressLine2 = $addressLine2;
        $this->addressLine3 = $addressLine3;
        $this->sortingCode = $sortingCode;
        $this->postalCode = $postalCode;
        $this->locality = $locality;
        $this->subLocality = $subLocality;
        $this->state = $state;
        $this->countryCode = $countryCode;
    }

    public function getOrganization(): ?string
    {
        return $this->organization;
    }

    public function setOrganization(?string $value): void
    {
        $this->organization = $value;
    }

    public function getNamePrefix(): ?string
    {
        return $this->namePrefix;
    }

    public function setNamePrefix(?string $value): void
    {
        $this->namePrefix = $value;
    }

    public function getFirstName(): ?string
    {
        return $this->firstName;
    }

    public function setFirstName(?string $value): void
    {
        $this->firstName = $value;
    }

    public function getLastName(): ?string
    {
        return $this->lastName;
    }

    public function setLastName(?string $value): void
    {
        $this->lastName = $value;
    }

    public function getAddressLine1(): ?string
    {
        return $this->addressLine1;
    }

    public function setAddressLine1(?string $value): void
    {
        $this->addressLine1 = $value;
    }

    public function getAddressLine2(): ?string
    {
        return $this->addressLine2;
    }

    public function setAddressLine2(?string $value): void
    {
        $this->addressLine2 = $value;
    }

    public function getAddressLine3(): ?string
    {
        return $this->addressLine3;
    }

    public function setAddressLine3(?string $value): void
    {
        $this->addressLine3 = $value;
    }

    public function getSortingCode(): ?string
    {
        return $this->sortingCode;
    }

    public function setSortingCode(?string $value): void
    {
        $this->sortingCode = $value;
    }

    public function getPostalCode(): ?string
    {
        return $this->postalCode;
    }

    public function setPostalCode(?string $value): void
    {
        $this->postalCode = $value;
    }

    public function getLocality(): ?string
    {
        return $this->locality;
    }

    public function setLocality(?string $value): void
    {
        $this->locality = $value;
    }

    public function getSubLocality(): ?string
    {
        return $this->subLocality;
    }

    public function setSubLocality(?string $value): void
    {
        $this->subLocality = $value;
    }

    public function getState(): ?string
    {
        return $this->state;
    }

    public function setState(?string $value): void
    {
        $this->state = $value;
    }

    public function getCountryCode(): ?string
    {
        return $this->countryCode;
    }

    public function setCountryCode(?string $value): void
    {
        $this->countryCode = $value;
    }
}


text: Specify a timeout value in seconds (default is 0 which implies no timeout)


text:
<link rel="import" href="chrome://resources/polymer/polymer/polymer.html">
<link rel="import" href="chrome://resources/polymer/core-list/core-list.html">
<link rel="import" href="chrome://resources/cr_elements/cr_collapse/cr_collapse.html">
<link rel="import" href="chrome://resources/cr_elements/cr_network_list_item/cr_network_list_item.html">

<polymer-element name="cr-network-list">
  <template>
    <link rel="stylesheet" href="cr_network_list.css">
    <cr-collapse on-core-resize="{{onResized_}}" opened="{{opened}}">
      <div id="container" vertical layout flex>
        <core-list id="networkList"
            data="{{networks}}"
            on-core-activate="{{onSelected_}}">
          <template>
            <cr-network-list-item networkState="{{model}}" isListItem>
            </cr-network-list-item>
          </template>
        </core-list>
      </div>
    </cr-collapse>
  </template>
  <script src="cr_network_list.js"></script>
</polymer-element>


text:
/* global angular */
(function(window, document) {
    'use strict';

    /*
     * AngularJS Toaster
     * Version: 2.2.0
     *
     * Copyright 2013-2016 Jiri Kavulak.
     * All Rights Reserved.
     * Use, reproduction, distribution, and modification of this code is subject to the terms and
     * conditions of the MIT license, available at http://www.opensource.org/licenses/mit-license.php
     *
     * Author: Jiri Kavulak
     * Related to project of John Papa, Hans Fjällemark and Nguyễn Thiện Hùng (thienhung1989)
     */

    angular.module('toaster', []).constant(
        'toasterConfig', {
            'limit': 0,                   // limits max number of toasts
            'tap-to-dismiss': true,
            'close-button': false,
            'close-html': '<button class="toast-close-button" type="button">×</button>',
            'newest-on-top': true,
            'time-out': 5000,
            'icon-classes': {
                error: 'toast-error',
                info: 'toast-info',
                wait: 'toast-wait',
                success: 'toast-success',
                warning: 'toast-warning'
            },
            'body-output-type': '', // Options: '', 'trustedHtml', 'template', 'templateWithData', 'directive'
            'body-template': 'toasterBodyTmpl.html',
            'icon-class': 'toast-info',
            'position-class': 'toast-top-right', // Options (see CSS):
            // 'toast-top-full-width', 'toast-bottom-full-width', 'toast-center',
            // 'toast-top-left', 'toast-top-center', 'toast-top-right',
            // 'toast-bottom-left', 'toast-bottom-center', 'toast-bottom-right',
            'title-class': 'toast-title',
            'message-class': 'toast-message',
            'prevent-duplicates': false,
            'mouseover-timer-stop': true // stop timeout on mouseover and restart timer on mouseout
        }
    ).run(['$templateCache', function($templateCache) {
            $templateCache.put('angularjs-toaster/toast.html',
                '
' +
                    '
' +
                        '

' +
                        '
{{toaster.title}}
' +
                        '
' +
                        '

' +
                        '

' +
                        '

' +
                        '

' +
                        '
{{toaster.body}}
' +
                        '
' +
                    '
' +
                '
');
        }
    ]).service(
        'toaster', [
            '$rootScope', 'toasterConfig', function($rootScope, toasterConfig) {
                // http://stackoverflow.com/questions/26501688/a-typescript-guid-class
                var Guid = (function() {
                    var Guid = {};
                    Guid.newGuid = function() {
                        return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
                            var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
                            return v.toString(16);
                        });
                    };
                    return Guid;
                }());

                this.pop = function(type, title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
                    if (angular.isObject(type)) {
                        var params = type; // Enable named parameters as pop argument
                        this.toast = {
                            type: params.type,
                            title: params.title,
                            body: params.body,
                            timeout: params.timeout,
                            bodyOutputType: params.bodyOutputType,
                            clickHandler: params.clickHandler,
                            showCloseButton: params.showCloseButton,
                            closeHtml: params.closeHtml,
                            toastId: params.toastId,
                            onShowCallback: params.onShowCallback,
                            onHideCallback: params.onHideCallback,
                            directiveData: params.directiveData,
                            tapToDismiss: params.tapToDismiss
                        };
                        toasterId = params.toasterId;
                    } else {
                        this.toast = {
                            type: type,
                            title: title,
                            body: body,
                            timeout: timeout,
                            bodyOutputType: bodyOutputType,
                            clickHandler: clickHandler,
                            showCloseButton: showCloseButton,
                            toastId: toastId,
                            onHideCallback: onHideCallback
                        };
                    }

                    if (!this.toast.toastId || !this.toast.toastId.length) {
                        this.toast.toastId = Guid.newGuid();
                    }

                    $rootScope.$emit('toaster-newToast', toasterId, this.toast.toastId);

                    return {
                        toasterId: toasterId,
                        toastId: this.toast.toastId
                    };
                };

                this.clear = function(toasterId, toastId) {
                    if (angular.isObject(toasterId)) {
                        $rootScope.$emit('toaster-clearToasts', toasterId.toasterId, toasterId.toastId);
                    } else {
                        $rootScope.$emit('toaster-clearToasts', toasterId, toastId);
                    }
                };

                // Create one method per icon class, to allow to call toaster.info() and similar
                for (var type in toasterConfig['icon-classes']) {
                    this[type] = createTypeMethod(type);
                }

                function createTypeMethod(toasterType) {
                    return function(title, body, timeout, bodyOutputType, clickHandler, toasterId, showCloseButton, toastId, onHideCallback) {
                        if (angular.isString(title)) {
                            return this.pop(
                                toasterType,
                                title,
                                body,
                                timeout,
                                bodyOutputType,
                                clickHandler,
                                toasterId,
                                showCloseButton,
                                toastId,
                                onHideCallback);
                        } else { // 'title' is actually an object with options
                            return this.pop(angular.extend(title, { type: toasterType }));
                        }
                    };
                }
            }]
        ).factory(
        'toasterEventRegistry', [
            '$rootScope', function($rootScope) {
                var deregisterNewToast = null, deregisterClearToasts = null, newToastEventSubscribers = [], clearToastsEventSubscribers = [], toasterFactory;

                toasterFactory = {
                    setup: function() {
                        if (!deregisterNewToast) {
                            deregisterNewToast = $rootScope.$on(
                                'toaster-newToast', function(event, toasterId, toastId) {
                                    for (var i = 0, len = newToastEventSubscribers.length; i < len; i++) {
                                        newToastEventSubscribers[i](event, toasterId, toastId);
                                    }
                                });
                        }

                        if (!deregisterClearToasts) {
                            deregisterClearToasts = $rootScope.$on(
                                'toaster-clearToasts', function(event, toasterId, toastId) {
                                    for (var i = 0, len = clearToastsEventSubscribers.length; i < len; i++) {
                                        clearToastsEventSubscribers[i](event, toasterId, toastId);
                                    }
                                });
                        }
                    },

                    subscribeToNewToastEvent: function(onNewToast) {
                        newToastEventSubscribers.push(onNewToast);
                    },
                    subscribeToClearToastsEvent: function(onClearToasts) {
                        clearToastsEventSubscribers.push(onClearToasts);
                    },
                    unsubscribeToNewToastEvent: function(onNewToast) {
                        var index = newToastEventSubscribers.indexOf(onNewToast);
                        if (index >= 0) {
                            newToastEventSubscribers.splice(index, 1);
                        }

                        if (newToastEventSubscribers.length === 0) {
                            deregisterNewToast();
                            deregisterNewToast = null;
                        }
                    },
                    unsubscribeToClearToastsEvent: function(onClearToasts) {
                        var index = clearToastsEventSubscribers.indexOf(onClearToasts);
                        if (index >= 0) {
                            clearToastsEventSubscribers.splice(index, 1);
                        }

                        if (clearToastsEventSubscribers.length === 0) {
                            deregisterClearToasts();
                            deregisterClearToasts = null;
                        }
                    }
                };
                return {
                    setup: toasterFactory.setup,
                    subscribeToNewToastEvent: toasterFactory.subscribeToNewToastEvent,
                    subscribeToClearToastsEvent: toasterFactory.subscribeToClearToastsEvent,
                    unsubscribeToNewToastEvent: toasterFactory.unsubscribeToNewToastEvent,
                    unsubscribeToClearToastsEvent: toasterFactory.unsubscribeToClearToastsEvent
                };
            }]
        )
        .directive('directiveTemplate', ['$compile', '$injector', function($compile, $injector) {
            return {
                restrict: 'A',
                scope: {
                    directiveName: '@directiveName',
                    directiveData: '@directiveData'
                },
                replace: true,
                link: function(scope, elm, attrs) {
                    scope.$watch('directiveName', function(directiveName) {
                        if (angular.isUndefined(directiveName) || directiveName.length <= 0)
                            throw new Error('A valid directive name must be provided via the toast body argument when using bodyOutputType: directive');

                        var directive;

                        try {
                            directive = $injector.get(attrs.$normalize(directiveName) + 'Directive');
                        } catch (e) {
                            throw new Error(directiveName + ' could not be found. ' +
                                'The name should appear as it exists in the markup, not camelCased as it would appear in the directive declaration,' +
                                ' e.g. directive-name not directiveName.');
                        }

                        var directiveDetails = directive[0];

                        if (directiveDetails.scope !== true && directiveDetails.scope) {
                            throw new Error('Cannot use a directive with an isolated scope. ' +
                                'The scope must be either true or falsy (e.g. false/null/undefined). ' +
                                'Occurred for directive ' + directiveName + '.');
                        }

                        if (directiveDetails.restrict.indexOf('A') < 0) {
                            throw new Error('Directives must be usable as attributes. ' +
                                'Add "A" to the restrict option (or remove the option entirely). Occurred for directive ' +
                                directiveName + '.');
                        }

                        if (scope.directiveData)
                            scope.directiveData = angular.fromJson(scope.directiveData);

                        var template = $compile('

')(scope);

                        elm.append(template);
                    });
                }
            };
        }])
        .directive(
        'toasterContainer', [
            '$parse', '$rootScope', '$interval', '$sce', 'toasterConfig', 'toaster', 'toasterEventRegistry',
            function($parse, $rootScope, $interval, $sce, toasterConfig, toaster, toasterEventRegistry) {
                return {
                    replace: true,
                    restrict: 'EA',
                    scope: true, // creates an internal scope for this directive (one per directive instance)
                    link: function(scope, elm, attrs) {
                        var mergedConfig;

                        // Merges configuration set in directive with default one
                        mergedConfig = angular.extend({}, toasterConfig, scope.$eval(attrs.toasterOptions));

                        scope.config = {
                            toasterId: mergedConfig['toaster-id'],
                            position: mergedConfig['position-class'],
                            title: mergedConfig['title-class'],
                            message: mergedConfig['message-class'],
                            tap: mergedConfig['tap-to-dismiss'],
                            closeButton: mergedConfig['close-button'],
                            closeHtml: mergedConfig['close-html'],
                            animation: mergedConfig['animation-class'],
                            mouseoverTimer: mergedConfig['mouseover-timer-stop']
                        };

                        scope.$on(
                            "$destroy", function() {
                                toasterEventRegistry.unsubscribeToNewToastEvent(scope._onNewToast);
                                toasterEventRegistry.unsubscribeToClearToastsEvent(scope._onClearToasts);
                            }
                        );

                        function setTimeout(toast, time) {
                            toast.timeoutPromise = $interval(
                                function() {
                                    scope.removeToast(toast.toastId);
                                }, time, 1
                            );
                        }

                        scope.configureTimer = function(toast) {
                            var timeout = angular.isNumber(toast.timeout) ? toast.timeout : mergedConfig['time-out'];
                            if (typeof timeout === "object") timeout = timeout[toast.type];
                            if (timeout > 0) {
                                setTimeout(toast, timeout);
                            }
                        };

                        function addToast(toast, toastId) {
                            toast.type = mergedConfig['icon-classes'][toast.type];
                            if (!toast.type) {
                                toast.type = mergedConfig['icon-class'];
                            }

                            if (mergedConfig['prevent-duplicates'] === true && scope.toasters.length) {
                                if (scope.toasters[scope.toasters.length - 1].body === toast.body) {
                                    return;
                                } else {
                                    var i, len, dupFound = false;
                                    for (i = 0, len = scope.toasters.length; i < len; i++) {
                                        if (scope.toasters[i].toastId === toastId) {
                                            dupFound = true;
                                            break;
                                        }
                                    }

                                    if (dupFound) return;
                                }
                            }

                            // set the showCloseButton property on the toast so that
                            // each template can bind directly to the property to show/hide
                            // the close button
                            var closeButton = mergedConfig['close-button'];

                            // if toast.showCloseButton is a boolean value,
                            // it was specifically overriden in the pop arguments
                            if (typeof toast.showCloseButton === "boolean") {

                            } else if (typeof closeButton === "boolean") {
                                toast.showCloseButton = closeButton;
                            } else if (typeof closeButton === "object") {
                                var closeButtonForType = closeButton[toast.type];

                                if (typeof closeButtonForType !== "undefined" && closeButtonForType !== null) {
                                    toast.showCloseButton = closeButtonForType;
                                }
                            } else {
                                // if an option was not set, default to false.
                                toast.showCloseButton = false;
                            }

                            if (toast.showCloseButton) {
                                toast.closeHtml = $sce.trustAsHtml(toast.closeHtml || scope.config.closeHtml);
                            }

                            // Set the toast.bodyOutputType to the default if it isn't set
                            toast.bodyOutputType = toast.bodyOutputType || mergedConfig['body-output-type'];
                            switch (toast.bodyOutputType) {
                                case 'trustedHtml':
                                    toast.html = $sce.trustAsHtml(toast.body);
                                    break;
                                case 'template':
                                    toast.bodyTemplate = toast.body || mergedConfig['body-template'];
                                    break;
                                case 'templateWithData':
                                    var fcGet = $parse(toast.body || mergedConfig['body-template']);
                                    var templateWithData = fcGet(scope);
                                    toast.bodyTemplate = templateWithData.template;
                                    toast.data = templateWithData.data;
                                    break;
                                case 'directive':
                                    toast.html = toast.body;
                                    break;
                            }

                            scope.configureTimer(toast);

                            if (mergedConfig['newest-on-top'] === true) {
                                scope.toasters.unshift(toast);
                                if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                                    scope.toasters.pop();
                                }
                            } else {
                                scope.toasters.push(toast);
                                if (mergedConfig['limit'] > 0 && scope.toasters.length > mergedConfig['limit']) {
                                    scope.toasters.shift();
                                }
                            }

                            if (angular.isFunction(toast.onShowCallback)) {
                                toast.onShowCallback(toast);
                            }
                        }

                        scope.removeToast = function(toastId) {
                            var i, len;
                            for (i = 0, len = scope.toasters.length; i < len; i++) {
                                if (scope.toasters[i].toastId === toastId) {
                                    removeToast(i);
                                    break;
                                }
                            }
                        };

                        function removeToast(toastIndex) {
                            var toast = scope.toasters[toastIndex];

                            // toast is always defined since the index always has a match
                            if (toast.timeoutPromise) {
                                $interval.cancel(toast.timeoutPromise);
                            }
                            scope.toasters.splice(toastIndex, 1);

                            if (angular.isFunction(toast.onHideCallback)) {
                                toast.onHideCallback(toast);
                            }
                        }

                        function removeAllToasts(toastId) {
                            for (var i = scope.toasters.length - 1; i >= 0; i--) {
                                if (isUndefinedOrNull(toastId)) {
                                    removeToast(i);
                                } else {
                                    if (scope.toasters[i].toastId == toastId) {
                                        removeToast(i);
                                    }
                                }
                            }
                        }

                        scope.toasters = [];

                        function isUndefinedOrNull(val) {
                            return angular.isUndefined(val) || val === null;
                        }

                        scope._onNewToast = function(event, toasterId, toastId) {
                            // Compatibility: if toaster has no toasterId defined, and if call to display
                            // hasn't either, then the request is for us

                            if ((isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
                                addToast(toaster.toast, toastId);
                            }
                        };
                        scope._onClearToasts = function(event, toasterId, toastId) {
                            // Compatibility: if toaster has no toasterId defined, and if call to display
                            // hasn't either, then the request is for us
                            if (toasterId == '*' || (isUndefinedOrNull(scope.config.toasterId) && isUndefinedOrNull(toasterId)) || (!isUndefinedOrNull(scope.config.toasterId) && !isUndefinedOrNull(toasterId) && scope.config.toasterId == toasterId)) {
                                removeAllToasts(toastId);
                            }
                        };

                        toasterEventRegistry.setup();

                        toasterEventRegistry.subscribeToNewToastEvent(scope._onNewToast);
                        toasterEventRegistry.subscribeToClearToastsEvent(scope._onClearToasts);
                    },
                    controller: [
                        '$scope', '$element', '$attrs', function($scope, $element, $attrs) {
                            // Called on mouseover
                            $scope.stopTimer = function(toast) {
                                if ($scope.config.mouseoverTimer === true) {
                                    if (toast.timeoutPromise) {
                                        $interval.cancel(toast.timeoutPromise);
                                        toast.timeoutPromise = null;
                                    }
                                }
                            };

                            // Called on mouseout
                            $scope.restartTimer = function(toast) {
                                if ($scope.config.mouseoverTimer === true) {
                                    if (!toast.timeoutPromise) {
                                        $scope.configureTimer(toast);
                                    }
                                } else if (toast.timeoutPromise === null) {
                                    $scope.removeToast(toast.toastId);
                                }
                            };

                            $scope.click = function(event, toast, isCloseButton) {
                                event.stopPropagation();

                                var tapToDismiss = typeof toast.tapToDismiss === "boolean"
                                                        ? toast.tapToDismiss
                                                        : $scope.config.tap;
                                if (tapToDismiss === true || (toast.showCloseButton === true && isCloseButton === true)) {
                                    var removeToast = true;
                                    if (toast.clickHandler) {
                                        if (angular.isFunction(toast.clickHandler)) {
                                            removeToast = toast.clickHandler(toast, isCloseButton);
                                        } else if (angular.isFunction($scope.$parent.$eval(toast.clickHandler))) {
                                            removeToast = $scope.$parent.$eval(toast.clickHandler)(toast, isCloseButton);
                                        } else {
                                            console.log("TOAST-NOTE: Your click handler is not inside a parent scope of toaster-container.");
                                        }
                                    }
                                    if (removeToast) {
                                        $scope.removeToast(toast.toastId);
                                    }
                                }
                            };
                        }],
                    templateUrl: 'angularjs-toaster/toast.html'
                };
            }]
        );
})(window, document);


text:
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.desk.moduleview import add_setup_section

def get_data():
	data = [
		{
			"label": _("Core"),
			"icon": "fa fa-wrench",
			"items": [
				{
					"type": "doctype",
					"name": "Company",
					"label": _("Company"),
					"description": _("Company (not Customer or Supplier) master."),
				},
				{
					"type": "doctype",
					"name": "System Settings",
					"label": _("System Settings"),
					"description": _("Language, Date and Time settings"),
					"hide_count": True
				},
				{
					"type": "doctype",
					"name": "Error Log",
					"description": _("Log of error on automated events (scheduler).")
				},
				{
					"type": "doctype",
					"name": "Error Snapshot",
					"description": _("Log of error during requests.")
				},
				{
					"type": "doctype",
					"name": "Domain Settings",
					"label": _("Domain Settings"),
					"description": _("Enable / Disable Domains"),
					"hide_count": True
				},
			]
		},
		{
			"label": _("Data"),
			"icon": "fa fa-th",
			"items": [
				{
					"type": "doctype",
					"name": "Data Import",
					"label": _("Import Data"),
					"icon": "octicon octicon-cloud-upload",
					"description": _("Import Data from CSV / Excel files.")
				},
				{
					"type": "doctype",
					"name": "Data Export",
					"label": _("Export Data"),
					"icon": "octicon octicon-cloud-upload",
					"description": _("Export Data in CSV / Excel format.")
				},
				{
					"type": "doctype",
					"name": "Naming Series",
					"description": _("Set numbering series for transactions."),
					"hide_count": True
				},
				{
					"type": "doctype",
					"name": "Rename Tool",
					"label": _("Bulk Rename"),
					"description": _("Rename many items by uploading a .csv file."),
					"hide_count": True
				},
				{
					"type": "doctype",
					"name": "Bulk Update",
					"label": _("Bulk Update"),
					"description": _("Update many values at one time."),
					"hide_count": True
				},
				{
					"type": "page",
					"name": "backups",
					"label": _("Download Backups"),
					"description": _("List of backups available for download"),
					"icon": "fa fa-download"
				},
				{
					"type": "doctype",
					"name": "Deleted Document",
					"label": _("Deleted Documents"),
					"description": _("Restore or permanently delete a document.")
				},
			]
		},
		{
			"label": _("Email / Notifications"),
			"icon": "fa fa-envelope",
			"items": [
				{
					"type": "doctype",
					"name": "Email Account",
					"description": _("Add / Manage Email Accounts.")
				},
				{
					"type": "doctype",
					"name": "Email Domain",
					"description": _("Add / Manage Email Domains.")
				},
				{
					"type": "doctype",
					"name": "Notification",
					"description": _("Setup Notifications based on various criteria.")
				},
				{
					"type": "doctype",
					"name": "Email Template",
					"description": _("Email Templates for common queries.")
				},
				{
					"type": "doctype",
					"name": "Auto Email Report",
					"description": _("Setup Reports to be emailed at regular intervals"),
				},
				{
					"type": "doctype",
					"name": "Newsletter",
					"description": _("Create and manage newsletter")
				},
				{
					"type": "doctype",
					"route": "Form/Notification Settings/{}".format(frappe.session.user),
					"name": "Notification Settings",
					"description": _("Configure notifications for mentions, assignments, energy points and more.")
				}
			]
		},
		{
			"label": _("Printing"),
			"icon": "fa fa-print",
			"items": [
				{
					"type": "page",
					"label": _("Print Format Builder"),
					"name": "print-format-builder",
					"description": _("Drag and Drop tool to build and customize Print Formats.")
				},
				{
					"type": "doctype",
					"name": "Print Settings",
					"description": _("Set default format, page size, print style etc.")
				},
				{
					"type": "doctype",
					"name": "Print Format",
					"description": _("Customized HTML Templates for printing transactions.")
				},
				{
					"type": "doctype",
					"name": "Print Style",
					"description": _("Stylesheets for Print Formats")
				},
			]
		},
		{
			"label": _("Workflow"),
			"icon": "fa fa-random",
			"items": [
				{
					"type": "doctype",
					"name": "Workflow",
					"description": _("Define workflows for forms.")
				},
				{
					"type": "doctype",
					"name": "Workflow State",
					"description": _("States for workflow (e.g. Draft, Approved, Cancelled).")
				},
				{
					"type": "doctype",
					"name": "Workflow Action",
					"description": _("Actions for workflow (e.g. Approve, Cancel).")
				},
			]
		},
		{
			"label": _("Automation"),
			"icon": "fa fa-random",
			"items": [
				{
					"type": "doctype",
					"name": "Assignment Rule",
					"description": _("Set up rules for user assignments.")
				},
				{
					"type": "doctype",
					"name": "Milestone",
					"description": _("Tracks milestones on the lifecycle of a document if it undergoes multiple stages.")
				},
				{
					"type": "doctype",
					"name": "Auto Repeat",
					"description": _("Automatically generates recurring documents.")
				},
			]
		},
	]
	add_setup_section(data, "frappe", "website", _("Website"), "fa fa-globe")
	return data


text:
const CopyWebpackPlugin = require('copy-webpack-plugin');
const path = require('path');

module.exports = {
  context: path.join(__dirname, 'app'),
  entry: {
    'main': path.join(__dirname, 'app/assets/js/main.js')
  },
  devtool: 'source-map',
  output: {
    path: path.join(__dirname, 'dist'),
    filename: 'assets/js/[name].js'
  },
  devServer: {
    inline: true,
    progress: true,
    colors: true,
    open: true,
    contentBase: path.join(__dirname, 'dist')
  },
  module: {
    loaders: [
      {
        test: /\.js$/,
        exclude: /(node_modules|bower_components)/,
        loader: 'babel-loader',
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
  plugins: [
    new CopyWebpackPlugin([
      {
        from: '*.html'
      }
    ])
  ]
};


text:
//
//  NSDictionary+Ext.h
//  Tinfinite
//
//  Created by yewei on 14/11/21.
//  Copyright (c) 2014年 Tinfinite. All rights reserved.
//

#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface NSDictionary (T8)

/**
 返回指定key的字符串值
 没有指定key的值,返回默认值
 */
-(NSString *)stringForKey:(NSString *)key withDefault:(NSString *)defVal;
/**
 返回指定key的字典
 没有指定key的值,返回默认值
 */
-(NSDictionary *)dictForKey:(NSString *)key withDefault:(NSDictionary *)defVal;
/**
 返回指定key的数组
 没有指定key的值,返回默认值
 */
-(NSArray *)arrayForKey:(NSString *)key withDefault:(NSArray *)defVal;
/**
 返回指定key的float值
 没有指定key的值,返回默认值
 */
-(CGFloat)floatForKey:(NSString *)key withDefault:(CGFloat)defVal;
/**
 返回指定key的timeInterval值
 没有指定key的值,返回默认值
 */
-(NSTimeInterval)timeIntervalForKey:(NSString *)key withDefault:(NSTimeInterval)defVal;
/**
 返回指定key的integer值
 没有指定key的值,返回默认值
 */
-(NSInteger)intForKey:(NSString *)key withDefault:(NSInteger)defVal;
/**
 返回指定key的long long值
 没有指定key的值,返回默认值
 */
-(long long)longLongForKey:(NSString *)key withDefault:(long long)defVal;
/**
 返回指定key的long值
 没有指定key的值,返回默认值
 */
-(long)longForKey:(NSString *)key withDefault:(long)defVal;
/**
 返回指定key的int值
 没有指定key的值,返回默认值
 */
-(int)intValueForKey:(NSString *)key withDefault:(int)defVal;

@end


text:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="@dimen/activity_vertical_margin">

    <TextView
        android:id="@+id/item_tv"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/primary_text"
        android:layout_centerInParent="true"
        android:textSize="25sp" />
</RelativeLayout>


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Recomendacoes;

/**
 * RecomendacoesSearch represents the model behind the search form about `app\models\Recomendacoes`.
 */
class RecomendacoesSearch extends Recomendacoes
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'idCandidato', 'anoTitulacao', 'dominio', 'aprendizado', 'assiduidade', 'relacionamento', 'iniciativa', 'expressao', 'ingles', 'classificacao', 'anoContato', 'conheceGraduacao', 'conhecePos', 'conheceEmpresa', 'conheceOutros', 'orientador', 'professor', 'empregador', 'coordenador', 'colegaCurso', 'colegaTrabalho', 'outrosContatos'], 'integer'],
            [['dataEnvio', 'prazo', 'nome', 'email', 'token', 'titulacao', 'cargo', 'instituicaoTitulacao', 'instituicaoAtual', 'informacoes', 'outrosLugares', 'outrasFuncoes'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Recomendacoes::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'idCandidato' => $this->idCandidato,
            'dataEnvio' => $this->dataEnvio,
            'prazo' => $this->prazo,
            'anoTitulacao' => $this->anoTitulacao,
            'dominio' => $this->dominio,
            'aprendizado' => $this->aprendizado,
            'assiduidade' => $this->assiduidade,
            'relacionamento' => $this->relacionamento,
            'iniciativa' => $this->iniciativa,
            'expressao' => $this->expressao,
            'ingles' => $this->ingles,
            'classificacao' => $this->classificacao,
            'anoContato' => $this->anoContato,
            'conheceGraduacao' => $this->conheceGraduacao,
            'conhecePos' => $this->conhecePos,
            'conheceEmpresa' => $this->conheceEmpresa,
            'conheceOutros' => $this->conheceOutros,
            'orientador' => $this->orientador,
            'professor' => $this->professor,
            'empregador' => $this->empregador,
            'coordenador' => $this->coordenador,
            'colegaCurso' => $this->colegaCurso,
            'colegaTrabalho' => $this->colegaTrabalho,
            'outrosContatos' => $this->outrosContatos,
        ]);

        $query->andFilterWhere(['like', 'nome', $this->nome])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', 'token', $this->token])
            ->andFilterWhere(['like', 'titulacao', $this->titulacao])
            ->andFilterWhere(['like', 'cargo', $this->cargo])
            ->andFilterWhere(['like', 'instituicaoTitulacao', $this->instituicaoTitulacao])
            ->andFilterWhere(['like', 'instituicaoAtual', $this->instituicaoAtual])
            ->andFilterWhere(['like', 'informacoes', $this->informacoes])
            ->andFilterWhere(['like', 'outrosLugares', $this->outrosLugares])
            ->andFilterWhere(['like', 'outrasFuncoes', $this->outrasFuncoes]);

        return $dataProvider;
    }
}


text:
import ActiveModelSerializer from './active-model-serializer';
import { camelize, singularize, pluralize } from '../utils/inflector';

export default ActiveModelSerializer.extend({

  keyForModel(type) {
    return camelize(type);
  },

  keyForAttribute(attr) {
    return camelize(attr);
  },

  keyForRelationship(type) {
    return camelize(pluralize(type));
  },

  keyForEmbeddedRelationship(attributeName) {
    return camelize(attributeName);
  },

  keyForRelationshipIds(type) {
    return camelize(pluralize(type));
  },

  keyForForeignKey(relationshipName) {
    return camelize(singularize(relationshipName));
  },

  getCoalescedIds(request) {
    return request.queryParams && request.queryParams.ids;
  }

});


text:
import functools

from framework.auth import Auth

from website.archiver import (
    StatResult, AggregateStatResult,
    ARCHIVER_NETWORK_ERROR,
    ARCHIVER_SIZE_EXCEEDED,
    ARCHIVER_FILE_NOT_FOUND,
    ARCHIVER_FORCED_FAILURE,
)

from website import (
    mails,
    settings
)
from website.util import sanitize

def send_archiver_size_exceeded_mails(src, user, stat_result):
    mails.send_mail(
        to_addr=settings.SUPPORT_EMAIL,
        mail=mails.ARCHIVE_SIZE_EXCEEDED_DESK,
        user=user,
        src=src,
        stat_result=stat_result
    )
    mails.send_mail(
        to_addr=user.username,
        mail=mails.ARCHIVE_SIZE_EXCEEDED_USER,
        user=user,
        src=src,
        can_change_preferences=False,
        mimetype='html',
    )

def send_archiver_copy_error_mails(src, user, results):
    mails.send_mail(
        to_addr=settings.SUPPORT_EMAIL,
        mail=mails.ARCHIVE_COPY_ERROR_DESK,
        user=user,
        src=src,
        results=results,
    )
    mails.send_mail(
        to_addr=user.username,
        mail=mails.ARCHIVE_COPY_ERROR_USER,
        user=user,
        src=src,
        results=results,
        can_change_preferences=False,
        mimetype='html',
    )

def send_archiver_file_not_found_mails(src, user, results):
    mails.send_mail(
        to_addr=settings.SUPPORT_EMAIL,
        mail=mails.ARCHIVE_FILE_NOT_FOUND_DESK,
        user=user,
        src=src,
        results=results,
    )
    mails.send_mail(
        to_addr=user.username,
        mail=mails.ARCHIVE_FILE_NOT_FOUND_USER,
        user=user,
        src=src,
        results=results,
        can_change_preferences=False,
        mimetype='html',
    )

def send_archiver_uncaught_error_mails(src, user, results):
    mails.send_mail(
        to_addr=settings.SUPPORT_EMAIL,
        mail=mails.ARCHIVE_UNCAUGHT_ERROR_DESK,
        user=user,
        src=src,
        results=results,
    )
    mails.send_mail(
        to_addr=user.username,
        mail=mails.ARCHIVE_UNCAUGHT_ERROR_USER,
        user=user,
        src=src,
        results=results,
        can_change_preferences=False,
        mimetype='html',
    )

def handle_archive_fail(reason, src, dst, user, result):
    if reason == ARCHIVER_NETWORK_ERROR:
        send_archiver_copy_error_mails(src, user, result)
    elif reason == ARCHIVER_SIZE_EXCEEDED:
        send_archiver_size_exceeded_mails(src, user, result)
    elif reason == ARCHIVER_FILE_NOT_FOUND:
        send_archiver_file_not_found_mails(src, user, result)
    elif reason == ARCHIVER_FORCED_FAILURE:  # Forced failure using scripts.force_fail_registration
        pass
    else:  # reason == ARCHIVER_UNCAUGHT_ERROR
        send_archiver_uncaught_error_mails(src, user, result)
    dst.root.sanction.forcibly_reject()
    dst.root.sanction.save()
    dst.root.delete_registration_tree(save=True)

def archive_provider_for(node, user):
    """A generic function to get the archive provider for some node, user pair.

    :param node: target node
    :param user: target user (currently unused, but left in for future-proofing
    the code for use with archive providers other than OSF Storage)
    """
    return node.get_addon(settings.ARCHIVE_PROVIDER)

def has_archive_provider(node, user):
    """A generic function for checking whether or not some node, user pair has
    an attached provider for archiving

    :param node: target node
    :param user: target user (currently unused, but left in for future-proofing
    the code for use with archive providers other than OSF Storage)
    """
    return node.has_addon(settings.ARCHIVE_PROVIDER)

def link_archive_provider(node, user):
    """A generic function for linking some node, user pair with the configured
    archive provider

    :param node: target node
    :param user: target user (currently unused, but left in for future-proofing
    the code for use with archive providers other than OSF Storage)
    """
    addon = node.get_or_add_addon(settings.ARCHIVE_PROVIDER, auth=Auth(user), log=False)
    if hasattr(addon, 'on_add'):
        addon.on_add()
    node.save()

def aggregate_file_tree_metadata(addon_short_name, fileobj_metadata, user):
    """Recursively traverse the addon's file tree and collect metadata in AggregateStatResult

    :param src_addon: AddonNodeSettings instance of addon being examined
    :param fileobj_metadata: file or folder metadata of current point of reference
    in file tree
    :param user: archive initatior
    :return: top-most recursive call returns AggregateStatResult containing addon file tree metadata
    """
    disk_usage = fileobj_metadata.get('size')
    if fileobj_metadata['kind'] == 'file':
        result = StatResult(
            target_name=fileobj_metadata['name'],
            target_id=fileobj_metadata['path'].lstrip('/'),
            disk_usage=disk_usage or 0,
        )
        return result
    else:
        return AggregateStatResult(
            target_id=fileobj_metadata['path'].lstrip('/'),
            target_name=fileobj_metadata['name'],
            targets=[aggregate_file_tree_metadata(addon_short_name, child, user) for child in fileobj_metadata.get('children', [])],
        )

def before_archive(node, user):
    from website.archiver.model import ArchiveJob
    link_archive_provider(node, user)
    job = ArchiveJob.objects.create(
        src_node=node.registered_from,
        dst_node=node,
        initiator=user
    )
    job.set_targets()

def _do_get_file_map(file_tree):
    """Reduces a tree of folders and files into a list of (<sha256>, <file_metadata>) pairs
    """
    file_map = []
    stack = [file_tree]
    while len(stack):
        tree_node = stack.pop(0)
        if tree_node['kind'] == 'file':
            file_map.append((tree_node['extra']['hashes']['sha256'], tree_node))
        else:
            stack = stack + tree_node['children']
    return file_map

def _memoize_get_file_map(func):
    cache = {}
    @functools.wraps(func)
    def wrapper(node):
        if node._id not in cache:
            osf_storage = node.get_addon('osfstorage')
            file_tree = osf_storage._get_file_tree(user=node.creator)
            cache[node._id] = _do_get_file_map(file_tree)
        return func(node, cache[node._id])
    return wrapper

@_memoize_get_file_map
def get_file_map(node, file_map):
    """
    note:: file_map is injected implictly by the decorator; this method is called like:

    get_file_map(node)
    """
    for (key, value) in file_map:
        yield (key, value, node._id)
    for child in node.nodes_primary:
        for key, value, node_id in get_file_map(child):
            yield (key, value, node_id)

def find_registration_file(value, node):
    from osf.models import AbstractNode as Node
    orig_sha256 = value['sha256']
    orig_name = sanitize.unescape_entities(
        value['selectedFileName'],
        safe={
            '<': '<',
            '>': '>'
        }
    )
    orig_node = value['nodeId']
    file_map = get_file_map(node)
    for sha256, value, node_id in file_map:
        registered_from_id = Node.load(node_id).registered_from._id
        if sha256 == orig_sha256 and registered_from_id == orig_node and orig_name == value['name']:
            return value, node_id
    return None, None

def find_registration_files(values, node):
    ret = []
    for i in range(len(values.get('extra', []))):
        ret.append(find_registration_file(values['extra'][i], node) + (i,))
    return ret

def get_title_for_question(schema, path):
    path = path.split('.')
    root = path.pop(0)
    item = None
    for page in schema['pages']:
        questions = {
            q['qid']: q
            for q in page['questions']
        }
        if root in questions:
            item = questions[root]
    title = item.get('title')
    while len(path):
        item = item.get(path.pop(0), {})
        title = item.get('title', title)
    return title

def find_selected_files(schema, metadata):
    targets = []
    paths = [('', p) for p in schema.schema['pages']]
    while len(paths):
        prefix, path = paths.pop(0)
        if path.get('questions'):
            paths = paths + [('', q) for q in path['questions']]
        elif path.get('type'):
            qid = path.get('qid', path.get('id'))
            if path['type'] == 'object':
                paths = paths + [('{}.{}.value'.format(prefix, qid), p) for p in path['properties']]
            elif path['type'] == 'osf-upload':
                targets.append('{}.{}'.format(prefix, qid).lstrip('.'))
    selected = {}
    for t in targets:
        parts = t.split('.')
        value = metadata.get(parts.pop(0))
        while value and len(parts):
            value = value.get(parts.pop(0))
        if value:
            selected[t] = value
    return selected

VIEW_FILE_URL_TEMPLATE = '/project/{node_id}/files/osfstorage/{path}/'

def deep_get(obj, path):
    parts = path.split('.')
    item = obj
    key = None
    while len(parts):
        key = parts.pop(0)
        item[key] = item.get(key, {})
        item = item[key]
    return item

def migrate_file_metadata(dst, schema):
    metadata = dst.registered_meta[schema._id]
    missing_files = []
    selected_files = find_selected_files(schema, metadata)
    for path, selected in selected_files.items():
        for registration_file, node_id, index in find_registration_files(selected, dst):
            if not registration_file:
                missing_files.append({
                    'file_name': selected['extra'][index]['selectedFileName'],
                    'question_title': get_title_for_question(schema.schema, path)
                })
                continue
            target = deep_get(metadata, path)
            target['extra'][index]['viewUrl'] = VIEW_FILE_URL_TEMPLATE.format(node_id=node_id, path=registration_file['path'].lstrip('/'))
    if missing_files:
        from website.archiver.tasks import ArchivedFileNotFound
        raise ArchivedFileNotFound(
            registration=dst,
            missing_files=missing_files
        )
    dst.registered_meta[schema._id] = metadata
    dst.save()