text:
# Remainder - modular arithmetic

# systematically restrict computation to a range
# long division - divide by a number, we get a quotient plus a remainder
# quotient is integer division //, the remainder is % (Docs)

# problem - get the ones digit of a number
num = 49
tens = num // 10
ones = num % 10
print tens, ones
print 10 * tens + ones, num

# application - 24 hour clock
# http://en.wikipedia.org/wiki/24-hour_clock

hour = 20
shift = 8
print (hour + shift) % 24

# application - screen wraparound
# Spaceship from week seven

width = 800
position = 797
move = 5
position = (position + move) % width
print position

# Data conversion operations

# convert an integer into string - str
# convert an hour into 24-hour format "03:00", always print leading zero

hour = 3
ones = hour % 10
tens = hour // 10
print tens, ones, ":00"
print str(tens), str(ones), ":00"
print str(tens) + str(ones) + ":00"

# convert a string into numbers using int and float

# Python modules - extra functions implemented outside basic Python

import simplegui    # access to drawing operations for interactive applications

import math         # access to standard math functions, e.g; trig

import random       # functions to generate random numbers

# look in Docs for useful functions

print math.pi


text:
class "SceneManager"

function SceneManager:SceneManager(...)
	for k,v in pairs(arg) do
		if type(v) == "table" then
			if v.__ptr ~= nil then
				arg[k] = v.__ptr
			end
		end
	end
	if self.__ptr == nil and arg[1] ~= "__skip_ptr__" then
		self.__ptr = Polycore.SceneManager(unpack(arg))
		Polycore.__ptr_lookup[self.__ptr] = self
	end
end

function SceneManager:addScene(newScene)
	local retVal = Polycore.SceneManager_addScene(self.__ptr, newScene.__ptr)
end

function SceneManager:Update()
	local retVal =  Polycore.SceneManager_Update(self.__ptr)
end

function SceneManager:UpdateVirtual()
	local retVal =  Polycore.SceneManager_UpdateVirtual(self.__ptr)
end

function SceneManager:removeScene(scene)
	local retVal = Polycore.SceneManager_removeScene(self.__ptr, scene.__ptr)
end

function SceneManager:registerRenderTexture(r_enderTexture)
	local retVal = Polycore.SceneManager_registerRenderTexture(self.__ptr, r_enderTexture.__ptr)
end

function SceneManager:__delete()
	Polycore.__ptr_lookup[self.__ptr] = nil
	Polycore.delete_SceneManager(self.__ptr)
end

redpajama_set_name: RedPajamaGithub


text:
import axios from 'axios';
import expiresSoon from './expires-soon';

const ENVIRONMENTS = {
  staging: 'https://api.staging.seniorvu.com',
  prod: 'https://api.seniorvu.com',
};
const DEFAULT_OPTS = {};

const PATHS = [
  'address',
  'amenities',
  'analyticsUrl',
  'appointments',
  'archivedLeads',
  'assets',
  'available',
  'awsSettings',
  'batchCreate',
  'calls',
  'carers',
  'cartItems',
  'claimRequests',
  'communities',
  'deleteCreated',
  'deviceTokens',
  'events',
  'forgotPassword',
  'hours',
  'image',
  'leads',
  'me',
  'neighborhoods',
  'password',
  'payment',
  'predict',
  'priorities',
  'proximity',
  'purchasedLeads',
  'reset',
  'reviews',
  'rooms',
  'statuses',
  'tasks',
  'tours',
  'upload',
  'users',
  'video',
  'webhook',
];

export default class SeniorVu {
  constructor(opts = {}, ax) {
    if (ax) this.ax = ax;
    else this.ax = axios.create();

    this.config(opts);

    // Create functions for each XHR verb
    ['get', 'post', 'put', 'delete'].forEach(verb => {
      this[verb] = body => {
        opts = {};
        opts.method = verb;

        const segments = this.chain && this.chain.segments ? this.chain.segments : [];
        opts.url = [this.opts.baseUrl].concat('api', segments).join('/');
        opts.params = this.chain.params;
        opts.data = body;

        if (verb === 'get') {
          opts.params = Object.assign({}, opts.params, body || {});
        }

        // Clear chain for reuse
        this.chain = null;

        // Should we catch a possible expired token here or let consumer handle it??
        const refresh = expiresSoon(this.expireAt) ? this.refreshToken() : Promise.resolve();

        return refresh
          .then(() => this.ax(opts))
          .then(res => ((res && res.data) ? res.data : res));
      };
    });

    this._buildMethods();
  }

  // NOTE: expose for tests. Should be a better way but mixing default/named exports is a no-no
  expiresSoon(...args) {
    return expiresSoon(...args);
  }

  config(opts = {}) {
    this.opts = this.opts || {};

    if (!opts.baseUrl && opts.env && opts.env.indexOf('staging') === 0) {
      this.opts.baseUrl = ENVIRONMENTS.staging;
    } else if (!opts.baseUrl && opts.env && opts.env.indexOf('prod') === 0) {
      this.opts.baseUrl = ENVIRONMENTS.prod;
    }

    // Delete any null props from the passed-in options
    for (const prop of Object.keys(opts)) {
      if (opts[prop] === null) {
        delete opts[prop];
      }
    }

    Object.assign(this.opts, DEFAULT_OPTS, opts);

    if (!this.opts.baseUrl) {
      this.opts.baseUrl = ENVIRONMENTS.prod;
    }

    // Handle incoming token
    if (this.opts.token) {
      this._updateToken(this.opts.token);
    }

    if (this.opts.expireAt) {
      this.expireAt = this.opts.expireAt;
    }

    return this;
  }

  authenticate(opts = {}) {
    opts = Object.assign({}, this.opts, opts);

    // Authenticate via one-time if we have one
    if (opts.oneTimeToken && this._isOneTimeToken(opts.oneTimeToken)) {
      return this.oneTimeTokenAuth(opts.oneTimeToken);
    }

    // Auth via username and password or apiKey
    if ((opts.email && opts.password) || opts.apiKey) {
      return axios.post(opts.baseUrl + '/auth/login', {
        email: opts.email,
        password: opts.password,
        apiKey: opts.apiKey,
      })
        .then(res => {
          if (res && res.data && res.data.token) {
            this.userId = res.data.userId;
            this._updateToken(res.data.token);

            return { token: this.token, userId: this.userId };
          }

          throw new Error('No token received from SeniorVu API');
        })
        .catch(error => this._handleError(error));
    }

    throw new Error('No authentication options provided');
  }

  register(opts) {
    return axios.post(this.opts.baseUrl + '/auth/registration', opts)
      .then(res => res.data)
      .catch(error => this._handleError(error));
  }

  oneTimeTokenAuth(token) {
    return this.ax(this.opts.baseUrl + '/auth/login', {
      token,
    })
      .then(res => {
        if (res && res.data.token) {
          this._updateToken(res.data.token);
        }
        if (res && res.data.userToken) {
          return {
            token: this.token,
            userToken: res.data.userToken,
          };
        }
      });
  }

  refreshToken() {
    // If a token is needed then the following request will receive a 401
    if (!this.token) return Promise.resolve();

    return this.ax({
      url: `${this.opts.baseUrl}/auth/refresh`,
      method: 'post',
      headers: { Authorization: `Bearer ${this.token}` },
    })
      .then(res => {
        if (res && res.data && res.data.token) {
          this._updateToken(res.data.token);
          this.expireAt = res.data.expireAt;
        } else {
          const e = new Error('Problem refreshing jwt');
          e.response = res;
          throw e;
        }
      })
      .catch(error => this._handleError(error));
  }

  _updateToken(token) {
    this.token = token;
    this.ax.defaults.headers.Authorization = `Bearer ${token}`;
  }

  _buildMethods() {
    for (const path of PATHS) {
      this[path] = arg => {
        return this._chain(path, arg);
      };
    }
  }

  // TODO: fix when API method exists
  _isOneTimeToken(token) {
    return /srvu-.{12,}/.test(token);
  }

  _startChain() {
    return new SeniorVuChain(this.opts, this.ax); /* eslint no-use-before-define: "off" */
  }

  _chain(...segments) {
    let instance = this;
    if (!(instance instanceof SeniorVuChain)) instance = this._startChain();

    instance.chain = instance.chain || { segments: [] };

    for (const s of segments) {
      if (s === null || s === undefined) continue;

      if (typeof s === 'object') {
        instance.chain.params = s;
      } else {
        instance.chain.segments.push(s);
      }
    }

    return instance;
  }

  _handleError(err) {
    let ex = null;
    if (err.response) {
      if (err.response.data && err.response.data.errors && err.response.data.errors.length > 0) {
        const msg = err.response.data.errors[0].message || err.response.data.errors[0];
        ex = new Error(msg);
      } else if (err.response.data) {
        ex = new Error(err.response.data);
      } else {
        ex = new Error('Unknown issue');
        ex.err = err;
      }
    } else if (err.request) {
      ex = new Error('No response from SeniorVu API');
    } else {
      ex = err;
      // ex = new Error('Error setting up request');
    }

    ex.axios = err;

    throw ex;
  }
}

class SeniorVuChain extends SeniorVu {
  authenticate() {
    throw new Error('Cannot re-authenticate while chaining a request');
  }
}


text:
class AutonAntlerMoose: public CommandBase
{
private:
	Timer* timer;
	double m_waitTime;
public:
	AutonAntlerMoose();
	void Initialize();
	void Execute();
	bool IsFinished();
	void End();
	void Interrupted();
	void SetGoal(double timeout) { m_waitTime = timeout; };
};

#endif


text:
package br.hugo.sistema.snmp;

import java.io.*;
import java.net.*;
import java.util.*;

/**
*    The class SNMPv1AgentInterface implements an interface for responding to requests sent from a remote SNMP
*   manager. The agent simply listens for requests for information, and passes requested OIDs on to concrete
*   subclasses of SNMPRequestListener. These are expected to retrieve requested information from the system,
*   and return this to the agent interface for inclusion in a response to the manager.
*   The approach is that from version 1 of SNMP, using no encryption of data. The agent listens on UDP port 161,
*   the standard SNMP port, unless an alternate (non-standard) port is supplied in the conbstructor.
*/

public class SNMPv1AgentInterface
                    implements Runnable
{
    public static final int SNMP_PORT = 161;

    // largest size for datagram packet payload; based on
    // RFC 1157, need to handle messages of at least 484 bytes
    public int receiveBufferSize = 512;

    int version = 0;

    private DatagramSocket dSocket;
    private Thread receiveThread;
    private Vector listenerVector;

    private PrintWriter errorLog;

    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the standard SNMP UDP port 161.
    */

    public SNMPv1AgentInterface(int version)
        throws SocketException
    {
        this(version, SNMP_PORT, new PrintWriter(System.out));
    }

    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied local port.
    */

    public SNMPv1AgentInterface(int version, int localPort)
        throws SocketException
    {
        this(version, localPort, new PrintWriter(System.out));
    }

    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied port, and sends error messages to the specified PrintWriter.
    */

    public SNMPv1AgentInterface(int version, PrintWriter errorReceiver)
        throws SocketException
    {
        this(version, SNMP_PORT, errorReceiver);
    }

    /**
    *   Construct a new agent object to listen for requests from remote SNMP managers. The agent listens
    *   on the supplied port, and sends error messages to the specified PrintWriter.
    */

    public SNMPv1AgentInterface(int version, int localPort, PrintWriter errorReceiver)
        throws SocketException
    {

        this.version = version;

        dSocket = new DatagramSocket(localPort);

        listenerVector = new Vector();

        receiveThread = new Thread(this);

        errorLog = errorReceiver;

    }

    /**
    *    Set the specified PrintWriter to receive error messages.
    */

    public void setErrorReceiver(PrintWriter errorReceiver)
    {
        errorLog = errorReceiver;
    }

    public void addRequestListener(SNMPRequestListener listener)
    {
        // see if listener already added; if so, ignore
        for (int i = 0; i < listenerVector.size(); i++)
        {
            if (listener == listenerVector.elementAt(i))
            {
                return;
            }
        }

        // if got here, it's not in the list; add it
        listenerVector.add(listener);
    }

    public void removeRequestListener(SNMPRequestListener listener)
    {
        // see if listener in list; if so, remove, if not, ignore
        for (int i = 0; i < listenerVector.size(); i++)
        {
            if (listener == listenerVector.elementAt(i))
            {
                listenerVector.removeElementAt(i);
                break;
            }
        }

    }

    /**
    *    Start listening for requests from remote managers.
    */

    public void startReceiving()
    {
        // if receiveThread not already running, start it
        if (!receiveThread.isAlive())
        {
            receiveThread = new Thread(this);
            receiveThread.start();
        }
    }

    /**
    *    Stop listening for requests from remote managers.
    */

    public void stopReceiving()
        throws SocketException
    {
        // interrupt receive thread so it will die a natural death
        receiveThread.interrupt();
    }

    /**
    *    The run() method for the agent interface's listener. Just waits for SNMP request messages to
    *    come in on port 161 (or the port supplied in the constructor), then dispatches the retrieved
    *   SNMPPDU and community name to each of the registered SNMPRequestListeners by calling their
    *   processRequest() methods.
    */

    public void run()
    {

        while (!receiveThread.isInterrupted())
        {

            try
            {

                DatagramPacket inPacket = new DatagramPacket(new byte[receiveBufferSize], receiveBufferSize);

                dSocket.receive(inPacket);

                InetAddress requesterAddress = inPacket.getAddress();
                int requesterPort = inPacket.getPort();

                byte[] encodedMessage = inPacket.getData();

                /*
                System.out.println("Message bytes length (in): " + inPacket.getLength());

                System.out.println("Message bytes (in):");
                for (int i = 0; i < encodedMessage.length; ++i)
                {
                    System.out.print(hexByte(encodedMessage[i]) + " ");
                }
                System.out.println("\n");
                */

                SNMPMessage receivedMessage = new SNMPMessage(SNMPBERCodec.extractNextTLV(encodedMessage,0).value);

                String communityName = receivedMessage.getCommunityName();
                SNMPPDU receivedPDU = receivedMessage.getPDU();
                byte requestPDUType = receivedPDU.getPDUType();

                //System.out.println("Received message; community = " + communityName + ", pdu type = " + Byte.toString(requestPDUType));
                //System.out.println("  read community = " + readCommunityName + ", write community = " + writeCommunityName);

                SNMPSequence requestedVarList = receivedPDU.getVarBindList();

                Hashtable variablePairHashtable = new Hashtable();
                SNMPSequence responseVarList = new SNMPSequence();
                int errorIndex = 0;
                int errorStatus = SNMPRequestException.NO_ERROR;
                int requestID = receivedPDU.getRequestID();

                try
                {

                    // pass the received PDU and community name to the processRequest method of any listeners;
                    // handle differently depending on whether the request is a get-next, or a get or set

                    if ((requestPDUType == SNMPBERCodec.SNMPGETREQUEST) || (requestPDUType == SNMPBERCodec.SNMPSETREQUEST))
                    {

                        // pass the received PDU and community name to any registered listeners
                        for (int i = 0; i < listenerVector.size(); i++)
                        {
                            SNMPRequestListener listener = (SNMPRequestListener)listenerVector.elementAt(i);

                            // return value is sequence of variable pairs for those OIDs handled by the listener
                            SNMPSequence handledVarList = listener.processRequest(receivedPDU, communityName);

                            // add to Hashtable of handled OIDs, if not already there
                            for (int j = 0; j < handledVarList.size(); j++)
                            {

                                SNMPSequence handledPair = (SNMPSequence)handledVarList.getSNMPObjectAt(j);
                                SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)handledPair.getSNMPObjectAt(0);
                                SNMPObject snmpObject = (SNMPObject)handledPair.getSNMPObjectAt(1);

                                if (!variablePairHashtable.containsKey(snmpOID))
                                {
                                    variablePairHashtable.put(snmpOID, snmpObject);
                                }

                            }

                        }

                        // construct response containing the handled OIDs; if any OID not handled, throw exception
                        for (int j = 0; j < requestedVarList.size(); j++)
                        {
                            SNMPSequence requestPair = (SNMPSequence)requestedVarList.getSNMPObjectAt(j);
                            SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)requestPair.getSNMPObjectAt(0);

                            // find corresponding SNMP object in hashtable
                            if (!variablePairHashtable.containsKey(snmpOID))
                            {
                                errorIndex = j + 1;
                                errorStatus = SNMPRequestException.VALUE_NOT_AVAILABLE;

                                if (requestPDUType == SNMPBERCodec.SNMPGETREQUEST)
                                    throw new SNMPGetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                                else
                                    throw new SNMPSetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                            }

                            SNMPObject snmpObject = (SNMPObject)variablePairHashtable.get(snmpOID);
                            SNMPVariablePair responsePair = new SNMPVariablePair(snmpOID, snmpObject);

                            responseVarList.addSNMPObject(responsePair);

                        }

                    }
                    else if (requestPDUType == SNMPBERCodec.SNMPGETNEXTREQUEST)
                    {
                        // pass the received PDU and community name to any registered listeners
                        for (int i = 0; i < listenerVector.size(); i++)
                        {
                            SNMPRequestListener listener = (SNMPRequestListener)listenerVector.elementAt(i);

                            // return value is sequence of nested variable pairs for those OIDs handled by the listener:
                            // consists of (supplied OID, (following OID, value)) nested variable pairs
                            SNMPSequence handledVarList = listener.processGetNextRequest(receivedPDU, communityName);

                            // add variable pair to Hashtable of handled OIDs, if not already there
                            for (int j = 0; j < handledVarList.size(); j++)
                            {

                                SNMPSequence handledPair = (SNMPSequence)handledVarList.getSNMPObjectAt(j);
                                SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)handledPair.getSNMPObjectAt(0);
                                SNMPObject snmpObject = (SNMPObject)handledPair.getSNMPObjectAt(1);

                                if (!variablePairHashtable.containsKey(snmpOID))
                                {
                                    variablePairHashtable.put(snmpOID, snmpObject);
                                }

                            }

                        }

                        // construct response containing the handled OIDs; if any OID not handled, throw exception
                        for (int j = 0; j < requestedVarList.size(); j++)
                        {
                            SNMPSequence requestPair = (SNMPSequence)requestedVarList.getSNMPObjectAt(j);
                            SNMPObjectIdentifier snmpOID = (SNMPObjectIdentifier)requestPair.getSNMPObjectAt(0);

                            // find corresponding SNMP object in hashtable
                            if (!variablePairHashtable.containsKey(snmpOID))
                            {
                               errorIndex = j + 1;
                               errorStatus = SNMPRequestException.VALUE_NOT_AVAILABLE;

                               throw new SNMPGetException("OID " + snmpOID + " not handled", errorIndex, errorStatus);
                            }

                            // value in hashtable is complete variable pair
                            SNMPVariablePair responsePair = (SNMPVariablePair)variablePairHashtable.get(snmpOID);

                            responseVarList.addSNMPObject(responsePair);

                        }

                    }
                    else
                    {
                        // some other PDU type; silently ignore
                        continue;
                    }

                }
                catch (SNMPRequestException e)
                {
                    // exception should contain the index and cause of error; return this in message
                    errorIndex = e.errorIndex;
                    errorStatus = e.errorStatus;

                    // just return request variable list as response variable list
                    responseVarList = requestedVarList;
                }
                catch (Exception e)
                {
                    // don't have a specific index and cause of error; return message as general error, index 0
                    errorIndex = 0;
                    errorStatus = SNMPRequestException.FAILED;

                    // just return request variable list as response variable list
                    responseVarList = requestedVarList;

                    // also report the exception locally
                    errorLog.println("Exception while processing request: " + e.toString());
                    errorLog.flush();
                }

                SNMPPDU pdu = new SNMPPDU(SNMPBERCodec.SNMPGETRESPONSE, requestID, errorStatus, errorIndex, responseVarList);
                SNMPMessage message = new SNMPMessage(version, communityName, pdu);
                byte[] messageEncoding = message.getBEREncoding();
                DatagramPacket outPacket = new DatagramPacket(messageEncoding, messageEncoding.length, requesterAddress, requesterPort);

                dSocket.send(outPacket);

            }
            catch (IOException e)
            {
                // just report the problem
                errorLog.println("IOException during request processing: " + e.getMessage());
                errorLog.flush();
            }
            catch (SNMPBadValueException e)
            {
                // just report the problem
                errorLog.println("SNMPBadValueException during request processing: " + e.getMessage());
                errorLog.flush();
            }
            catch (Exception e)
            {
                // just report the problem
                errorLog.println("Exception during request processing: " + e.toString());
                errorLog.flush();
            }

        }

    }

    private String hexByte(byte b)
    {
        int pos = b;
        if (pos < 0)
            pos += 256;
        String returnString = new String();
        returnString += Integer.toHexString(pos/16);
        returnString += Integer.toHexString(pos%16);
        return returnString;
    }

    /**
    *   Set the size of the buffer used to receive response packets. RFC 1157 stipulates that an SNMP
    *   implementation must be able to receive packets of at least 484 bytes, so if you try to set the
    *   size to a value less than this, the receive buffer size will be set to 484 bytes. In addition,
    *   the maximum size of a UDP packet payload is 65535 bytes, so setting the buffer to a larger size
    *   will just waste memory. The default value is 512 bytes. The value may need to be increased if
    *   get-requests are issued for multiple OIDs.
    */

    public void setReceiveBufferSize(int receiveBufferSize)
    {
        if (receiveBufferSize >= 484)
        {
            this.receiveBufferSize = receiveBufferSize;
        }
        else
        {
            this.receiveBufferSize = 484;
        }
    }

    /**
    *   Returns the current size of the buffer used to receive response packets.
    */

    public int getReceiveBufferSize()
    {
        return this.receiveBufferSize;
    }

}


text:
package contract

import "gopkg.in/mgo.v2/bson"

type ContractSigningRequest struct {
	Id         bson.ObjectId `json:"-" bson:"_id,omitempty"`
	ContractId string        `json:"contractId"`
	Party      string        `json:"party"`
}


text:
package net.ssehub.easy.instantiation.serializer.xml.loader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import net.ssehub.easy.basics.logger.EASyLoggerFactory;
import net.ssehub.easy.basics.logger.EASyLoggerFactory.EASyLogger;
import net.ssehub.easy.basics.messages.IMessage;
import net.ssehub.easy.basics.modelManagement.IModel;
import net.ssehub.easy.basics.modelManagement.IModelLoader;
import net.ssehub.easy.basics.modelManagement.ImportResolver;
import net.ssehub.easy.basics.modelManagement.ModelInfo;
import net.ssehub.easy.basics.modelManagement.Version;
import net.ssehub.easy.instantiation.serializer.xml.Bundle;
import net.ssehub.easy.instantiation.serializer.xml.XmlIo;
import net.ssehub.easy.varModel.model.Project;

/**
 * Loader to load IVML files.
 *
 * @author Sass
 *
 */
public class IVMLModelLoader implements IModelLoader<Project> {

    public static final IVMLModelLoader INSTANCE = new IVMLModelLoader();

    protected static EASyLogger logger = EASyLoggerFactory.INSTANCE.getLogger(IVMLModelLoader.class,
            Bundle.ID);

    private List<Project> projects;

    /**
     * Prevents external creation.
     */
    private IVMLModelLoader() {
    }

    @Override
    public net.ssehub.easy.basics.modelManagement.IModelLoader.LoadResult<Project> load(ModelInfo<Project> info,
        ImportResolver<Project> resolver) {
        LoadResult<Project> loadResult = null;
        for (Project project : projects) {
            if (info.getName().equals(project.getName()) && Version.equals(info.getVersion(), project.getVersion())) {
                List<Project> projectList = new ArrayList<Project>();
                projectList.add(project);
                loadResult = new LoadResult<Project>(projectList, new ArrayList<IMessage>());
                break;
            }
        }
        return loadResult;
    }

    @Override
    public void scan(File location,
            net.ssehub.easy.basics.modelManagement.IModelLoader.IModelInfoHolder<Project> holder) {
        if (location.getName().endsWith(".xml")) {
            projects = new ArrayList<Project>();
            try {
                List<IModel> models = XmlIo.read(location, true);
                for (IModel iModel : models) {
                    if (iModel instanceof Project) {
                        Project project = (Project) iModel;
                        projects.add(project);
                        ModelInfo<Project> projectModel = new ModelInfo<Project>(project, location.toURI(), this);
                        holder.addResult(projectModel);
                    }
                }
            } catch (FileNotFoundException e) {
                logger.exception(e);
            } catch (IOException e) {
                logger.exception(e);
            }

        }

    }

}


text:
namespace cpr {

VerifySsl::VerifySsl(bool verify) : verify_{verify} {}

VerifySsl::operator bool() const {
    return verify_;
}

} // namespace cpr


text:
                <button id="closeAddEpubCross" type="button" class="close" data-dismiss="modal" tabindex="999" title="{{strings.i18n_close}} {{strings.biblemesh_import_books}}" aria-label="{{strings.i18n_close}} {{strings.biblemesh_import_books}}">×</button>

{{strings.biblemesh_import_books}}

{{strings.biblemesh_import_instructions}}

{{strings.biblemesh_import_instructions2}}

{{strings.biblemesh_import_instructions_note}}

                <form class="form-horizontal" role="form">
                {{#canHandleUrl}}

                    {{strings.i18n_from_the_web}}

                        <input tabindex="1000" type="text" id="url-upload" class="form-control" placeholder="{{strings.i18n_enter_a_url}}" aria-labelledby="add1">

                {{/canHandleUrl}}

                    {{strings.i18n_from_local_file}}

                        <input tabindex="1000" type="file" multiple="multiple" id="epub-upload" class="form-control" aria-labelledby="add2">

                {{#canHandleDirectory}}

                    {{strings.i18n_unpacked_directory}}

                        <input tabindex="1000" type="file" id="dir-upload" webkitdirectory="" mozdirectory="" directory="" class="form-control" aria-labelledby="add3">

                {{/canHandleDirectory}}
                </form>

                <button tabindex="1000" type="button" class="btn btn-default add-book" data-dismiss="modal" disabled="disabled">{{strings.biblemesh_import_books}}</button>

                <button tabindex="1000" type="button" class="btn btn-primary" data-dismiss="modal">{{strings.i18n_cancel}}</button>


text:
<?php

namespace Ojs\ApiBundle\Controller\Journal;

use FOS\RestBundle\Controller\Annotations\View;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Ojs\JournalBundle\Form\Type\ThemeType;
use Ojs\JournalBundle\Entity\Theme;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use FOS\RestBundle\Util\Codes;
use FOS\RestBundle\Controller\Annotations;
use FOS\RestBundle\Request\ParamFetcherInterface;
use Symfony\Component\Form\FormTypeInterface;
use Ojs\ApiBundle\Exception\InvalidFormException;
use Ojs\ApiBundle\Controller\ApiController;

class JournalThemeRestController extends ApiController
{
    /**
     * List all Themes.
     *
     * @ApiDoc(
     *   resource = true,
     *   statusCodes = {
     *     200 = "Returned when successful"
     *   }
     * )
     *
     * @Annotations\QueryParam(name="offset", requirements="\d+", nullable=true, description="Offset from which to start listing Themes.")
     * @Annotations\QueryParam(name="limit", requirements="\d+", default="5", description="How many Themes to return.")
     *
     *
     * @param Request               $request      the request object
     * @param ParamFetcherInterface $paramFetcher param fetcher service
     *
     * @return array
     */
    public function getThemesAction(Request $request, ParamFetcherInterface $paramFetcher)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('VIEW', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        $offset = $paramFetcher->get('offset');
        $offset = null === $offset ? 0 : $offset;
        $limit = $paramFetcher->get('limit');
        return $this->container->get('ojs_api.journal_theme.handler')->all($limit, $offset);
    }

    /**
     * Get single Theme.
     *
     * @ApiDoc(
     *   resource = true,
     *   description = "Gets a Theme for a given id",
     *   output = "Ojs\ThemeBundle\Entity\Theme",
     *   statusCodes = {
     *     200 = "Returned when successful",
     *     404 = "Returned when the Theme is not found"
     *   }
     * )
     *
     * @param int     $id      the Theme id
     *
     * @return array
     *
     * @throws NotFoundHttpException when Theme not exist
     */
    public function getThemeAction($id)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('VIEW', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        $entity = $this->getOr404($id);
        return $entity;
    }

    /**
     * Presents the form to use to create a new Theme.
     *
     * @ApiDoc(
     *   resource = true,
     *   statusCodes = {
     *     200 = "Returned when successful"
     *   }
     * )
     *
     * @return FormTypeInterface
     */
    public function newThemeAction()
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('CREATE', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        return $this->createForm(new ThemeType(), null, ['csrf_protection' => false]);
    }

    /**
     * Create a Theme from the submitted data.
     *
     * @ApiDoc(
     *   resource = true,
     *   description = "Creates a new Theme from the submitted data.",
     *   statusCodes = {
     *     200 = "Returned when successful",
     *     400 = "Returned when the form has errors"
     *   }
     * )
     *
     * @param Request $request the request object
     *
     * @return FormTypeInterface|View
     */
    public function postThemeAction(Request $request)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('CREATE', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        try {
            $journalService = $this->container->get('ojs.journal_service');
            $newEntity = $this->container->get('ojs_api.journal_theme.handler')->post(
                $request->request->all()
            );
            $routeOptions = array(
                'id' => $newEntity->getId(),
                'journalId' => $journalService->getSelectedJournal()->getId(),
                '_format' => $request->get('_format')
            );
            return $this->routeRedirectView('api_1_get_themes', $routeOptions, Codes::HTTP_CREATED);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * Update existing Theme from the submitted data or create a new Theme at a specific location.
     *
     * @ApiDoc(
     *   resource = true,
     *   statusCodes = {
     *     201 = "Returned when the Theme is created",
     *     204 = "Returned when successful",
     *     400 = "Returned when the form has errors"
     *   }
     * )
     *
     * @param Request $request the request object
     * @param int     $id      the Theme id
     *
     * @return FormTypeInterface|View
     *
     * @throws NotFoundHttpException when Theme not exist
     */
    public function putThemeAction(Request $request, $id)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('CREATE', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        try {
            $journalService = $this->container->get('ojs.journal_service');
            if (!($entity = $this->container->get('ojs_api.journal_theme.handler')->get($id))) {
                $statusCode = Codes::HTTP_CREATED;
                $entity = $this->container->get('ojs_api.journal_theme.handler')->post(
                    $request->request->all()
                );
            } else {
                $statusCode = Codes::HTTP_NO_CONTENT;
                $entity = $this->container->get('ojs_api.journal_theme.handler')->put(
                    $entity,
                    $request->request->all()
                );
            }
            $routeOptions = array(
                'id' => $entity->getId(),
                'journalId' => $journalService->getSelectedJournal()->getId(),
                '_format' => $request->get('_format')
            );
            return $this->routeRedirectView('api_1_get_theme', $routeOptions, $statusCode);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * Update existing journal_theme from the submitted data or create a new journal_theme at a specific location.
     *
     * @ApiDoc(
     *   resource = true,
     *   statusCodes = {
     *     204 = "Returned when successful",
     *     400 = "Returned when the form has errors"
     *   }
     * )
     *
     * @param Request $request the request object
     * @param int     $id      the journal_theme id
     *
     * @return FormTypeInterface|View
     *
     * @throws NotFoundHttpException when journal_theme not exist
     */
    public function patchThemeAction(Request $request, $id)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('EDIT', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        try {
            $journalService = $this->container->get('ojs.journal_service');
            $entity = $this->container->get('ojs_api.journal_theme.handler')->patch(
                $this->getOr404($id),
                $request->request->all()
            );
            $routeOptions = array(
                'id' => $entity->getId(),
                'journalId' => $journalService->getSelectedJournal()->getId(),
                '_format' => $request->get('_format')
            );
            return $this->routeRedirectView('api_1_get_theme', $routeOptions, Codes::HTTP_NO_CONTENT);
        } catch (InvalidFormException $exception) {
            return $exception->getForm();
        }
    }

    /**
     * @param $id
     * @throws NotFoundHttpException
     * @return Response
     * @ApiDoc(
     *      resource = false,
     *      description = "Delete Theme",
     *      requirements = {
     *          {
     *              "name" = "id",
     *              "dataType" = "integer",
     *              "requirement" = "Numeric",
     *              "description" = "Theme ID"
     *          }
     *      },
     *      statusCodes = {
     *          "204" = "Deleted Successfully",
     *          "404" = "Object cannot found"
     *      }
     * )
     *
     */
    public function deleteThemeAction($id)
    {
        $journal = $this->get('ojs.journal_service')->getSelectedJournal();
        if (!$this->isGranted('DELETE', $journal, 'theme')) {
            throw new AccessDeniedHttpException;
        }
        $entity = $this->getOr404($id);
        $this->container->get('ojs_api.journal_theme.handler')->delete($entity);
        return $this->view(null, Codes::HTTP_NO_CONTENT, []);
    }

    /**
     * Fetch a Theme or throw an 404 Exception.
     *
     * @param mixed $id
     *
     * @return Theme
     *
     * @throws NotFoundHttpException
     */
    protected function getOr404($id)
    {
        if (!($entity = $this->container->get('ojs_api.journal_theme.handler')->get($id))) {
            throw new NotFoundHttpException(sprintf('The resource \'%s\' was not found.',$id));
        }
        return $entity;
    }
}


text:
from decimal import Decimal
from django.db.models.fields import DecimalField

class CurrencyField(DecimalField):
    """
    A CurrencyField is simply a subclass of DecimalField with a fixed format:
    max_digits = 30, decimal_places=2, and defaults to 0.00
    """
    def __init__(self, **kwargs):
        defaults = {
            'max_digits': 30,
            'decimal_places': 2,
            'default': Decimal('0.0')
        }
        defaults.update(kwargs)
        super(CurrencyField, self).__init__(**defaults)

    def south_field_triple(self):  # pragma: no cover
        """
        Returns a suitable description of this field for South.
        This is excluded from coverage reports since it is pretty much a piece
        of South itself, and does not influence program behavior at all in
        case we don't use South.
        """
        # We'll just introspect the _actual_ field.
        from south.modelsinspector import introspector
        field_class = "django.db.models.fields.DecimalField"
        args, kwargs = introspector(self)
        # That's our definition!
        return (field_class, args, kwargs)

def upload_to_classname(instance, filename):
    basedir = str(instance.__class__.__name__).lower()
    ext = os.path.splitext(filename)[1]
    filename = None

    if not filename and hasattr(instance, "slug") and getattr(instance, "slug"):
        filename = getattr(instance, "slug")

    if not filename and instance.pk:
        filename = "image_" + str(instance.pk)

    if not filename:
        filename = "image_" + str(random.randint(1000, 1000000))
        while os.path.exists(os.path.join(settings.MEDIA_ROOT, basedir, filename + ext)):
            filename = "image_" + str(random.randint(1000, 1000000))

    return os.path.join(settings.MEDIA_ROOT, basedir, filename + ext)


text:
[![Stories in Ready](https://badge.waffle.io/TimeoutZero/ireadme.png?label=ready&title=Ready)](https://waffle.io/TimeoutZero/ireadme)
# ireadme - Interactive Readme
Creates Todos to your workflow


text:
'use strict';

/*jshint -W117 */
/*jshint globalstrict: true*/
/* jasmine specs for directives go here */

describe('Directive: leaflet', function() {
    var $compile = null, $rootScope = null, $timeout, leafletData = null, leafletMapDefaults = null;

    beforeEach(module('leaflet-directive'));
    beforeEach(inject(function(_$compile_, _$rootScope_, _$timeout_, _leafletData_, _leafletMapDefaults_) {
        $compile = _$compile_;
        $rootScope = _$rootScope_;
        $timeout = _$timeout_;
        leafletData = _leafletData_;
        leafletMapDefaults = _leafletMapDefaults_;
    }));

    afterEach(inject(function($rootScope) {
        $rootScope.$apply();
    }));

    it('should have loaded leaflet library inside the directive', function() {
        var element = angular.element('<leaflet></leaflet>');
        element = $compile(element)($rootScope);
        $rootScope.$digest();
        expect(element.text()).toEqual('+-Leaflet | © OpenStreetMap contributors');
    });

    it('should set default center if not center is provided', function() {
        var element = angular.element('<leaflet></leaflet>');
        element = $compile(element)($rootScope);
        var leafletMap;
        leafletData.getMap().then(function(map) {
            leafletMap = map;
        });
        $rootScope.$digest();
        expect(leafletMap.getZoom()).toEqual(1);
        expect(leafletMap.getCenter().lat).toEqual(0);
        expect(leafletMap.getCenter().lng).toEqual(0);
    });

    it('should set default tile if not tiles nor layers are provided', function() {
        var element = angular.element('<leaflet></leaflet>');
        element = $compile(element)($rootScope);
        var leafletTiles;
        leafletData.getTiles().then(function(tiles) {
            leafletTiles = tiles;
        });
        $rootScope.$digest();
        var defaults = leafletMapDefaults.getDefaults();
        expect(leafletTiles._url).toEqual(defaults.tileLayer);
    });

    it('should set the max zoom if specified', function() {
        angular.extend($rootScope, { defaults: { maxZoom: 15 } });
        var element = angular.element('<leaflet defaults="defaults"></leaflet>');
        element = $compile(element)($rootScope);
        var leafletMap;
        leafletData.getMap().then(function(map) {
            leafletMap = map;
        });
        $rootScope.$digest();
        expect(leafletMap.getMaxZoom()).toEqual(15);
    });

    it('should set the min zoom if specified', function() {
        angular.extend($rootScope, { defaults: { minZoom: 4 } });
        var element = angular.element('<leaflet defaults="defaults"></leaflet>');
        element = $compile(element)($rootScope);
        var leafletMap;
        leafletData.getMap().then(function(map) {
            leafletMap = map;
        });
        $rootScope.$digest();
        expect(leafletMap.getMinZoom()).toEqual(4);
    });

    it('should set the CSS width and height if they are passed as string attributes', function() {
        var element = angular.element('<leaflet defaults="defaults" width="640px" height="480px"></leaflet>');
        element = $compile(element)($rootScope);

        expect(element.css("width")).toBe("640px");
        expect(element.css("height")).toBe("480px");
    });

    it('should set the CSS width and height if they are passed as number attributes', function() {
        var element = angular.element('<leaflet defaults="defaults" width=640 height=480></leaflet>');
        element = $compile(element)($rootScope);

        expect(element.css("width")).toBe("640px");
        expect(element.css("height")).toBe("480px");
    });

    it('should set tileLayer and tileLayer options if specified', function() {
        angular.extend($rootScope, {
            defaults: {
                tileLayer: "http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png",
                tileLayerOptions: {
                    detectRetina: true,
                    opacity: 0.8
                }
            }
        });
        var element = angular.element('<leaflet defaults="defaults"></leaflet>');
        element = $compile(element)($rootScope);
        var leafletTiles;
        leafletData.getTiles().then(function(tiles) {
            leafletTiles = tiles;
        });
        $rootScope.$digest();
        var defaults = leafletMapDefaults.getDefaults();
        expect(leafletTiles.options.detectRetina).toEqual(true);
        expect(leafletTiles.options.opacity).toEqual(0.8);
        expect(leafletTiles._url).toEqual("http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png");
        expect(defaults.tileLayer).toEqual("http://{s}.tile.opencyclemap.org/cycle/{z}/{x}/{y}.png");
    });

    it('should set zoom control button properly if zoomControlPosition option is set', function() {
        angular.extend($rootScope, {
            defaults: {
                zoomControlPosition: 'topright'
            }
        });
        var element = angular.element('<leaflet defaults="defaults"></leaflet>');
        element = $compile(element)($rootScope);
        var leafletMap;
        leafletData.getMap().then(function(map) {
            leafletMap = map;
        });
        $rootScope.$digest();
        expect(leafletMap.zoomControl.getPosition()).toEqual('topright');
    });

    it('should remove zoom control button if unset on defaults', function() {
        angular.extend($rootScope, {
            defaults: {
                zoomControl: false
            }
        });
        var element = angular.element('<leaflet defaults="defaults"></leaflet>');
        element = $compile(element)($rootScope);
        var leafletMap;
        leafletData.getMap().then(function(map) {
            leafletMap = map;
        });
        $rootScope.$digest();
        expect(leafletMap.zoomControl).toBe(undefined);
    });
});


text:
using namespace std;
using namespace fiber_bundle; // Workaround for MS C++ bug.

//==============================================================================
// CLASS ST3_LITE
//==============================================================================

//==============================================================================
// ST3 FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

fiber_bundle::st3_lite::
st3_lite()
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:
}

fiber_bundle::st3_lite::
st3_lite(const st3_lite& xother)
{
  // Preconditions:

  // Body:

  *this = xother;

  // Postconditions:

  ensure(invariant());

  // Exit:
}

fiber_bundle::st3_lite&
fiber_bundle::st3_lite::
operator=(const st3_lite& xother)
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());

  // Exit:

  return *this;
}

fiber_bundle::st3_lite::
~st3_lite()
{
  // Preconditions:

  // Body:

  // Postconditions:

  // Exit:

}

fiber_bundle::st3_lite::
st3_lite(const row_dofs_type& xrow_dofs)
{
  // Preconditions:

  // Body:

  *this = xrow_dofs;

  // Postconditions:

  ensure(invariant());

  // Exit:
}

fiber_bundle::st3_lite&
fiber_bundle::st3_lite::
operator=(const row_dofs_type& xrow_dofs)
{
  // Preconditions:

  // Body:

  vd_lite::operator=(xrow_dofs);

  // Postconditions:

  postcondition_of(vd_lite::operator=(xrow_dofs));

  // Exit:

  return *this;

}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// STP FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

int
fiber_bundle::st3_lite::
p() const
{
  // Preconditions:

  // Body:

  int result = 3;

  // Postconditions:

  ensure(invariant());
  ensure(result == 3);

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// VD FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

fiber_bundle::st3_lite::value_type
fiber_bundle::st3_lite::
component(int xi, int xj, int xk) const
{
  // Preconditions:

  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  value_type result = component(index_for_ijk(xi, xj, xk));

  // Postconditions:

  ensure(invariant());

  // Exit:

  return result;
}

void
fiber_bundle::st3_lite::
put_component(int xi, int xj, int xk, value_type xvalue)
{
  // Preconditions:

  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  put_component(index_for_ijk(xi, xj, xk), xvalue);

  // Postconditions:

  ensure(isunordered_or_equals(component(xi, xj, xk), xvalue));

  // Exit:

  return;
}

int
fiber_bundle::st3_lite::
index_for_ijk(int xi, int xj, int xk) const
{
  // Preconditions:

  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  int ldd = dd();

  // Bubble sort the indices.

  int ltmp;

  if(xi > xj) { ltmp = xi; xi = xj; xj = ltmp; }
  if(xj > xk) { ltmp = xj; xj = xk; xk = ltmp; }
  if(xi > xj) { ltmp = xi; xi = xj; xj = ltmp; }

  //$$SCRIBBLE: This works for ldd = 3 (only?).

  int result = (xi*ldd + xj)*ldd + xk;
  result -= (xi*(5 + xi) + (xj*(xj+1))/2);

  // Postconditions:

  ensure(result >= 0);
  ensure(result < d());

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// TUPLE FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// ABSTRACT POSET MEMBER FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

const std::string&
fiber_bundle::st3_lite::
class_name() const
{
  // Preconditions:

  // Body:

  const string& result = static_class_name();

  // Postconditions:

  ensure(!result.empty());

  // Exit:

  return result;
}

const std::string&
fiber_bundle::st3_lite::
static_class_name()
{
  // Preconditions:

  // Body:

  static const string result("st3_lite");

  // Postconditions:

  ensure(!result.empty());

  // Exit:

  return result;
}

fiber_bundle::st3_lite*
fiber_bundle::st3_lite::
clone() const
{
  st3_lite* result = 0;

  // Preconditions:

  // Body:

  result = new st3_lite();

  // Postconditions:

  ensure(result != 0);
  ensure(is_same_type(*result));

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// ANY FACET OF CLASS ST3_LITE
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

bool
fiber_bundle::st3_lite::
is_ancestor_of(const any_lite& xother) const
{
  // Preconditions:

  require(&xother != 0);

  // Body:

  // True if other conforms to this.

  bool result = dynamic_cast<const st3_lite*>(&xother) != 0;

  // Postconditions:

  return result;
}

bool
fiber_bundle::st3_lite::
invariant() const
{
  bool result = true;

  if(invariant_check())
  {
    // Prevent recursive calls to invariant.

    disable_invariant_check();

    // Must satisfy base class invariant.

    invariance(stp_lite::invariant());

    // Invariances for this class:

    // Finished, turn invariant checking back on.

    enable_invariant_check();
  }

  // Exit

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// CLASS ST3
//==============================================================================

// ===========================================================
// HOST FACTORY FACET OF CLASS ST2
// ===========================================================

// PUBLIC MEMBER FUNCTIONS

const sheaf::poset_path&
fiber_bundle::st3::
standard_schema_path()
{
  // Preconditions:

  // Body:

  static const poset_path result(standard_schema_poset_name(), "st3_schema");

  // Postconditions:

  // Exit:

  return result;
}

void
fiber_bundle::st3::
make_standard_schema(namespace_poset& xns)
{
  // Preconditions:

  require(xns.state_is_read_write_accessible());
  require(xns.contains_poset(standard_schema_poset_name()));
  require(!xns.contains_poset_member(standard_schema_path()));

  // Body:

  schema_poset_member lschema(xns,
                              standard_schema_path().member_name(),
                              stp::standard_schema_path(),
                              "",
                              false);

  lschema.detach_from_state();

  // Postconditions:

  ensure(xns.contains_poset_member(standard_schema_path()));

  // Exit:

  return;
}

fiber_bundle::st3::host_type&
fiber_bundle::st3::
new_host(namespace_type& xns,
         const poset_path& xhost_path,
         const poset_path& xschema_path,
         const poset_path& xvector_space_path,
         bool xauto_access)
{
  // cout << endl << "Entering st3::new_host." << endl;

  // Preconditions:

  require(xns.state_is_auto_read_write_accessible(xauto_access));

  require(!xhost_path.empty());
  require(!xns.contains_path(xhost_path, xauto_access));

  require(xschema_path.full());
  require(xns.path_is_auto_read_accessible(xschema_path, xauto_access));
  require(schema_poset_member::conforms_to(xns, xschema_path, standard_schema_path()));

  require(xns.path_is_auto_read_accessible(xvector_space_path, xauto_access));
  require(xns.contains_poset<scalar_type::host_type>(xvector_space_path, xauto_access));

  // Body:

  host_type& result =
    host_type::new_table(xns, xhost_path, xschema_path, 3, xvector_space_path, xauto_access);

  // Postconditions:

  ensure(xns.owns(result, xauto_access));
  ensure(result.path(true) == xhost_path);
  ensure(result.state_is_not_read_accessible());
  ensure(result.schema(true).path(xauto_access) == xschema_path);

  ensure(result.factor_ct(true) == result.d(true));
  ensure(result.d(true) == schema_poset_member::row_dof_ct(xns, xschema_path, xauto_access));
  ensure(result.vector_space_path(true) == xvector_space_path );
  ensure(result.p(true) == 3);
  ensure(result.dd(true) == result.d(true));
  ensure(result.vector_space_path(true) == xhost_path );

  // Exit:

  // cout << "Leaving st3::new_host." << endl;
  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// ST3 FACET OF CLASS ST3
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

fiber_bundle::st3::
st3()
{

  // Preconditions:

  // Body:

  // Postconditions:

  ensure(invariant());
}

fiber_bundle::st3::
st3(const poset_state_handle* xhost, pod_index_type xhub_id)
{
  // Preconditions:

  require(xhost != 0);
  require(xhost->state_is_read_accessible());
  require(xhost->contains_member(xhub_id));

  // Body:

  attach_to_state(xhost, xhub_id);

  // Postconditions:

  ensure(invariant());
  // ensure(host() == xhost);
  ensure(index() == xhub_id);
  ensure(is_attached());
}

fiber_bundle::st3::
st3(const poset_state_handle* xhost, const scoped_index& xid)
{
  // Preconditions:

  require(xhost != 0);
  require(xhost->state_is_read_accessible());
  require(xhost->contains_member(xid));

  // Body:

  attach_to_state(xhost, xid.hub_pod());

  // Postconditions:

  ensure(invariant());
  // ensure(host() == xhost);
  ensure(index() ==~ xid);
  ensure(is_attached());
}

fiber_bundle::st3::
st3(const poset_state_handle* xhost, const std::string& xname)
{

  // Preconditions:

  require(xhost != 0);
  require(xhost->state_is_read_accessible());
  require(!xname.empty());
  require(xhost->contains_member(xname));

  // Body:

  attach_to_state(xhost, xname);

  // Postconditions:

  ensure(invariant());
  // ensure(host() == xhost);
  ensure(name() == xname);
  ensure(is_attached());

}

fiber_bundle::st3::
st3(abstract_poset_member* xother)
{

  // Preconditions:

  require(xother != 0);

  // Body:

  attach_to_state(xother);

  // Postconditions:

  ensure(invariant());
  ensure(is_attached());
  ensure(is_same_state(xother));

}

fiber_bundle::st3::
st3(poset_state_handle* xhost, bool xauto_access)
{

  // Preconditions:

  require(precondition_of(new_jim_state(xhost, 0, false, xauto_access)));

  // Body:

  new_jim_state(xhost, 0, false, xauto_access);

  // Postconditions:

  ensure(postcondition_of(new_jim_state(xhost, 0, false, xauto_access)));

  // Exit:

  return;
}

///
fiber_bundle::st3&
fiber_bundle::st3::
operator=(const abstract_poset_member& xother)
{
  // Preconditions:

  require(is_ancestor_of(&xother));
  require(precondition_of(attach_to_state(&xother)));

  // Body:

  attach_to_state(&xother);

  // Postconditions:

  ensure(postcondition_of(attach_to_state(&xother)));

  // Exit:

  return *this;
}

///
fiber_bundle::st3&
fiber_bundle::st3::
operator=(const st3& xother)
{
  // Preconditions:

  require(precondition_of(attach_to_state(&xother)));

  // Body:

  attach_to_state(&xother);

  // Postconditions:

  ensure(postcondition_of(attach_to_state(&xother)));

  // Exit:

  return *this;
}

fiber_bundle::st3::
~st3()
{

  // Preconditions:

  // Body:

  // Postconditions:

}

const fiber_bundle::st3::volatile_type&
fiber_bundle::st3::
lite_prototype() const
{
  // Preconditions:

  // Body:

  static const volatile_type result;

  // Postconditions:

  // Exit:

  return result;
}

///
fiber_bundle::st3::volatile_type*
fiber_bundle::st3::
lite_type() const
{
  // Preconditions:

  // Body:

  volatile_type* result = new volatile_type(sheaf::row_dofs(*this));

  // Postconditions:

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// VD FACET OF CLASS ST3
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

fiber_bundle::st3::value_type
fiber_bundle::st3::
component(int xi, int xj, int xk) const
{
  // Preconditions:

  require(state_is_read_accessible());
  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  value_type result = component(index_for_ijk(xi, xj, xk));

  // Postconditions:

  ensure(invariant());

  // Exit:

  return result;
}

fiber_bundle::st3::value_type
fiber_bundle::st3::
component(int xi, int xj, int xk, bool xauto_access) const
{
  // Preconditions:

  require(state_is_auto_read_accessible(xauto_access));
  require((0 <= xi) && (xi < dd(xauto_access)));
  require((0 <= xj) && (xj < dd(xauto_access)));
  require((0 <= xk) && (xk < dd(xauto_access)));

  // Body:

  if(xauto_access)
  {
    get_read_access();
  }

  value_type result = component(index_for_ijk(xi, xj, xk));

  if(xauto_access)
  {
    release_access();
  }

  // Postconditions:

  ensure(invariant());

  // Exit:

  return result;
}

void
fiber_bundle::st3::
put_component(int xi, int xj, int xk, value_type xvalue)
{

  // Preconditions:

  require(state_is_read_write_accessible());
  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  put_component(index_for_ijk(xi, xj, xk), xvalue);

  // Postconditions:

  ensure(isunordered_or_equals(component(xi, xj, xk), xvalue));

  // Exit:

  return;
}

void
fiber_bundle::st3::
put_component(int xi, int xj, int xk, value_type xvalue, bool xauto_access)
{
  // Preconditions:

  require(state_is_auto_read_write_accessible(xauto_access));
  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  if(xauto_access)
  {
    get_read_write_access(true);
  }

  put_component(index_for_ijk(xi, xj, xk), xvalue);

  if(xauto_access)
  {
    release_access();
  }

  // Postconditions:

  ensure(isunordered_or_equals(component(xi, xj, xk), xvalue));

  // Exit:

  return;
}

int
fiber_bundle::st3::
index_for_ijk(int xi, int xj, int xk) const
{
  // Preconditions:

  require(state_is_read_write_accessible());
  require((0 <= xi) && (xi < dd()));
  require((0 <= xj) && (xj < dd()));
  require((0 <= xk) && (xk < dd()));

  // Body:

  int ldd = dd();

  // Bubble sort the indices.

  int ltmp;

  if(xi > xj) { ltmp = xi; xi = xj; xj = ltmp; }
  if(xj > xk) { ltmp = xj; xj = xk; xk = ltmp; }
  if(xi > xj) { ltmp = xi; xi = xj; xj = ltmp; }

  //$$SCRIBBLE: This works for ldd = 3 (only?).

  int result = (xi*ldd + xj)*ldd + xk;
  result -= (xi*(5 + xi) + (xj*(xj+1))/2);

  // Postconditions:

  ensure(result >= 0);
  ensure(result < d());

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// TUPLE FACET OF CLASS ST3
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// ABSTRACT POSET MEMBER FACET OF CLASS ST3
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

const std::string&
fiber_bundle::st3::
class_name() const
{
  // Preconditions:

  // Body:

  const string& result = static_class_name();

  // Postconditions:

  ensure(!result.empty());

  // Exit:

  return result;
}

const std::string&
fiber_bundle::st3::
static_class_name()
{
  // Preconditions:

  // Body:

  static const string result("st3");

  // Postconditions:

  ensure(!result.empty());

  // Exit:

  return result;
}

fiber_bundle::st3*
fiber_bundle::st3::
clone() const
{

  // Preconditions:

  // Body:

  // Create new handle of the current class.

  st3* result = new st3();

  // Postconditions:

  ensure(result != 0);
  ensure(result->invariant());

  // Exit:

  return result;

}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS

//==============================================================================
// ANY FACET OF CLASS ST3
//==============================================================================

// PUBLIC MEMBER FUNCTIONS

bool
fiber_bundle::st3::
is_ancestor_of(const any* xother) const
{

  // Preconditions:

  require(xother != 0);

  // Body:

  // If xother may be dynamically cast to the type of this then this is an
  // ancestor of other.

  bool result = dynamic_cast<const st3*>(xother) != 0;

  // Postconditions:

  //ensure(invariant());
  //ensure(other->invariant());

  // Exit:

  return result;

}

bool
fiber_bundle::st3::
invariant() const
{
  bool result = true;

  // Body:

  if (invariant_check())
  {
    // Prevent recursive calls to invariant.

    disable_invariant_check();

    // Must satisfy base class invariant.

    invariance(stp::invariant());

    // Invariances for this class:

    invariance((state_is_read_accessible() ? p() == 3 : true));

    // Finished, turn invariant checking back on.

    enable_invariant_check();
  }

  // Exit:

  return result;
}

// PROTECTED MEMBER FUNCTIONS

// PRIVATE MEMBER FUNCTIONS


text:
package org.jbpm.services.task.commands;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;

import org.jbpm.services.task.assignment.AssignmentService;
import org.jbpm.services.task.assignment.AssignmentServiceProvider;
import org.jbpm.services.task.deadlines.notifications.impl.NotificationListenerManager;
import org.jbpm.services.task.events.TaskEventSupport;
import org.jbpm.services.task.impl.util.DeadlineSchedulerHelper;
import org.jbpm.services.task.utils.ContentMarshallerHelper;
import org.kie.api.runtime.Context;
import org.kie.api.runtime.EnvironmentName;
import org.kie.api.task.model.Content;
import org.kie.api.task.model.OrganizationalEntity;
import org.kie.api.task.model.Status;
import org.kie.api.task.model.Task;
import org.kie.api.task.model.TaskData;
import org.kie.internal.task.api.ContentMarshallerContext;
import org.kie.internal.task.api.TaskDeadlinesService.DeadlineType;
import org.kie.internal.task.api.TaskPersistenceContext;
import org.kie.internal.task.api.UserInfo;
import org.kie.internal.task.api.model.Deadline;
import org.kie.internal.task.api.model.Escalation;
import org.kie.internal.task.api.model.InternalPeopleAssignments;
import org.kie.internal.task.api.model.InternalTask;
import org.kie.internal.task.api.model.InternalTaskData;
import org.kie.internal.task.api.model.Notification;
import org.kie.internal.task.api.model.NotificationEvent;
import org.kie.internal.task.api.model.NotificationType;
import org.kie.internal.task.api.model.Reassignment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@XmlRootElement(name="execute-deadlines-command")
@XmlAccessorType(XmlAccessType.NONE)
public class ExecuteDeadlinesCommand extends TaskCommand<Void> {

	private static final long serialVersionUID = 3140157192156956692L;
	private static final Logger logger = LoggerFactory.getLogger(ExecuteDeadlinesCommand.class);

	@XmlElement
	@XmlSchemaType(name="long")
	private Long deadlineId;
	@XmlElement
	private DeadlineType type;

	public ExecuteDeadlinesCommand() {

	}

	public ExecuteDeadlinesCommand(long taskId, long deadlineId, DeadlineType type) {
		this.taskId = taskId;
		this.deadlineId = deadlineId;
		this.type = type;
	}

	@SuppressWarnings("unchecked")
	@Override
	public Void execute(Context context) {
		TaskContext ctx = (TaskContext) context;
		UserInfo userInfo = (UserInfo) context.get(EnvironmentName.TASK_USER_INFO);

		TaskPersistenceContext persistenceContext = ctx.getPersistenceContext();

		try {
	        Task task = persistenceContext.findTask(taskId);
	        Deadline deadline = persistenceContext.findDeadline(deadlineId);
	        if (task == null || deadline == null) {
	        	return null;
	        }
	        TaskData taskData = task.getTaskData();

	        if (taskData != null) {
	            // check if task is still in valid status
	            if (type.isValidStatus(taskData.getStatus())) {
	                Map<String, Object> variables = null;

	                    Content content = persistenceContext.findContent(taskData.getDocumentContentId());

	                    if (content != null) {
	                        ContentMarshallerContext mContext = ctx.getTaskContentService().getMarshallerContext(task);
	                        Object objectFromBytes = ContentMarshallerHelper.unmarshall(content.getContent(), mContext.getEnvironment(), mContext.getClassloader());

	                        if (objectFromBytes instanceof Map) {
	                            variables = (Map<String, Object>) objectFromBytes;

	                        } else {

	                            variables = new HashMap<String, Object>();
	                            variables.put("content", objectFromBytes);
	                        }
	                    } else {
	                        variables = Collections.emptyMap();
	                    }

	                if (deadline == null || deadline.getEscalations() == null ) {
	                    return null;
	                }

	                TaskEventSupport taskEventSupport = ctx.getTaskEventSupport();

	                for (Escalation escalation : deadline.getEscalations()) {

	                    // we won't impl constraints for now
	                    //escalation.getConstraints()

	                    // run reassignment first to allow notification to be send to new potential owners
	                    if (!escalation.getReassignments().isEmpty()) {

	                        taskEventSupport.fireBeforeTaskReassigned(task, ctx);

	                        // get first and ignore the rest.
	                        Reassignment reassignment = escalation.getReassignments().get(0);
	                        logger.debug("Reassigning to {}", reassignment.getPotentialOwners());
	                        ((InternalTaskData) task.getTaskData()).setStatus(Status.Ready);

	                        List<OrganizationalEntity> potentialOwners = new ArrayList<OrganizationalEntity>(reassignment.getPotentialOwners());
	                        ((InternalPeopleAssignments) task.getPeopleAssignments()).setPotentialOwners(potentialOwners);
	                        ((InternalTaskData) task.getTaskData()).setActualOwner(null);

	                        // use assignment service to directly assign actual owner if enabled
	                        AssignmentService assignmentService = AssignmentServiceProvider.get();
	                        if (assignmentService.isEnabled()) {
	                            assignmentService.assignTask(task, ctx);
	                        }

	                        taskEventSupport.fireAfterTaskReassigned(task, ctx);
	                    }
	                    for (Notification notification : escalation.getNotifications()) {
	                        if (notification.getNotificationType() == NotificationType.Email) {

	                            taskEventSupport.fireBeforeTaskNotified(task, ctx);
	                            logger.debug("Sending an Email");
	                            NotificationListenerManager.get().broadcast(new NotificationEvent(notification, task, variables), userInfo);

	                            taskEventSupport.fireAfterTaskNotified(task, ctx);
	                        }
	                    }
	                }
	            }

	        }

	        deadline.setEscalated(true);

			persistenceContext.updateDeadline(deadline);
			persistenceContext.updateTask(task);
			DeadlineSchedulerHelper.rescheduleDeadlinesForTask((InternalTask) task, ctx, true, type);
		} catch (Exception e) {

        	logger.error("Error when executing deadlines", e);
        }
		return null;
	}

}


text:
import { TestBed, inject } from '@angular/core/testing';

import { CheeseSearchService } from './cheese-search.service';

describe('CheeseSearchService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [CheeseSearchService]
    });
  });

  it('should be created', inject([CheeseSearchService], (service: CheeseSearchService) => {
    expect(service).toBeTruthy();
  }));
});


text:
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/** @constructor */
function TaskManager() { }

cr.addSingletonGetter(TaskManager);

TaskManager.prototype = {
  /**
   * Handle window close.
   * @this
   */
  onClose: function() {
    if (!this.disabled_) {
      this.disabled_ = true;
      commands.disableTaskManager();
    }
  },

  /**
   * Handles selection changes.
   * This is also called when data of tasks are refreshed, even if selection
   * has not been changed.
   * @this
   */
  onSelectionChange: function() {
    var sm = this.selectionModel_;
    var dm = this.dataModel_;
    var selectedIndexes = sm.selectedIndexes;
    var is_end_process_enabled = true;
    if (selectedIndexes.length == 0)
      is_end_process_enabled = false;
    for (var i = 0; i < selectedIndexes.length; i++) {
      var index = selectedIndexes[i];
      var task = dm.item(index);
      if (task['type'] == 'BROWSER')
        is_end_process_enabled = false;
    }
    if (this.is_end_process_enabled_ != is_end_process_enabled) {
      if (is_end_process_enabled)
        $('kill-process').removeAttribute('disabled');
      else
        $('kill-process').setAttribute('disabled', 'true');

      this.is_end_process_enabled_ = is_end_process_enabled;
    }
  },

  /**
   * Closes taskmanager dialog.
   * After this function is called, onClose() will be called.
   * @this
   */
  close: function() {
    window.close();
  },

  /**
   * Sends commands to kill selected processes.
   * @this
   */
  killSelectedProcesses: function() {
    var selectedIndexes = this.selectionModel_.selectedIndexes;
    var dm = this.dataModel_;
    var uniqueIds = [];
    for (var i = 0; i < selectedIndexes.length; i++) {
      var index = selectedIndexes[i];
      var task = dm.item(index);
      uniqueIds.push(task['uniqueId'][0]);
    }

    commands.killSelectedProcesses(uniqueIds);
  },

  /**
   * Initializes taskmanager.
   * @this
   */
  initialize: function(dialogDom, opt) {
    if (!dialogDom) {
      console.log('ERROR: dialogDom is not defined.');
      return;
    }

    measureTime.startInterval('Load.DOM');

    this.opt_ = opt;

    this.initialized_ = true;

    this.elementsCache_ = {};
    this.dialogDom_ = dialogDom;
    this.document_ = dialogDom.ownerDocument;

    this.localized_column_ = [];
    for (var i = 0; i < DEFAULT_COLUMNS.length; i++) {
      var column_label_id = DEFAULT_COLUMNS[i][1];
      this.localized_column_[i] = loadTimeData.getString(column_label_id);
    }

    this.initElements_();
    this.initColumnModel_();
    this.selectionModel_ = new cr.ui.ListSelectionModel();
    this.dataModel_ = new cr.ui.ArrayDataModel([]);

    this.selectionModel_.addEventListener('change',
                                          this.onSelectionChange.bind(this));

    // Initializes compare functions for column sort.
    var dm = this.dataModel_;
    // List of columns to sort by its numerical value as opposed to the
    // formatted value, e.g., 20480 vs. 20KB.
    var COLUMNS_SORTED_BY_VALUE = [
        'cpuUsage', 'physicalMemory', 'sharedMemory', 'privateMemory',
        'networkUsage', 'webCoreImageCacheSize', 'webCoreScriptsCacheSize',
        'webCoreCSSCacheSize', 'fps', 'sqliteMemoryUsed', 'goatsTeleported',
        'v8MemoryAllocatedSize'];

    for (var i = 0; i < DEFAULT_COLUMNS.length; i++) {
      var columnId = DEFAULT_COLUMNS[i][0];
      var compareFunc = (function() {
          var columnIdToSort = columnId;
          if (COLUMNS_SORTED_BY_VALUE.indexOf(columnId) != -1)
            columnIdToSort += 'Value';

          return function(a, b) {
              var aValues = a[columnIdToSort];
              var bValues = b[columnIdToSort];
              var aValue = aValues && aValues[0] || 0;
              var bvalue = bValues && bValues[0] || 0;
              return dm.defaultValuesCompareFunction(aValue, bvalue);
          };
      })();
      dm.setCompareFunction(columnId, compareFunc);
    }

    if (isColumnEnabled(DEFAULT_SORT_COLUMN))
      dm.sort(DEFAULT_SORT_COLUMN, DEFAULT_SORT_DIRECTION);

    this.initTable_();

    commands.enableTaskManager();

    // Populate the static localized strings.
    i18nTemplate.process(this.document_, loadTimeData);

    measureTime.recordInterval('Load.DOM');
    measureTime.recordInterval('Load.Total');

    loadDelayedIncludes(this);
  },

  /**
   * Initializes the visibilities and handlers of the elements.
   * This method is called by initialize().
   * @private
   * @this
   */
  initElements_: function() {
    // <if expr="pp_ifdef('chromeos')">
    // The 'close-window' element exists only on ChromeOS.
    // This <if ... /if> section is removed while flattening HTML if chrome is
    // built as Desktop Chrome.
    if (!this.opt_['isShowCloseButton'])
      $('close-window').style.display = 'none';
    $('close-window').addEventListener('click', this.close.bind(this));
    // </if>

    $('kill-process').addEventListener('click',
                                       this.killSelectedProcesses.bind(this));
    $('about-memory-link').addEventListener('click', commands.openAboutMemory);
  },

  /**
   * Additional initialization of taskmanager. This function is called when
   * the loading of delayed scripts finished.
   * @this
   */
  delayedInitialize: function() {
    this.initColumnMenu_();
    this.initTableMenu_();

    var dm = this.dataModel_;
    for (var i = 0; i < dm.length; i++) {
      var processId = dm.item(i)['processId'][0];
      for (var j = 0; j < DEFAULT_COLUMNS.length; j++) {
        var columnId = DEFAULT_COLUMNS[j][0];

        var row = dm.item(i)[columnId];
        if (!row)
          continue;

        for (var k = 0; k < row.length; k++) {
          var labelId = 'detail-' + columnId + '-pid' + processId + '-' + k;
          var label = $(labelId);

          // Initialize a context-menu, if the label exists and its context-
          // menu is not initialized yet.
          if (label && !label.contextMenu)
            cr.ui.contextMenuHandler.setContextMenu(label,
                                                    this.tableContextMenu_);
        }
      }
    }

    this.isFinishedInitDelayed_ = true;
    this.table_.redraw();
  },

  initColumnModel_: function() {
    var table_columns = new Array();
    for (var i = 0; i < DEFAULT_COLUMNS.length; i++) {
      var column = DEFAULT_COLUMNS[i];
      var columnId = column[0];
      if (!isColumnEnabled(columnId))
        continue;

      table_columns.push(new cr.ui.table.TableColumn(columnId,
                                                     this.localized_column_[i],
                                                     column[2]));
    }

    for (var i = 0; i < table_columns.length; i++) {
      table_columns[i].renderFunction = this.renderColumn_.bind(this);
    }

    this.columnModel_ = new cr.ui.table.TableColumnModel(table_columns);
  },

  initColumnMenu_: function() {
    this.column_menu_commands_ = [];

    this.commandsElement_ = this.document_.createElement('commands');
    this.document_.body.appendChild(this.commandsElement_);

    this.columnSelectContextMenu_ = this.document_.createElement('menu');
    for (var i = 0; i < DEFAULT_COLUMNS.length; i++) {
      var column = DEFAULT_COLUMNS[i];

      // Creates command element to receive event.
      var command = this.document_.createElement('command');
      command.id = COMMAND_CONTEXTMENU_COLUMN_PREFIX + '-' + column[0];
      cr.ui.Command.decorate(command);
      this.column_menu_commands_[command.id] = command;
      this.commandsElement_.appendChild(command);

      // Creates menuitem element.
      var item = this.document_.createElement('menuitem');
      item.command = command;
      command.menuitem = item;
      item.textContent = this.localized_column_[i];
      if (isColumnEnabled(column[0]))
        item.setAttributeNode(this.document_.createAttribute('checked'));
      this.columnSelectContextMenu_.appendChild(item);
    }

    this.document_.body.appendChild(this.columnSelectContextMenu_);
    cr.ui.Menu.decorate(this.columnSelectContextMenu_);

    cr.ui.contextMenuHandler.setContextMenu(this.table_.header,
                                            this.columnSelectContextMenu_);
    cr.ui.contextMenuHandler.setContextMenu(this.table_.list,
                                            this.columnSelectContextMenu_);

    this.document_.addEventListener('command', this.onCommand_.bind(this));
    this.document_.addEventListener('canExecute',
                                    this.onCommandCanExecute_.bind(this));
  },

  initTableMenu_: function() {
    this.table_menu_commands_ = [];
    this.tableContextMenu_ = this.document_.createElement('menu');

    var addMenuItem = function(tm, command_id, string_id) {
      // Creates command element to receive event.
      var command = tm.document_.createElement('command');
      command.id = COMMAND_CONTEXTMENU_TABLE_PREFIX + '-' + command_id;
      cr.ui.Command.decorate(command);
      tm.table_menu_commands_[command.id] = command;
      tm.commandsElement_.appendChild(command);

      // Creates menuitem element.
      var item = tm.document_.createElement('menuitem');
      item.command = command;
      command.menuitem = item;
      item.textContent = loadTimeData.getString(string_id);
      tm.tableContextMenu_.appendChild(item);
    };

    addMenuItem(this, 'inspect', 'inspect');
    addMenuItem(this, 'activate', 'activate');

    this.document_.body.appendChild(this.tableContextMenu_);
    cr.ui.Menu.decorate(this.tableContextMenu_);
  },

  initTable_: function() {
    if (!this.dataModel_ || !this.selectionModel_ || !this.columnModel_) {
      console.log('ERROR: some models are not defined.');
      return;
    }

    this.table_ = this.dialogDom_.querySelector('.detail-table');
    cr.ui.Table.decorate(this.table_);

    this.table_.dataModel = this.dataModel_;
    this.table_.selectionModel = this.selectionModel_;
    this.table_.columnModel = this.columnModel_;

    // Expands height of row when a process has some tasks.
    this.table_.fixedHeight = false;

    this.table_.list.addEventListener('contextmenu',
                                      this.onTableContextMenuOpened_.bind(this),
                                      true);

    // Sets custom row render function.
    this.table_.setRenderFunction(this.getRow_.bind(this));
  },

  /**
   * Returns a list item element of the list. This method trys to reuse the
   * cached element, or creates a new element.
   * @return {cr.ui.ListItem}  list item element which contains the given data.
   * @private
   * @this
   */
  getRow_: function(data, table) {
    // Trys to reuse the cached row;
    var listItemElement = this.renderRowFromCache_(data, table);
    if (listItemElement)
      return listItemElement;

    // Initializes the cache.
    var pid = data['processId'][0];
    this.elementsCache_[pid] = {
      listItem: null,
      cell: [],
      icon: [],
      columns: {}
    };

    // Create new row.
    return this.renderRow_(data, table);
  },

  /**
   * Returns a list item element with re-using the previous cached element, or
   * returns null if failed.
   * @return {cr.ui.ListItem} cached un-used element to be reused.
   * @private
   * @this
   */
  renderRowFromCache_: function(data, table) {
    var pid = data['processId'][0];

    // Checks whether the cache exists or not.
    var cache = this.elementsCache_[pid];
    if (!cache)
      return null;

    var listItemElement = cache.listItem;
    var cm = table.columnModel;
    // Checks whether the number of columns has been changed or not.
    if (cache.cachedColumnSize != cm.size)
      return null;
    // Checks whether the number of childlen tasks has been changed or not.
    if (cache.cachedChildSize != data['uniqueId'].length)
      return null;

    // Updates informations of the task if necessary.
    for (var i = 0; i < cm.size; i++) {
      var columnId = cm.getId(i);
      var columnData = data[columnId];
      var oldColumnData = listItemElement.data[columnId];
      var columnElements = cache.columns[columnId];

      if (!columnData || !oldColumnData || !columnElements)
        return null;

      // Sets new width of the cell.
      var cellElement = cache.cell[i];
      cellElement.style.width = cm.getWidth(i) + '%';

      for (var j = 0; j < columnData.length; j++) {
        // Sets the new text, if the text has been changed.
        if (oldColumnData[j] != columnData[j]) {
          var textElement = columnElements[j];
          textElement.textContent = columnData[j];
        }
      }
    }

    // Updates icon of the task if necessary.
    var oldIcons = listItemElement.data['icon'];
    var newIcons = data['icon'];
    if (oldIcons && newIcons) {
      for (var j = 0; j < columnData.length; j++) {
        var oldIcon = oldIcons[j];
        var newIcon = newIcons[j];
        if (oldIcon != newIcon) {
          var iconElement = cache.icon[j];
          iconElement.src = newIcon;
        }
      }
    }
    listItemElement.data = data;

    // Removes 'selected' and 'lead' attributes.
    listItemElement.removeAttribute('selected');
    listItemElement.removeAttribute('lead');

    return listItemElement;
  },

  /**
   * Create a new list item element.
   * @return {cr.ui.ListItem} created new list item element.
   * @private
   * @this
   */
  renderRow_: function(data, table) {
    var pid = data['processId'][0];
    var cm = table.columnModel;
    var listItem = new cr.ui.ListItem({label: ''});

    listItem.className = 'table-row';
    if (this.opt_.isBackgroundMode && data.isBackgroundResource)
      listItem.className += ' table-background-row';

    for (var i = 0; i < cm.size; i++) {
      var cell = document.createElement('div');
      cell.style.width = cm.getWidth(i) + '%';
      cell.className = 'table-row-cell';
      cell.id = 'column-' + pid + '-' + cm.getId(i);
      cell.appendChild(
          cm.getRenderFunction(i).call(null, data, cm.getId(i), table));

      listItem.appendChild(cell);

      // Stores the cell element to the dictionary.
      this.elementsCache_[pid].cell[i] = cell;
    }

    // Specifies the height of the row. The height of each row is
    // 'num_of_tasks * HEIGHT_OF_TASK' px.
    listItem.style.height = (data['uniqueId'].length * HEIGHT_OF_TASK) + 'px';

    listItem.data = data;

    // Stores the list item element, the number of columns and the number of
    // childlen.
    this.elementsCache_[pid].listItem = listItem;
    this.elementsCache_[pid].cachedColumnSize = cm.size;
    this.elementsCache_[pid].cachedChildSize = data['uniqueId'].length;

    return listItem;
  },

  /**
   * Create a new element of the cell.
   * @return {HTMLDIVElement} created cell
   * @private
   * @this
   */
  renderColumn_: function(entry, columnId, table) {
    var container = this.document_.createElement('div');
    container.className = 'detail-container-' + columnId;
    var pid = entry['processId'][0];

    var cache = [];
    var cacheIcon = [];

    if (entry && entry[columnId]) {
      container.id = 'detail-container-' + columnId + '-pid' + entry.processId;

      for (var i = 0; i < entry[columnId].length; i++) {
        var label = document.createElement('div');
        if (columnId == 'title') {
          // Creates a page title element with icon.
          var image = this.document_.createElement('img');
          image.className = 'detail-title-image';
          image.src = entry['icon'][i];
          image.id = 'detail-title-icon-pid' + pid + '-' + i;
          label.appendChild(image);
          var text = this.document_.createElement('div');
          text.className = 'detail-title-text';
          text.id = 'detail-title-text-pid' + pid + '-' + i;
          text.textContent = entry['title'][i];
          label.appendChild(text);

          // Chech if the delayed scripts (included in includes.js) have been
          // loaded or not. If the delayed scripts ware not loaded yet, a
          // context menu could not be initialized. In such case, it will be
          // initialized at delayedInitialize() just after loading of delayed
          // scripts instead of here.
          if (this.isFinishedInitDelayed_)
            cr.ui.contextMenuHandler.setContextMenu(label,
                                                    this.tableContextMenu_);

          label.addEventListener('dblclick', (function(uniqueId) {
              commands.activatePage(uniqueId);
          }).bind(this, entry['uniqueId'][i]));

          label.data = entry;
          label.index_in_group = i;

          cache[i] = text;
          cacheIcon[i] = image;
        } else {
          label.textContent = entry[columnId][i];
          cache[i] = label;
        }
        label.id = 'detail-' + columnId + '-pid' + pid + '-' + i;
        label.className = 'detail-' + columnId + ' pid' + pid;
        container.appendChild(label);
      }

      this.elementsCache_[pid].columns[columnId] = cache;
      if (columnId == 'title')
        this.elementsCache_[pid].icon = cacheIcon;
    }
    return container;
  },

  /**
   * Updates the task list with the supplied task.
   * @private
   * @this
   */
  processTaskChange: function(task) {
    var dm = this.dataModel_;
    var sm = this.selectionModel_;
    if (!dm || !sm) return;

    this.table_.list.startBatchUpdates();
    sm.beginChange();

    var type = task.type;
    var start = task.start;
    var length = task.length;
    var tasks = task.tasks;

    // We have to store the selected pids and restore them after
    // splice(), because it might replace some items but the replaced
    // items would lose the selection.
    var oldSelectedIndexes = sm.selectedIndexes;

    // Create map of selected PIDs.
    var selectedPids = {};
    for (var i = 0; i < oldSelectedIndexes.length; i++) {
      var item = dm.item(oldSelectedIndexes[i]);
      if (item) selectedPids[item['processId'][0]] = true;
    }

    var args = tasks.slice();
    args.unshift(start, dm.length);
    dm.splice.apply(dm, args);

    // Create new array of selected indexes from map of old PIDs.
    var newSelectedIndexes = [];
    for (var i = 0; i < dm.length; i++) {
      if (selectedPids[dm.item(i)['processId'][0]])
        newSelectedIndexes.push(i);
    }

    sm.selectedIndexes = newSelectedIndexes;

    var pids = [];
    for (var i = 0; i < dm.length; i++) {
      pids.push(dm.item(i)['processId'][0]);
    }

    // Sweeps unused caches, which elements no longer exist on the list.
    for (var pid in this.elementsCache_) {
      if (pids.indexOf(pid) == -1)
        delete this.elementsCache_[pid];
    }

    sm.endChange();
    this.table_.list.endBatchUpdates();
  },

  /**
   * Respond to a command being executed.
   * @this
   */
  onCommand_: function(event) {
    var command = event.command;
    var command_id = command.id.split('-', 2);

    var main_command = command_id[0];
    var sub_command = command_id[1];

    if (main_command == COMMAND_CONTEXTMENU_COLUMN_PREFIX) {
      this.onColumnContextMenu_(sub_command, command);
    } else if (main_command == COMMAND_CONTEXTMENU_TABLE_PREFIX) {
      var target_unique_id = this.currentContextMenuTarget_;

      if (!target_unique_id)
        return;

      if (sub_command == 'inspect')
        commands.inspect(target_unique_id);
      else if (sub_command == 'activate')
        commands.activatePage(target_unique_id);

      this.currentContextMenuTarget_ = undefined;
    }
  },

  onCommandCanExecute_: function(event) {
    event.canExecute = true;
  },

  /**
   * Store resourceIndex of target resource of context menu, because resource
   * will be replaced when it is refreshed.
   * @this
   */
  onTableContextMenuOpened_: function(e) {
    if (!this.isFinishedInitDelayed_)
      return;

    var mc = this.table_menu_commands_;
    var inspect_menuitem =
        mc[COMMAND_CONTEXTMENU_TABLE_PREFIX + '-inspect'].menuitem;
    var activate_menuitem =
        mc[COMMAND_CONTEXTMENU_TABLE_PREFIX + '-activate'].menuitem;

    // Disabled by default.
    inspect_menuitem.disabled = true;
    activate_menuitem.disabled = true;

    var target = e.target;
    for (;; target = target.parentNode) {
      if (!target) return;
      var classes = target.classList;
      if (classes &&
          Array.prototype.indexOf.call(classes, 'detail-title') != -1) break;
    }

    var index_in_group = target.index_in_group;

    // Sets the uniqueId for current target page under the mouse corsor.
    this.currentContextMenuTarget_ = target.data['uniqueId'][index_in_group];

    // Enables if the page can be inspected.
    if (target.data['canInspect'][index_in_group])
      inspect_menuitem.disabled = false;

    // Enables if the page can be activated.
    if (target.data['canActivate'][index_in_group])
      activate_menuitem.disabled = false;
  },

  onColumnContextMenu_: function(columnId, command) {
    var menuitem = command.menuitem;
    var checkedItemCount = 0;
    var checked = isColumnEnabled(columnId);

    // Leaves a item visible when user tries making invisible but it is the
    // last one.
    var enabledColumns = getEnabledColumns();
    for (var id in enabledColumns) {
      if (enabledColumns[id])
        checkedItemCount++;
    }
    if (checkedItemCount == 1 && checked)
      return;

    // Toggles the visibility of the column.
    var newChecked = !checked;
    menuitem.checked = newChecked;
    setColumnEnabled(columnId, newChecked);

    this.initColumnModel_();
    this.table_.columnModel = this.columnModel_;
    this.table_.redraw();
  },
};

// |taskmanager| has been declared in preload.js.
taskmanager = TaskManager.getInstance();

function init() {
  var params = parseQueryParams(window.location);
  var opt = {};
  opt['isBackgroundMode'] = params.background;
  opt['isShowCloseButton'] = params.showclose;
  taskmanager.initialize(document.body, opt);
}

document.addEventListener('DOMContentLoaded', init);
document.addEventListener('Close', taskmanager.onClose.bind(taskmanager));


text:
import Command from './base';
import { inherit } from 'content-kit-utils';

function TextFormatCommand(options) {
  options = options || {};
  Command.call(this, options);
  this.tag = options.tag;
  this.mappedTags = options.mappedTags || [];
  this.mappedTags.push(this.tag);
  this.action = options.action || this.name;
  this.removeAction = options.removeAction || this.action;
}
inherit(TextFormatCommand, Command);

TextFormatCommand.prototype = {
  exec: function(value) {
    document.execCommand(this.action, false, value || null);
  },
  unexec: function(value) {
    document.execCommand(this.removeAction, false, value || null);
  }
};

export default TextFormatCommand;