text:
from helpers import *
from basecommands import simplecommand
from basecommands import Validate

vanished = []

def is_authorized(player):
    return player.hasPermission("utils.vanish")

def is_vanished(player):
    return uid(player) in vanished

#this can be used to silently set the vanished state of a player
def set_state(player, state):
    if state == is_vanished(player):
        return

    if state:
        enable_vanish(player)
    else:
        disable_vanish(player)

def enable_vanish(target):
    vanished.append(uid(target))
    for player in list(server.getOnlinePlayers()):
        if not is_authorized(player):
            player.hidePlayer(target)

def disable_vanish(target):
    vanished.remove(uid(target))
    for player in list(server.getOnlinePlayers()):
        player.showPlayer(target)

@simplecommand("vanish",
        aliases = ["v"],
        usage = "[on/off]",
        description = "Toggles vanish mode, hiding you and your online status \nfrom other players.",
        senderLimit = 0,
        amin = 0,
        amax = 1,
        helpNoargs = False,
        helpSubcmd = True
)
def vanish_command(sender, command, label, args):
    try:
        current_state = is_vanished(sender)
        new_state = not current_state

        if len(args) == 1:
            arg = args[0].lower()
            if arg == "on":
                new_state = True
            elif arg == "off":
                new_state = False

        if current_state == new_state:
            return "&cYou were %s vanished!" % ("already" if current_state else "not yet")

        set_state(sender, new_state)
        return "&a%s vanish mode!" % ("Enabled" if new_state else "Disabled")
    except:
        error(trace())

@hook.event("player.PlayerJoinEvent")
def on_player_join(event):
    player = event.getPlayer()

    if not is_authorized(player):
        for uuid in vanished:
            player.hidePlayer(retrieve_player(uuid))

    elif is_vanished(player):
        msg(player, "&cKeep in mind that you are still vanished! Use /vanish to disable.")

@hook.event("player.PlayerQuitEvent")
def on_player_quit(event):
    player = event.getPlayer()

    if not is_authorized(player):
        for uuid in vanished:
            player.showPlayer(retrieve_player(uuid))

@simplecommand("vanishother",
        usage = "{player} [on/off]",
        description = "Toggles vanish mode for someone, hiding them and their online status from other players.",
        amin = 1,
        amax = 2,
        helpNoargs = True,
        helpSubcmd = True)
def vanishother_command(sender, command, label, args):
    target = server.getPlayer(args[0])
    Validate.notNone(target, "&cThe specified player is not online")

    current_state = is_vanished(target)
    new_state     = not current_state

    if len(args) == 2:
        arg = args[1].lower()
        if arg == "on":
            new_state = True
        elif arg == "off":
            new_state = False

    if current_state == new_state:
        return "&cThat player was already vanished!" if current_state else "&cThat player was not yet vanished!"

    set_state(target, new_state)

    enabled_str = "enabled" if new_state else "disabled"
    if target != sender:
        msg(target, "&aVanish mode %s by %s" % (enabled_str, sender.getDisplayName() if is_player(sender) else "&9CONSOLE"))
    return "&aVanish mode %s%s" % (enabled_str, " for " + target.getDisplayName() if target != sender else "")


text:
CTweener::CTweener()
: CTweener(Easings::Linear::easeIn, 0.0f, 1.0f, CTime::Seconds(1.0f))
{

}

CTweener::CTweener(TEasingFunction theFunction, float startValue, float endValue, CTime duration)
{
    mEasingFunction = theFunction;
    mStartValue = startValue;
    mEndValue = endValue;
    mRange = endValue - startValue;
    mDuration = duration;
    mReversible = false;
    Reset();
}

CTweener::~CTweener()
{

}

void CTweener::Reset()
{
    mCurrentTime = CTime::Zero;
    mCurrentValue = mStartValue;
}

float CTweener::Advance(CTime elapsedTime)
{
    mCurrentTime += elapsedTime;
    if (mCurrentTime > mDuration && mReversible)
    {
        Reverse();
    }

    if (mCurrentTime < CTime::Zero)
    {
        mCurrentValue = mStartValue;
    }
    else if (mCurrentTime > mDuration)
    {
        mCurrentValue = mEndValue;
    }
    else
    {
        mCurrentValue =  mEasingFunction(mCurrentTime.asSeconds(), mStartValue, mRange, mDuration.asSeconds());
    }
    return mCurrentValue;
}

float CTweener::GetCurrentValue()
{
    return mCurrentValue;
}

CTime CTweener::GetCurrentTime()
{
    return mCurrentTime;
}

CTime CTweener::GetDuration()
{
    return mDuration;
}

void CTweener::SetReversible(bool reversible)
{
    mReversible = reversible;
}

bool CTweener::IsDone()
{
    return mCurrentTime >= mDuration;
}

void CTweener::Reverse()
{
    mCurrentTime -= mDuration;
    float temp = mStartValue;
    mStartValue = mEndValue;
    mEndValue = temp;
    mRange = mEndValue - mStartValue;
}

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Cewi\CakephpTbStarter\View\Helper;

use Cake\View\Helper\HtmlHelper as Helper;
use Cake\View\View;

/**
 * CakePHP FormHelper
 * @author wichmanc
 */
class HtmlHelper extends Helper
{

    use IconTrait;

    /**
     * Converts "normal" postLinks in iconified postLinks
     * title is converted to an icon depending on action name
     * if $option keetTitle is set, icon will be added to teh original title.
     *
     * @access public
     * @since 04.01.2015
     * @param string $title
     * @param type $url
     * @param array $options Options. If keepTitle is set, icon will be added to the original title.
     * @return string
     */
    public function link($title, $url = null, array $options = [])
    {
        if (isset($options['icon']) && !empty($options['icon'])) {
            $options['title'] = $title;
            $title = $this->_icon($options['icon']);
            if (!isset($options['short']) || $options['short'] == false) {
                $title .= ' ' . $options['title'];
            }
            unset($options['icon']);
            unset($options['short']);
            $options['escape'] = FALSE;
        };
        return parent::link($title, $url, $options);
    }

    /**
     * prints out an span with the icon
     *
     * @access public
     * @since 04.01.2015
     * @param string $iconName
     * @return string
     */
    public function icon($iconName = '')
    {
        return $this->_icon($iconName);
    }

}


text:
#ifndef weaver_node_prog_n_gram_path_h_
#define weaver_node_prog_n_gram_path_h_

#include <string>

#include "common/property_predicate.h"
#include "db/remote_node.h"
#include "node_prog/node.h"
#include "node_prog/edge.h"
#include "node_prog/base_classes.h"
#include "node_prog/cache_response.h"

namespace node_prog
{
    /* parameter passing to a node */
    struct n_gram_path_params: public virtual Node_Parameters_Base
    {
        /* node & edge predicates */
        std::vector<predicate::prop_predicate> node_preds;
        std::vector<predicate::prop_predicate> edge_preds;

        std::unordered_map<uint32_t, uint32_t> progress;

        /* coordinator */
        db::remote_node coord;
        std::vector<node_handle_t> remaining_path;
        uint32_t step;
        bool unigram;

        n_gram_path_params();
        ~n_gram_path_params() { }
        uint64_t size() const;
        void pack(e::packer&) const;
        void unpack(e::unpacker&);

        // no caching
        bool search_cache() { return false; }
        cache_key_t cache_key() { return cache_key_t(); }
    };

    /* overall state of a node */
    struct n_gram_path_state: public virtual Node_State_Base
    {
        n_gram_path_state();
        ~n_gram_path_state() { }
        uint64_t size() const;
        void pack(e::packer&) const;
        void unpack(e::unpacker&);
    };

   std::pair<search_type, std::vector<std::pair<db::remote_node, n_gram_path_params>>>
   n_gram_path_node_program(node &n,   /* current node */
       db::remote_node &rn,                 /* current node for access remotely */
       n_gram_path_params &params,     /* passed parameters */
       std::function<n_gram_path_state&()> state_getter,   /* the function to get state */
       std::function<void(std::shared_ptr<Cache_Value_Base>, std::shared_ptr<std::vector<db::remote_node>>, cache_key_t)>&,                           /* caching thing */
       cache_response<Cache_Value_Base>*);
}

#endif


text:
import React from 'react';
import { storiesOf } from '@storybook/react';
import CustomSelectorWrapper from '../examples/CustomSelectorWrapper';

storiesOf('CustomSelector', module)
  .add('basical', () => (
    <CustomSelectorWrapper />
  ))
  .add('disabled', () => (
    <CustomSelectorWrapper disabled />
  ));


text:
import logging
import os
from absl import flags

from chrome_ent_test.infra.core import environment, before_all, test
from infra import ChromeEnterpriseTestCase

FLAGS = flags.FLAGS

@environment(file="../policy_test.asset.textpb")
class BookmarkBarEnabledTest(ChromeEnterpriseTestCase):
  """Test the BookmarkBarEnabled

    https://cloud.google.com/docs/chrome-enterprise/policies/?policy=BookmarkBarEnabled.

    If this setting is left not set the user can decide to use this function
    or not.
    """

  @before_all
  def setup(self):
    self.InstallChrome(self.win_config['client'])
    self.EnableUITest(self.win_config['client'])

  def _getUIStructure(self, instance_name):
    local_dir = os.path.dirname(os.path.abspath(__file__))
    output = self.RunUITest(instance_name,
                            os.path.join(local_dir, 'bookmarkbar_webdriver.py'))
    return output

  @test
  def test_bookmark_bar_enabled(self):
    # Enable bookmark bar
    self.SetPolicy(self.win_config['dc'], r'BookmarkBarEnabled', 1, 'DWORD')
    self.RunCommand(self.win_config['client'], 'gpupdate /force')
    logging.info('Enabled bookmark bar')

    output = self._getUIStructure(self.win_config['client'])
    self.assertIn('Bookmarkbar is found', output)

  @test
  def test_bookmark_bar_disabled(self):
    # Disable bookmark bar
    self.SetPolicy(self.win_config['dc'], r'BookmarkBarEnabled', 0, 'DWORD')
    self.RunCommand(self.win_config['client'], 'gpupdate /force')
    logging.info('Disabled bookmark bar')

    output = self._getUIStructure(self.win_config['client'])
    self.assertIn('Bookmarkbar is missing', output)


text:
package consulo.ui.app;

import consulo.disposer.Disposer;
import consulo.ui.*;
import consulo.ui.annotation.RequiredUIAccess;
import consulo.ui.layout.DockLayout;
import consulo.ui.layout.HorizontalLayout;
import consulo.ui.layout.Layout;
import consulo.ui.Size;
import consulo.ui.border.BorderPosition;
import consulo.ui.border.BorderStyle;
import consulo.ui.style.ComponentColors;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

/**
 * @author VISTALL
 * @since 25-Oct-17
 * <p>
 * Wrapper like {@link com.intellij.openapi.ui.DialogWrapper} but for Consulo UI
 */
public abstract class WindowWrapper {
  private Window myWindow;
  private String myTitle;

  private Boolean myPreOkEnabled;

  private Button myOkButton;

  public WindowWrapper(@Nonnull String title) {
    myTitle = title;
  }

  @Nonnull
  @RequiredUIAccess
  protected abstract Component createCenterComponent();

  @Nullable
  protected Size getDefaultSize() {
    return null;
  }

  /**
   * Not block UI
   */
  @RequiredUIAccess
  public void showAsync() {
    if (myWindow != null) {
      throw new IllegalArgumentException();
    }

    myWindow = Window.create(myTitle, WindowOptions.builder().owner(Window.getActiveWindow()).build());
    Size defaultSize = getDefaultSize();
    if (defaultSize != null) {
      myWindow.setSize(defaultSize);
    }

    Layout rootLayout = buildRootLayout();
    myWindow.setContent(rootLayout);

    myWindow.show();
  }

  @Nonnull
  @RequiredUIAccess
  protected Layout buildRootLayout() {
    DockLayout rootLayout = DockLayout.create();
    rootLayout.center(createCenterComponent());
    rootLayout.bottom(buildButtonsLayout());
    return rootLayout;
  }

  @Nonnull
  @RequiredUIAccess
  protected Layout buildButtonsLayout() {
    DockLayout dockLayout = DockLayout.create();
    dockLayout.addBorder(BorderPosition.TOP, BorderStyle.LINE, ComponentColors.BORDER, 1);

    HorizontalLayout bottomLayout = HorizontalLayout.create();
    myOkButton = Button.create("OK", e -> doOKAction());
    if(myPreOkEnabled != null) {
      myOkButton.setEnabled(myPreOkEnabled);
    }
    bottomLayout.add(myOkButton);
    Button cancelButton = Button.create("Cancel", e -> doCancelAction());
    bottomLayout.add(cancelButton);

    bottomLayout.addBorders(BorderStyle.EMPTY, null, 5);

    return dockLayout.right(bottomLayout);
  }

  @RequiredUIAccess
  public void doOKAction() {
    close();
  }

  @RequiredUIAccess
  public void setOKEnabled(boolean value) {
    if(myOkButton == null) {
      myPreOkEnabled = value;
    }
    else {
      myOkButton.setEnabled(value);
    }
  }

  @RequiredUIAccess
  public void doCancelAction() {
    close();
  }

  @RequiredUIAccess
  public void close() {
    if (myWindow == null) {
      return;
    }
    myWindow.close();
    Disposer.dispose(myWindow);
    myWindow = null;
    myOkButton = null;
  }
}


text:
package org.fi;

import org.fi.*;
import org.fi.FMServer.FailType;
import org.fi.FMJoinPoint.*;

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

public class FMFilter {

    //JINSU hack
    //Filter Id specified in wl-config.xml
    //public static String FID = FMLogic.FILTER_ID;
  public FMFilter() {}

  // *************************************************
  // This is the part where "extensible. Given information
  // in fac, and ft.  You can specify which failure that you
  // want to exercise
  // *************************************************
  public static boolean passServerFilter(FMAllContext fac, FailType ft, FIState fis) {
    String FID = FMLogic.FILTER_ID;
    if(FID.equals("") || FID == null) {
        FID = FMLogic.getFilterId();
    }
    boolean passFilter = false;
    FID = FID.toLowerCase().trim();
    if(FID.equals("readrepair1")) {
        passFilter = filterReadRepairTest1(fac, ft, fis);

    }
    else if(FID.equals("readrepair2")) {
        passFilter = filterReadRepairTest2(fac, ft, fis);

    }
    else if(FID.equals("readrepair3")) {
        passFilter = filterReadRepairTest3(fac, ft, fis);

    }
    else if(FID.equals("insertion1")) {
        passFilter = filterInsertionTest1(fac, ft, fis);
    }
    else if(FID.equals("insertion2")) {
        passFilter = filterInsertionTest2(fac, ft, fis);

    }
    else {
        passFilter = filterReadRepairTest3(fac, ft, fis);

    }

    //boolean passFilter = true;

    //JINSU hack for Cassandra corruption to pass by.
    //passFilter = filterReadRepairTest1(fac, ft, fis);
//    passFilter = filterReadRepairTest2(fac, ft, fis);

//passFilter = filterReadRepairTest3(fac, ft, fis);

//passFilter = filterSimpleRRTest(fac, ft, fis);

    // passFilter = filterWriteBug1(fac, ft, fis);
    // passFilter = filterWriteBug3(fac, ft, fis);
    // passFilter = filterWriteBug5(fac, ft, fis);
    // passFilter = filterWriteBug6(fac, ft, fis);
    // passFilter = filterWriteBug7(fac, ft, fis);

    // passFilter = filterAppendBug2(fac, ft, fis);
    // passFilter = filterAppendBug4(fac, ft, fis);
    // passFilter = filterAppendBug5(fac, ft, fis); Can't reproduce so far
    // passFilter = filterAppendBug6(fac, ft, fis);
    // passFilter = filterAppendBug7(fac, ft, fis);
    // passFilter = filterAppendBug8(fac, ft, fis);

		//JINSU : putting in filter for crash failure
		//I honestly don't know what this is gonna do.
		//please explain...
		//passFilter = filterTest(fac, ft, fis);

    return passFilter;

  }

    //JINSU : Checks if to see if we are dealing with digest messages.
    private static boolean cassDigestTest(FIState fis, String node) {
        FMJoinPoint fjp = fis.fjp;
        FMContext ctx = fis.ctx;
        FailType ft = fis.ft;
        if ( ctx.getMessageType().equalsIgnoreCase(FMClient.READ_RESPONSE_DIGEST)
            && ft == FailType.CORRUPTION
            && cassNodeTest(ctx, node) ) {
            return true;
        }
        return false;
    }

    //JINSU : Checks if the message is the data messages.
    private static boolean cassDataTest(FIState fis, String node) {
        FMJoinPoint fjp = fis.fjp;
        FMContext ctx = fis.ctx;
        FailType ft = fis.ft;
        if ( ctx.getMessageType().equalsIgnoreCase(FMClient.READ_RESPONSE_NORMAL)
             && cassNodeTest(ctx, node) ) {
            return true;
        }
        return false;

    }

    //JINSU : Checks to see if the context contains node.
    private static boolean cassNodeTest(FMContext ctx, String node) {
        return ctx.getNodeId().equalsIgnoreCase(node);
    }

    private static boolean filterInsertionTest1(FMAllContext fac, FailType ft, FIState fis) {
        FMJoinPoint fjp = fac.fjp;
        FMContext ctx = fac.ctx;
        System.out.println("filter JPS || " + fjp.getJoinPointStr() + "\nfilter ctx || " + ctx);

        if( FMLogic.getCurrentFsn() == 1 && ft == FailType.CRASH
                && fjp.getJoinPointStr().contains("DataOutputStream")
                && (cassNodeTest(ctx, "Node1")
                    ) ) {
             return true;

                   }

        return false;
    }

    private static boolean filterInsertionTest2(FMAllContext fac, FailType ft, FIState fis) {
        FMJoinPoint fjp = fac.fjp;
        FMContext ctx = fac.ctx;
        System.out.println("filter JPS || " + fjp.getJoinPointStr() + "\nfilter ctx || " + ctx);

        if( FMLogic.getCurrentFsn() == 1 && ft == FailType.CRASH
                && fjp.getJoinPlc() == JoinPlc.BEFORE
                && fjp.getJoinPointStr().contains("DataInputStream")
                && (cassNodeTest(ctx, "Node0")
                    ) ) {
             return true;

                   }

        return false;
    }

	// ************************************************************
	// JINSU: A small filter function that only returns true when the failure type is CRASH and the join place is before.
	private static boolean filterReadRepairTest3(FMAllContext fac, FailType ft, FIState fis) {
		FMJoinPoint fjp = fac.fjp;
		FMContext ctx = fac.ctx;
        int fsnNum = FMLogic.getCurrentFsn();

        if ( ( fsnNum == 1  )
                    && cassDigestTest(fis, "Node2") )
            return true;
        if( fsnNum == 3) {
                }
               if( ( fsnNum == 2 || fsnNum == 3 )
               && (cassDataTest(fis, "Node2") )
               && ft == FailType.CORRUPTION
          )
            return true;

        if( ( fsnNum == 2 || fsnNum == 3 )
                && cassDataTest(fis, "Node3")
                && ft == FailType.CRASH )
            return true;

        return false;
    }

	// ************************************************************
	// JINSU: A small filter function that only returns true when the failure type is CRASH and the join place is before.
	private static boolean filterReadRepairTest2(FMAllContext fac, FailType ft, FIState fis) {
		FMJoinPoint fjp = fac.fjp;
		FMContext ctx = fac.ctx;
        int fsnNum = FMLogic.getCurrentFsn();

        if ( ( fsnNum == 1 || fsnNum == 2 || fsnNum == 3 )
                    && cassDataTest(fis, "Node1")
                    && ft == FailType.CORRUPTION )
            return true;
        if( ( fsnNum == 2 || fsnNum == 3 )
                && ft == FailType.CRASH
                && fjp.getJoinPlc() == JoinPlc.BEFORE
                && fjp.getJoinPointStr().contains("DataOutputStream")
                && (cassNodeTest(ctx, "Node1") )
                ) {
            return true;

                   }
        return false;
    }

	// ************************************************************
	// JINSU: A small filter function that only returns true when the failure type is CRASH and the join place is before.
	private static boolean filterReadRepairTest1(FMAllContext fac, FailType ft, FIState fis) {
		FMJoinPoint fjp = fac.fjp;
		FMContext ctx = fac.ctx;
        int fsnNum = FMLogic.getCurrentFsn();

        if ( fsnNum == 1 && cassDigestTest(fis, "Node2") )
            return true;
        if( ( fsnNum == 2
                    || fsnNum == 3 )
                && ft == FailType.CRASH
                && fjp.getJoinPlc() == JoinPlc.BEFORE
                && fjp.getJoinPointStr().contains("DataOutputStream")
                && (cassNodeTest(ctx, "Node3")
                   ) ) {
            return true;

                   }
        if ( ( fsnNum == 2 || fsnNum  == 3 )
                && cassDataTest(fis, "Node1")
                && ft == FailType.CORRUPTION
           ) {
            return true;
           }
        return false;
    }

  // **************************************************
  private static boolean filterTransientDisk(FMAllContext fac,
                                             FailType ft, FIState fis) {

    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String nodeId = ctx.getNodeId();
    boolean isDiskIO = Util.isDiskIO(ctx.getTargetIO());
    boolean transientFailure = (ft == FailType.EXCEPTION || ft == FailType.RETFALSE);
    boolean writeIO = (fjp.getJoinIot() == JoinIot.WRITE);
    boolean inDatanode = nodeId.contains("DataNode");

    if (transientFailure &&
        isDiskIO && inDatanode && writeIO) {
      return true;
    }
    return false;

  }

  // **************************************************
  // Append-Bug 2:
  // http://hdfswiki.pbworks.com/Block-lost-when-primary-crashes-in-recoverBlock
  // Block is lost if primary datanode crashes in the middle tryUpdateBlock.
  // # available datanode = 2
  // # replica = 2
  // # disks / datanode = 1
  // # failures = 1
  // # failure type = crash
  // **************************************************
  private static boolean filterAppendBug2(FMAllContext fac,
                                          FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();

    if (ft == FailType.CRASH &&
        joinPlace == JoinPlc.AFTER &&
        ctx.getNodeId().equals("DataNode-1") &&
        fst.toString().contains("tryUpdateBlock") &&
        joinPoint.contains("renameTo") &&
        !ctx.getTargetIO().contains(".meta_tmp") && // rename metafile to tmpfile
        FMLogic.getMaxFsn() == 1)
      return true;
    return false;
  }

  // **************************************************
  // append-bug #4:
  //  http://hdfswiki.pbworks.com/UpdateBlock-fails-due-to-unmatched-file-length
  // # available datanodes = 3
  // # replicas = 3
  // # disks / datanode = 1
  // # failures = 1
  // failure type = bad disk
  //     When/where failure happens = (see below)
  //     This bug is non-deterministic, to reproduce it, add a sufficient sleep
  // before out.write() in BlockReceiver.receivePacket() in dn1 and dn2 but not dn3
  //   ALSO: go to datanode/BlockReceiver.java, and enable "enableAddDelay"
  // **************************************************
  private static boolean filterAppendBug4(FMAllContext fac,
                                          FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());
    int fsn = FMLogic.getCurrentFsn();
    if (
        ft == FailType.BADDISK &&
        //joinPlace == JoinPlc.AFTER &&
        ctx.getNodeId().equals("DataNode-3") &&
        fst.toString().contains("receivePacket") &&
        joinPoint.contains("write") &&
        isDataFile &&
        FMLogic.getMaxFsn() == 1)

      return true;
    return false;

  }

  // **************************************************
  // append-bug #5:
  // http://hdfswiki.pbworks.com/
  // CRC-does-not-match-when-retrying-appending-a-partial-block
  // # available datanodes = 2
  // # replicas = 2
  // # ALSO: change FILE_SIZE to 16 in workload-driver Driver/Hdfs.java
  // # disks / datanode = 1
  // # failures = 1
  // failure type = bad disk
  // NOTE: I couldn't reproduce this so far
  // **************************************************
  private static boolean filterAppendBug5(FMAllContext fac,
                                          FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());

    if (ft == FailType.BADDISK &&
        //        joinPlace == JoinPlc.AFTER &&
        ctx.getNodeId().equals("DataNode-2") &&
        fst.toString().contains("receivePacket") &&
        joinPoint.contains("write") &&
        isDataFile &&
        FMLogic.getMaxFsn() == 1)
      return true;
    return false;

  }

  // **************************************************
  // Append-Bug 6:
  //  http://hdfswiki.pbworks.com/
  //  DFSClient-incorrectly-asks-for-new-block-if-primary-
  //  crashes-during-first-recoverBlock
  // this filter is exactly the same as that of append bug 2
  // all we need to do is the primary data node crash during recoverBlock
  // # available datanodes = 2
  // # replicas = 2
  // # disks / datanode = 1
  // # failures = 1
  // failure type = crash
  // When/where failure happens = during primary's recoverBlock
  // **************************************************
  private static boolean filterAppendBug6(FMAllContext fac,
                                          FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();

    if (ft == FailType.CRASH &&
        joinPlace == JoinPlc.AFTER &&
        ctx.getNodeId().equals("DataNode-1") &&
        fst.toString().contains("tryUpdateBlock") &&
        joinPoint.contains("renameTo") &&
        !ctx.getTargetIO().contains(".meta_tmp") && // rename metafile to tmpfile
        FMLogic.getMaxFsn() == 1)
      return true;
    return false;

  }

  // **************************************************
  // append Bug #7
  // http://hdfswiki.pbworks.com/Generation-Stamp-mismatches%2C-leading-to-failed-append
  // # available datanodes = 3
  // # replicas = 3
  // # disks / datanode = 1
  // # failures = 2
  // failure type = crash
  // **************************************************
  private static boolean filterAppendBug7(FMAllContext fac,
                                          FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());
    int fsn = FMLogic.getCurrentFsn();

    if (
        (fsn == 1 &&
         ft == FailType.CRASH &&
         joinPlace == JoinPlc.AFTER &&
         ctx.getNodeId().equals("DataNode-3") &&
         fst.toString().contains("receivePacket") &&
         joinPoint.contains("write") &&
         isDataFile &&
         FMLogic.getMaxFsn() == 2)
        ||
        (fsn == 2 &&
         ft == FailType.CRASH &&
         joinPlace == JoinPlc.AFTER &&
         ctx.getNodeId().equals("DataNode-1") &&
         fst.toString().contains("tryUpdateBlock") &&
         joinPoint.contains("renameTo") &&
         !ctx.getTargetIO().contains(".meta_tmp") &&
         FMLogic.getMaxFsn() == 2)
        )
      return true;

    return false;
  }

  // **************************************************
  // append Bug #8
  // http://hdfswiki.pbworks.com/
  // Corrupted-block-if-a-crash-happens-before-writing-to-
  // checksumOut-but-after-writing-to-dataOut
  // # available datanodes = 1
  // # replicas = 1
  // # disks / datanode = 1
  // # failures = 1
  // failure type = crash
  // **************************************************
    private static boolean filterAppendBug8(FMAllContext fac,
                                            FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    JoinPlc joinPlace = fjp.getJoinPlc();
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());

    if (ft == FailType.CRASH &&
        joinPlace == JoinPlc.AFTER &&
        ctx.getNodeId().equals("DataNode-1") &&
        fst.toString().contains("receivePacket") &&
        joinPoint.contains("write") &&
        isDataFile &&
        FMLogic.getMaxFsn() == 1)
      return true;
    return false;

  }

  // **************************************************
  // WRITE BUG # 1:
  // http://hdfswiki.pbworks.com/FrontPage
  //   dfs.replication = 1
  //   #datanodes      = 1
  //   #disks/datanode = 2  (see hdfs-site.xml, dfs.data.dir, enable two data disks)
  //   MAX_FSN         = 1
  //   Workload        = putfile
  //   FailTpe         = BadDisk
  // **************************************************
  private static boolean filterWriteBug1(FMAllContext fac,
                                      FailType ft, FIState fis) {

    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    String diskId = Util.getDiskIdFromTargetIO(ctx.getTargetIO());
    boolean firstDisk = diskId.equals("Disk1");
    boolean secondPhase = joinPoint.contains("renameTo");
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());
    boolean badDiskFailure = (ft == FailType.BADDISK);

    if (firstDisk && secondPhase && isDataFile && badDiskFailure) {
      return true;
    }

    return false;
  }

  // **************************************************
  // WRITE BUG # 3:
  //   http://hdfswiki.pbworks.com/Namenode-returning-the-same-Datanode-to-client%2C-due-to-infrequent-heartbeat
  //   There is _one_ bad-disk failure during the first phase.
  // Setup:
  //   dfs.replication = 2 (in "hdfs-site.xml")
  //   #datanodes      = 3 (in "slaves")
  //   MAX_FSN         = 1 (in Driver.java)
  //   Workload        = putfile
  //   FailType        = BadDisk
  // **************************************************
  private static boolean filterWriteBug3(FMAllContext fac,
                                      FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());
    boolean firstPhase = joinPoint.contains("RandomAccessFile(File, String)");

    if (ft == FailType.BADDISK &&
        ctx.getNodeId().equals("DataNode-1") &&
        firstPhase &&
        isDataFile &&
        FMLogic.getMaxFsn() == 1) {
      return true;
    }

    return false;
  }

  // **************************************************
  // WRITE BUG # 5:
  //   http://hdfswiki.pbworks.com/Client-uselessly-retries-recoverBlock-5-times
  //   There are two bad-disk failures.
  //   The first one happens in the 2nd phase at DN-2
  //   This will force the client to create another pipeline
  //   just for DN-1.  But DN-1 fails again.
  //   The client gives up, without contacting the namenode again
  // Setup:
  //   dfs.replication = 2 (in "hdfs-site.xml")
  //   #datanodes      = 4 (in "slaves")
  //   MAX_FSN         = 2 (in Driver.java)
  //   Workload        = putfile
  //   FailType        = BadDisk
  // **************************************************
  private static boolean filterWriteBug5(FMAllContext fac,
                                      FailType ft, FIState fis) {
    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    boolean secondPhase = joinPoint.contains("renameTo");
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());

    if (ft == FailType.BADDISK &&
        secondPhase &&
        isDataFile &&
        FMLogic.getMaxFsn() == 2  &&
        fst.contains("PacketResponder", "lastDataNodeRun")
        ) {
      return true;
    }

    return false;
  }

  // **************************************************
  // WRITE BUG # 6:
  //   http://hdfswiki.pbworks.com/A-block-is-stuck-in-ongoingRecovery-due-to-exception-not-propagated
  // Setup:
  //   dfs.replication = 2 (in "hdfs-site.xml")
  //   #datanodes      = 4 (in "slaves")
  //   MAX_FSN         = 2 (in Driver.java)
  //   Workload        = putfile
  //   FailType        = Exception/Retfalse
  // **************************************************
  private static boolean filterWriteBug6(FMAllContext fac,
                                      FailType ft, FIState fis) {

    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    boolean secondPhase = joinPoint.contains("renameTo");
    boolean isMetaFile = Util.isMetaFile(ctx.getTargetIO());
    boolean isCurrentTmpMeta = Util.isCurrentTmpMeta(ctx.getTargetIO());
    int fsn = FMLogic.getCurrentFsn();
    String nodeId = ctx.getNodeId();

    // the 1st failure
    if (fsn == 1 &&
        ft == FailType.EXCEPTION &&
        isMetaFile &&
        nodeId.equals("DataNode-1") &&
        fst.contains("BlockReceiver", "flush") &&
        joinPoint.contains("DataOutputStream.flush")) {
      return true;
    }

    // the 2nd failure
    if (fsn == 2 &&
        ft == FailType.RETFALSE &&
        isCurrentTmpMeta &&
        nodeId.equals("DataNode-2") &&
        fst.contains("FSDataset", "tryUpdateBlock") &&
        joinPoint.contains("File.renameTo")) {
      return true;
    }

    return false;

  }

  // **************************************************
  // WRITE BUG # 7:
  //   http://hdfswiki.pbworks.com
  // Setup:
  //   dfs.replication = 2 (in "hdfs-site.xml")
  //   #datanodes      = 4 (in "slaves")
  //   MAX_FSN         = 2 (in Driver.java)
  //   Workload        = putfile
  //   FailType        = Exception/Retfalse
  // **************************************************
  private static boolean filterWriteBug7(FMAllContext fac,
                                      FailType ft, FIState fis) {

    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    String joinPoint = fjp.getJoinPointStr();
    boolean secondPhase =
      joinPoint.contains("renameTo") && fst.contains("PacketResponder", "run");
    boolean transientFailure = (ft == FailType.EXCEPTION || ft == FailType.RETFALSE);
    boolean isMetaFile = Util.isMetaFile(ctx.getTargetIO());
    int fsn = FMLogic.getCurrentFsn();
    String nodeId = ctx.getNodeId();

    if (transientFailure && isMetaFile && secondPhase) {

      // Note: This is concurrent failures!
      if (fsn == 1 && nodeId.equals("DataNode-1"))
        return true;
      if (fsn == 2 && nodeId.equals("DataNode-2"))
        return true;
    }

    return false;

  }

  // ********************************
  // Playing around with filters here
  // *********************************
  private static boolean passServerFilterRepository
    (FMAllContext fac, FailType ft, FIState fis) {

    FMJoinPoint fjp = fac.fjp;
    FMContext ctx = fac.ctx;
    FMStackTrace fst = fac.fst;
    int fsn = FMLogic.getCurrentFsn();
    String nodeId = ctx.getNodeId();
    boolean isBlockFile = Util.isBlockFile(ctx.getTargetIO());
    boolean isMetaFile = Util.isMetaFile(ctx.getTargetIO());
    boolean isDataFile = Util.isDataFile(ctx.getTargetIO());
    boolean isNetIoToDn = Util.isNetIOtoDataNode(fac.ctx.getTargetIO());
    JoinIot ioType = fjp.getJoinIot();
    String joinPoint = fjp.getJoinPointStr();
    String diskId = Util.getDiskIdFromTargetIO(ctx.getTargetIO());
    JoinPlc jplc = fjp.getJoinPlc();
    // nodeId.equals("DataNode-2") && diskId.equals("Disk1"))

    boolean firstPhase = joinPoint.contains("RandomAccessFile(File, String)");
    boolean secondPhase =
      joinPoint.contains("renameTo") ||
      joinPoint.contains("flush");

    // just an optimization .. specifically we're interested
    // in client write and datanode failure only
    // hence we only "filter" data file/meta write
    // [file][/rhh/dfs/data1/tmp/blk_7307724612204181421]

    // and for network stream, node id should not be client (unknown so far)
    boolean passFilter = false;

    // abc
    if (nodeId.contains("DataNode") &&
        ft == FailType.EXCEPTION || ft == FailType.RETFALSE) {
      passFilter = true;
    }

    // System.out.println("_passFilter_ " + passFilter);

    return passFilter;
  }

}


text:
module SmartAnswer
  class BenefitCapCalculatorFlow < Flow
    def define
      name 'benefit-cap-calculator'
      status :published
      satisfies_need "100696"

      # Q1
      multiple_choice :receive_housing_benefit? do
        option :yes
        option :no

        save_input_as :housing_benefit

        next_node do |response|
          if response == 'yes'
            :working_tax_credit?
          else
            :outcome_not_affected_no_housing_benefit
          end
        end
      end

      # Q2
      multiple_choice :working_tax_credit? do
        option :yes
        option :no

        next_node do |response|
          if response == 'yes'
            :outcome_not_affected_exemptions
          else
            :receiving_exemption_benefits?
          end
        end
      end

      #Q3
      multiple_choice :receiving_exemption_benefits? do
        option :yes
        option :no

        next_node do |response|
          if response == 'yes'
            :outcome_not_affected_exemptions
          else
            :receiving_non_exemption_benefits?
          end
        end
      end

      #Q4
      checkbox_question :receiving_non_exemption_benefits? do
        option :bereavement
        option :carers
        option :child_benefit
        option :child_tax
        option :esa
        option :guardian
        option :incapacity
        option :income_support
        option :jsa
        option :maternity
        option :sda
        option :widowed_mother
        option :widowed_parent
        option :widow_pension
        option :widows_aged

        calculate :benefit_related_questions do |response|
          questions = response.split(",").map { |r| :"#{r}_amount?" }
          questions << :housing_benefit_amount? if housing_benefit == 'yes'
          questions << :single_couple_lone_parent?
          questions.shift
          questions
        end

        calculate :total_benefits do
          0
        end

        calculate :benefit_cap do
          0
        end

        next_node do |response|
          first_value = response.split(",").first
          if response == "none"
            :outcome_not_affected
          else
            :"#{first_value}_amount?"
          end
        end
      end

      #Q5a
      money_question :bereavement_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5b
      money_question :carers_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5c
      money_question :child_benefit_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5d
      money_question :child_tax_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5e
      money_question :esa_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5f
      money_question :guardian_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5g
      money_question :incapacity_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5h
      money_question :income_support_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5i
      money_question :jsa_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5j
      money_question :maternity_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5k
      money_question :sda_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5l
      money_question :widowed_mother_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5m
      money_question :widowed_parent_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5n
      money_question :widow_pension_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5o
      money_question :widows_aged_amount? do
        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q5p
      money_question :housing_benefit_amount? do
        save_input_as :housing_benefit_amount

        calculate :total_benefits do |response|
          total_benefits + response.to_f
        end

        next_node do
          benefit_related_questions.shift
        end
      end

      #Q6
      multiple_choice :single_couple_lone_parent? do
        option :single
        option :couple
        option :parent

        calculate :benefit_cap do |response|
          if response == 'single'
            benefit_cap = 350
          else
            benefit_cap = 500
          end
          sprintf("%.2f", benefit_cap)
        end

        next_node do |response|
          if response == 'single'
            cap = 350
          else
            cap = 500
          end

          if total_benefits > cap
            :outcome_affected_greater_than_cap
          else
            :outcome_not_affected_less_than_cap
          end
        end
      end

      ##OUTCOMES

      use_outcome_templates

      ## Outcome 1
      outcome :outcome_not_affected_exemptions

      ## Outcome 2
      outcome :outcome_not_affected_no_housing_benefit

      ## Outcome 3
      outcome :outcome_affected_greater_than_cap do
        precalculate :total_benefits do
          sprintf("%.2f", total_benefits)
        end

        precalculate :housing_benefit_amount do
          sprintf("%.2f", housing_benefit_amount)
        end

        precalculate :total_over_cap do
          sprintf("%.2f", (total_benefits.to_f - benefit_cap.to_f))
        end

        precalculate :new_housing_benefit_amount do
          housing_benefit_amount.to_f - total_over_cap.to_f
        end

        precalculate :new_housing_benefit do
          amount = sprintf("%.2f", new_housing_benefit_amount)
          if amount < "0.5"
            amount = sprintf("%.2f", 0.5)
          end
          amount
        end
      end

      ## Outcome 4
      outcome :outcome_not_affected_less_than_cap do
        precalculate :total_benefits do
          sprintf("%.2f", total_benefits)
        end
      end

      ## Outcome 5
      outcome :outcome_not_affected
    end
  end
end


text:
import os
import pytest

def test_list_command(script, data):
    """
    Test default behavior of list command.

    """
    script.pip(
        'install', '-f', data.find_links, '--no-index', 'simple==1.0',
        'simple2==3.0',
    )
    result = script.pip('list')
    assert 'simple (1.0)' in result.stdout, str(result)
    assert 'simple2 (3.0)' in result.stdout, str(result)

def test_local_flag(script, data):
    """
    Test the behavior of --local flag in the list command

    """
    script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0')
    result = script.pip('list', '--local')
    assert 'simple (1.0)' in result.stdout

def test_user_flag(script, data, virtualenv):
    """
    Test the behavior of --user flag in the list command

    """
    virtualenv.system_site_packages = True
    script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0')
    script.pip('install', '-f', data.find_links, '--no-index',
               '--user', 'simple2==2.0')
    result = script.pip('list', '--user')
    assert 'simple (1.0)' not in result.stdout
    assert 'simple2 (2.0)' in result.stdout

@pytest.mark.network
def test_uptodate_flag(script, data):
    """
    Test the behavior of --uptodate flag in the list command

    """
    script.pip(
        'install', '-f', data.find_links, '--no-index', 'simple==1.0',
        'simple2==3.0',
    )
    script.pip(
        'install', '-e',
        'git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package'
    )
    result = script.pip(
        'list', '-f', data.find_links, '--no-index', '--uptodate',
        expect_stderr=True,
    )
    assert 'simple (1.0)' not in result.stdout  # 3.0 is latest
    assert 'pip-test-package (0.1.1,' in result.stdout  # editables included
    assert 'simple2 (3.0)' in result.stdout, str(result)

@pytest.mark.network
def test_outdated_flag(script, data):
    """
    Test the behavior of --outdated flag in the list command

    """
    script.pip(
        'install', '-f', data.find_links, '--no-index', 'simple==1.0',
        'simple2==3.0', 'simplewheel==1.0',
    )
    script.pip(
        'install', '-e',
        'git+https://github.com/pypa/pip-test-package.git'
        '@0.1#egg=pip-test-package'
    )
    result = script.pip(
        'list', '-f', data.find_links, '--no-index', '--outdated',
        expect_stderr=True,
    )
    assert 'simple (1.0) - Latest: 3.0 [sdist]' in result.stdout
    assert 'simplewheel (1.0) - Latest: 2.0 [wheel]' in result.stdout
    assert 'pip-test-package (0.1, ' in result.stdout
    assert ' Latest: 0.1.1 [sdist]' in result.stdout
    assert 'simple2' not in result.stdout, str(result)  # 3.0 is latest

@pytest.mark.network
def test_editables_flag(script, data):
    """
    Test the behavior of --editables flag in the list command
    """
    script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0')
    result = script.pip(
        'install', '-e',
        'git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package'
    )
    result = script.pip('list', '--editable')
    assert 'simple (1.0)' not in result.stdout, str(result)
    assert os.path.join('src', 'pip-test-package') in result.stdout, (
        str(result)
    )

@pytest.mark.network
def test_uptodate_editables_flag(script, data):
    """
    test the behavior of --editable --uptodate flag in the list command
    """
    script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0')
    result = script.pip(
        'install', '-e',
        'git+https://github.com/pypa/pip-test-package.git#egg=pip-test-package'
    )
    result = script.pip(
        'list', '-f', data.find_links, '--no-index',
        '--editable', '--uptodate',
        expect_stderr=True,
    )
    assert 'simple (1.0)' not in result.stdout, str(result)
    assert os.path.join('src', 'pip-test-package') in result.stdout, (
        str(result)
    )

@pytest.mark.network
def test_outdated_editables_flag(script, data):
    """
    test the behavior of --editable --outdated flag in the list command
    """
    script.pip('install', '-f', data.find_links, '--no-index', 'simple==1.0')
    result = script.pip(
        'install', '-e',
        'git+https://github.com/pypa/pip-test-package.git'
        '@0.1#egg=pip-test-package'
    )
    result = script.pip(
        'list', '-f', data.find_links, '--no-index',
        '--editable', '--outdated',
        expect_stderr=True,
    )
    assert 'simple (1.0)' not in result.stdout, str(result)
    assert os.path.join('src', 'pip-test-package') in result.stdout, (
        str(result)
    )


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package org.apache.cloudstack.storage.snapshot;

import java.util.List;

import javax.inject.Inject;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStore;
import org.apache.cloudstack.engine.subsystem.api.storage.DataStoreManager;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.Event;
import org.apache.cloudstack.engine.subsystem.api.storage.ObjectInDataStoreStateMachine.State;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotDataFactory;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotInfo;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotResult;
import org.apache.cloudstack.engine.subsystem.api.storage.SnapshotService;
import org.apache.cloudstack.engine.subsystem.api.storage.StrategyPriority;
import org.apache.cloudstack.engine.subsystem.api.storage.VolumeInfo;
import org.apache.cloudstack.framework.config.dao.ConfigurationDao;
import org.apache.cloudstack.framework.jobs.AsyncJob;
import org.apache.cloudstack.framework.jobs.dao.SyncQueueItemDao;
import org.apache.cloudstack.storage.command.CreateObjectAnswer;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreDao;
import org.apache.cloudstack.storage.datastore.db.SnapshotDataStoreVO;
import org.apache.cloudstack.storage.datastore.PrimaryDataStoreImpl;
import org.apache.cloudstack.storage.to.SnapshotObjectTO;
import org.apache.cloudstack.utils.identity.ManagementServerNode;

import com.cloud.event.EventTypes;
import com.cloud.event.UsageEventUtils;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.hypervisor.Hypervisor;
import com.cloud.hypervisor.Hypervisor.HypervisorType;
import com.cloud.storage.CreateSnapshotPayload;
import com.cloud.storage.DataStoreRole;
import com.cloud.storage.Snapshot;
import com.cloud.storage.SnapshotVO;
import com.cloud.storage.StoragePool;
import com.cloud.storage.StoragePoolStatus;
import com.cloud.storage.Volume;
import com.cloud.storage.VolumeVO;
import com.cloud.storage.VolumeDetailVO;
import com.cloud.storage.dao.SnapshotDao;
import com.cloud.storage.dao.SnapshotDetailsDao;
import com.cloud.storage.dao.VolumeDao;
import com.cloud.storage.dao.VolumeDetailsDao;
import com.cloud.utils.db.Transaction;
import com.cloud.utils.db.TransactionCallbackNoReturn;
import com.cloud.utils.db.TransactionStatus;
import com.cloud.storage.snapshot.SnapshotManager;
import com.cloud.storage.Storage.ImageFormat;
import com.cloud.storage.Storage.StoragePoolType;
import com.cloud.utils.NumbersUtil;
import com.cloud.utils.db.DB;
import com.cloud.utils.exception.CloudRuntimeException;
import com.cloud.utils.fsm.NoTransitionException;

@Component
public class XenserverSnapshotStrategy extends SnapshotStrategyBase {
    private static final Logger s_logger = Logger.getLogger(XenserverSnapshotStrategy.class);

    @Inject
    SnapshotService snapshotSvr;
    @Inject
    DataStoreManager dataStoreMgr;
    @Inject
    SnapshotDataStoreDao snapshotStoreDao;
    @Inject
    ConfigurationDao configDao;
    @Inject
    SnapshotDao snapshotDao;
    @Inject
    VolumeDao volumeDao;
    @Inject
    SnapshotDataFactory snapshotDataFactory;
    @Inject
    private SnapshotDao _snapshotDao;
    @Inject
    private SnapshotDetailsDao _snapshotDetailsDao;
    @Inject
    private SyncQueueItemDao _syncQueueItemDao;
    @Inject
    VolumeDetailsDao _volumeDetailsDaoImpl;

    @Override
    public SnapshotInfo backupSnapshot(SnapshotInfo snapshot) {
        SnapshotInfo parentSnapshot = snapshot.getParent();

        if (parentSnapshot != null && snapshot.getPath().equalsIgnoreCase(parentSnapshot.getPath())) {
            // don't need to backup this snapshot
            SnapshotDataStoreVO parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(parentSnapshot.getId(), DataStoreRole.Image);
            if (parentSnapshotOnBackupStore != null && parentSnapshotOnBackupStore.getState() == State.Ready) {
                DataStore store = dataStoreMgr.getDataStore(parentSnapshotOnBackupStore.getDataStoreId(), parentSnapshotOnBackupStore.getRole());

                SnapshotInfo snapshotOnImageStore = (SnapshotInfo)store.create(snapshot);
                snapshotOnImageStore.processEvent(Event.CreateOnlyRequested);

                SnapshotObjectTO snapTO = new SnapshotObjectTO();
                snapTO.setPath(parentSnapshotOnBackupStore.getInstallPath());

                CreateObjectAnswer createSnapshotAnswer = new CreateObjectAnswer(snapTO);

                snapshotOnImageStore.processEvent(Event.OperationSuccessed, createSnapshotAnswer);
                SnapshotObject snapObj = (SnapshotObject)snapshot;
                try {
                    snapObj.processEvent(Snapshot.Event.OperationNotPerformed);
                } catch (NoTransitionException e) {
                    s_logger.debug("Failed to change state: " + snapshot.getId() + ": " + e.toString());
                    throw new CloudRuntimeException(e.toString());
                }
                return snapshotDataFactory.getSnapshot(snapObj.getId(), store);
            } else {
                s_logger.debug("parent snapshot hasn't been backed up yet");
            }
        }

        // determine full snapshot backup or not

        boolean fullBackup = true;
        SnapshotDataStoreVO parentSnapshotOnBackupStore = snapshotStoreDao.findLatestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Image);
        SnapshotDataStoreVO parentSnapshotOnPrimaryStore = snapshotStoreDao.findLatestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Primary);
        HypervisorType hypervisorType = snapshot.getBaseVolume().getHypervisorType();
        if (parentSnapshotOnPrimaryStore != null && parentSnapshotOnBackupStore != null && hypervisorType == Hypervisor.HypervisorType.XenServer) { // CS does incremental backup only for XenServer

            // In case of volume migration from one pool to other pool, CS should take full snapshot to avoid any issues with delta chain,
            // to check if this is a migrated volume, compare the current pool id of volume and store_id of oldest snapshot on primary for this volume.
            // Why oldest? Because at this point CS has two snapshot on primary entries for same volume, one with old pool_id and other one with
            // current pool id. So, verify and if volume found to be migrated, delete snapshot entry with previous pool store_id.
            SnapshotDataStoreVO oldestSnapshotOnPrimary = snapshotStoreDao.findOldestSnapshotForVolume(snapshot.getVolumeId(), DataStoreRole.Primary);
            VolumeVO volume = volumeDao.findById(snapshot.getVolumeId());
            if (oldestSnapshotOnPrimary != null) {
                if (oldestSnapshotOnPrimary.getDataStoreId() == volume.getPoolId() && oldestSnapshotOnPrimary.getId() != parentSnapshotOnPrimaryStore.getId()) {
                    int _deltaSnapshotMax = NumbersUtil.parseInt(configDao.getValue("snapshot.delta.max"),
                            SnapshotManager.DELTAMAX);
                    int deltaSnap = _deltaSnapshotMax;
                    int i;

                    for (i = 1; i < deltaSnap; i++) {
                        Long prevBackupId = parentSnapshotOnBackupStore.getParentSnapshotId();
                        if (prevBackupId == 0) {
                            break;
                        }
                        parentSnapshotOnBackupStore = snapshotStoreDao.findBySnapshot(prevBackupId, DataStoreRole.Image);
                        if (parentSnapshotOnBackupStore == null) {
                            break;
                        }
                    }

                    if (i >= deltaSnap) {
                        fullBackup = true;
                    } else {
                        fullBackup = false;
                    }
                } else if (oldestSnapshotOnPrimary.getId() != parentSnapshotOnPrimaryStore.getId()){
                    // if there is an snapshot entry for previousPool(primary storage) of migrated volume, delete it becasue CS created one more snapshot entry for current pool
                    snapshotStoreDao.remove(oldestSnapshotOnPrimary.getId());
                }
            }
        }

        snapshot.setFullBackup(fullBackup);
        return snapshotSvr.backupSnapshot(snapshot);
    }

    protected boolean deleteSnapshotChain(SnapshotInfo snapshot) {
        s_logger.debug("delete snapshot chain for snapshot: " + snapshot.getId());
        boolean result = false;
        boolean resultIsSet = false;   //need to track, the snapshot itself is deleted or not.
        try {
            while (snapshot != null &&
                (snapshot.getState() == Snapshot.State.Destroying || snapshot.getState() == Snapshot.State.Destroyed || snapshot.getState() == Snapshot.State.Error)) {
                SnapshotInfo child = snapshot.getChild();

                if (child != null) {
                    s_logger.debug("the snapshot has child, can't delete it on the storage");
                    break;
                }
                s_logger.debug("Snapshot: " + snapshot.getId() + " doesn't have children, so it's ok to delete it and its parents");
                SnapshotInfo parent = snapshot.getParent();
                boolean deleted = false;
                if (parent != null) {
                    if (parent.getPath() != null && parent.getPath().equalsIgnoreCase(snapshot.getPath())) {
                        //NOTE: if both snapshots share the same path, it's for xenserver's empty delta snapshot. We can't delete the snapshot on the backend, as parent snapshot still reference to it
                        //Instead, mark it as destroyed in the db.
                        s_logger.debug("for empty delta snapshot, only mark it as destroyed in db");
                        snapshot.processEvent(Event.DestroyRequested);
                        snapshot.processEvent(Event.OperationSuccessed);
                        deleted = true;
                        if (!resultIsSet) {
                            result = true;
                            resultIsSet = true;
                        }
                    }
                }
                if (!deleted) {
                    try {
                        boolean r = snapshotSvr.deleteSnapshot(snapshot);
                        if (r) {
                            // delete snapshot in cache if there is
                            List<SnapshotInfo> cacheSnaps = snapshotDataFactory.listSnapshotOnCache(snapshot.getId());
                            for (SnapshotInfo cacheSnap : cacheSnaps) {
                                s_logger.debug("Delete snapshot " + snapshot.getId() + " from image cache store: " + cacheSnap.getDataStore().getName());
                                cacheSnap.delete();
                            }
                        }
                        if (!resultIsSet) {
                            result = r;
                            resultIsSet = true;
                        }
                    } catch (Exception e) {
                        // Snapshots which are not successfully deleted will be retried again.
                        s_logger.debug("Failed to delete snapshot on storage. ", e);
                    }
                }
                snapshot = parent;
            }
        } catch (Exception e) {
            s_logger.debug("delete snapshot failed: ", e);
        }
        return result;
    }

    @Override
    public boolean deleteSnapshot(Long snapshotId) {
        SnapshotVO snapshotVO = snapshotDao.findById(snapshotId);

        if (snapshotVO.getState() == Snapshot.State.Allocated) {
            snapshotDao.remove(snapshotId);
            return true;
        }

        if (snapshotVO.getState() == Snapshot.State.Destroyed) {
            return true;
        }

        if (Snapshot.State.Error.equals(snapshotVO.getState())) {
            List<SnapshotDataStoreVO> storeRefs = snapshotStoreDao.findBySnapshotId(snapshotId);
            for (SnapshotDataStoreVO ref : storeRefs) {
                snapshotStoreDao.expunge(ref.getId());
            }
            snapshotDao.remove(snapshotId);
            return true;
        }

        if (snapshotVO.getState() == Snapshot.State.CreatedOnPrimary) {
            snapshotVO.setState(Snapshot.State.Destroyed);
            snapshotDao.update(snapshotId, snapshotVO);
            return true;
        }

        if (!Snapshot.State.BackedUp.equals(snapshotVO.getState()) && !Snapshot.State.Error.equals(snapshotVO.getState()) &&
                !Snapshot.State.Destroying.equals(snapshotVO.getState())) {
            throw new InvalidParameterValueException("Can't delete snapshotshot " + snapshotId + " due to it is in " + snapshotVO.getState() + " Status");
        }

        // first mark the snapshot as destroyed, so that ui can't see it, but we
        // may not destroy the snapshot on the storage, as other snapshots may
        // depend on it.
        SnapshotInfo snapshotOnImage = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Image);
        if (snapshotOnImage == null) {
            s_logger.debug("Can't find snapshot on backup storage, delete it in db");
            snapshotDao.remove(snapshotId);
            return true;
        }

        SnapshotObject obj = (SnapshotObject)snapshotOnImage;
        try {
            obj.processEvent(Snapshot.Event.DestroyRequested);
            List<VolumeDetailVO> volumesFromSnapshot;
            volumesFromSnapshot = _volumeDetailsDaoImpl.findDetails("SNAPSHOT_ID", String.valueOf(snapshotId), null);

            if (volumesFromSnapshot.size() > 0) {
                try {
                    obj.processEvent(Snapshot.Event.OperationFailed);
                } catch (NoTransitionException e1) {
                    s_logger.debug("Failed to change snapshot state: " + e1.toString());
                }
                throw new InvalidParameterValueException("Unable to perform delete operation, Snapshot with id: " + snapshotId + " is in use  ");
            }
        } catch (NoTransitionException e) {
            s_logger.debug("Failed to set the state to destroying: ", e);
            return false;
        }

        try {
            boolean result = deleteSnapshotChain(snapshotOnImage);
            obj.processEvent(Snapshot.Event.OperationSucceeded);
            if (result) {
                //snapshot is deleted on backup storage, need to delete it on primary storage
                SnapshotDataStoreVO snapshotOnPrimary = snapshotStoreDao.findBySnapshot(snapshotId, DataStoreRole.Primary);
                if (snapshotOnPrimary != null) {
                    SnapshotInfo snapshotOnPrimaryInfo = snapshotDataFactory.getSnapshot(snapshotId, DataStoreRole.Primary);
                    long volumeId = snapshotOnPrimary.getVolumeId();
                    VolumeVO volumeVO = volumeDao.findById(volumeId);
                    if (((PrimaryDataStoreImpl)snapshotOnPrimaryInfo.getDataStore()).getPoolType() == StoragePoolType.RBD && volumeVO != null) {
                        snapshotSvr.deleteSnapshot(snapshotOnPrimaryInfo);
                    }
                    snapshotOnPrimary.setState(State.Destroyed);
                    snapshotStoreDao.update(snapshotOnPrimary.getId(), snapshotOnPrimary);
                }
            }
        } catch (Exception e) {
            s_logger.debug("Failed to delete snapshot: ", e);
            try {
                obj.processEvent(Snapshot.Event.OperationFailed);
            } catch (NoTransitionException e1) {
                s_logger.debug("Failed to change snapshot state: " + e.toString());
            }
            return false;
        }

        return true;
    }

    @Override
    public boolean revertSnapshot(SnapshotInfo snapshot) {
        if (canHandle(snapshot, SnapshotOperation.REVERT) == StrategyPriority.CANT_HANDLE) {
            throw new CloudRuntimeException("Reverting not supported. Create a template or volume based on the snapshot instead.");
        }

        SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());

        if (snapshotVO == null) {
            throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
        }

        try {
            VolumeInfo volumeInfo = snapshot.getBaseVolume();
            StoragePool store = (StoragePool)volumeInfo.getDataStore();

            if (store != null && store.getStatus() != StoragePoolStatus.Up) {
                snapshot.processEvent(Event.OperationFailed);

                throw new CloudRuntimeException("store is not in up state");
            }

            volumeInfo.stateTransit(Volume.Event.RevertSnapshotRequested);

            boolean result = false;

            try {
                result =  snapshotSvr.revertSnapshot(snapshot);

                if (!result) {
                    s_logger.debug("Failed to revert snapshot: " + snapshot.getId());

                    throw new CloudRuntimeException("Failed to revert snapshot: " + snapshot.getId());
                }
            } finally {
                if (result) {
                    volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
                } else {
                    volumeInfo.stateTransit(Volume.Event.OperationFailed);
                }
            }

            return result;
        } finally {
            if (snapshotVO != null) {
                snapshotDao.releaseFromLockTable(snapshot.getId());
            }
        }
    }

    @Override
    @DB
    public SnapshotInfo takeSnapshot(SnapshotInfo snapshot) {
        SnapshotInfo snapshotOnPrimary = null;
        Object payload = snapshot.getPayload();
        CreateSnapshotPayload createSnapshotPayload = null;
        if (payload != null) {
            createSnapshotPayload = (CreateSnapshotPayload)payload;
            if (createSnapshotPayload.getQuiescevm()) {
                throw new InvalidParameterValueException("can't handle quiescevm equal true for volume snapshot");
            }
        }

        SnapshotVO snapshotVO = snapshotDao.acquireInLockTable(snapshot.getId());
        if (snapshotVO == null) {
            throw new CloudRuntimeException("Failed to get lock on snapshot:" + snapshot.getId());
        }

        try {
            VolumeInfo volumeInfo = snapshot.getBaseVolume();
            volumeInfo.stateTransit(Volume.Event.SnapshotRequested);
            SnapshotResult result = null;
            try {
                result = snapshotSvr.takeSnapshot(snapshot);
                if (result.isFailed()) {
                    s_logger.debug("Failed to take snapshot: " + result.getResult());
                    throw new CloudRuntimeException(result.getResult());
                }
            } finally {
                if (result != null && result.isSuccess()) {
                    volumeInfo.stateTransit(Volume.Event.OperationSucceeded);
                } else {
                    volumeInfo.stateTransit(Volume.Event.OperationFailed);
                }
            }
            snapshotOnPrimary = result.getSnapshot();
            snapshotOnPrimary.addPayload(snapshot.getPayload());

            /*The Management Server ID is stored in snapshot_details table with the snapshot id and (name, value): (MS_ID, <ms_id>), to know which snapshots have not been completed in case of some failure situation like
             *  Mgmt server down etc. and by fetching the entries on restart the cleaning up of failed snapshots is done*/
            _snapshotDetailsDao.addDetail(((SnapshotObject)snapshotOnPrimary).getId(), AsyncJob.Constants.MS_ID, Long.toString(ManagementServerNode.getManagementServerId()), false);
            return snapshotOnPrimary;
        } finally {
            if (snapshotVO != null) {
                snapshotDao.releaseFromLockTable(snapshot.getId());
            }
        }
    }

    @Override
    public void postSnapshotCreation(SnapshotInfo snapshotOnPrimary) {
        Transaction.execute(new TransactionCallbackNoReturn() {
            @Override
            public void doInTransactionWithoutResult(TransactionStatus status) {
                _snapshotDetailsDao.removeDetail(((SnapshotObject)snapshotOnPrimary).getId(), AsyncJob.Constants.MS_ID);
                DataStore primaryStore = snapshotOnPrimary.getDataStore();
                try {
                    SnapshotInfo parent = snapshotOnPrimary.getParent();
                    if (parent != null && primaryStore instanceof PrimaryDataStoreImpl) {
                        if (((PrimaryDataStoreImpl)primaryStore).getPoolType() != StoragePoolType.RBD) {
                            Long parentSnapshotId = parent.getId();
                            while (parentSnapshotId != null && parentSnapshotId != 0L) {
                                SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), parentSnapshotId);
                                if (snapshotDataStoreVO != null) {
                                    parentSnapshotId = snapshotDataStoreVO.getParentSnapshotId();
                                    UsageEventUtils.publishUsageEvent(EventTypes.EVENT_SNAPSHOT_OFF_PRIMARY, parent.getAccountId(), parent.getDataCenterId(), parent.getId(),
                                            parent.getName(), null, null, 0L, 0L, parent.getClass().getName(), parent.getUuid());
                                    snapshotStoreDao.remove(snapshotDataStoreVO.getId());
                                } else {
                                    parentSnapshotId = null;
                                }
                            }
                        }
                        SnapshotDataStoreVO snapshotDataStoreVO = snapshotStoreDao.findByStoreSnapshot(primaryStore.getRole(), primaryStore.getId(), snapshotOnPrimary.getId());
                        if (snapshotDataStoreVO != null) {
                            snapshotDataStoreVO.setParentSnapshotId(0L);
                            snapshotStoreDao.update(snapshotDataStoreVO.getId(), snapshotDataStoreVO);
                        }
                    }
                } catch (Exception e) {
                    s_logger.debug("Failed to clean up snapshots on primary storage", e);
                }
            }
        });
    }

    @Override
    public StrategyPriority canHandle(Snapshot snapshot, SnapshotOperation op) {
        if (SnapshotOperation.REVERT.equals(op)) {
            long volumeId = snapshot.getVolumeId();
            VolumeVO volumeVO = volumeDao.findById(volumeId);

            if (volumeVO != null && ImageFormat.QCOW2.equals(volumeVO.getFormat())) {
                return StrategyPriority.DEFAULT;
            }

            return StrategyPriority.CANT_HANDLE;
        }

        return StrategyPriority.DEFAULT;
    }

}


text:
import { addDays } from '@fullcalendar/core'
import { DayGridViewWrapper } from '../lib/wrappers/DayGridViewWrapper'
import { TimeGridViewWrapper } from '../lib/wrappers/TimeGridViewWrapper'
import { CalendarWrapper } from '../lib/wrappers/CalendarWrapper'
import { ListViewWrapper } from '../lib/wrappers/ListViewWrapper'

describe('navLinks', () => {
  pushOptions({
    now: '2016-08-20',
    navLinks: true,
    headerToolbar: {
      left: 'prev,next today',
      center: 'title',
      right: 'dayGridMonth,timeGridWeek,timeGridDay,listWeek', // affects which view is jumped to by default
    },
  })

  describeTimeZones((tz) => {
    describe('in month view', () => {
      pushOptions({
        initialView: 'dayGridMonth',
      })

      it('moves to day', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let calendar = initCalendar()
        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

        dayGridWrapper.clickNavLink('2016-08-09')
        expectDayView(calendar, 'timeGridDay', tz.parseDate('2016-08-09'))
        expect(dateClickSpy).not.toHaveBeenCalled()
      })

      // https://github.com/fullcalendar/fullcalendar/issues/4619
      it('moves to day when no toolbars', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let calendar = initCalendar({
          headerToolbar: null,
        })
        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

        dayGridWrapper.clickNavLink('2016-08-09')
        expectDayView(calendar, 'dayGridDay', tz.parseDate('2016-08-09')) // is hash-key order-dependent I think :(
        expect(dateClickSpy).not.toHaveBeenCalled()
      })

      // https://github.com/fullcalendar/fullcalendar/issues/3869
      it('moves to two different days', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let calendar = initCalendar()

        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid
        dayGridWrapper.clickNavLink('2016-08-09')
        expectDayView(calendar, 'timeGridDay', tz.parseDate('2016-08-09'))
        expect(dateClickSpy).not.toHaveBeenCalled()

        calendar.changeView('dayGridMonth')
        let dayGridWrapper2 = new DayGridViewWrapper(calendar).dayGrid
        dayGridWrapper2.clickNavLink('2016-08-10')
        expectDayView(calendar, 'timeGridDay', tz.parseDate('2016-08-10'))
      })

      it('moves to day specifically', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let calendar = initCalendar({
          navLinkDayClick: 'day',
        })
        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

        dayGridWrapper.clickNavLink('2016-08-09')
        expectDayView(calendar, 'timeGridDay', tz.parseDate('2016-08-09'))
        expect(dateClickSpy).not.toHaveBeenCalled()
      })

      it('moves to dayGridDay specifically', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let calendar = initCalendar({
          navLinkDayClick: 'dayGridDay',
        })
        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

        dayGridWrapper.clickNavLink('2016-08-09')
        expectDayView(calendar, 'dayGridDay', tz.parseDate('2016-08-09'))
        expect(dateClickSpy).not.toHaveBeenCalled()
      })

      it('executes a custom handler', () => {
        let dateClickSpy = spyOnCalendarCallback('dateClick')
        let navLinkDayClickSpy = spyOnCalendarCallback('navLinkDayClick', (date, ev) => {
          expect(date).toEqualDate(tz.parseDate('2016-08-09'))
          expect(typeof ev).toBe('object')
        })
        let calendar = initCalendar()
        let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

        dayGridWrapper.clickNavLink('2016-08-09')
        expect(dateClickSpy).not.toHaveBeenCalled()
        expect(navLinkDayClickSpy).toHaveBeenCalled()
      })

      describe('with weekNumbers', () => {
        pushOptions({
          weekNumbers: true,
        })

        it('moves to week', () => {
          let dateClickSpy = spyOnCalendarCallback('dateClick')
          let calendar = initCalendar()
          let dayGridWrapper = new DayGridViewWrapper(calendar).dayGrid

          $.simulateMouseClick(dayGridWrapper.getWeekNavLinkEls()[1])
          expectWeekView(calendar, 'timeGridWeek', tz.parseDate('2016-08-07'))
          expect(dateClickSpy).not.toHaveBeenCalled()
        })
      })

      it('does not have clickable day header', () => {
        let calendar = initCalendar()
        let headerWrapper = new DayGridViewWrapper(calendar).header

        expect(headerWrapper.getNavLinkEls().length).toBe(0)
      })
    })
  })

  describe('in week view', () => {
    pushOptions({
      initialView: 'timeGridWeek',
    })

    it('moves to day view', () => {
      let dateClickSpy = spyOnCalendarCallback('dateClick')
      let calendar = initCalendar()
      let headerWrapper = new TimeGridViewWrapper(calendar).header

      headerWrapper.clickNavLink('2016-08-15')
      expectDayView(calendar, 'timeGridDay', '2016-08-15')
      expect(dateClickSpy).not.toHaveBeenCalled()
    })
  })

  describe('in listWeek', () => {
    pushOptions({
      initialView: 'listWeek',
      events: [
        {
          title: 'event 1',
          start: '2016-08-20',
        },
      ],
    })

    it('moves to day view', () => {
      let dateClickSpy = spyOnCalendarCallback('dateClick')
      let calendar = initCalendar()
      let listWrapper = new ListViewWrapper(calendar)

      listWrapper.clickNavLink('2016-08-20')
      expectDayView(calendar, 'timeGridDay', '2016-08-20')
      expect(dateClickSpy).not.toHaveBeenCalled()
    })
  })

  describe('in day view', () => {
    pushOptions({
      initialView: 'timeGridDay',
    })

    it('moves to week view', () => {
      let dateClickSpy = spyOnCalendarCallback('dateClick')
      let calendar = initCalendar({
        weekNumbers: true,
      })
      let viewWrapper = new TimeGridViewWrapper(calendar)

      $.simulateMouseClick(viewWrapper.getHeaderWeekNumberLink())
      expectWeekView(calendar, 'timeGridWeek', '2016-08-14')
      expect(dateClickSpy).not.toHaveBeenCalled()
    })

    it('does not have a clickable day header', () => {
      let calendar = initCalendar()
      let headerWrapper = new TimeGridViewWrapper(calendar).header

      expect(headerWrapper.getNavLinkEls().length).toBe(0)
    })
  })

  function expectDayView(calendar, viewName, dayDate) {
    let calendarWrapper = new CalendarWrapper(calendar)
    let start = calendar.view.activeStart
    let end = calendar.view.activeEnd

    expect(calendarWrapper.getViewName()).toBe(viewName)
    expect(start).toEqualDate(dayDate)
    expect(addDays(end, -1)).toEqualDate(dayDate)
  }

  function expectWeekView(calendar, viewName, firstDayDate) {
    let calendarWrapper = new CalendarWrapper(calendar)
    let start = calendar.view.activeStart
    let end = calendar.view.activeEnd

    expect(calendarWrapper.getViewName()).toBe(viewName)
    expect(start).toEqualDate(firstDayDate)
    expect(addDays(end, -7)).toEqualDate(firstDayDate)
  }
})


text:
<?xml version="1.0" encoding="utf-8" standalone="yes" ?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
  <channel>
    <title>Fuzhao Xue | IsaacChanghau</title>
    <link>/authors/fuzhao-xue/</link>
      <atom:link href="/authors/fuzhao-xue/index.xml" rel="self" type="application/rss+xml" />
    <description>Fuzhao Xue</description>
    <generator>Source Themes Academic (https://sourcethemes.com/academic/)</generator><language>en-us</language><copyright>© IsaacChanghau · 2017-2021</copyright><lastBuildDate>Tue, 09 Feb 2021 00:00:00 +0000</lastBuildDate>
    <image>
      <url>/images/icon_hu1b364a951019a703f13d3cf900b79a27_31514_512x512_fill_lanczos_center_3.png</url>
      <title>Fuzhao Xue</title>
      <link>/authors/fuzhao-xue/</link>
    </image>

    <item>
      <title>GDPNet: Refining Latent Multi-View Graph for Relation Extraction</title>
      <link>/publication/gdpnet/</link>
      <pubDate>Tue, 09 Feb 2021 00:00:00 +0000</pubDate>
      <guid>/publication/gdpnet/</guid>
      <description></description>
    </item>

  </channel>
</rss>


text:
class Manager(object):

    def __init__(self):
        super(Manager, self).__init__()

    def init_host(self):
        """Handle initialization if this is a standalone service.

        Child class should override this method

        """
        pass


text:
package org.springframework.boot.actuate.metrics.web.servlet;

import java.io.IOException;
import java.lang.reflect.AnnotatedElement;
import java.util.Collections;
import java.util.Set;
import java.util.function.Supplier;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import io.micrometer.core.annotation.Timed;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Timer;
import io.micrometer.core.instrument.Timer.Builder;
import io.micrometer.core.instrument.Timer.Sample;

import org.springframework.context.ApplicationContext;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.util.NestedServletException;

/**
 * Intercepts incoming HTTP requests and records metrics about Spring MVC execution time
 * and results.
 *
 * @author Jon Schneider
 * @author Phillip Webb
 * @since 2.0.0
 */
public class WebMvcMetricsFilter extends OncePerRequestFilter {

	private final MeterRegistry registry;

	private final WebMvcTagsProvider tagsProvider;

	private final String metricName;

	private final boolean autoTimeRequests;

	/**
	 * Create a new {@link WebMvcMetricsFilter} instance.
	 * @param context the source application context
	 * @param registry the meter registry
	 * @param tagsProvider the tags provider
	 * @param metricName the metric name
	 * @param autoTimeRequests if requests should be automatically timed
	 * @deprecated since 2.0.7 in favor of
	 * {@link #WebMvcMetricsFilter(MeterRegistry, WebMvcTagsProvider, String, boolean)}
	 */
	@Deprecated
	public WebMvcMetricsFilter(ApplicationContext context, MeterRegistry registry,
			WebMvcTagsProvider tagsProvider, String metricName,
			boolean autoTimeRequests) {
		this(registry, tagsProvider, metricName, autoTimeRequests);
	}

	/**
	 * Create a new {@link WebMvcMetricsFilter} instance.
	 * @param registry the meter registry
	 * @param tagsProvider the tags provider
	 * @param metricName the metric name
	 * @param autoTimeRequests if requests should be automatically timed
	 * @since 2.0.7
	 */
	public WebMvcMetricsFilter(MeterRegistry registry, WebMvcTagsProvider tagsProvider,
			String metricName, boolean autoTimeRequests) {
		this.registry = registry;
		this.tagsProvider = tagsProvider;
		this.metricName = metricName;
		this.autoTimeRequests = autoTimeRequests;
	}

	@Override
	protected boolean shouldNotFilterAsyncDispatch() {
		return false;
	}

	@Override
	protected void doFilterInternal(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
		filterAndRecordMetrics(request, response, filterChain);
	}

	private void filterAndRecordMetrics(HttpServletRequest request,
			HttpServletResponse response, FilterChain filterChain)
			throws IOException, ServletException {
		TimingContext timingContext = TimingContext.get(request);
		if (timingContext == null) {
			timingContext = startAndAttachTimingContext(request);
		}
		try {
			filterChain.doFilter(request, response);
			if (!request.isAsyncStarted()) {
				// Only record when async processing has finished or never been started.
				// If async was started by something further down the chain we wait
				// until the second filter invocation (but we'll be using the
				// TimingContext that was attached to the first)
				Throwable exception = (Throwable) request
						.getAttribute(DispatcherServlet.EXCEPTION_ATTRIBUTE);
				record(timingContext, response, request, exception);
			}
		}
		catch (NestedServletException ex) {
			response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
			record(timingContext, response, request, ex.getCause());
			throw ex;
		}
	}

	private TimingContext startAndAttachTimingContext(HttpServletRequest request) {
		Timer.Sample timerSample = Timer.start(this.registry);
		TimingContext timingContext = new TimingContext(timerSample);
		timingContext.attachTo(request);
		return timingContext;
	}

	private Set<Timed> getTimedAnnotations(Object handler) {
		if (!(handler instanceof HandlerMethod)) {
			return Collections.emptySet();
		}
		return getTimedAnnotations((HandlerMethod) handler);
	}

	private Set<Timed> getTimedAnnotations(HandlerMethod handler) {
		Set<Timed> timed = findTimedAnnotations(handler.getMethod());
		if (timed.isEmpty()) {
			return findTimedAnnotations(handler.getBeanType());
		}
		return timed;
	}

	private Set<Timed> findTimedAnnotations(AnnotatedElement element) {
		return AnnotationUtils.getDeclaredRepeatableAnnotations(element, Timed.class);
	}

	private void record(TimingContext timingContext, HttpServletResponse response,
			HttpServletRequest request, Throwable exception) {
		Object handlerObject = request
				.getAttribute(HandlerMapping.BEST_MATCHING_HANDLER_ATTRIBUTE);
		Set<Timed> annotations = getTimedAnnotations(handlerObject);
		Timer.Sample timerSample = timingContext.getTimerSample();
		Supplier<Iterable<Tag>> tags = () -> this.tagsProvider.getTags(request, response,
				handlerObject, exception);
		if (annotations.isEmpty()) {
			if (this.autoTimeRequests) {
				stop(timerSample, tags, Timer.builder(this.metricName));
			}
		}
		else {
			for (Timed annotation : annotations) {
				stop(timerSample, tags, Timer.builder(annotation, this.metricName));
			}
		}
	}

	private void stop(Timer.Sample timerSample, Supplier<Iterable<Tag>> tags,
			Builder builder) {
		timerSample.stop(builder.tags(tags.get()).register(this.registry));
	}

	/**
	 * Context object attached to a request to retain information across the multiple
	 * filter calls that happen with async requests.
	 */
	private static class TimingContext {

		private static final String ATTRIBUTE = TimingContext.class.getName();

		private final Timer.Sample timerSample;

		TimingContext(Sample timerSample) {
			this.timerSample = timerSample;
		}

		public Timer.Sample getTimerSample() {
			return this.timerSample;
		}

		public void attachTo(HttpServletRequest request) {
			request.setAttribute(ATTRIBUTE, this);
		}

		public static TimingContext get(HttpServletRequest request) {
			return (TimingContext) request.getAttribute(ATTRIBUTE);
		}

	}

}


text:
<!DOCTYPE html>

	    <meta charset="utf-8">
	    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	    <meta name="Keywords" content="">
	    <meta name="Description" content="">
	    <title>Admin</title>
		<?= view('admin/Asset'); ?>

		<?= view('admin/Menu'); ?>

			                我的项目

			                        wuzheng40/Demo

			                LIST

我的项目

关注的项目

关注的人

			               {{Page}}

			                我的任务

            	查看我的任务


text:
package org.iotp.server.actors;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Optional;

import org.iotp.analytics.ruleengine.common.msg.cluster.ServerAddress;
import org.iotp.infomgt.dao.alarm.AlarmService;
import org.iotp.infomgt.dao.asset.AssetService;
import org.iotp.infomgt.dao.attributes.AttributesService;
import org.iotp.infomgt.dao.customer.CustomerService;
import org.iotp.infomgt.dao.device.DeviceService;
import org.iotp.infomgt.dao.event.EventService;
import org.iotp.infomgt.dao.plugin.PluginService;
import org.iotp.infomgt.dao.rule.RuleService;
import org.iotp.infomgt.dao.tenant.TenantService;
import org.iotp.infomgt.dao.timeseries.TimeseriesService;
import org.iotp.infomgt.data.Event;
import org.iotp.infomgt.data.common.DataConstants;
import org.iotp.infomgt.data.id.EntityId;
import org.iotp.infomgt.data.id.TenantId;
import org.iotp.infomgt.data.plugin.ComponentLifecycleEvent;
import org.iotp.server.actors.service.ActorService;
import org.iotp.server.controller.plugin.PluginWebSocketMsgEndpoint;
import org.iotp.server.service.cluster.discovery.DiscoveryService;
import org.iotp.server.service.cluster.routing.ClusterRoutingService;
import org.iotp.server.service.cluster.rpc.ClusterRpcService;
import org.iotp.server.service.component.ComponentDiscoveryService;
import org.iotp.server.service.security.device.DeviceAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Scheduler;
import lombok.Getter;
import lombok.Setter;

@Component
public class ActorSystemContext {
    private static final String AKKA_CONF_FILE_NAME = "actor-system.conf";

    protected final ObjectMapper mapper = new ObjectMapper();

    @Getter @Setter private ActorService actorService;

    @Autowired
    @Getter private DiscoveryService discoveryService;

    @Autowired
    @Getter @Setter private ComponentDiscoveryService componentService;

    @Autowired
    @Getter private ClusterRoutingService routingService;

    @Autowired
    @Getter private ClusterRpcService rpcService;

    @Autowired
    @Getter private DeviceAuthService deviceAuthService;

    @Autowired
    @Getter private DeviceService deviceService;

    @Autowired
    @Getter private AssetService assetService;

    @Autowired
    @Getter private TenantService tenantService;

    @Autowired
    @Getter private CustomerService customerService;

    @Autowired
    @Getter private RuleService ruleService;

    @Autowired
    @Getter private PluginService pluginService;

    @Autowired
    @Getter private TimeseriesService tsService;

    @Autowired
    @Getter private AttributesService attributesService;

    @Autowired
    @Getter private EventService eventService;

    @Autowired
    @Getter private AlarmService alarmService;

    @Autowired
    @Getter @Setter private PluginWebSocketMsgEndpoint wsMsgEndpoint;

    @Value("${actors.session.sync.timeout}")
    @Getter private long syncSessionTimeout;

    @Value("${actors.plugin.termination.delay}")
    @Getter private long pluginActorTerminationDelay;

    @Value("${actors.plugin.processing.timeout}")
    @Getter private long pluginProcessingTimeout;

    @Value("${actors.plugin.error_persist_frequency}")
    @Getter private long pluginErrorPersistFrequency;

    @Value("${actors.rule.termination.delay}")
    @Getter private long ruleActorTerminationDelay;

    @Value("${actors.rule.error_persist_frequency}")
    @Getter private long ruleErrorPersistFrequency;

    @Value("${actors.statistics.enabled}")
    @Getter private boolean statisticsEnabled;

    @Value("${actors.statistics.persist_frequency}")
    @Getter private long statisticsPersistFrequency;

    @Getter @Setter private ActorSystem actorSystem;

    @Getter @Setter private ActorRef appActor;

    @Getter @Setter private ActorRef sessionManagerActor;

    @Getter @Setter private ActorRef statsActor;

    @Getter private final Config config;

    public ActorSystemContext() {
        config = ConfigFactory.parseResources(AKKA_CONF_FILE_NAME).withFallback(ConfigFactory.load());
    }

    public Scheduler getScheduler() {
        return actorSystem.scheduler();
    }

    public void persistError(TenantId tenantId, EntityId entityId, String method, Exception e) {
        Event event = new Event();
        event.setTenantId(tenantId);
        event.setEntityId(entityId);
        event.setType(DataConstants.ERROR);
        event.setBody(toBodyJson(discoveryService.getCurrentServer().getServerAddress(), method, toString(e)));
        persistEvent(event);
    }

    public void persistLifecycleEvent(TenantId tenantId, EntityId entityId, ComponentLifecycleEvent lcEvent, Exception e) {
        Event event = new Event();
        event.setTenantId(tenantId);
        event.setEntityId(entityId);
        event.setType(DataConstants.LC_EVENT);
        event.setBody(toBodyJson(discoveryService.getCurrentServer().getServerAddress(), lcEvent, Optional.ofNullable(e)));
        persistEvent(event);
    }

    private void persistEvent(Event event) {
        eventService.save(event);
    }

    private String toString(Exception e) {
        StringWriter sw = new StringWriter();
        e.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }

    private JsonNode toBodyJson(ServerAddress server, ComponentLifecycleEvent event, Optional<Exception> e) {
        ObjectNode node = mapper.createObjectNode().put("server", server.toString()).put("event", event.name());
        if (e.isPresent()) {
            node = node.put("success", false);
            node = node.put("error", toString(e.get()));
        } else {
            node = node.put("success", true);
        }
        return node;
    }

    private JsonNode toBodyJson(ServerAddress server, String method, String body) {
        return mapper.createObjectNode().put("server", server.toString()).put("method", method).put("error", body);
    }
}


text:
Configuración de Usuario

          Editar Perfil

          Cambiar Imagen de Perfil

          Cambiar Contraseña

          Manejar Roles


text:
@interface LSAnswer : _LSAnswer {}
// Custom logic goes here.
@end


text:
/*
 * Created by IntelliJ IDEA.
 * User: max
 * Date: Nov 15, 2001
 * Time: 5:14:35 PM
 * To change template for new interface use
 * Code Style | Class Templates options (Tools | IDE Options).
 */
package com.intellij.codeInspection.reference;

import com.intellij.codeInspection.InspectionsBundle;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.util.Key;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

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

public abstract class RefEntityImpl implements RefEntity {
  private static final String NO_NAME = InspectionsBundle.message("inspection.reference.noname");
  private RefEntityImpl myOwner;
  protected List<RefEntity> myChildren;
  private final String myName;
  private Map<Key, Object> myUserMap;
  protected int myFlags = 0;
  protected final RefManagerImpl myManager;

  protected RefEntityImpl(String name, @NotNull RefManager manager) {
    myManager = (RefManagerImpl)manager;
    myName = name != null ? name : NO_NAME;
    myOwner = null;
    myChildren = null;
  }

  @NotNull
  @Override
  public String getName() {
    return myName;
  }

  @NotNull
  @Override
  public String getQualifiedName() {
    return myName;
  }

  @Override
  public List<RefEntity> getChildren() {
    return myChildren;
  }

  @Override
  public RefEntity getOwner() {
    return myOwner;
  }

  protected void setOwner(RefEntityImpl owner) {
    myOwner = owner;
  }

  public void add(RefEntity child) {
    if (myChildren == null) {
      myChildren = new ArrayList<RefEntity>();
    }

    myChildren.add(child);
    ((RefEntityImpl)child).setOwner(this);
  }

  protected void removeChild(RefEntity child) {
    if (myChildren != null) {
      myChildren.remove(child);
      ((RefEntityImpl)child).setOwner(null);
    }
  }

  public String toString() {
    return getName();
  }

 @Override
 @Nullable
  public <T> T getUserData(@NotNull Key<T> key){
    synchronized(this){
      if (myUserMap == null) return null;
      //noinspection unchecked
      return (T)myUserMap.get(key);
    }
  }

  @Override
  public void accept(@NotNull final RefVisitor refVisitor) {
    ApplicationManager.getApplication().runReadAction(new Runnable() {
      @Override
      public void run() {
        refVisitor.visitElement(RefEntityImpl.this);
      }
    });
  }

  @Override
  public <T> void putUserData(@NotNull Key<T> key, T value){
    synchronized(this){
      if (myUserMap == null){
        if (value == null) return;
        myUserMap = new THashMap<Key, Object>();
      }
      if (value != null){
        //noinspection unchecked
        myUserMap.put(key, value);
      }
      else{
        myUserMap.remove(key);
        if (myUserMap.isEmpty()){
          myUserMap = null;
        }
      }
    }
  }

  public boolean checkFlag(int mask) {
    return (myFlags & mask) != 0;
  }

  public void setFlag(boolean b, int mask) {
    if (b) {
      myFlags |= mask;
    }
    else {
      myFlags &= ~mask;
    }
  }

  @Override
  public String getExternalName() {
    return myName;
  }

  @NotNull
  @Override
  public RefManagerImpl getRefManager() {
    return myManager;
  }
}