text:
package nachos.threads;

import java.util.List;
import java.util.ArrayList;
import nachos.machine.*;

/**
 * A KThread is a thread that can be used to execute Nachos kernel code. Nachos
 * allows multiple threads to run concurrently.
 *
 * To create a new thread of execution, first declare a class that implements
 * the <tt>Runnable</tt> interface. That class then implements the <tt>run</tt>
 * method. An instance of the class can then be allocated, passed as an argument
 * when creating <tt>KThread</tt>, and forked. For example, a thread that
 * computes pi could be written as follows:
 *
 *

 *

 *
 *

 * class PiRun implements Runnable {
 *     public void run() {
 *         // compute pi
 *         ...
 *     }
 * }
 *

 *
 *

 *

 * The following code would then create a thread and start it running:
 *
 *

 *

 *
 *

 * PiRun p = new PiRun();
 * new KThread(p).fork();
 *

 *
 *

 */
public class KThread {
    /**
     * Get the current thread.
     *
     * @return the current thread.
     */
    public static KThread currentThread() {
        Lib.assertTrue(currentThread != null);
        return currentThread;
    }

    /**
     * Allocate a new <tt>KThread</tt>. If this is the first <tt>KThread</tt>,
     * create an idle thread as well.
     */
    public KThread() {
        if (currentThread != null) {
            tcb = new TCB();
        } else {
            readyQueue = ThreadedKernel.scheduler.newThreadQueue(false);
            readyQueue.acquire(this);

            currentThread = this;
            tcb = TCB.currentTCB();
            name = "main";
            restoreState();

            createIdleThread();
        }
    }

    /**
     * Allocate a new KThread.
     *
     * @param target
     *            the object whose <tt>run</tt> method is called.
     */
    public KThread(Runnable target) {
        this();
        this.target = target;
    }

    /**
     * Set the target of this thread.
     *
     * @param target
     *            the object whose <tt>run</tt> method is called.
     * @return this thread.
     */
    public KThread setTarget(Runnable target) {
        Lib.assertTrue(status == statusNew);

        this.target = target;
        return this;
    }

    /**
     * Set the name of this thread. This name is used for debugging purposes
     * only.
     *
     * @param name
     *            the name to give to this thread.
     * @return this thread.
     */
    public KThread setName(String name) {
        this.name = name;
        return this;
    }

    /**
     * Get the name of this thread. This name is used for debugging purposes
     * only.
     *
     * @return the name given to this thread.
     */
    public String getName() {
        return name;
    }

    /**
     * Get the full name of this thread. This includes its name along with its
     * numerical ID. This name is used for debugging purposes only.
     *
     * @return the full name given to this thread.
     */
    public String toString() {
        return (name + " (#" + id + ")");
    }

    /**
     * Deterministically and consistently compare this thread to another thread.
     */
    public int compareTo(Object o) {
        KThread thread = (KThread) o;

        if (id < thread.id)
            return -1;
        else if (id > thread.id)
            return 1;
        else
            return 0;
    }

    /**
     * Causes this thread to begin execution. The result is that two threads are
     * running concurrently: the current thread (which returns from the call to
     * the <tt>fork</tt> method) and the other thread (which executes its
     * target's <tt>run</tt> method).
     */
    public void fork() {
        Lib.assertTrue(status == statusNew);
        Lib.assertTrue(target != null);

        Lib.debug(dbgThread, "Forking thread: " + toString() + " Runnable: " + target);

        boolean intStatus = Machine.interrupt().disable();

        tcb.start(new Runnable() {
            public void run() {
                runThread();
            }
        });

        ready();

        Machine.interrupt().restore(intStatus);
    }

    private void runThread() {
        begin();
        target.run();
        finish();
    }

    private void begin() {
        Lib.debug(dbgThread, "Beginning thread: " + toString());

        Lib.assertTrue(this == currentThread);

        restoreState();

        Machine.interrupt().enable();
    }

    /**
     * Finish the current thread and schedule it to be destroyed when it is safe
     * to do so. This method is automatically called when a thread's
     * <tt>run</tt> method returns, but it may also be called directly.
     *
     * The current thread cannot be immediately destroyed because its stack and
     * other execution state are still in use. Instead, this thread will be
     * destroyed automatically by the next thread to run, when it is safe to
     * delete this thread.
     */
    public static void finish() {
        Lib.debug(dbgThread, "Finishing thread: " + currentThread.toString());

        Machine.interrupt().disable();

        Machine.autoGrader().finishingCurrentThread();

        Lib.assertTrue(toBeDestroyed == null);
        toBeDestroyed = currentThread;

        currentThread.status = statusFinished;

        // currentThread.joinLock.acquire();
        // currentThread.joinCondition.wakeAll();
        // currentThread.joinLock.release();
        currentThread.joinSemaphore.V();

        sleep();
    }

    /**
     * Relinquish the CPU if any other thread is ready to run. If so, put the
     * current thread on the ready queue, so that it will eventually be
     * rescheuled.
     *
     *

     * Returns immediately if no other thread is ready to run. Otherwise returns
     * when the current thread is chosen to run again by
     * <tt>readyQueue.nextThread()</tt>.
     *
     *

     * Interrupts are disabled, so that the current thread can atomically add
     * itself to the ready queue and switch to the next thread. On return,
     * restores interrupts to the previous state, in case <tt>yield()</tt> was
     * called with interrupts disabled.
     */
    public static void yield() {
        Lib.debug(dbgThread, "Yielding thread: " + currentThread.toString());

        Lib.assertTrue(currentThread.status == statusRunning);

        boolean intStatus = Machine.interrupt().disable();

        currentThread.ready();

        runNextThread();

        Machine.interrupt().restore(intStatus);
    }

    /**
     * Relinquish the CPU, because the current thread has either finished or it
     * is blocked. This thread must be the current thread.
     *
     *

     * If the current thread is blocked (on a synchronization primitive, i.e. a
     * <tt>Semaphore</tt>, <tt>Lock</tt>, or <tt>Condition</tt>), eventually
     * some thread will wake this thread up, putting it back on the ready queue
     * so that it can be rescheduled. Otherwise, <tt>finish()</tt> should have
     * scheduled this thread to be destroyed by the next thread to run.
     */
    public static void sleep() {
        Lib.debug(dbgThread, "Sleeping thread: " + currentThread.toString());

        Lib.assertTrue(Machine.interrupt().disabled());

        if (currentThread.status != statusFinished)
            currentThread.status = statusBlocked;

        runNextThread();
    }

    /**
     * Moves this thread to the ready state and adds this to the scheduler's
     * ready queue.
     */
    public void ready() {
        Lib.debug(dbgThread, "Ready thread: " + toString());

        Lib.assertTrue(Machine.interrupt().disabled());
        Lib.assertTrue(status != statusReady);

        status = statusReady;
        if (this != idleThread)
            readyQueue.waitForAccess(this);

        Machine.autoGrader().readyThread(this);
    }

    /**
     * Waits for this thread to finish. If this thread is already finished,
     * return immediately. This method must only be called once; the second call
     * is not guaranteed to return. This thread must not be the current thread.
     */
    public void join() {
        Lib.debug(dbgThread, "Joining to thread: " + toString());

        Lib.assertTrue(this != currentThread);

        if (status != statusFinished){
            // joinLock.acquire();
            // joinCondition.sleep();
            // joinLock.release();
            joinSemaphore.P();
        }
    }

    /**
     * Create the idle thread. Whenever there are no threads ready to be run,
     * and <tt>runNextThread()</tt> is called, it will run the idle thread. The
     * idle thread must never block, and it will only be allowed to run when all
     * other threads are blocked.
     *
     *

     * Note that <tt>ready()</tt> never adds the idle thread to the ready set.
     */
    private static void createIdleThread() {
        Lib.assertTrue(idleThread == null);

        idleThread = new KThread(new Runnable() {
            public void run() {
                while (true)
                    yield();
            }
        });
        idleThread.setName("idle");

        Machine.autoGrader().setIdleThread(idleThread);

        idleThread.fork();
    }

    /**
     * Determine the next thread to run, then dispatch the CPU to the thread
     * using <tt>run()</tt>.
     */
    private static void runNextThread() {
        KThread nextThread = readyQueue.nextThread();
        if (nextThread == null)
            nextThread = idleThread;

        nextThread.run();
    }

    /**
     * Dispatch the CPU to this thread. Save the state of the current thread,
     * switch to the new thread by calling <tt>TCB.contextSwitch()</tt>, and
     * load the state of the new thread. The new thread becomes the current
     * thread.
     *
     *

     * If the new thread and the old thread are the same, this method must still
     * call <tt>saveState()</tt>, <tt>contextSwitch()</tt>, and
     * <tt>restoreState()</tt>.
     *
     *

     * The state of the previously running thread must already have been changed
     * from running to blocked or ready (depending on whether the thread is
     * sleeping or yielding).
     *
     * @param finishing
     *            <tt>true</tt> if the current thread is finished, and should be
     *            destroyed by the new thread.
     */
    private void run() {
        Lib.assertTrue(Machine.interrupt().disabled());

        Machine.yield();

        currentThread.saveState();

        Lib.debug(dbgThread, "Switching from: " + currentThread.toString() + " to: " + toString());

        currentThread = this;

        tcb.contextSwitch();

        currentThread.restoreState();
    }

    /**
     * Prepare this thread to be run. Set <tt>status</tt> to
     * <tt>statusRunning</tt> and check <tt>toBeDestroyed</tt>.
     */
    protected void restoreState() {
        Lib.debug(dbgThread, "Running thread: " + currentThread.toString());

        Lib.assertTrue(Machine.interrupt().disabled());
        Lib.assertTrue(this == currentThread);
        Lib.assertTrue(tcb == TCB.currentTCB());

        Machine.autoGrader().runningThread(this);

        status = statusRunning;

        if (toBeDestroyed != null) {
            toBeDestroyed.tcb.destroy();
            toBeDestroyed.tcb = null;
            toBeDestroyed = null;
        }
    }

    /**
     * Prepare this thread to give up the processor. Kernel threads do not need
     * to do anything here.
     */
    protected void saveState() {
        Lib.assertTrue(Machine.interrupt().disabled());
        Lib.assertTrue(this == currentThread);
    }

    private static class PingTest implements Runnable {
        PingTest(int which) {
            this.which = which;
        }

        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println("*** thread " + which + " looped " + i + " times");
                currentThread.yield();
            }
        }

        private int which;
    }

    private static void doPingTest() {
        System.out.println("[test:KThread] pingpong test started");
        new KThread(new PingTest(1)).setName("forked thread").fork();
        new PingTest(0).run();
        System.out.println("[test:KThread] pingpong test passed");
    }

    private static class JoinTestRec {
        JoinTestRec() {
            c = 0;
        }
        public int c;
    }

    private static class JoinModifier implements Runnable {
        JoinModifier(int id, JoinTestRec rec, Lock lock) {
            i = id;
            r = rec;
            l = lock;
        }

        public void run() {
            l.acquire();
            r.c++;
            System.out.println("*** modifier " + i + " modifies count to " + r.c);
            l.release();
        }

        private int i;
        private JoinTestRec r;
        private Lock l;
    }

    private static void doMultipleModifierJoinTest(int n){
        System.out.println("[test:KThread] " + n + " modifier join test started");
        JoinTestRec r = new JoinTestRec();
        List<KThread> pool = new ArrayList<KThread>();
        Lock recLock = new Lock();
        for (int i = 0; i < n; ++ i){
            KThread p = new KThread(new JoinModifier(i, r, recLock)).setName("modifier" + i);
            pool.add(p);
            p.fork();
        }
        for (int i = 0; i < n; ++ i)
            pool.get(i).join();
        Lib.assertTrue(r.c == n);
        System.out.println("[test:KThread] " + n + " modifier join test passed");
    }

    private static void doJoinMutipleTimesJoinTest(){
        System.out.println("[test:KThread] multiple time join test started");
        JoinTestRec r = new JoinTestRec();
        KThread p = new KThread(new JoinModifier(0, r, new Lock())).setName("modifier");
        p.fork();
        p.join();
        p.join();
        Lib.assertTrue(r.c == 1);
        System.out.println("[test:KThread] multiple time join test passed");
    }

    private static void doJoinTest() {
        doMultipleModifierJoinTest(1);
        doMultipleModifierJoinTest(10);
        doJoinMutipleTimesJoinTest();
    }

    /**
     * Tests whether this module is working.
     */
    public static void selfTest() {
        Lib.debug(dbgThread, "Enter KThread.selfTest");

        doPingTest();
        doJoinTest();
    }

    private static final char dbgThread = 't';

    /**
     * Additional state used by schedulers.
     *
     * @see nachos.threads.PriorityScheduler.ThreadState
     */
    public Object schedulingState = null;

    private static final int statusNew = 0;
    private static final int statusReady = 1;
    private static final int statusRunning = 2;
    private static final int statusBlocked = 3;
    private static final int statusFinished = 4;

    /**
     * The status of this thread. A thread can either be new (not yet forked),
     * ready (on the ready queue but not running), running, or blocked (not on
     * the ready queue and not running).
     */
    private int status = statusNew;
    private String name = "(unnamed thread)";
    private Runnable target;
    private TCB tcb;
    private Semaphore joinSemaphore = new Semaphore(0);
    // private Lock joinLock = new Lock();
    // private Condition joinCondition = new Condition(joinLock);

    /**
     * Unique identifer for this thread. Used to deterministically compare
     * threads.
     */
    private int id = numCreated++;
    /** Number of times the KThread constructor was called. */
    private static int numCreated = 0;

    private static ThreadQueue readyQueue = null;
    private static KThread currentThread = null;
    private static KThread toBeDestroyed = null;
    private static KThread idleThread = null;
}


text:
/**
 * @file   Items.h
 *
 * @brief   This file provides data Model for Json Schema Array Items.
 */

#ifndef ITEMS_H_
#define ITEMS_H_

#include <string>
#include <vector>
#include <map>
#include "Properties.h"
#include "Helpers.h"
#include "AllowedValues.h"
#include <memory>

namespace RAML
{
    class Properties;
    class AllowedValues;
    /**
     * @class   Items
     * @brief   This class provides data Model for Json Schema Array Items.
     */
    class Items
    {
        public:
            /**
                  * Constructor of Items.
                  */
            Items() {}

            /**
                 * This method is for setting Properties to Items
                 *
                 * @param propName - Properties name as string.
                 * @param property - pointer to Properties.
                 */
            void addProperty(const std::string &propName, const std::shared_ptr<Properties> &property)
            {
                if (m_properties.end() == m_properties.find(propName))
                {
                    m_properties[propName] =  property;
                }
            }

            /**
                 * This method is for getting Properties from Items.
                 *
                 * @param propName - Properties name as string.
                 *
                 * @return  pointer to Properties to put the value got
                 */
            std::shared_ptr<Properties> getproperty(const std::string &propName)
            {
                if (m_properties.end() != m_properties.find(propName))
                {
                    return m_properties[propName];
                }
                return nullptr;
            }

            /**
                 * This method is for getting Properties from Items.
                 *
                 * @return map of Properties name as string and pointer to Properties
                 */
            std::map<std::string, std::shared_ptr<Properties> > const &getProperties()
            {
                return m_properties;
            }

            /**
                 * This method is for setting Type to Items
                 *
                 * @param type - Type as string.
                 */
            void setType(const std::string &type)
            {
                m_type = type;
            }

            /**
                 * This method is for getting Type from Items.
                 *
                 * @return Type as string
                 */
            std::string getType()
            {
                return m_type;
            }

            /**
                 * This method is for setting RequiredValue to Items
                 *
                 * @param reqValue - RequiredValue as string.
                 */
            void setRequiredValue(const std::string &reqValue)
            {
                auto it = m_required.begin();
                for (; it != m_required.end(); ++it)
                {
                    if (*it == reqValue)
                        break;
                }
                if (m_required.end() == it)
                {
                    m_required.push_back(reqValue);
                }
            }

            /**
                 * This method is for getting RequiredValue from Items.
                 *
                 * @return list of RequiredValue as string
                 */
            std::vector<std::string> const &getRequiredValues()
            {
                return m_required;
            }

            /**
                 * This method is for setting AllowedValues to Items
                 *
                 * @param values -list of AllowedValues.
                 */
            template <typename T>
            bool setAllowedValues(const std::vector<T> &values)
            {
                m_allowedValues.addValues(values);
                return true;
            }

            /**
                 * This method is for getting size of AllowedValues from Items.
                 *
                 * @return size of AllowedValues
                 */
            inline int getAllowedValuesSize() const
            {
                return m_allowedValues.size();
            }

            /**
                 * This method is for getting AllowedValues from Items.
                 *
                 * @return list of AllowedValues
                 */
            inline std::vector<ValueVariant> getAllowedValues()
            {
                return m_allowedValues.getValues();
            }

            /**
                 * This method is for getting AllowedValues as Integer from Items.
                 *
                 * @return list of AllowedValues as Integer
                 */
            inline std::vector<int> getAllowedValuesInt()
            {
                return m_allowedValues.getValuesInt();
            }

            /**
                 * This method is for getting AllowedValues as String from Items.
                 *
                 * @return list of AllowedValues as String
                 */
            inline std::vector<std::string> getAllowedValuesString()
            {
                return m_allowedValues.getValuesString();
            }
        private:
            std::map<std::string, std::shared_ptr<Properties> > m_properties;
            std::string m_type;
            std::vector<std::string>  m_required;
            AllowedValues m_allowedValues;
    };

    /** ItemsPtr - shared Ptr to Items.*/
    typedef std::shared_ptr<Items> ItemsPtr;
}
#endif

redpajama_set_name: RedPajamaGithub


text:
.. toctree::
   :maxdepth: 2

.. _learning:

Learning
==========
This module contains algorithms for solving the structured learning model.
Most are based on structured support vector machines.

Currently, I advise to use the OneSlackSSVM, which solves the QP using CVXOPT.
SubgradientSSVM is a very simple implementation, that also might be interesting.

NSlackSSVM is the n-slack formulation of the QP and should work reliably,
but is not as optimized as OneSlackSSVM.
The rest is experimental / for testing.

.. automodule:: pystruct.learners
   :no-members:
   :no-inherited-members:

.. currentmodule:: pystruct

.. autosummary::
   :toctree: generated/
   :template: class.rst

    learners.OneSlackSSVM
    learners.NSlackSSVM
    learners.SubgradientSSVM
    learners.StructuredPerceptron
    learners.LatentSSVM
    learners.SubgradientLatentSSVM
    learners.PrimalDSStructuredSVM
    learners.FrankWolfeSSVM

.. _models:

Models
========
This module contains model formulations for several settings. They provide the
glue between the learning algorithm and the data (and inference).

There are two main classes of models, conditional random field models (CRFs)
and classification models (Clfs).

The BinaryClf implements a standard binary classifier, the MultiClassClf a
linear multi-class classifier. Together with a max-margin learner, these
produce standard binary SVMs and Crammer-Singer multi-class SVMs. MultiLabelClf
implements a multi label model with different possible pairwise interactions.

GraphCRF implements a simple pairwise model for arbitrary graphs, while
EdgeFeatureGraphCRF allows for arbitrary features for each edge, symmetric,
assymmetric and arbitrary potentials.

GridCRF is a convenience class for grid graphs.

.. automodule:: pystruct.models
   :no-members:
   :no-inherited-members:

.. currentmodule:: pystruct

Classifiers
-----------

.. autosummary::
   :toctree: generated/
   :template: class.rst

    models.BinaryClf
    models.MultiClassClf
    models.MultiLabelClf

Conditional Random Fields
-------------------------

.. autosummary::
   :toctree: generated/
   :template: class.rst

    models.GraphCRF
    models.EdgeFeatureGraphCRF
    models.LatentGraphCRF
    models.LatentNodeCRF
    models.ChainCRF
    models.GridCRF
    models.DirectionalGridCRF

.. _inference:

Inference
===========

.. automodule:: pystruct.inference
   :no-members:
   :no-inherited-members:

.. currentmodule:: pystruct

.. autosummary::
   :toctree: generated/
   :template: function.rst

   inference.inference_dispatch
   inference.inference_qpbo
   inference.inference_lp
   inference.inference_ad3
   inference.inference_ogm

Utilities
===========
.. automodule:: pystruct.utils
   :no-members:
   :no-inherited-members:

.. currentmodule:: pystruct

.. autosummary::
   :toctree: generated/
   :template: class_with_call.rst

    utils.SaveLogger

plot_learning
-------------

.. automodule:: pystruct.plot_learning
   :no-members:
   :no-inherited-members:

.. currentmodule:: pystruct

.. autosummary::
   :toctree: generated/
   :template: function.rst

    plot_learning.plot_learning


text:
module.exports = rnd;

function rnd(){
  return Math.random();
}


text:
namespace ApiTemplate
{
    using ApiTemplate.Commands;
    using ApiTemplate.Mappers;
    using ApiTemplate.Repositories;
    using ApiTemplate.Services;
    using ApiTemplate.ViewModels;
    using Boxed.Mapping;
    using Microsoft.Extensions.DependencyInjection;

    /// <summary>
    /// <see cref="IServiceCollection"/> extension methods add project services.
    /// </summary>
    /// <remarks>
    /// AddSingleton - Only one instance is ever created and returned.
    /// AddScoped - A new instance is created and returned for each request/response cycle.
    /// AddTransient - A new instance is created and returned each time.
    /// </remarks>
    public static class ProjectServiceCollectionExtensions
    {
        public static IServiceCollection AddProjectCommands(this IServiceCollection services) =>
            services
                .AddSingleton<IDeleteCarCommand, DeleteCarCommand>()
                .AddSingleton<IGetCarCommand, GetCarCommand>()
                .AddSingleton<IGetCarPageCommand, GetCarPageCommand>()
                .AddSingleton<IPatchCarCommand, PatchCarCommand>()
                .AddSingleton<IPostCarCommand, PostCarCommand>()
                .AddSingleton<IPutCarCommand, PutCarCommand>();

        public static IServiceCollection AddProjectMappers(this IServiceCollection services) =>
            services
                .AddSingleton<IMapper<Models.Car, Car>, CarToCarMapper>()
                .AddSingleton<IMapper<Models.Car, SaveCar>, CarToSaveCarMapper>()
                .AddSingleton<IMapper<SaveCar, Models.Car>, CarToSaveCarMapper>();

        public static IServiceCollection AddProjectRepositories(this IServiceCollection services) =>
            services
                .AddSingleton<ICarRepository, CarRepository>();

        public static IServiceCollection AddProjectServices(this IServiceCollection services) =>
            services
                .AddSingleton<IClockService, ClockService>();
    }
}


text:
layout: cards/cards
cards:
  - headline: Develop a content model and its types
    text: Learn how to develop a content model and its types.
    link: /content-strategy/create-content-model/develop-content-model
---


text:
package com.netflix.zuul.dependency.ribbon;

import com.netflix.client.ClientException;
import com.netflix.client.ClientFactory;
import com.netflix.client.config.DefaultClientConfigImpl;
import com.netflix.config.*;
import com.netflix.zuul.ZuulApplicationInfo;
import com.netflix.zuul.constants.ZuulConstants;
import org.apache.commons.configuration.AbstractConfiguration;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles Eureka VIP names and addresses.
 *
 * @author mhawthorne
 */
public class RibbonConfig {

    static String APPLICATION_NAME = null;

    static String APPLICATION_STACK = null;

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

    private static final DynamicBooleanProperty AUTODETECT_BACKEND_VIPS =
            DynamicPropertyFactory.getInstance().getBooleanProperty(ZuulConstants.ZUUL_AUTODETECT_BACKEND_VIPS, true);
    private static final DynamicStringProperty DEFAULT_CLIENT =
            DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_NIWS_DEFAULTCLIENT, null);

    /**
     * This method attempts to set up the default Ribbon origin VIP from properties and environment.
     * One method is through autoscale name convention. The Autoscaling group name can be set up as follow : zuul-origin_stack.
     * Zuul will derive the origin VIP  as origin-stack.{zuul.ribbon.vipAddress.template}
     * <p/>
     * the client may also be specified by the property ZuulConstants.ZUUL_NIWS_DEFAULTCLIENT
     *
     * @throws ClientException
     */
    public static void setupDefaultRibbonConfig() throws ClientException {
        final DeploymentContext config = ConfigurationManager.getDeploymentContext();

        String stack = config.getDeploymentStack();

        if (stack != null && stack.contains("_")) { //use stack for client and stack  client_stack
            setAppInfoFromZuulStack(stack);
        } else {
            String env = config.getDeploymentEnvironment();
            if (stack != null) {
                setApplicationName(stack);
            } else {
                if (DEFAULT_CLIENT.get() == null)
                    throw new RuntimeException("Can't figure out default origin vips. Set stack as appName_stack of set zuul.niws.defaultClient param");
                setApplicationName(DEFAULT_CLIENT.get());
            }

            setApplicationStack(env);
        }
        String vip = RibbonConfig.getDefaultVipName();
        String vipAddr = RibbonConfig.getDefaultVipAddress(getApplicationStack());
        String namespace = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_RIBBON_NAMESPACE, "ribbon").get();

        setIfNotDefined(vip, vipAddr);
        setIfNotDefined(getApplicationName() + "." + namespace + ".Port", "7001");
        setIfNotDefined(getApplicationName() + "." + namespace + ".AppName", getApplicationName());
        setIfNotDefined(getApplicationName() + "." + namespace + ".ReadTimeout", "2000");
        setIfNotDefined(getApplicationName() + "." + namespace + ".ConnectTimeout", "2000");
        setIfNotDefined(getApplicationName() + "." + namespace + ".MaxAutoRetriesNextServer", "1");
        setIfNotDefined(getApplicationName() + "." + namespace + ".FollowRedirects", "false");
        setIfNotDefined(getApplicationName() + "." + namespace + ".ConnIdleEvictTimeMilliSeconds", "3600000");
        setIfNotDefined(getApplicationName() + "." + namespace + ".EnableZoneAffinity", "true");
        DefaultClientConfigImpl clientConfig = DefaultClientConfigImpl.getClientConfigWithDefaultValues(getApplicationName(),
                namespace);
        ClientFactory.registerClientFromProperties(getApplicationName(), clientConfig);
    }

    private static void setIfNotDefined(String key, String value) {
        final AbstractConfiguration config = ConfigurationManager.getConfigInstance();
        if (config.getString(key) == null) {
            LOG.info("Setting default NIWS Property " + key + "=" + value);
            config.setProperty(key, value);
        }
    }

    /**
     * Parses out the the applicationName and application stack from the zuul "stack" element.
     * when deployed, the applicaiton
     *
     * @param stack
     * @return
     */
    public static boolean setAppInfoFromZuulStack(String stack) {
        String[] stackSplit = stack.split("_");
        if (stackSplit == null || stackSplit.length != 2) return false;

        setApplicationName(stackSplit[0]);
        setApplicationStack(stackSplit[1]);
        return true;
    }

    /**
     * @return the APPLICATION_NAME
     */
    public static String getApplicationName() {
        return APPLICATION_NAME;
    }

    /**
     * sets the application name of the origin
     *
     * @param applicationName
     */
    public static void setApplicationName(String applicationName) {
        RibbonConfig.APPLICATION_NAME = applicationName;
        if (ZuulApplicationInfo.getApplicationName() == null) ZuulApplicationInfo.setApplicationName(applicationName);
        LOG.info("Setting back end VIP application = " + applicationName);
    }

    /**
     * returns the application_stack
     *
     * @return
     */
    public static String getApplicationStack() {
        return APPLICATION_STACK;
    }

    /**
     * sets the default origin application stack
     *
     * @param stack
     */
    public static void setApplicationStack(String stack) {
        RibbonConfig.APPLICATION_STACK = stack;
        if (ZuulApplicationInfo.getStack() == null) ZuulApplicationInfo.setStack(stack);
        LOG.info("Setting back end VIP stack = " + stack);
    }

    /**
     * true if the app shoudl autodetect the origin vip
     *
     * @return true if the app shoudl autodetect the origin vip
     */
    public static final boolean isAutodetectingBackendVips() {
        return AUTODETECT_BACKEND_VIPS.get();
    }

    /**
     * returns the Ribbon property name for the default origin vip
     *
     * @return
     */
    public static final String getDefaultVipName() {
        String client = getApplicationName();
        if (client == null) client = DEFAULT_CLIENT.get();

        String namespace = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_RIBBON_NAMESPACE, "ribbon").get();

        String vipTemplate = "%s." + namespace + ".DeploymentContextBasedVipAddresses";
        return String.format(vipTemplate, client);
    }

    /**
     * builds the default vip address of the origin based on the stack.
     * You need to configure zuul.ribbon.vipAddress.template . eg zuul.ribbon.vipAddress.template=%s-%s.netflix.net:8888 where %s(1) is client and %s(2) is stack
     *
     * @param stack
     * @return
     */
    public static final String getDefaultVipAddress(String stack) {
        String client = getApplicationName();
        if (client == null) client = DEFAULT_CLIENT.get();

        String vipAddressTemplate = DynamicPropertyFactory.getInstance().getStringProperty(ZuulConstants.ZUUL_RIBBON_VIPADDRESS_TEMPLATE, null).get();
        if (vipAddressTemplate == null)
            throw new RuntimeException("need to configure zuul.ribbon.vipAddress.template . eg zuul.ribbon.vipAddress.template=%s-%s.netflix.net:8888 where %s(1) is client and %s(2) is stack");

        return String.format(vipAddressTemplate, client, stack);
    }

    public static final class UnitTest {

        @Test
        public void defaultVipAddressForStandardStack() {
            //todo fix
//            assertEquals("null-prod.netflix.net:7001", RibbonConfig.getDefaultVipAddress("prod"));
        }

        @Test
        public void defaultVipAddressForLatAmStack() {
            //todo fix
//            assertEquals("null-prod.latam.netflix.net:7001", RibbonConfig.getDefaultVipAddress("prod.latam"));
        }

    }

}


text:
free_data="$(free)"
mem_data="$(echo "$free_data" | grep 'Mem:')"
free_mem="$(echo "$mem_data" | awk '{print $4}')"
buffers="$(echo "$mem_data" | awk '{print $6}')"
cache="$(echo "$mem_data" | awk '{print $7}')"
total_free=$((free_mem + buffers + cache))
used_swap="$(echo "$free_data" | grep 'Swap:' | awk '{print $3}')"

echo -e "Free memory:\t$total_free kB ($((total_free / 1024)) MB)\nUsed swap:\t$used_swap kB ($((used_swap / 1024)) MB)"
if [[ $used_swap -eq 0 ]]; then
    echo "Congratulations! No swap is in use."
elif [[ $used_swap -lt $total_free ]]; then
    echo "Freeing swap..."
    sudo swapoff -a
    sudo swapon -a
else
    echo "Not enough free memory. Exiting."
    exit 1
fi


text:
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Autofac;
using Foundations.Extensions;
using Xunit;

namespace Foundations.Test
{
    public class AssemblyTests
    {
        [Fact]
        public void GetMatchingAssembliesReturnsValidMatches()
        {
            var expected = new List<Assembly>
            {
                typeof(FactAttribute).Assembly,
                typeof(ContainerBuilder).Assembly
            };

            var names = new List<string>
            {
                "Autofac",
                "xunit.core"
            };

            var actual = names.GetAssembliesFromNames();

            Assert.Equal(expected.Count, actual.Count());

            foreach (var assembly in expected)
            {
                Assert.True(actual.Contains(assembly));
            }
        }

        [Fact]
        public void GetMatchingAssembliesWithSomeInvalidNamesStillWorks()
        {
            var expected = new List<Assembly>
            {
                typeof(FactAttribute).Assembly,
                typeof(ContainerBuilder).Assembly
            };

            var names = new List<string>
            {
                "Autofac",
                "xunit.core",
                "blah blah blah"
            };

            var actual = names.GetAssembliesFromNames();

            foreach (var assembly in expected)
            {
                Assert.True(actual.Contains(assembly));
            }
        }
    }
}


text:
package net.spy.memcached.protocol.binary;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import net.spy.memcached.KeyUtil;
import net.spy.memcached.ops.CASOperation;
import net.spy.memcached.ops.OperationCallback;
import net.spy.memcached.ops.OperationState;
import net.spy.memcached.ops.OperationStatus;
import net.spy.memcached.ops.StoreType;
import net.spy.memcached.ops.VBucketAware;

/**
 * Optimized Set operation for folding a bunch of sets together.
 */
public class OptimizedSetImpl extends MultiKeyOperationImpl {

  private static final OperationCallback NOOP_CALLBACK = new NoopCallback();

  private final int terminalOpaque = generateOpaque();
  private final Map<Integer, OperationCallback> callbacks =
      new HashMap<Integer, OperationCallback>();
  private final List<CASOperation> ops = new ArrayList<CASOperation>();

  // If nothing else, this will be a NOOP.
  private int byteCount = MIN_RECV_PACKET;

  /**
   * Construct an optimized get starting with the given get operation.
   */
  public OptimizedSetImpl(CASOperation firstStore) {
    super(DUMMY_OPCODE, -1, NOOP_CALLBACK);
    addOperation(firstStore);
  }

  public void addOperation(CASOperation op) {
    ops.add(op);

    // Count the bytes required by this operation.
    Iterator<String> is = op.getKeys().iterator();
    String k = is.next();
    int keylen = KeyUtil.getKeyBytes(k).length;

    byteCount += MIN_RECV_PACKET + StoreOperationImpl.EXTRA_LEN + keylen
      + op.getData().length;
  }

  public int size() {
    return ops.size();
  }

  public int bytes() {
    return byteCount;
  }

  @Override
  public void initialize() {
    // Now create a buffer.
    ByteBuffer bb = ByteBuffer.allocate(byteCount);
    for (CASOperation so : ops) {
      Iterator<String> is = so.getKeys().iterator();
      String k = is.next();
      byte[] keyBytes = KeyUtil.getKeyBytes(k);
      assert !is.hasNext();

      int myOpaque = generateOpaque();
      callbacks.put(myOpaque, so.getCallback());
      byte[] data = so.getData();

      // Custom header
      bb.put(REQ_MAGIC);
      bb.put(cmdMap(so.getStoreType()));
      bb.putShort((short) keyBytes.length);
      bb.put((byte) StoreOperationImpl.EXTRA_LEN); // extralen
      bb.put((byte) 0); // data type
      bb.putShort(((VBucketAware) so).getVBucket(k)); // vbucket
      bb.putInt(keyBytes.length + data.length + StoreOperationImpl.EXTRA_LEN);
      bb.putInt(myOpaque);
      bb.putLong(so.getCasValue()); // cas
      // Extras
      bb.putInt(so.getFlags());
      bb.putInt(so.getExpiration());
      // the actual key
      bb.put(keyBytes);
      // And the value
      bb.put(data);
    }
    // Add the noop
    bb.put(REQ_MAGIC);
    bb.put((byte) NoopOperationImpl.CMD);
    bb.putShort((short) 0);
    bb.put((byte) 0); // extralen
    bb.put((byte) 0); // data type
    bb.putShort((short) 0); // reserved
    bb.putInt(0);
    bb.putInt(terminalOpaque);
    bb.putLong(0); // cas

    bb.flip();
    setBuffer(bb);
  }

  private static byte cmdMap(StoreType t) {
    byte rv;
    switch (t) {
    case set:
      rv = StoreOperationImpl.SETQ;
      break;
    case add:
      rv = StoreOperationImpl.ADDQ;
      break;
    case replace:
      rv = StoreOperationImpl.REPLACEQ;
      break;
    default:
      rv = DUMMY_OPCODE;
    }
    // Check fall-through.
    assert rv != DUMMY_OPCODE : "Unhandled store type:  " + t;
    return rv;
  }

  @Override
  protected void finishedPayload(byte[] pl) throws IOException {
    if (responseOpaque == terminalOpaque) {
      for (OperationCallback cb : callbacks.values()) {
        cb.receivedStatus(STATUS_OK);
        cb.complete();
      }
      transitionState(OperationState.COMPLETE);
    } else {
      OperationCallback cb = callbacks.remove(responseOpaque);
      assert cb != null : "No callback for " + responseOpaque;
      assert errorCode != 0 : "Got no error on a quiet mutation.";
      super.finishedPayload(pl);
    }
    resetInput();
  }

  @Override
  protected boolean opaqueIsValid() {
    return responseOpaque == terminalOpaque
        || callbacks.containsKey(responseOpaque);
  }

  static class NoopCallback implements OperationCallback {

    public void complete() {
      // noop
    }

    public void receivedStatus(OperationStatus status) {
      // noop
    }
  }
}


text:
"""Setup script for the Pisces package distribution.

For more information see the Pisces Web pages at
http://www.cnri.reston.va.us/software/pisces/
"""

from distutils.core import setup

setup(# Distribution meta-data
    name = "Pisces",
    version = "1.0",
    description = "Python library for SPKI certificates",
    author = "Jeremy Hylton",
    author_email = "jeremy@alum.mit.edu",
    url = "http://www.cnri.reston.va.us/software/pisces/",

    # Description of the modules and packages in the distribution
    packages = ['pisces', 'pisces.spkilib', 'pisces.ttls']
    )


text:
```puppet
include pip
```

## Installing a package using pip:

```puppet

pip::install { 'Django':
  package        => 'Django', # defaults to $title
  version        => '1.6',    # if undef installs latest version
  python_version => '3.3',    # defaults to 2.7
  ensure         => present,  # defaults to present
}

```


text:
layout: post101
title:  Replication Operations
categories: XAP101ADM
parent: replication.html
weight: 500
---

{% summary %}  {% endsummary %}

The replication module used to synchronize the data and state between two space instances, but each space operations is handled slightly different to achieve maximum reliability and performance.

# Which Operations are Replicated?

- Write/Update/Take of space objects.
- Registration to notify events.
- Object/Notifications lease cancellation or renewal.
- Committed transactions.

{% refer %}
All the operations that are replicated, are also recovered during the space recovery process. See [Space Instance Recovery](./space-instance-recovery.html)
{%endrefer%}

# Which Operations are Not Replicated?

- Notifications on space operations.
- Object/Notifications lease expiration.
- Data loading from the database.
- Uncommitted transactions.
- Space tasks
- Read only operations - read/count etc.

#  Replication Granularity

By default, all data and operations are replicated to all target spaces that belong to the same replication group.
You can control the replication granularity and limit what is replicated and what not. Below are the different replication granularity options:

- **Class level replication** - replicate only specific classes. To configure that you need to set:

{% highlight java %}
cluster-config.groups.group.repl-policy.policy-type=partial-replication
{% endhighlight %}

and add the following annotation to the space class:

{% highlight java %}
@SpaceClass(replicate=false)
public class MyPojo
{
 ...
}
{% endhighlight %}

- **Operation level replication** - space can be configured so that only specific operations are replicated from a source space to the target space(s).

{% info %}
In replicated topology, **the take and clear operations are identical**. Therefore, referrals to the take operation in this section are also relevant for the clear operation.
{%endinfo%}

This can be done by setting the following property:

For example:

{% highlight xml %}
<os-core:embedded-space id="space" name="mySpace">
    <os-core:properties>
        <props>
             <prop key="cluster-config.groups.group.repl-policy.permitted-operations">write, extend_lease, lease_expiration, notify</prop>
        </props>
    </os-core:properties>
</os-core:embedded-space>
{% endhighlight %}

In the example above, the `take` and `update` operations are not replicated , while the `write`, `extend_lease`, `lease_expiration`, and `notify_registration` operations are replicated to all spaces.

{% note %}
All possible operations  are - write, take, extend_lease, update, discard, lease_expiration, notify
An empty value means no operations to be replicated.
{%endnote%}

- **Instance level granularity** - [replication filters](#Replication Filters) can be used to control which objects are replicate and which are not, per object instance.

## Transaction replication

Space transaction is replicated as part of the commit process. This means that uncommitted transactions are saved only on the active space instance and in case of a space instance failure must be restarted by the application.
Once transaction is committed on the active space instance, it is replicated to all the target space instances as one atomic operation.

## Notification registration replication

By default notify registrations are replicated to the target space instance but only the source notifies the listener registered to those events.
The replication in this case is done to ensure that if the source space fails the target will continue to send the events to the registered listeners.
This behavior can be controlled with the following configuration:

Here are the system behaviors when using these options:

{: .table .table-bordered .table-condensed}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
|  cluster-config.groups.group.repl-policy.replicate-notify-templates  | Boolean value. If set to **true**, the notify templates are replicated to the target space. | true|
|  cluster-config.groups.group.repl-policy.trigger-notify-templates  | Boolean value. If set to **true**, the replicated operations will trigger the notify templates and send events to the registered listeners. | false |

A table describing the behavior of combining the different properties:

{: .table .table-bordered .table-condensed}
| Replicate Notify Template Setting | Trigger Notify Template Setting | Explanation |
|:----------------------------------|:--------------------------------|:------------|
| True | False | Client gets notification from the active space after registration.{% wbr %}If the active source space fails the target  space instance will continue to send the events to the registered listeners. |
| False | False | Client gets notification only from those spaces to which it registered.{% wbr %}Client does not get notifications from spaces which received their data by replication. Failover is not supported|
| False | True | Client gets notification only from those spaces that it registered for notification.{% wbr %}Notification occurs when data has been delivered to the space, either by a client application or from the replication. |
| True | True | Client gets notification from all cluster spaces after registration.{% wbr %}Client gets multiple notifications for every space event. |

{% info %}
Enabling both the Replicate notify templates and trigger notify templates triggers an event for each space, so it may result in more events than you initially intended.
 You can use the source of the event to check which space triggered it.
{%endinfo%}

# Conflicting operation handling

Certain scenarios can cause the replication target space instance to receive duplicate or conflicting data updates.
It usually happens in active-active topologies where the replication channel is bidirectional and each space both sends and receives data updates via replication.
Most common scenarios:

1. The same object is added/updated or removed at the same time on two space instances.
1. Data recovery in topology that has more than 2 space instances in the same replication group.
1. Frequent lease expiration/renewal of the same object

The default behavior in these cases is to treat the conflicting operations as duplicates and ignore them.
This can be controlled using the following property:

{: .table .table-bordered .table-condensed}
| Property | Description | Default Value |
|:---------|:------------|:--------------|
| cluster-config.groups.group.repl-policy.on-conflicting-packets | Enum value. If set to **ignore**, the conflicting operations are ignored. If set to **override** the newest operation will override the data in the target.| ignore|

# Replication Optimizations

By default some operations are replicated in an optimized way - only the minimum required data for the operation is replicated.
For example the take operation only replicates the object ID to minimize the network overhead.

Additional optimizations that can affect the replication performance is the update operation. Regular object updates replicate the whole object state - all the properties even those that were not changed. This can be optimized by using `WriteModifier.PARTIAL_UPDATE` modifier when performing the object update. When this modifier is used, the replication will replicate only the changed properties and not the whole object.

{% refer %}
When mirror is used additional settings are required to support the partial update. See [Optimizing the Mirror Activity]({%currentjavaurl%}/asynchronous-persistency-with-the-mirror.html#Optimizing the Mirror Activity).
{%endrefer%}

# Replication Filters

You can call your own business logic whenever the data is replicated. For example, you can modify the space objects data, compress/decompress, or block specific operations and space objects from being replicated to other spaces. Your business logic is called whenever the replication packet leaves the source space (output event), and arrives at the target space (input event).
This is described under the [Cluster Replication Filters](./cluster-replication-filters.html) section.


text:
class Morphology
{
public:
    Morphology(QImage* originImage);
    virtual ~Morphology();

    // return operated image
    QImage* doDilation(const StructElement& se);
    QImage* doErosion(const StructElement& se);
    QImage* doOpening(const StructElement& se);
    QImage* doClosing(const StructElement& se);

    QImage* getOperatedImage() const;

    // return if undo successfully
    bool undo();
    // return if redo successfully
    bool redo();
    // return if can undo
    bool canUndo() const;
    // return if can redo
    bool canRedo() const;

    enum EdgeType {
        ET_STANDARD,
        ET_INTERNAL,
        ET_EXTERNAL
    };

protected:
    static const int BUFFER_SIZE = 32;
    QImage* bufferImage[BUFFER_SIZE];
    int bufferCurrentIndex;
    int bufferUsedIndex;

    virtual QImage* dilationHelper(const QImage& image,
                                   const StructElement& se) const = 0;
    virtual QImage* erosionHelper(const QImage& image,
                                  const StructElement& se) const = 0;
    QImage* openingHelper(const QImage& image,
                          const StructElement& se) const;
    QImage* closingHelper(const QImage& image,
                          const StructElement& se) const;

    // push image to buffer
    void pushImage(QImage* image);

    bool sameImage(const QImage& left, const QImage& right) const;
};

#endif // MORPHOLOGY_H


text:
import React, { Component } from "react"
import * as PropTypes from "prop-types"
import { Header, Grid, Container, Segment, Card, Icon, Image } from 'semantic-ui-react'
import BigTitle from '../components/Text/BigTitle'

const propTypes = {
  data: PropTypes.object.isRequired,
}

class NoticiaTemplate extends Component {
  componentDidMount() {
    //this.props.updateTitle(this.props.data.contentfulNews.title, this.props.data.contentfulNews.date)
  }
  render() {
    const node = this.props.data.contentfulNews
    return (
      <Segment
        inverted
        textAlign='right'
        style={{
          minHeight: 700,
          //padding: '8em 0em',
          paddingTop: 0,
          marginBottom: '8em',
          backgroundColor: 'rgba(0,0,0,0)'
        }}
        vertical
      >
          <Grid container stackable verticalAlign='middle' textAlign="right">
            <Grid.Row>
              <Grid.Column floated='right' width={6}>
                <Image
                  bordered
                  size='large'
                  //href={`/noticias/${(node.title.normalize('NFD').replace(/[\u0300-\u036f]/g, "").replace(/[^A-Z0-9]+/ig, "_")).toLowerCase()}`}
                  src={node.media["0"].responsiveResolution.src}
                />
              </Grid.Column>
              <Grid.Column width={10}>
                <p style={{ color:"white", fontSize: '1.33em', textAlign: 'justify' }}>
                  {node.content.content}
                </p>
                <Grid.Row>
                  <Grid.Column width={16}>
                    <Header inverted>
                      Share Buttons
                    </Header>
                  </Grid.Column>
                </Grid.Row>
              </Grid.Column>
            </Grid.Row>
          </Grid>
        </Segment>
    )
  }
}

export default NoticiaTemplate

export const pageQuery = graphql`
  query articleQuery($id: String!) {
    contentfulNews(id: { eq: $id }) {
      id
      title
      date
      content {
        content
      }
      media {
        responsiveResolution {
          src
        }
      }
    }
  }
`


text:
<?php

/**
 * Product option fee service.
 */
class Service_Product_Option_Fee extends Service
{
	/**
	 * Query models based on optional filters passed in.
	 *
	 * @param array $options The optional data to use.
	 *
	 * @return Query
	 */
	protected static function query(array $options = array())
	{
		$options = array_merge(array(
			'status' => 'active',
		), $options);

		$fees = Model_Product_Option_Fee::query();

		if (!empty($options['id'])) {
			$fees->where('id', $options['id']);
		}

		if (!empty($options['option'])) {
			$fees->related('option');
			$fees->where('option.id', $options['option']->id);
		}

		if (!empty($options['status'])) {
			$fees->where('status', $options['status']);
		}

		return $fees;
	}

	/**
	 * Creates a new product option fee.
	 *
	 * @param string               $name           The name of the product option fee.
	 * @param int                  $interval       Interval amount (1, 6, etc).
	 * @param string               $interval_unit  Interval unit (day, month, year, etc).
	 * @param float                $interval_price Interval price (5.00, 12.99, etc).
	 * @param Model_Product_Option $option         The option the fee belongs to.
	 * @param array                $data           Optional data.
	 *
	 * @return Model_Product_Option_Fee
	 */
	public static function create($name, $interval, $interval_unit, $interval_price, Model_Product_Option $option, array $data = array())
	{
		$fee = Model_Product_Option_Fee::forge();
		$fee->name           = $name;
		$fee->interval       = $interval;
		$fee->interval_unit  = $interval_unit;
		$fee->interval_price = $interval_price;
		$fee->option         = $option;

		$fee->populate($data);

		try {
			$fee->save();
		} catch (FuelException $e) {
			Log::error($e);
			return false;
		}

		Service_Event::trigger('product.option.fee.create', $fee->option->product->seller, $fee->to_array());

		return $fee;
	}

	/**
	 * Updates a product option fee.
	 *
	 * @param Model_Product_Option_Fee $fee  The product option fee to update.
	 * @param array                    $data The data to use to update the product option fee.
	 *
	 * @return Model_Product_Option_Fee
	 */
	public static function update(Model_Product_Option_Fee $fee, array $data = array())
	{
		$fee->populate($data);

		try {
			$fee->save();
		} catch (FuelException $e) {
			Log::error($e);
			return false;
		}

		Service_Event::trigger('product.option.fee.update', $fee->option->product->seller, $fee->to_array());

		return $fee;
	}

	/**
	 * Deletes a product option fee.
	 *
	 * @param Model_Product_Option_Fee $fee The product option fee to delete.
	 *
	 * @return bool
	 */
	public static function delete(Model_Product_Option_Fee $fee)
	{
		$fee->status = 'deleted';

		try {
			$fee->save();
		} catch (FuelException $e) {
			Log::error($e);
			return false;
		}

		Service_Event::trigger('product.option.fee.delete', $fee->option->product->seller, $fee->to_array());

		return true;
	}
}


text:
// Copyright (c) Microsoft. All rights reserved. Licensed under the Apache License, Version 2.0.
// See LICENSE.txt in the project root for complete license information.

/// <reference path='services.ts' />

/* @internal */
namespace ts.BreakpointResolver {
    /**
     * Get the breakpoint span in given sourceFile
     */
    export function spanInSourceFileAtLocation(sourceFile: SourceFile, position: number) {
        // Cannot set breakpoint in dts file
        if (sourceFile.isDeclarationFile) {
            return undefined;
        }

        let tokenAtLocation = getTokenAtPosition(sourceFile, position);
        const lineOfPosition = sourceFile.getLineAndCharacterOfPosition(position).line;
        if (sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getStart(sourceFile)).line > lineOfPosition) {
            // Get previous token if the token is returned starts on new line
            // eg: let x =10; |--- cursor is here
            //     let y = 10;
            // token at position will return let keyword on second line as the token but we would like to use
            // token on same line if trailing trivia (comments or white spaces on same line) part of the last token on that line
            tokenAtLocation = findPrecedingToken(tokenAtLocation.pos, sourceFile);

            // It's a blank line
            if (!tokenAtLocation || sourceFile.getLineAndCharacterOfPosition(tokenAtLocation.getEnd()).line !== lineOfPosition) {
                return undefined;
            }
        }

        // Cannot set breakpoint in ambient declarations
        if (isInAmbientContext(tokenAtLocation)) {
            return undefined;
        }

        // Get the span in the node based on its syntax
        return spanInNode(tokenAtLocation);

        function textSpan(startNode: Node, endNode?: Node) {
            const start = startNode.decorators ?
                skipTrivia(sourceFile.text, startNode.decorators.end) :
                startNode.getStart(sourceFile);
            return createTextSpanFromBounds(start, (endNode || startNode).getEnd());
        }

        function textSpanEndingAtNextToken(startNode: Node, previousTokenToFindNextEndToken: Node): TextSpan {
            return textSpan(startNode, findNextToken(previousTokenToFindNextEndToken, previousTokenToFindNextEndToken.parent));
        }

        function spanInNodeIfStartsOnSameLine(node: Node, otherwiseOnNode?: Node): TextSpan {
            if (node && lineOfPosition === sourceFile.getLineAndCharacterOfPosition(node.getStart(sourceFile)).line) {
                return spanInNode(node);
            }
            return spanInNode(otherwiseOnNode);
        }

        function spanInNodeArray<T extends Node>(nodeArray: NodeArray<T>) {
            return createTextSpanFromBounds(skipTrivia(sourceFile.text, nodeArray.pos), nodeArray.end);
        }

        function spanInPreviousNode(node: Node): TextSpan {
            return spanInNode(findPrecedingToken(node.pos, sourceFile));
        }

        function spanInNextNode(node: Node): TextSpan {
            return spanInNode(findNextToken(node, node.parent));
        }

        function spanInNode(node: Node): TextSpan {
            if (node) {
                switch (node.kind) {
                    case SyntaxKind.VariableStatement:
                        // Span on first variable declaration
                        return spanInVariableDeclaration((<VariableStatement>node).declarationList.declarations[0]);

                    case SyntaxKind.VariableDeclaration:
                    case SyntaxKind.PropertyDeclaration:
                    case SyntaxKind.PropertySignature:
                        return spanInVariableDeclaration(<VariableDeclaration>node);

                    case SyntaxKind.Parameter:
                        return spanInParameterDeclaration(<ParameterDeclaration>node);

                    case SyntaxKind.FunctionDeclaration:
                    case SyntaxKind.MethodDeclaration:
                    case SyntaxKind.MethodSignature:
                    case SyntaxKind.GetAccessor:
                    case SyntaxKind.SetAccessor:
                    case SyntaxKind.Constructor:
                    case SyntaxKind.FunctionExpression:
                    case SyntaxKind.ArrowFunction:
                        return spanInFunctionDeclaration(<FunctionLikeDeclaration>node);

                    case SyntaxKind.Block:
                        if (isFunctionBlock(node)) {
                            return spanInFunctionBlock(<Block>node);
                        }
                    // Fall through
                    case SyntaxKind.ModuleBlock:
                        return spanInBlock(<Block>node);

                    case SyntaxKind.CatchClause:
                        return spanInBlock((<CatchClause>node).block);

                    case SyntaxKind.ExpressionStatement:
                        // span on the expression
                        return textSpan((<ExpressionStatement>node).expression);

                    case SyntaxKind.ReturnStatement:
                        // span on return keyword and expression if present
                        return textSpan(node.getChildAt(0), (<ReturnStatement>node).expression);

                    case SyntaxKind.WhileStatement:
                        // Span on while(...)
                        return textSpanEndingAtNextToken(node, (<WhileStatement>node).expression);

                    case SyntaxKind.DoStatement:
                        // span in statement of the do statement
                        return spanInNode((<DoStatement>node).statement);

                    case SyntaxKind.DebuggerStatement:
                        // span on debugger keyword
                        return textSpan(node.getChildAt(0));

                    case SyntaxKind.IfStatement:
                        // set on if(..) span
                        return textSpanEndingAtNextToken(node, (<IfStatement>node).expression);

                    case SyntaxKind.LabeledStatement:
                        // span in statement
                        return spanInNode((<LabeledStatement>node).statement);

                    case SyntaxKind.BreakStatement:
                    case SyntaxKind.ContinueStatement:
                        // On break or continue keyword and label if present
                        return textSpan(node.getChildAt(0), (<BreakOrContinueStatement>node).label);

                    case SyntaxKind.ForStatement:
                        return spanInForStatement(<ForStatement>node);

                    case SyntaxKind.ForInStatement:
                        // span of for (a in ...)
                        return textSpanEndingAtNextToken(node, (<ForInStatement>node).expression);

                    case SyntaxKind.ForOfStatement:
                        // span in initializer
                        return spanInInitializerOfForLike(<ForOfStatement | ForInStatement>node);

                    case SyntaxKind.SwitchStatement:
                        // span on switch(...)
                        return textSpanEndingAtNextToken(node, (<SwitchStatement>node).expression);

                    case SyntaxKind.CaseClause:
                    case SyntaxKind.DefaultClause:
                        // span in first statement of the clause
                        return spanInNode((<CaseOrDefaultClause>node).statements[0]);

                    case SyntaxKind.TryStatement:
                        // span in try block
                        return spanInBlock((<TryStatement>node).tryBlock);

                    case SyntaxKind.ThrowStatement:
                        // span in throw ...
                        return textSpan(node, (<ThrowStatement>node).expression);

                    case SyntaxKind.ExportAssignment:
                        // span on export = id
                        return textSpan(node, (<ExportAssignment>node).expression);

                    case SyntaxKind.ImportEqualsDeclaration:
                        // import statement without including semicolon
                        return textSpan(node, (<ImportEqualsDeclaration>node).moduleReference);

                    case SyntaxKind.ImportDeclaration:
                        // import statement without including semicolon
                        return textSpan(node, (<ImportDeclaration>node).moduleSpecifier);

                    case SyntaxKind.ExportDeclaration:
                        // import statement without including semicolon
                        return textSpan(node, (<ExportDeclaration>node).moduleSpecifier);

                    case SyntaxKind.ModuleDeclaration:
                        // span on complete module if it is instantiated
                        if (getModuleInstanceState(node) !== ModuleInstanceState.Instantiated) {
                            return undefined;
                        }

                    case SyntaxKind.ClassDeclaration:
                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.EnumMember:
                    case SyntaxKind.BindingElement:
                        // span on complete node
                        return textSpan(node);

                    case SyntaxKind.WithStatement:
                        // span in statement
                        return spanInNode((<WithStatement>node).statement);

                    case SyntaxKind.Decorator:
                        return spanInNodeArray(node.parent.decorators);

                    case SyntaxKind.ObjectBindingPattern:
                    case SyntaxKind.ArrayBindingPattern:
                        return spanInBindingPattern(<BindingPattern>node);

                    // No breakpoint in interface, type alias
                    case SyntaxKind.InterfaceDeclaration:
                    case SyntaxKind.TypeAliasDeclaration:
                        return undefined;

                    // Tokens:
                    case SyntaxKind.SemicolonToken:
                    case SyntaxKind.EndOfFileToken:
                        return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile));

                    case SyntaxKind.CommaToken:
                        return spanInPreviousNode(node);

                    case SyntaxKind.OpenBraceToken:
                        return spanInOpenBraceToken(node);

                    case SyntaxKind.CloseBraceToken:
                        return spanInCloseBraceToken(node);

                    case SyntaxKind.CloseBracketToken:
                        return spanInCloseBracketToken(node);

                    case SyntaxKind.OpenParenToken:
                        return spanInOpenParenToken(node);

                    case SyntaxKind.CloseParenToken:
                        return spanInCloseParenToken(node);

                    case SyntaxKind.ColonToken:
                        return spanInColonToken(node);

                    case SyntaxKind.GreaterThanToken:
                    case SyntaxKind.LessThanToken:
                        return spanInGreaterThanOrLessThanToken(node);

                    // Keywords:
                    case SyntaxKind.WhileKeyword:
                        return spanInWhileKeyword(node);

                    case SyntaxKind.ElseKeyword:
                    case SyntaxKind.CatchKeyword:
                    case SyntaxKind.FinallyKeyword:
                        return spanInNextNode(node);

                    case SyntaxKind.OfKeyword:
                        return spanInOfKeyword(node);

                    default:
                        // Destructuring pattern in destructuring assignment
                        // [a, b, c] of
                        // [a, b, c] = expression
                        if (isArrayLiteralOrObjectLiteralDestructuringPattern(node)) {
                            return spanInArrayLiteralOrObjectLiteralDestructuringPattern(<DestructuringPattern>node);
                        }

                        // Set breakpoint on identifier element of destructuring pattern
                        // a or ...c  or d: x from
                        // [a, b, ...c] or { a, b } or { d: x } from destructuring pattern
                        if ((node.kind === SyntaxKind.Identifier ||
                            node.kind == SyntaxKind.SpreadElement ||
                            node.kind === SyntaxKind.PropertyAssignment ||
                            node.kind === SyntaxKind.ShorthandPropertyAssignment) &&
                            isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                            return textSpan(node);
                        }

                        if (node.kind === SyntaxKind.BinaryExpression) {
                            const binaryExpression = <BinaryExpression>node;
                            // Set breakpoint in destructuring pattern if its destructuring assignment
                            // [a, b, c] or {a, b, c} of
                            // [a, b, c] = expression or
                            // {a, b, c} = expression
                            if (isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left)) {
                                return spanInArrayLiteralOrObjectLiteralDestructuringPattern(
                                    <ArrayLiteralExpression | ObjectLiteralExpression>binaryExpression.left);
                            }

                            if (binaryExpression.operatorToken.kind === SyntaxKind.EqualsToken &&
                                isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.parent)) {
                                // Set breakpoint on assignment expression element of destructuring pattern
                                // a = expression of
                                // [a = expression, b, c] = someExpression or
                                // { a = expression, b, c } = someExpression
                                return textSpan(node);
                            }

                            if (binaryExpression.operatorToken.kind === SyntaxKind.CommaToken) {
                                return spanInNode(binaryExpression.left);
                            }
                        }

                        if (isPartOfExpression(node)) {
                            switch (node.parent.kind) {
                                case SyntaxKind.DoStatement:
                                    // Set span as if on while keyword
                                    return spanInPreviousNode(node);

                                case SyntaxKind.Decorator:
                                    // Set breakpoint on the decorator emit
                                    return spanInNode(node.parent);

                                case SyntaxKind.ForStatement:
                                case SyntaxKind.ForOfStatement:
                                    return textSpan(node);

                                case SyntaxKind.BinaryExpression:
                                    if ((<BinaryExpression>node.parent).operatorToken.kind === SyntaxKind.CommaToken) {
                                        // If this is a comma expression, the breakpoint is possible in this expression
                                        return textSpan(node);
                                    }
                                    break;

                                case SyntaxKind.ArrowFunction:
                                    if ((<FunctionLikeDeclaration>node.parent).body === node) {
                                        // If this is body of arrow function, it is allowed to have the breakpoint
                                        return textSpan(node);
                                    }
                                    break;
                            }
                        }

                        // If this is name of property assignment, set breakpoint in the initializer
                        if (node.parent.kind === SyntaxKind.PropertyAssignment &&
                            (<PropertyDeclaration>node.parent).name === node &&
                            !isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent.parent)) {
                            return spanInNode((<PropertyDeclaration>node.parent).initializer);
                        }

                        // Breakpoint in type assertion goes to its operand
                        if (node.parent.kind === SyntaxKind.TypeAssertionExpression && (<TypeAssertion>node.parent).type === node) {
                            return spanInNextNode((<TypeAssertion>node.parent).type);
                        }

                        // return type of function go to previous token
                        if (isFunctionLike(node.parent) && (<FunctionLikeDeclaration>node.parent).type === node) {
                            return spanInPreviousNode(node);
                        }

                        // initializer of variable/parameter declaration go to previous node
                        if ((node.parent.kind === SyntaxKind.VariableDeclaration ||
                            node.parent.kind === SyntaxKind.Parameter)) {
                            const paramOrVarDecl = <VariableDeclaration | ParameterDeclaration>node.parent;
                            if (paramOrVarDecl.initializer === node ||
                                paramOrVarDecl.type === node ||
                                isAssignmentOperator(node.kind)) {
                                return spanInPreviousNode(node);
                            }
                        }

                        if (node.parent.kind === SyntaxKind.BinaryExpression) {
                            const binaryExpression = <BinaryExpression>node.parent;
                            if (isArrayLiteralOrObjectLiteralDestructuringPattern(binaryExpression.left) &&
                                (binaryExpression.right === node ||
                                    binaryExpression.operatorToken === node)) {
                                // If initializer of destructuring assignment move to previous token
                                return spanInPreviousNode(node);
                            }
                        }

                        // Default go to parent to set the breakpoint
                        return spanInNode(node.parent);
                }
            }

            function textSpanFromVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
                const declarations = variableDeclaration.parent.declarations;
                if (declarations && declarations[0] === variableDeclaration) {
                    // First declaration - include let keyword
                    return textSpan(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent), variableDeclaration);
                }
                else {
                    // Span only on this declaration
                    return textSpan(variableDeclaration);
                }
            }

            function spanInVariableDeclaration(variableDeclaration: VariableDeclaration): TextSpan {
                // If declaration of for in statement, just set the span in parent
                if (variableDeclaration.parent.parent.kind === SyntaxKind.ForInStatement) {
                    return spanInNode(variableDeclaration.parent.parent);
                }

                // If this is a destructuring pattern, set breakpoint in binding pattern
                if (isBindingPattern(variableDeclaration.name)) {
                    return spanInBindingPattern(<BindingPattern>variableDeclaration.name);
                }

                // Breakpoint is possible in variableDeclaration only if there is initialization
                // or its declaration from 'for of'
                if (variableDeclaration.initializer ||
                    hasModifier(variableDeclaration, ModifierFlags.Export) ||
                    variableDeclaration.parent.parent.kind === SyntaxKind.ForOfStatement) {
                    return textSpanFromVariableDeclaration(variableDeclaration);
                }

                const declarations = variableDeclaration.parent.declarations;
                if (declarations && declarations[0] !== variableDeclaration) {
                    // If we cannot set breakpoint on this declaration, set it on previous one
                    // Because the variable declaration may be binding pattern and
                    // we would like to set breakpoint in last binding element if that's the case,
                    // use preceding token instead
                    return spanInNode(findPrecedingToken(variableDeclaration.pos, sourceFile, variableDeclaration.parent));
                }
            }

            function canHaveSpanInParameterDeclaration(parameter: ParameterDeclaration): boolean {
                // Breakpoint is possible on parameter only if it has initializer, is a rest parameter, or has public or private modifier
                return !!parameter.initializer || parameter.dotDotDotToken !== undefined ||
                    hasModifier(parameter, ModifierFlags.Public | ModifierFlags.Private);
            }

            function spanInParameterDeclaration(parameter: ParameterDeclaration): TextSpan {
                if (isBindingPattern(parameter.name)) {
                    // Set breakpoint in binding pattern
                    return spanInBindingPattern(<BindingPattern>parameter.name);
                }
                else if (canHaveSpanInParameterDeclaration(parameter)) {
                    return textSpan(parameter);
                }
                else {
                    const functionDeclaration = <FunctionLikeDeclaration>parameter.parent;
                    const indexOfParameter = indexOf(functionDeclaration.parameters, parameter);
                    if (indexOfParameter) {
                        // Not a first parameter, go to previous parameter
                        return spanInParameterDeclaration(functionDeclaration.parameters[indexOfParameter - 1]);
                    }
                    else {
                        // Set breakpoint in the function declaration body
                        return spanInNode(functionDeclaration.body);
                    }
                }
            }

            function canFunctionHaveSpanInWholeDeclaration(functionDeclaration: FunctionLikeDeclaration) {
                return hasModifier(functionDeclaration, ModifierFlags.Export) ||
                    (functionDeclaration.parent.kind === SyntaxKind.ClassDeclaration && functionDeclaration.kind !== SyntaxKind.Constructor);
            }

            function spanInFunctionDeclaration(functionDeclaration: FunctionLikeDeclaration): TextSpan {
                // No breakpoints in the function signature
                if (!functionDeclaration.body) {
                    return undefined;
                }

                if (canFunctionHaveSpanInWholeDeclaration(functionDeclaration)) {
                    // Set the span on whole function declaration
                    return textSpan(functionDeclaration);
                }

                // Set span in function body
                return spanInNode(functionDeclaration.body);
            }

            function spanInFunctionBlock(block: Block): TextSpan {
                const nodeForSpanInBlock = block.statements.length ? block.statements[0] : block.getLastToken();
                if (canFunctionHaveSpanInWholeDeclaration(<FunctionLikeDeclaration>block.parent)) {
                    return spanInNodeIfStartsOnSameLine(block.parent, nodeForSpanInBlock);
                }

                return spanInNode(nodeForSpanInBlock);
            }

            function spanInBlock(block: Block): TextSpan {
                switch (block.parent.kind) {
                    case SyntaxKind.ModuleDeclaration:
                        if (getModuleInstanceState(block.parent) !== ModuleInstanceState.Instantiated) {
                            return undefined;
                        }

                    // Set on parent if on same line otherwise on first statement
                    case SyntaxKind.WhileStatement:
                    case SyntaxKind.IfStatement:
                    case SyntaxKind.ForInStatement:
                        return spanInNodeIfStartsOnSameLine(block.parent, block.statements[0]);

                    // Set span on previous token if it starts on same line otherwise on the first statement of the block
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForOfStatement:
                        return spanInNodeIfStartsOnSameLine(findPrecedingToken(block.pos, sourceFile, block.parent), block.statements[0]);
                }

                // Default action is to set on first statement
                return spanInNode(block.statements[0]);
            }

            function spanInInitializerOfForLike(forLikeStatement: ForStatement | ForOfStatement | ForInStatement): TextSpan {
                if (forLikeStatement.initializer.kind === SyntaxKind.VariableDeclarationList) {
                    // Declaration list - set breakpoint in first declaration
                    const variableDeclarationList = <VariableDeclarationList>forLikeStatement.initializer;
                    if (variableDeclarationList.declarations.length > 0) {
                        return spanInNode(variableDeclarationList.declarations[0]);
                    }
                }
                else {
                    // Expression - set breakpoint in it
                    return spanInNode(forLikeStatement.initializer);
                }
            }

            function spanInForStatement(forStatement: ForStatement): TextSpan {
                if (forStatement.initializer) {
                    return spanInInitializerOfForLike(forStatement);
                }

                if (forStatement.condition) {
                    return textSpan(forStatement.condition);
                }
                if (forStatement.incrementor) {
                    return textSpan(forStatement.incrementor);
                }
            }

            function spanInBindingPattern(bindingPattern: BindingPattern): TextSpan {
                // Set breakpoint in first binding element
                const firstBindingElement = forEach(bindingPattern.elements,
                    element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);

                if (firstBindingElement) {
                    return spanInNode(firstBindingElement);
                }

                // Empty binding pattern of binding element, set breakpoint on binding element
                if (bindingPattern.parent.kind === SyntaxKind.BindingElement) {
                    return textSpan(bindingPattern.parent);
                }

                // Variable declaration is used as the span
                return textSpanFromVariableDeclaration(<VariableDeclaration>bindingPattern.parent);
            }

            function spanInArrayLiteralOrObjectLiteralDestructuringPattern(node: DestructuringPattern): TextSpan {
                Debug.assert(node.kind !== SyntaxKind.ArrayBindingPattern && node.kind !== SyntaxKind.ObjectBindingPattern);
                const elements: NodeArray<Expression | ObjectLiteralElement> =
                    node.kind === SyntaxKind.ArrayLiteralExpression ?
                        (<ArrayLiteralExpression>node).elements :
                        (<ObjectLiteralExpression>node).properties;

                const firstBindingElement = forEach(elements,
                    element => element.kind !== SyntaxKind.OmittedExpression ? element : undefined);

                if (firstBindingElement) {
                    return spanInNode(firstBindingElement);
                }

                // Could be ArrayLiteral from destructuring assignment or
                // just nested element in another destructuring assignment
                // set breakpoint on assignment when parent is destructuring assignment
                // Otherwise set breakpoint for this element
                return textSpan(node.parent.kind === SyntaxKind.BinaryExpression ? node.parent : node);
            }

            // Tokens:
            function spanInOpenBraceToken(node: Node): TextSpan {
                switch (node.parent.kind) {
                    case SyntaxKind.EnumDeclaration:
                        const enumDeclaration = <EnumDeclaration>node.parent;
                        return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), enumDeclaration.members.length ? enumDeclaration.members[0] : enumDeclaration.getLastToken(sourceFile));

                    case SyntaxKind.ClassDeclaration:
                        const classDeclaration = <ClassDeclaration>node.parent;
                        return spanInNodeIfStartsOnSameLine(findPrecedingToken(node.pos, sourceFile, node.parent), classDeclaration.members.length ? classDeclaration.members[0] : classDeclaration.getLastToken(sourceFile));

                    case SyntaxKind.CaseBlock:
                        return spanInNodeIfStartsOnSameLine(node.parent.parent, (<CaseBlock>node.parent).clauses[0]);
                }

                // Default to parent node
                return spanInNode(node.parent);
            }

            function spanInCloseBraceToken(node: Node): TextSpan {
                switch (node.parent.kind) {
                    case SyntaxKind.ModuleBlock:
                        // If this is not an instantiated module block, no bp span
                        if (getModuleInstanceState(node.parent.parent) !== ModuleInstanceState.Instantiated) {
                            return undefined;
                        }

                    case SyntaxKind.EnumDeclaration:
                    case SyntaxKind.ClassDeclaration:
                        // Span on close brace token
                        return textSpan(node);

                    case SyntaxKind.Block:
                        if (isFunctionBlock(node.parent)) {
                            // Span on close brace token
                            return textSpan(node);
                        }
                        // fall through

                    case SyntaxKind.CatchClause:
                        return spanInNode(lastOrUndefined((<Block>node.parent).statements));

                    case SyntaxKind.CaseBlock:
                        // breakpoint in last statement of the last clause
                        const caseBlock = <CaseBlock>node.parent;
                        const lastClause = lastOrUndefined(caseBlock.clauses);
                        if (lastClause) {
                            return spanInNode(lastOrUndefined(lastClause.statements));
                        }
                        return undefined;

                    case SyntaxKind.ObjectBindingPattern:
                        // Breakpoint in last binding element or binding pattern if it contains no elements
                        const bindingPattern = <BindingPattern>node.parent;
                        return spanInNode(lastOrUndefined(bindingPattern.elements) || bindingPattern);

                    // Default to parent node
                    default:
                        if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                            // Breakpoint in last binding element or binding pattern if it contains no elements
                            const objectLiteral = <ObjectLiteralExpression>node.parent;
                            return textSpan(lastOrUndefined(objectLiteral.properties) || objectLiteral);
                        }
                        return spanInNode(node.parent);
                }
            }

            function spanInCloseBracketToken(node: Node): TextSpan {
                switch (node.parent.kind) {
                    case SyntaxKind.ArrayBindingPattern:
                        // Breakpoint in last binding element or binding pattern if it contains no elements
                        const bindingPattern = <BindingPattern>node.parent;
                        return textSpan(lastOrUndefined(bindingPattern.elements) || bindingPattern);

                    default:
                        if (isArrayLiteralOrObjectLiteralDestructuringPattern(node.parent)) {
                            // Breakpoint in last binding element or binding pattern if it contains no elements
                            const arrayLiteral = <ArrayLiteralExpression>node.parent;
                            return textSpan(lastOrUndefined(arrayLiteral.elements) || arrayLiteral);
                        }

                        // Default to parent node
                        return spanInNode(node.parent);
                }
            }

            function spanInOpenParenToken(node: Node): TextSpan {
                if (node.parent.kind === SyntaxKind.DoStatement || // Go to while keyword and do action instead
                    node.parent.kind === SyntaxKind.CallExpression ||
                    node.parent.kind === SyntaxKind.NewExpression) {
                    return spanInPreviousNode(node);
                }

                if (node.parent.kind === SyntaxKind.ParenthesizedExpression) {
                    return spanInNextNode(node);
                }

                // Default to parent node
                return spanInNode(node.parent);
            }

            function spanInCloseParenToken(node: Node): TextSpan {
                // Is this close paren token of parameter list, set span in previous token
                switch (node.parent.kind) {
                    case SyntaxKind.FunctionExpression:
                    case SyntaxKind.FunctionDeclaration:
                    case SyntaxKind.ArrowFunction:
                    case SyntaxKind.MethodDeclaration:
                    case SyntaxKind.MethodSignature:
                    case SyntaxKind.GetAccessor:
                    case SyntaxKind.SetAccessor:
                    case SyntaxKind.Constructor:
                    case SyntaxKind.WhileStatement:
                    case SyntaxKind.DoStatement:
                    case SyntaxKind.ForStatement:
                    case SyntaxKind.ForOfStatement:
                    case SyntaxKind.CallExpression:
                    case SyntaxKind.NewExpression:
                    case SyntaxKind.ParenthesizedExpression:
                        return spanInPreviousNode(node);

                    // Default to parent node
                    default:
                        return spanInNode(node.parent);
                }
            }

            function spanInColonToken(node: Node): TextSpan {
                // Is this : specifying return annotation of the function declaration
                if (isFunctionLike(node.parent) ||
                    node.parent.kind === SyntaxKind.PropertyAssignment ||
                    node.parent.kind === SyntaxKind.Parameter) {
                    return spanInPreviousNode(node);
                }

                return spanInNode(node.parent);
            }

            function spanInGreaterThanOrLessThanToken(node: Node): TextSpan {
                if (node.parent.kind === SyntaxKind.TypeAssertionExpression) {
                    return spanInNextNode(node);
                }

                return spanInNode(node.parent);
            }

            function spanInWhileKeyword(node: Node): TextSpan {
                if (node.parent.kind === SyntaxKind.DoStatement) {
                    // Set span on while expression
                    return textSpanEndingAtNextToken(node, (<DoStatement>node.parent).expression);
                }

                // Default to parent node
                return spanInNode(node.parent);
            }

            function spanInOfKeyword(node: Node): TextSpan {
                if (node.parent.kind === SyntaxKind.ForOfStatement) {
                    // Set using next token
                    return spanInNextNode(node);
                }

                // Default to parent node
                return spanInNode(node.parent);
            }
        }
    }
}