text:
import sys, os, arcgisscripting, subprocess

def check_output(command,console):
    if console == True:
        process = subprocess.Popen(command)
    else:
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True)
    output,error = process.communicate()
    returncode = process.poll()
    return returncode,output

### create the geoprocessor object
gp = arcgisscripting.create(9.3)

### report that something is happening
gp.AddMessage("Starting raw_flightlines_to_CHM ...")

### define positions of arguments in argv array
arg_input_folder     =  1
arg_tile_size        =  2
arg_buffer           =  3
arg_terrain_type     =  4
arg_beam_width       =  5
arg_step             =  6
arg_cores            =  7
arg_empty_temp_dir   =  8
arg_output_dir       =  9
arg_output_base_name = 10
arg_output_format    = 11
arg_verbose          = 12
arg_count_needed     = 13

### get number of arguments
argc = len(sys.argv)

### make sure we have right number of arguments
if argc != arg_count_needed:
    gp.AddMessage("Error. Wrong number of arguments. Got " + str(argc) + " expected " + str(arg_count_needed))
    sys.exit(1)

### report arguments (for debug)
#gp.AddMessage("Arguments:")
#for i in range(0, argc):
#    gp.AddMessage("[" + str(i) + "]" + sys.argv[i])

### get selected arguments
empty_temp_dir = sys.argv[arg_empty_temp_dir]
output_base_name = sys.argv[arg_output_base_name]

### get the path to LAStools
lastools_path = os.path.dirname(os.path.dirname(os.path.dirname(sys.argv[0])))

### make sure the path does not contain spaces
if lastools_path.count(" ") > 0:
    gp.AddMessage("Error. Path to .\\lastools installation contains spaces.")
    gp.AddMessage("This does not work: " + lastools_path)
    gp.AddMessage("This would work:    C:\\software\\lastools")
    sys.exit(1)

### make sure the path does not contain open or closing brackets
if (lastools_path.count("(") > 0) or (lastools_path.count(")") > 0):
    gp.AddMessage("Error. Path to .\\lastools installation contains brackets.")
    gp.AddMessage("This does not work: " + lastools_path)
    gp.AddMessage("This would work:    C:\\software\\lastools")
    sys.exit(1)

### complete the path to where the LAStools executables are
lastools_path = lastools_path + "\\bin"

### check if path exists
if os.path.exists(lastools_path) == False:
    gp.AddMessage("Cannot find .\\lastools\\bin at " + lastools_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + lastools_path + " ...")

### create the full path to the lastile executable
lastile_path = lastools_path+"\\lastile.exe"

### check if the lastile executable exists
if os.path.exists(lastile_path) == False:
    gp.AddMessage("Cannot find lastile.exe at " + lastile_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + lastile_path + " ...")

### create the full path to the lasground executable
lasground_path = lastools_path+"\\lasground.exe"

### check if the lasground executable exists
if os.path.exists(lasground_path) == False:
    gp.AddMessage("Cannot find lasground.exe at " + lasground_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + lasground_path + " ...")

### create the full path to the lasheight executable
lasheight_path = lastools_path+"\\lasheight.exe"

### check if the lasheight executable exists
if os.path.exists(lasheight_path) == False:
    gp.AddMessage("Cannot find lasheight.exe at " + lasheight_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + lasheight_path + " ...")

### create the full path to the lasthin executable
lasthin_path = lastools_path+"\\lasthin.exe"

### check if the lasthin executable exists
if os.path.exists(lasthin_path) == False:
    gp.AddMessage("Cannot find lasthin.exe at " + lasthin_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + lasthin_path + " ...")

### create the full path to the las2dem executable
las2dem_path = lastools_path+"\\las2dem.exe"

### check if the las2dem executable exists
if os.path.exists(las2dem_path) == False:
    gp.AddMessage("Cannot find las2dem.exe at " + las2dem_path)
    sys.exit(1)
else:
    gp.AddMessage("Found " + las2dem_path + " ...")

### check if the empty temp directory exists
if os.path.exists(empty_temp_dir) == False:
    gp.AddMessage("Cannot find empty temp dir " + empty_temp_dir)
    sys.exit(1)
else:
    gp.AddMessage("Found " + empty_temp_dir + " ...")

### make sure the empty temp directory is emtpy
if os.listdir(empty_temp_dir) != []:
    gp.AddMessage("Empty temp directory '" + empty_temp_dir + "' is not empty")
    sys.exit(1)
else:
    gp.AddMessage("And it's empty ...")

###################################################
### first step: tile folder of flightlines
###################################################

### create the command string for lastile.exe
command = ['"'+lastile_path+'"']

### maybe use '-verbose' option
if sys.argv[arg_verbose] == "true":
    command.append("-v")

### add input LiDAR
command.append("-i")
command.append('"'+sys.argv[arg_input_folder]+'\\*.las"')
command.append("-i")
command.append('"'+sys.argv[arg_input_folder]+'\\*.laz"')

### they are flight lines
command.append("-files_are_flightlines")

### maybe use a user-defined tile size
if sys.argv[arg_tile_size] != "1000":
    command.append("-tile_size")
    command.append(sys.argv[arg_tile_size].replace(",","."))

### maybe create a buffer around the tiles
if sys.argv[arg_buffer] != "0":
    command.append("-buffer")
    command.append(sys.argv[arg_buffer].replace(",","."))

### an empty temp directory must have been selected
if empty_temp_dir != "#":
    command.append("-odir")
    command.append('"'+empty_temp_dir+'"')
else:
    gp.AddMessage("Error. no empty temp directory was specified.")
    sys.exit(1)

### use default if base name not given
if output_base_name == "#":
    output_base_name = "tile"

### give tiles a base name
command.append("-o")
command.append('"' + output_base_name + '.laz"')

### store temporary tiles in compressed format
command.append("-olaz")

### report command string
gp.AddMessage("LAStools command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of lastile
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in lastile step.")
    sys.exit(1)

### report success
gp.AddMessage("lastile step done.")

###################################################
### second step: ground classify each tile
###################################################

### create the command string for lasground.exe
command = ['"'+lasground_path+'"']

### maybe use '-verbose' option
if sys.argv[arg_verbose] == "true":
    command.append("-v")

### add input LiDAR
command.append("-i")
command.append('"' + empty_temp_dir + "\\" + output_base_name + "*.laz" + '"')

### what type of terrain do we have
if sys.argv[arg_terrain_type] == "wilderness":
    command.append("-wilderness")
elif sys.argv[arg_terrain_type] == "city or warehouses":
    command.append("-city")
    command.append("-extra_fine")
elif sys.argv[arg_terrain_type] == "towns or flats":
    command.append("-town")
    command.append("-fine")
elif sys.argv[arg_terrain_type] == "metropolis":
    command.append("-metro")
    command.append("-ultra_fine")

### give ground-classified tiles a meaningful appendix
command.append("-odix")
command.append("_g")

### store ground-classified tiles in compressed format
command.append("-olaz")

### maybe we should run on multiple cores
if sys.argv[arg_cores] != "1":
    command.append("-cores")
    command.append(sys.argv[arg_cores])

### report command string
gp.AddMessage("LAStools command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of lasground
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in lasground step.")
    sys.exit(1)

### report success
gp.AddMessage("lasground step done.")

###################################################
### third step: height-normalize each tile
###################################################

### create the command string for lasheight.exe
command = ['"'+lasheight_path+'"']

### maybe use '-verbose' option
if sys.argv[arg_verbose] == "true":
    command.append("-v")

### add input LiDAR
command.append("-i")
command.append('"' + empty_temp_dir + "\\" + output_base_name + "*_g.laz" + '"')

### height normalize
command.append("-replace_z")

### give height-classified tiles a meaningful appendix
command.append("-odix")
command.append("h")

### store height-classified tiles in compressed format
command.append("-olaz")

### maybe we should run on multiple cores
if sys.argv[arg_cores] != "1":
    command.append("-cores")
    command.append(sys.argv[arg_cores])

### report command string
gp.AddMessage("LAStools command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of lasheight
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in lasheight step.")
    sys.exit(1)

### report success
gp.AddMessage("lasheight step done.")

###################################################
### fourth step: splat and thin highest each tile
###################################################

### create the command string for lasheight.exe
command = ['"'+lasthin_path+'"']

### maybe use '-verbose' option
if sys.argv[arg_verbose] == "true":
    command.append("-v")

### add input LiDAR
command.append("-i")
command.append('"' + empty_temp_dir + "\\" + output_base_name + "*_gh.laz" + '"')

### keep the highest
command.append("-highest")

### on a grid with four by four times the final step size
command.append("-step")
command.append(str(0.25*float(sys.argv[arg_step].replace(",","."))))

### maybe splat with half the laser beam width
if sys.argv[arg_beam_width] != "#":
    command.append("-subcircle")
    command.append(str(0.5*float(sys.argv[arg_beam_width].replace(",","."))))

### give thin-classified tiles a meaningful appendix
command.append("-odix")
command.append("t")

### store thin-classified tiles in compressed format
command.append("-olaz")

### maybe we should run on multiple cores
if sys.argv[arg_cores] != "1":
    command.append("-cores")
    command.append(sys.argv[arg_cores])

### report command string
gp.AddMessage("LAStools command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of lasthin
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in lasthin step.")
    sys.exit(1)

### report success
gp.AddMessage("lasthin step done.")

###################################################
### fifth step: raster the CHMs
###################################################

### create the command string for las2dem.exe
command = ['"'+las2dem_path+'"']

### maybe use '-verbose' option
if sys.argv[arg_verbose] == "true":
    command.append("-v")

### add input LiDAR
command.append("-i")
command.append('"' + empty_temp_dir + "\\" + output_base_name + "*_ght.laz" + '"')

### raster tile with requested step
command.append("-step")
command.append(sys.argv[arg_step].replace(",","."))

### raster only tile interiors
command.append("-use_tile_bb")

### store rastered tiles in requested directory
command.append("-odir")
command.append(sys.argv[arg_output_dir])

### give the tiles a meaningful appendix
command.append("-ocut")
command.append("4")
command.append("-odix")
command.append("_chm")

### store rastered tiles in requested format
command.append("-o" + sys.argv[arg_output_format])

### maybe we should run on multiple cores
if sys.argv[arg_cores] != "1":
    command.append("-cores")
    command.append(sys.argv[arg_cores])

### report command string
gp.AddMessage("LAStools command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of las2dem
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in las2dem (CHM) step.")
    sys.exit(1)

### report success
gp.AddMessage("las2dem (CHM) step done.")

###################################################
### final step: clean-up all temporary files
###################################################

### create the command string for clean-up
command = ["del"]

### add temporary files wildcard
command.append('"' + empty_temp_dir + "\\" + output_base_name + "*.laz" + '"')

### report command string
gp.AddMessage("clean-up command line:")
command_length = len(command)
command_string = str(command[0])
command[0] = command[0].strip('"')
for i in range(1, command_length):
    command_string = command_string + " " + str(command[i])
    command[i] = command[i].strip('"')
gp.AddMessage(command_string)

### run command
returncode,output = check_output(command, False)

### report output of clean-up
gp.AddMessage(str(output))

### check return code
if returncode != 0:
    gp.AddMessage("Error. raw_flightlines_to_CHM failed in clean-up step.")
    sys.exit(1)

### report success
gp.AddMessage("clean-up step done.")

### report happy end
gp.AddMessage("Success. raw_flightlines_to_CHM done.")


text:
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.kit.dama.transfer.client.impl.ui.model;

/**
 *
 * @author jejkal
 */
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.table.*;

/**
 * The ButtonColumn class provides a renderer and an editor that looks like a
 * JButton. The renderer and editor will then be used for a specified column in
 * the table. The TableModel will contain the String to be displayed on the
 * button.
 *
 * The button can be invoked by a mouse click or by pressing the space bar when
 * the cell has focus. Optionaly a mnemonic can be set to invoke the button.
 * When the button is invoked the provided Action is invoked. The source of the
 * Action will be the table. The action command will contain the model row
 * number of the button that was clicked.
 *
 */
public class ButtonColumn extends AbstractCellEditor
        implements TableCellRenderer, TableCellEditor, ActionListener, MouseListener {

  private JTable table;
  private Action action;
  private int mnemonic;
  private Border originalBorder;
  private Border focusBorder;
  private JButton renderButton;
  private JButton editButton;
  private String text;
  private boolean isButtonColumnEditor;

  /**
   * Create the ButtonColumn to be used as a renderer and editor. The renderer
   * and editor will automatically be installed on the TableColumn of the
   * specified column.
   *
   * @param table the table containing the button renderer/editor
   * @param action the Action to be invoked when the button is invoked
   * @param column the column to which the button renderer/editor is added
   */
  public ButtonColumn(JTable table, Action action, int column) {
    this.table = table;
    this.action = action;

    renderButton = new JButton();
    editButton = new JButton();
    editButton.setFocusPainted(false);
    editButton.addActionListener(ButtonColumn.this);
    originalBorder = editButton.getBorder();
    setFocusBorder(new LineBorder(Color.BLUE));

    TableColumnModel columnModel = table.getColumnModel();
    columnModel.getColumn(column).setCellRenderer(ButtonColumn.this);
    columnModel.getColumn(column).setCellEditor(ButtonColumn.this);
    table.addMouseListener(ButtonColumn.this);
  }

  /**
   * Get foreground color of the button when the cell has focus
   *
   * @return the foreground color
   */
  public Border getFocusBorder() {
    return focusBorder;
  }

  /**
   * The foreground color of the button when the cell has focus
   *
   * @param focusBorder the foreground color
   */
  public final void setFocusBorder(Border focusBorder) {
    this.focusBorder = focusBorder;
    editButton.setBorder(focusBorder);
  }

  public int getMnemonic() {
    return mnemonic;
  }

  /**
   * The mnemonic to activate the button when the cell has focus
   *
   * @param mnemonic the mnemonic
   */
  public void setMnemonic(int mnemonic) {
    this.mnemonic = mnemonic;
    renderButton.setMnemonic(mnemonic);
    editButton.setMnemonic(mnemonic);
  }

  @Override
  public Component getTableCellEditorComponent(
          JTable table, Object value, boolean isSelected, int row, int column) {
    text = (value == null) ? "" : value.toString();
    editButton.setText(text);
    return editButton;
  }

  @Override
  public Object getCellEditorValue() {
    return text;
  }

  @Override
  public Component getTableCellRendererComponent(
          JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
      renderButton.setForeground(table.getSelectionForeground());
      renderButton.setBackground(table.getSelectionBackground());
    } else {
      renderButton.setForeground(table.getForeground());
      renderButton.setBackground(UIManager.getColor("Button.background"));
    }

    if (hasFocus) {
      renderButton.setBorder(focusBorder);
    } else {
      renderButton.setBorder(originalBorder);
    }

    renderButton.setText((value == null) ? "" : value.toString());
    return renderButton;
  }

  /*
   *  The button has been pressed. Stop editing and invoke the custom Action
   */
  @Override
  public void actionPerformed(ActionEvent e) {
    if (table.getEditingRow() == -1) {
      return;
    }
    int row = table.convertRowIndexToModel(table.getEditingRow());
    fireEditingStopped();

    //  Invoke the Action

    ActionEvent event = new ActionEvent(
            table,
            ActionEvent.ACTION_PERFORMED,
            "" + row);
    action.actionPerformed(event);
  }

//
//  Implement MouseListener interface
//
    /*
   *  When the mouse is pressed the editor is invoked. If you then then drag
   *  the mouse to another cell before releasing it, the editor is still
   *  active. Make sure editing is stopped when the mouse is released.
   */
  @Override
  public void mousePressed(MouseEvent e) {
    if (table.isEditing()
            && table.getCellEditor() == this) {
      isButtonColumnEditor = true;
    }
  }

  @Override
  public void mouseReleased(MouseEvent e) {
    if (isButtonColumnEditor
            && table.isEditing()) {
      table.getCellEditor().stopCellEditing();
    }

    isButtonColumnEditor = false;
    actionPerformed(null);
  }

  @Override
  public void mouseClicked(MouseEvent e) {
  }

  @Override
  public void mouseEntered(MouseEvent e) {
  }

  @Override
  public void mouseExited(MouseEvent e) {
  }
}

redpajama_set_name: RedPajamaGithub


text:
package cz.metacentrum.perun.taskslib.service.impl;

import java.util.List;

import cz.metacentrum.perun.taskslib.dao.TaskResultDao;
import cz.metacentrum.perun.taskslib.model.TaskResult;
import cz.metacentrum.perun.taskslib.service.ResultManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cz.metacentrum.perun.core.api.exceptions.InternalErrorException;

/**
 *
 * @author Michal Karm Babacek
 *         JavaDoc coming soon...
 *
 */
@Transactional
@Service(value = "resultManager")
public class ResultManagerImpl implements ResultManager {

	@Autowired
	private TaskResultDao taskResultDao;

	@Override
	public List<TaskResult> getTaskResults() {
		return taskResultDao.getTaskResults();

	}

	@Override
	public List<TaskResult> getTaskResultsByTask(int taskId) {
		return taskResultDao.getTaskResultsByTask(taskId);

	}

	@Override
	public TaskResult getTaskResultById(int taskResultId) {
		return taskResultDao.getTaskResultById(taskResultId);
	}

	@Override
	public int clearByTask(int taskId) {
		return taskResultDao.clearByTask(taskId);
	}

	@Override
	public int clearAll() {
		return taskResultDao.clearAll();
	}

	@Override
	public int insertNewTaskResult(TaskResult taskResult, int engineID) throws InternalErrorException {
		return taskResultDao.insertNewTaskResult(taskResult, engineID);
	}

	@Override
	public List<TaskResult> getTaskResults(int engineID) {
		return taskResultDao.getTaskResults(engineID);
	}

	@Override
	public TaskResult getTaskResultById(int taskResultId, int engineID) {
		return taskResultDao.getTaskResultById(taskResultId, engineID);
	}

	@Override
	public int clearByTask(int taskId, int engineID) {
		return taskResultDao.clearByTask(taskId, engineID);
	}

	@Override
	public int clearAll(int engineID) {
		return taskResultDao.clearAll(engineID);
	}

	@Override
	public int clearOld(int engineID, int numDays) throws InternalErrorException {
		return taskResultDao.clearOld(engineID, numDays);
	}

	@Override
	public List<TaskResult> getTaskResultsByTask(int taskId, int engineID) {
		return taskResultDao.getTaskResultsByTask(taskId, engineID);
	}

	public List<TaskResult> getTaskResultsForDestinations(List<String> destinationsNames) throws InternalErrorException {
		return taskResultDao.getTaskResultsForDestinations(destinationsNames);
	}

	public void setTaskResultDao(TaskResultDao taskResultDao) {
		this.taskResultDao = taskResultDao;
	}

	public TaskResultDao getTaskResultDao() {
		return taskResultDao;
	}

}


text:
#include "config.h"
#include "core/svg/SVGAnimatedTypeAnimator.h"

#include "core/css/parser/CSSParser.h"
#include "core/svg/SVGAnimateTransformElement.h"
#include "core/svg/SVGAnimatedColor.h"
#include "core/svg/SVGAnimationElement.h"
#include "core/svg/SVGLength.h"
#include "core/svg/SVGLengthList.h"
#include "core/svg/SVGNumber.h"
#include "core/svg/SVGPointList.h"
#include "core/svg/SVGString.h"
#include "core/svg/SVGTransformList.h"

namespace blink {

SVGAnimatedTypeAnimator::SVGAnimatedTypeAnimator(SVGAnimationElement* animationElement)
    : m_animationElement(animationElement)
    , m_contextElement(nullptr)
    , m_type(AnimatedUnknown)
{
    ASSERT(m_animationElement);
}

void SVGAnimatedTypeAnimator::clear()
{
    m_contextElement = nullptr;
    m_animatedProperty = nullptr;
    m_type = AnimatedUnknown;
}

void SVGAnimatedTypeAnimator::reset(SVGElement* contextElement)
{
    ASSERT(contextElement);
    m_contextElement = contextElement;

    const QualifiedName& attributeName = m_animationElement->attributeName();
    m_animatedProperty = m_contextElement->propertyFromAttribute(attributeName);
    m_type = m_animatedProperty ? m_animatedProperty->type()
        : SVGElement::animatedPropertyTypeForCSSAttribute(attributeName);

    // Only <animateTransform> is allowed to animate AnimatedTransformList.
    // http://www.w3.org/TR/SVG/animate.html#AnimationAttributesAndProperties
    if (m_type == AnimatedTransformList && !isSVGAnimateTransformElement(*m_animationElement))
        m_type = AnimatedUnknown;

    ASSERT(m_type != AnimatedPoint
        && m_type != AnimatedStringList
        && m_type != AnimatedTransform);
}

PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGAnimatedTypeAnimator::createPropertyForAnimation(const String& value)
{
    ASSERT(m_contextElement);

    if (isAnimatingSVGDom()) {
        // SVG DOM animVal animation code-path.

        if (m_type == AnimatedTransformList) {
            // TransformList must be animated via <animateTransform>,
            // and its {from,by,to} attribute values needs to be parsed w.r.t. its "type" attribute.
            // Spec: http://www.w3.org/TR/SVG/single-page.html#animate-AnimateTransformElement
            ASSERT(m_animationElement);
            SVGTransformType transformType = toSVGAnimateTransformElement(m_animationElement)->transformType();
            return SVGTransformList::create(transformType, value);
        }

        ASSERT(m_animatedProperty);
        return m_animatedProperty->currentValueBase()->cloneForAnimation(value);
    }

    ASSERT(isAnimatingCSSProperty());

    // CSS properties animation code-path.
    // Create a basic instance of the corresponding SVG property.
    // The instance will not have full context info. (e.g. SVGLengthMode)

    switch (m_type) {
    case AnimatedColor:
        return SVGColorProperty::create(value.isEmpty() ? StyleColor::currentColor() : CSSParser::colorFromRGBColorString(value));
    case AnimatedNumber: {
        RefPtrWillBeRawPtr<SVGNumber> property = SVGNumber::create();
        property->setValueAsString(value, IGNORE_EXCEPTION);
        return property.release();
    }
    case AnimatedLength: {
        RefPtrWillBeRawPtr<SVGLength> property = SVGLength::create();
        property->setValueAsString(value, IGNORE_EXCEPTION);
        return property.release();
    }
    case AnimatedLengthList: {
        RefPtrWillBeRawPtr<SVGLengthList> property = SVGLengthList::create();
        property->setValueAsString(value, IGNORE_EXCEPTION);
        return property.release();
    }
    case AnimatedString: {
        RefPtrWillBeRawPtr<SVGString> property = SVGString::create();
        property->setValueAsString(value, IGNORE_EXCEPTION);
        return property.release();
    }

    // These types don't appear in the table in SVGElement::animatedPropertyTypeForCSSAttribute() and thus don't need support.
    case AnimatedAngle:
    case AnimatedBoolean:
    case AnimatedEnumeration:
    case AnimatedInteger:
    case AnimatedIntegerOptionalInteger:
    case AnimatedNumberList:
    case AnimatedNumberOptionalNumber:
    case AnimatedPath:
    case AnimatedPoint:
    case AnimatedPoints:
    case AnimatedPreserveAspectRatio:
    case AnimatedRect:
    case AnimatedStringList:
    case AnimatedTransform:
    case AnimatedTransformList:
        ASSERT_NOT_REACHED();

    case AnimatedUnknown:
        ASSERT_NOT_REACHED();
    };

    ASSERT_NOT_REACHED();
    return nullptr;
}

PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGAnimatedTypeAnimator::constructFromString(const String& value)
{
    return createPropertyForAnimation(value);
}

void SVGAnimatedTypeAnimator::calculateFromAndToValues(RefPtrWillBeMember<SVGPropertyBase>& from, RefPtrWillBeMember<SVGPropertyBase>& to, const String& fromString, const String& toString)
{
    from = constructFromString(fromString);
    to = constructFromString(toString);
}

void SVGAnimatedTypeAnimator::calculateFromAndByValues(RefPtrWillBeMember<SVGPropertyBase>& from, RefPtrWillBeMember<SVGPropertyBase>& to, const String& fromString, const String& byString)
{
    from = constructFromString(fromString);
    to = constructFromString(byString);
    // FIXME(oilpan): Below .get() should be removed after transition types are gone.
    to->add(from.get(), m_contextElement);
}

namespace {

void setAnimatedValueOnAllTargetProperties(const SVGElementInstances& list, const QualifiedName& attributeName, PassRefPtrWillBeRawPtr<SVGPropertyBase> passValue)
{
    RefPtrWillBeRawPtr<SVGPropertyBase> value = passValue;

    for (SVGElement* elementInstance : list) {
        RefPtrWillBeRawPtr<SVGAnimatedPropertyBase> animatedProperty = elementInstance->propertyFromAttribute(attributeName);
        if (animatedProperty)
            animatedProperty->setAnimatedValue(value);
    }
}

}

PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGAnimatedTypeAnimator::resetAnimation(const SVGElementInstances& list)
{
    ASSERT(isAnimatingSVGDom());
    RefPtrWillBeRawPtr<SVGPropertyBase> animatedValue = m_animatedProperty->createAnimatedValue();
    ASSERT(animatedValue->type() == m_type);
    setAnimatedValueOnAllTargetProperties(list, m_animatedProperty->attributeName(), animatedValue);

    return animatedValue.release();
}

PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGAnimatedTypeAnimator::startAnimValAnimation(const SVGElementInstances& list)
{
    ASSERT(isAnimatingSVGDom());
    SVGElement::InstanceUpdateBlocker blocker(m_contextElement);

    return resetAnimation(list);
}

void SVGAnimatedTypeAnimator::stopAnimValAnimation(const SVGElementInstances& list)
{
    if (!isAnimatingSVGDom())
        return;

    ASSERT(m_contextElement);
    SVGElement::InstanceUpdateBlocker blocker(m_contextElement);

    for (SVGElement* elementInstance : list) {
        RefPtrWillBeRawPtr<SVGAnimatedPropertyBase> animatedProperty = elementInstance->propertyFromAttribute(m_animatedProperty->attributeName());
        if (animatedProperty)
            animatedProperty->animationEnded();
    }
}

PassRefPtrWillBeRawPtr<SVGPropertyBase> SVGAnimatedTypeAnimator::resetAnimValToBaseVal(const SVGElementInstances& list)
{
    SVGElement::InstanceUpdateBlocker blocker(m_contextElement);

    return resetAnimation(list);
}

class ParsePropertyFromString {
    STACK_ALLOCATED();
public:
    explicit ParsePropertyFromString(SVGAnimatedTypeAnimator* animator)
        : m_animator(animator)
    {
    }

    PassRefPtrWillBeRawPtr<SVGPropertyBase> operator()(SVGAnimationElement*, const String& value)
    {
        return m_animator->createPropertyForAnimation(value);
    }

private:
    RawPtrWillBeMember<SVGAnimatedTypeAnimator> m_animator;
};

void SVGAnimatedTypeAnimator::calculateAnimatedValue(float percentage, unsigned repeatCount, SVGPropertyBase* from, SVGPropertyBase* to, SVGPropertyBase* toAtEndOfDuration, SVGPropertyBase* animated)
{
    ASSERT(m_animationElement);
    ASSERT(m_contextElement);

    RefPtrWillBeRawPtr<SVGPropertyBase> fromValue = m_animationElement->animationMode() == ToAnimation ? animated : from;
    RefPtrWillBeRawPtr<SVGPropertyBase> toValue = to;
    RefPtrWillBeRawPtr<SVGPropertyBase> toAtEndOfDurationValue = toAtEndOfDuration;
    RefPtrWillBeRawPtr<SVGPropertyBase> animatedValue = animated;

    // Apply CSS inheritance rules.
    ParsePropertyFromString parsePropertyFromString(this);
    m_animationElement->adjustForInheritance<RefPtrWillBeRawPtr<SVGPropertyBase>, ParsePropertyFromString>(parsePropertyFromString, m_animationElement->fromPropertyValueType(), fromValue, m_contextElement);
    m_animationElement->adjustForInheritance<RefPtrWillBeRawPtr<SVGPropertyBase>, ParsePropertyFromString>(parsePropertyFromString, m_animationElement->toPropertyValueType(), toValue, m_contextElement);

    animatedValue->calculateAnimatedValue(m_animationElement, percentage, repeatCount, fromValue, toValue, toAtEndOfDurationValue, m_contextElement);
}

float SVGAnimatedTypeAnimator::calculateDistance(const String& fromString, const String& toString)
{
    ASSERT(m_contextElement);
    RefPtrWillBeRawPtr<SVGPropertyBase> fromValue = createPropertyForAnimation(fromString);
    RefPtrWillBeRawPtr<SVGPropertyBase> toValue = createPropertyForAnimation(toString);
    return fromValue->calculateDistance(toValue, m_contextElement);
}

DEFINE_TRACE(SVGAnimatedTypeAnimator)
{
    visitor->trace(m_animationElement);
    visitor->trace(m_contextElement);
    visitor->trace(m_animatedProperty);
}

}


text:
/**
 * weapon.js
 *
 * Class for handling weapons
 */

/* global Projectile, stage */

var Weapon;

(function () {
  "use strict";

  var BASE_FIRE_RATE = 250;

  Weapon = function (params) {
    this.projectile = Projectile;
    this.fireRate = BASE_FIRE_RATE; // milliseconds
    this.fireCounter = 0;

    this.ship = params.ship;
  };

  Weapon.prototype.fire = function () {
    this.fireProjectile(this.ship.rotation);
  };

  Weapon.prototype.fireProjectile = function (rotation) {
    var accelDir = vec3.create();
    accelDir[0] = Math.cos(rotation);
    accelDir[1] = Math.sin(rotation);

    var velocity = this.ship.velocity;
    var proj = new this.projectile({
      owner: this.ship
    , position: this.ship.position
    , rotation: this.ship.rotation
    });
    proj.launch({
      accelDir: accelDir
    , velocity: velocity
    });

    stage.addProjectile(proj);
  };

  /**
   * Basic projectile firing, just fire forward the direction the ship is
   * facing and with the ship's base velocity
   */
  Weapon.prototype.update = function (tick, tryShoot) {
    var shoot = this.fireCounter === 0;

    if (this.fireCounter > this.fireRate) {
      this.fireCounter = this.fireCounter % this.fireRate;
      shoot = true;

      if (!tryShoot) {
        this.fireCounter = 0;
      }
    }

    if (this.fireCounter !== 0 || (tryShoot && shoot)) {
      this.fireCounter += tick;
    }

    if (!tryShoot || !shoot) {
      return;
    }

    this.fire();
  };

}());


text:
package com.xiezizuocai.pureacg.ui.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.xiezizuocai.pureacg.R;
import com.xiezizuocai.pureacg.utils.ImageUtil;
import com.xiezizuocai.pureacg.utils.ShareUtil;

import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;

import uk.co.senab.photoview.PhotoViewAttacher;

/**
 * Created by Administrator on 2016/8/16.
 */
@ContentView(R.layout.activity_latest_pic_details)
public class PicDetailsActivity extends BaseActivity {

    @ViewInject(R.id.toolbar)
    private Toolbar toolbar;

    @ViewInject(R.id.image_view)
    private ImageView image;

    private String url;

     private PhotoViewAttacher attacher;

    private Bitmap bitmap;

    @Override
    protected void onCreate( Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        url = getIntent().getStringExtra("url");
        initView();
    }

    public static void startPicDetailsActivity(Activity activity, String url) {
        Intent intent = new Intent(activity, PicDetailsActivity.class);
        intent.putExtra("url", url);
        activity.startActivity(intent);
    }

    private void initView() {
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow_white_24dp);
        setToolbarTitle(R.string.fragment_title_latest_pic);  // 设置工具栏标题

        attacher = new PhotoViewAttacher(image);
        Glide.with(this)
                .load(url)
                .asBitmap()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                        image.setImageBitmap(resource);
                        attacher.update();
                        bitmap = resource;
                    }
                });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_pic_details_menu,menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()){

            case android.R.id.home:
                finish();
                break;

            case R.id.action_share:
                ShareUtil.shareImage(this, ImageUtil.saveImage(this,url,bitmap,image,"share"));
                break;

            case R.id.action_save:
                ImageUtil.saveImage(this,url,bitmap,image,"save");
                break;

            case R.id.action_click_me:

                break;
        }
        return super.onOptionsItemSelected(item);
    }

}


text:
"""
    test_hashing
    ~~~~~~~~~~~~

    hashing tests
"""

from pytest import raises
from utils import authenticate, init_app_with_options
from passlib.hash import pbkdf2_sha256, django_pbkdf2_sha256, plaintext

from flask_security.utils import encrypt_password, verify_password, get_hmac

def test_verify_password_bcrypt_double_hash(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SALT': 'salty',
        'SECURITY_PASSWORD_SINGLE_HASH': False,
    })
    with app.app_context():
        assert verify_password('pass', encrypt_password('pass'))

def test_verify_password_bcrypt_single_hash(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SALT': None,
        'SECURITY_PASSWORD_SINGLE_HASH': True,
    })
    with app.app_context():
        assert verify_password('pass', encrypt_password('pass'))

def test_verify_password_single_hash_list(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SALT': 'salty',
        'SECURITY_PASSWORD_SINGLE_HASH': ['django_pbkdf2_sha256', 'plaintext'],
        'SECURITY_PASSWORD_SCHEMES': [
            'bcrypt', 'pbkdf2_sha256', 'django_pbkdf2_sha256', 'plaintext'
        ]
    })
    with app.app_context():
        # double hash
        assert verify_password('pass', encrypt_password('pass'))
        assert verify_password('pass', pbkdf2_sha256.hash(get_hmac('pass')))
        # single hash
        assert verify_password('pass', django_pbkdf2_sha256.hash('pass'))
        assert verify_password('pass', plaintext.hash('pass'))

def test_verify_password_backward_compatibility(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SINGLE_HASH': False,
        'SECURITY_PASSWORD_SCHEMES': ['bcrypt', 'plaintext']
    })
    with app.app_context():
        # double hash
        assert verify_password('pass', encrypt_password('pass'))
        # single hash
        assert verify_password('pass', plaintext.hash('pass'))

def test_verify_password_bcrypt_rounds_too_low(app, sqlalchemy_datastore):
    with raises(ValueError) as exc_msg:
        init_app_with_options(app, sqlalchemy_datastore, **{
            'SECURITY_PASSWORD_HASH': 'bcrypt',
            'SECURITY_PASSWORD_SALT': 'salty',
            'SECURITY_PASSWORD_HASH_OPTIONS': {'bcrypt': {'rounds': 3}}
        })
    assert all(s in str(exc_msg) for s in ['rounds', 'too low'])

def test_login_with_bcrypt_enabled(app, sqlalchemy_datastore):
    init_app_with_options(app, sqlalchemy_datastore, **{
        'SECURITY_PASSWORD_HASH': 'bcrypt',
        'SECURITY_PASSWORD_SALT': 'salty',
        'SECURITY_PASSWORD_SINGLE_HASH': False,
    })
    response = authenticate(app.test_client(), follow_redirects=True)
    assert b'Home Page' in response.data

def test_missing_hash_salt_option(app, sqlalchemy_datastore):
    with raises(RuntimeError):
        init_app_with_options(app, sqlalchemy_datastore, **{
            'SECURITY_PASSWORD_HASH': 'bcrypt',
            'SECURITY_PASSWORD_SALT': None,
            'SECURITY_PASSWORD_SINGLE_HASH': False,
        })


text:
/** @file generaldata.h
 *  @brief general class for manipulation with data
 *
 *  @author Lukas Pospisil
 */

#ifndef PASC_GENERALDATA_H
#define	PASC_GENERALDATA_H

#include "general/common/common.h"

namespace pascinference {
namespace data {

/** \class GeneralData
 *  \brief general class for manipulation with data
 *
 *  Parent class for manipulation with data.
 *  All specific data implementations should be defined as inherited classes from this class.
 *
*/
class GeneralData {
	protected:

	public:

		/** @brief default constructor
		 */
		GeneralData() {};

		/** @brief default destructor
		 */
		~GeneralData() {};

		/** @brief print basic information about data
		 *
		 * @param output where to print
		 */
		virtual void print(ConsoleOutput &output) const;

		virtual void print(ConsoleOutput &output_global, ConsoleOutput &output_local) const;

		/** @brief print content of data
		 *
		 * Print all values in inner data structures.
		 *
		 * @param output where to print
		 */
		virtual void printcontent(ConsoleOutput &output) const;

		virtual void printcontent(ConsoleOutput &output_global, ConsoleOutput &output_local) const;

		/** @brief get the name of data
		 */
		virtual std::string get_name() const;

		/** @brief append name to input stream
		 *
		 */
		friend ConsoleOutput &operator<<(ConsoleOutput &output, const GeneralData &data); /* cannot be virtual, therefore it call virtual print() */

};

/* general print, call virtual print() */
extern ConsoleOutput &operator<<(ConsoleOutput &output, const GeneralData &data);

}
} /* end of namespace */

#endif


text:
package com.datastax.oss.driver.internal.core.servererrors;

import com.datastax.oss.driver.api.core.servererrors.WriteType;

public interface WriteTypeRegistry {
  WriteType fromName(String name);

  /** @return all the values known to this driver instance. */
  Iterable<WriteType> getValues();
}


text:
from calvin.runtime.south.calvinsys import base_calvinsys_object
from calvin.utilities.calvinlogger import get_logger
import paho.mqtt.publish

_log = get_logger(__name__)

class Publish(base_calvinsys_object.BaseCalvinsysObject):
    """
    Publish data to given MQTT broker (using paho.mqtt implementation)
    """

    init_schema = {
        "type": "object",
        "properties": {
            "hostname": {
                "description": "hostname of broker",
                "type": "string"
            },
            "port": {
                "description": "port to use, defaults to 1883",
                "type": "integer"
            },
            "qos": {
                "description": "MQTT qos, default 0",
                "type": "number"
            },
            "client_id": {
                "description": "MQTT client id to use; will be generated if not given",
                "type": "string"
            },
            "will": {
                "description": "message to send on connection lost",
                "type": "object",
                "properties": {
                    "topic": {
                        "type": "string",
                    },
                    "payload": {
                        "type": "string"
                    },
                    "qos": {
                        "type": "string"
                    },
                    "retain": {
                        "type": "string"
                    }
                },
                "required": ["topic"]
            },
            "auth": {
                "type": "object",
                "properties": {
                    "username": {
                        "type": "string"
                    },
                    "password": {
                        "type": "string"
                    }
                },
               "required": ["username"]
            },
            "tls": {
                "description": "TLS configuration for client",
                "type": "object",
                "properties": {
                    "ca_certs": {
                        "type": "string",
                    },
                    "certfile": {
                        "type": "string"
                    },
                    "keyfile": {
                        "type": "string"
                    },
                    "tls_version": {
                        "type": "string"
                    },
                    "ciphers": {
                        "type": "string"
                    }
                },
                "required": ["ca_certs"]
            },
            "transport": {
                "description": "transport to use",
                "enum": ["tcp", "websocket"]

            },
            "topic": {
                "description": "topic to publish under - if given will be prefixed as topic for all messages",
                "type": "string"
            },
            "payload": {
                "description": "payload to publish - if given will be used as default payload for all messages",
                "type": ["string", "integer", "null", "boolean", "number"]
            }
        },
        "required": ["hostname"],
    }

    can_write_schema = {
        "description": "True if ready to publish next message",
        "type": "boolean"
    }

    write_schema = {
        "description": "Publish mqtt data",
        "type": ["number", "integer", "null", "boolean", "object", "string"],
        "properties": {
            "topic": {
                "type": "string"
            },
            "payload": {
                "type": ["number", "integer", "string", "null", "boolean"]
            },
        },
        "required": ["topic"]
    }

    def init(self, hostname, port=1883, qos=0, client_id='', will=None, auth=None, tls=None, transport='tcp', topic=None):
        def expand_specials(topic):
            import re
            matches = re.findall(r"##(\w+)##", topic)
            for match in matches:
                if match == "CALVINRTNAME":
                    m = self.calvinsys._node.node_name
                elif match == "CALVINRTID":
                    m = self.calvinsys._node.id
                topic = topic.replace("##{}##".format(match), m)
            return topic

        def on_connect(client, userdata, flags, rc):
            if rc != 0:
                _log.warning("Connection to MQTT broker {}:{} failed".format(hostname, port))
            else :
                _log.info("Connected to MQTT broker {}:{}".format(hostname, port))
                self.running = True

        def on_publish(client, userdata, mid):
            self.busy = False

        def on_disconnect(client, userdata, rc):
            _log.warning("MQTT broker {}:{} disconnected".format(hostname, port))

        # Config
        self.settings = {
            "hostname": hostname,
            "port": port,
            "client_id": client_id,
            "qos": qos,
            "will": will,
            "auth": auth,
            "tls": tls,
            "transport": transport
        }

        self.topic = expand_specials(topic) if topic else None

        self.data = []

        self.client = paho.mqtt.client.Client(client_id=client_id, transport=transport)
        self.client.on_connect = on_connect
        self.client.on_publish = on_publish
        self.client.on_disconnect = on_disconnect

        if will:
            payload = will.get("payload")
            if isinstance(payload, basestring):
                payload = payload.encode("ascii")
            topic = will.get("topic")
            if isinstance(topic, basestring):
                topic = topic.encode("ascii")

            self.client.will_set(topic=topic, payload=payload)

        if auth:
            self.client.username_pw_set(username=auth.get("username"), password=auth.get("password"))

        if tls:
            self.client.tls_set(ca_certs=tls.get("ca_certs"), certfile=tls.get("certfile"), keyfile=tls.get("keyfile"))

        self.client.connect_async(host=hostname, port=port)
        self.client.loop_start()
        self.running = False
        self.busy = False

    def can_write(self):
        return self.running and not self.busy

    def write(self, data):
        topic = None
        payload = None

        if isinstance(data, dict):
            payload = data.get("payload")
            topic = data.get("topic")

            if self.topic and topic:
                topic = "{}{}".format(self.topic, topic)
            elif self.topic :
                topic = self.topic
        else:
            payload = data
            topic = self.topic

        assert topic is not None

        self.busy = True
        self.client.publish(topic=topic, payload=payload)

    def close(self):
        self.client.disconnect()
        self.client.loop_stop()
        self.client = None


text:
import numpy as np

from .base_lutman import Base_LutMan, get_wf_idx_from_name

from pycqed.measurement.waveform_control_CC import waveform as wf
from pycqed.instrument_drivers.meta_instrument.LutMans.ro_lutman_config import (
    FeedlineMapCollection,
    read_ro_lutman_bit_map,
)

from qcodes.instrument.parameter import ManualParameter
from qcodes.utils import validators as vals

def create_pulse(
        shape: str,
        amplitude: float,
        length: float,
        phase: float,
        delay: float = 0,
        sampling_rate: float = 1.8e9
):
    kw = {}
    if shape == 'square':
        shape_function = wf.block_pulse
        kw['length'] = length
    elif shape == 'gaussian':
        shape_function = wf.gauss_pulse
        nr_sigma = 4
        kw['sigma_length'] = length/nr_sigma
        kw['nr_sigma'] = nr_sigma
    else:
        raise NotImplementedError('Primitive pulse shape ' + shape + ' not implemented.')

    return shape_function(
        amp=amplitude,
        sampling_rate=sampling_rate,
        delay=delay,
        phase=phase, **kw
    )

class Base_RO_LutMan(Base_LutMan):

    def __init__(
            self,
            name,
            num_res=2,
            feedline_number: int = 0,
            feedline_map='S7',
            **kw
    ):
        self._num_res = num_res
        self._feedline_number = feedline_number

        # FIXME: we should not be aware of topology here
        map_collection: FeedlineMapCollection = read_ro_lutman_bit_map()
        self._resonator_codeword_bit_mapping = map_collection.get_bitmap(
            map_id=feedline_map,
            feedline_nr=self._feedline_number,
        )

        # capping the resonator bit mapping in case a limited number of resonators is used
        self._resonator_codeword_bit_mapping = self._resonator_codeword_bit_mapping[:self._num_res]

        # Initial values on parameters that otherwise depend on each other
        self._resonator_combinations = [
            [self._resonator_codeword_bit_mapping[0]]
        ]
        self._pulse_type = 'M_simple'
        super().__init__(name, **kw)

    ##########################################################################
    # Base_LutMan overrides
    ##########################################################################

    def _add_waveform_parameters(self):
        # parameters really set manually by user, not touched within PycQED
        self.add_parameter(
            'pulse_primitive_shape',
            vals=vals.Enum('square', 'gaussian'),
            parameter_class=ManualParameter,
            docstring='defines the shape of the segments of the pulse',
            initial_value='square'
        )
        self.add_parameter(
            'gaussian_convolution',
            vals=vals.Bool(),
            parameter_class=ManualParameter,
            initial_value=False
        )
        self.add_parameter(
            'gaussian_convolution_sigma',
            vals=vals.Numbers(),
            parameter_class=ManualParameter,
            initial_value=5.0e-9,
            unit='s'
        )

        # mixer corrections are done globally
        self.add_parameter(
            'mixer_apply_predistortion_matrix',
            vals=vals.Bool(),
            parameter_class=ManualParameter,
            initial_value=False
        )
        self.add_parameter(
            'mixer_alpha',
            vals=vals.Numbers(),
            parameter_class=ManualParameter,
            initial_value=1.0
        )
        self.add_parameter(
            'mixer_phi',
            vals=vals.Numbers(),
            unit='deg',
            parameter_class=ManualParameter,
            initial_value=0.0
        )
        self.add_parameter(
            'mixer_offs_I',  # FIXME: not really used
            unit='V',
            parameter_class=ManualParameter,
            initial_value=0
        )
        self.add_parameter(
            'mixer_offs_Q',  # FIXME: not really used
            unit='V',
            parameter_class=ManualParameter,
            initial_value=0
        )

        # pulse attributes
        self.add_parameter(
            'resonator_combinations',
            vals=vals.Lists(),
            docstring=(
            'Resonator combinations specifies which pulses are uploaded to'
            'the device. Given as a list of lists:'
            'e.g. [[0], [2], [0, 2]] specifies that pulses for readout'
            'of resonator 0, 2, and a pulse for mux readout on both should be'
            'uploaded.'),
            set_cmd=self._set_resonator_combinations,
            get_cmd=self._get_resonator_combinations
        )

        self.add_parameter(
            'pulse_type',
            vals=vals.Enum('M_up_down_down', 'M_simple', 'M_up_down_down_final'),
            set_cmd=self._set_pulse_type,
            get_cmd=self._get_pulse_type,
            docstring='defines sequence of segments of the pulse'
        )
        for res in self._resonator_codeword_bit_mapping:
            self.add_parameter(
                'M_modulation_R{}'.format(res),
                vals=vals.Numbers(),
                unit='Hz',
                parameter_class=ManualParameter,
                initial_value=20.0e6
            )
            self.add_parameter(
                'M_length_R{}'.format(res),
                unit='s',
                vals=vals.Numbers(1e-9, 8000e-9),
                parameter_class=ManualParameter,
                initial_value=2000e-9
            )
            self.add_parameter(
                'M_amp_R{}'.format(res),
                unit='V',
                vals=vals.Numbers(0, 1),
                parameter_class=ManualParameter,
                initial_value=0.1
            )
            self.add_parameter(
                'M_delay_R{}'.format(res),
                unit='V',
                vals=vals.Numbers(0, 500e-9),
                parameter_class=ManualParameter,
                initial_value=0
            )
            self.add_parameter(
                'M_final_amp_R{}'.format(res),
                unit='V',
                vals=vals.Numbers(0, 1),
                parameter_class=ManualParameter,
                initial_value=0.1
            )
            self.add_parameter(
                'M_final_length_R{}'.format(res),
                unit='s',
                vals=vals.Numbers(1e-9, 8000e-9),
                parameter_class=ManualParameter,
                initial_value=1000e-9
            )
            self.add_parameter(
                'M_final_delay_R{}'.format(res),
                unit='s',
                vals=vals.Numbers(1e-9, 8000e-9),
                parameter_class=ManualParameter,
                initial_value=200e-9
            )
            self.add_parameter(
                'M_phi_R{}'.format(res),
                unit='deg',
                vals=vals.Numbers(0, 360),
                parameter_class=ManualParameter,
                initial_value=0.0
            )
            self.add_parameter(
                'M_down_length0_R{}'.format(res),
                unit='s',
                vals=vals.Numbers(1e-9, 8000e-9),
                parameter_class=ManualParameter,
                initial_value=200.0e-9
            )
            self.add_parameter(
                'M_down_length1_R{}'.format(res),
                unit='s',
                vals=vals.Numbers(1e-9, 8000e-9),
                parameter_class=ManualParameter,
                initial_value=200.0e-9
            )
            self.add_parameter(
                'M_down_amp0_R{}'.format(res),
                unit='V',
                vals=vals.Numbers(-1, 1),
                parameter_class=ManualParameter,
                initial_value=0.1
            )
            self.add_parameter(
                'M_down_amp1_R{}'.format(res),
                unit='V',
                vals=vals.Numbers(-1, 1),
                parameter_class=ManualParameter,
                initial_value=0.1
            )
            self.add_parameter(
                'M_down_phi0_R{}'.format(res),
                unit='deg',
                parameter_class=ManualParameter,
                initial_value=180.0
            )
            self.add_parameter(
                'M_down_phi1_R{}'.format(res),
                unit='deg',
                parameter_class=ManualParameter,
                initial_value=180.0
            )

    def set_default_lutmap(self):
        """
        Updates the LutMap based on the "resonator_combinations" and "pulse_type"
        parameters.
        """
        lm = {}

        # LutMap format:
        # CW: {'name': name}
        # As the LutMap is going to contain a list of the actual codewords that are used,
        # we start by iterating through the used read-out combinations.
        for resonator_combination in self._resonator_combinations:
            case = 0

            if not resonator_combination:
                wavename = 'empty'
            else:
                wavename = self._pulse_type
                for resonator in resonator_combination:
                    wavename += '_R' + str(resonator)
                    try:
                        case += 2**self._resonator_codeword_bit_mapping.index(resonator)
                    except ValueError:
                        # The allowed resonators is determined by the feedline
                        raise ValueError(
                            "{} not in allowed resonators ({}).".format(
                                resonator, self._resonator_codeword_bit_mapping))

            lm[case] = {'name': wavename, 'resonators': resonator_combination}

        self.LutMap(lm)

    def generate_standard_waveforms(self):
        """
        Generates waveforms for reading out from each individual resonator.
        """
        # Only generate the combinations required/specified in the LutMap
        # RO pulses
        sampling_rate = self.get('sampling_rate')

        # Prepare gauss pulse for convolution (if desired)
        if self.gaussian_convolution():
            if self.pulse_primitive_shape() != 'square':
                print("Warning: recommend to set pulse_primitive_shape to " +
                      "'square' when using gaussian_convolution.")
            sigma = self.gaussian_convolution_sigma()

            def norm_gauss(x, mu, sigma):
                n = 1/(sigma*np.sqrt(2*np.pi))
                return n*np.exp((-((x-mu)/sigma)**2)/2)

            gauss_length = 6*sigma  # in units of time
            hgsl = int(gauss_length*sampling_rate/2)  # half no. of samples
            gauss_sample_length = hgsl*2  # no. of samples
            gauss_samples = np.arange(0, gauss_sample_length, 1)/sampling_rate
            norm_gauss_p = norm_gauss(x=gauss_samples,
                                      mu=gauss_length/2, sigma=sigma)
        else:
            gauss_length = 0

        # Prepare pulses for all resonators
        self._wave_dict = {}
        for res in self._resonator_codeword_bit_mapping:
            res_wave_dict = {}
            # 1. Generate Pulse envelopes
            # Simple pulse
            up_len = self.get('M_length_R{}'.format(res))-gauss_length
            M = create_pulse(
                shape=self.pulse_primitive_shape(),
                amplitude=self.get('M_amp_R{}'.format(res)),
                length=up_len,
                delay=self.get('M_delay_R{}'.format(res)),
                phase=self.get('M_phi_R{}'.format(res)),
                sampling_rate=sampling_rate
            )
            res_wave_dict['M_simple_R{}'.format(res)] = M

            # # 3-step RO pulse with ramp-up and double depletion
            # up_len = self.get('M_length_R{}'.format(res))-gauss_length/2
            # M_up = create_pulse(
            #     shape=self.pulse_primitive_shape(),
            #     amplitude=self.get('M_amp_R{}'.format(res)),
            #     length=up_len,
            #     delay=0,
            #     phase=self.get('M_phi_R{}'.format(res)),
            #     sampling_rate=sampling_rate
            # )

            # M_down0 = create_pulse(
            #     shape=self.pulse_primitive_shape(),
            #     amplitude=self.get('M_down_amp0_R{}'.format(res)),
            #     length=self.get('M_down_length0_R{}'.format(res)),  # ns
            #     delay=0,
            #     phase=self.get('M_down_phi0_R{}'.format(res)),
            #     sampling_rate=sampling_rate
            # )

            # down1_len = self.get('M_down_length1_R{}'.format(res))-gauss_length/2
            # M_down1 = create_pulse(
            #     shape=self.pulse_primitive_shape(),
            #     amplitude=self.get('M_down_amp1_R{}'.format(res)),
            #     length=down1_len,
            #     delay=0,
            #     phase=self.get('M_down_phi1_R{}'.format(res)),
            #     sampling_rate=sampling_rate
            # )

            # M_up_down_down = (np.concatenate((M_up[0], M_down0[0], M_down1[0])),
            #                   np.concatenate((M_up[1], M_down0[1], M_down1[1])))
            # res_wave_dict['M_up_down_down_R{}'.format(res)] = M_up_down_down

            # pulse with up, down, down depletion with an additional final
            # strong measurement at some delay
            M_final = create_pulse(
                shape=self.pulse_primitive_shape(),
                amplitude=self.get('M_final_amp_R{}'.format(res)),
                length=self.get('M_final_length_R{}'.format(res)),  # ns
                delay=self.get('M_final_delay_R{}'.format(res)),
                phase=self.get('M_phi_R{}'.format(res)),
                sampling_rate=sampling_rate
            )

            # M_up_down_down_final = (np.concatenate((M_up_down_down[0], M_final[0])),
            #                         np.concatenate((M_up_down_down[1], M_final[1])))
            # res_wave_dict['M_up_down_down_final_R{}'.format(res)] = M_up_down_down_final

            # 2. convolve with gaussian (if desired)
            if self.gaussian_convolution():
                for key, val in res_wave_dict.items():
                    if 'M_simple_R' in key:
                        M_conv0 = np.convolve(val[0], norm_gauss_p)
                        M_conv1 = np.convolve(val[1], norm_gauss_p)
                        #M_conv0 = M_conv0[hgsl: -hgsl+1]
                        #M_conv1 = M_conv1[hgsl: -hgsl+1]
                        res_wave_dict[key] = (
                            M_conv0/sampling_rate, M_conv1/sampling_rate)

            # 3. modulation with base frequency
            for key, val in res_wave_dict.items():
                res_wave_dict[key] = wf.mod_pulse(
                    pulse_I=val[0],
                    pulse_Q=val[1],
                    f_modulation=self.get('M_modulation_R{}'.format(res)),
                    sampling_rate=self.get('sampling_rate')
                )

            # 4. apply mixer predistortion
            if self.mixer_apply_predistortion_matrix():
                Mat = wf.mixer_predistortion_matrix(
                    self.mixer_alpha(), self.mixer_phi())
                for key, val in res_wave_dict.items():
                    res_wave_dict[key] = np.dot(Mat, val)

            # 5. Add to global dict
            self._wave_dict.update(**res_wave_dict)

        return self._wave_dict

    ##########################################################################
    # Private parameter helpers
    ##########################################################################

    def _set_resonator_combinations(self, value):
        self._resonator_combinations = value
        self.set_default_lutmap()

    def _get_resonator_combinations(self):
        return self._resonator_combinations

    def _set_pulse_type(self, value):
        self._pulse_type = value
        self.set_default_lutmap()

    def _get_pulse_type(self):
        return self._pulse_type

class UHFQC_RO_LutMan(Base_RO_LutMan):

    def __init__(
            self,
            name,
            num_res: int = 1,
            feedline_number: int = 0,
            feedline_map='S7',
            **kw
    ):
        if num_res > 10:
            raise ValueError('At most 10 resonators can be read out.')

        super().__init__(
            name,
            num_res=num_res,
            feedline_number=feedline_number,
            feedline_map=feedline_map,
            **kw
        )

        # acquisition delay added in ZI Seqc program, see HAL_ShimSQ.ro_acq_delay
        self.add_parameter(
            'acquisition_delay',
            vals=vals.Numbers(min_value=0),
            unit='s',
            parameter_class=ManualParameter,
            initial_value=270e-9
        )
        self.add_parameter(
            'timeout',
            vals=vals.Numbers(min_value=0),
            unit='s',
            parameter_class=ManualParameter,
            initial_value=5
        )
        # Parameter that stores LO frequency.
        # NB: this appears to be the primary place where this information is stored, it is not set from code within PycQED
        self.add_parameter(
            'LO_freq',
            vals=vals.Numbers(),
            unit='Hz',
            parameter_class=ManualParameter,
            initial_value=None
        )

        # Set to a default because box is not expected to change
        self._voltage_min = -1.0
        self._voltage_max = 1.0-1.0/2**13
        # Used to select which waveform to upload in the 'single_pulse' mode.
        self._single_pulse_name = None
        # By default, use the DIO triggered mode
        self._mode = 'DIO_triggered'
        # Sample rate of the instrument
        self.sampling_rate(1.8e9)  # FIXME: hardcoded

    ##########################################################################
    # Base_LutMan overrides
    ##########################################################################

    def load_waveform_onto_AWG_lookuptable(
            self,
            wave_id: str,
            regenerate_waveforms: bool=False
    ):
        """
        Load a waveform into the AWG.

        Args:
            wave_id: can be either the "name" of a waveform or
                the integer codeword corresponding to a combination of
                readout waveforms.

            regenerate_waveforms (bool) : if True regenerates all waveforms
        """
        if regenerate_waveforms:
            self.generate_standard_waveforms()

        if wave_id not in self.LutMap().keys():
            wave_id = get_wf_idx_from_name(wave_id, self.LutMap())

        # Create the combined waveform
        I_wave = np.array([])
        Q_wave = np.array([])
        for resonator in self.LutMap()[wave_id]['resonators']:
            # Create the waveform name
            wavename = self.pulse_type() + '_R' + str(resonator)
            # adding new wave (not necessarily same length)
            I_wave = add_waves_different_length(I_wave, self._wave_dict[wavename][0])
            Q_wave = add_waves_different_length(Q_wave, self._wave_dict[wavename][1])

        # clipping the waveform
        I_wave = np.clip(I_wave, self._voltage_min, self._voltage_max)
        Q_wave = np.clip(Q_wave, self._voltage_min, self._voltage_max)

        # I and Q hardcoded to channels 1 and 2, codeword hardcoded to zero
        # in 'single_pulse' mode. In this mode we only ever upload a single
        # waveform to the instrument!
        if self._mode == 'single_pulse':
            # With this extra if-statement we prevent uploading to other waveforms
            # than codeword 0 with the waveform selected by the user.
            if self._single_pulse_name == self.LutMap()[wave_id]['name']:
                self.AWG.get_instr().set('wave_ch1_cw000', I_wave)
                self.AWG.get_instr().set('wave_ch2_cw000', Q_wave)
        else:
            self.AWG.get_instr().set('wave_ch1_cw{:03}'.format(wave_id), I_wave)
            self.AWG.get_instr().set('wave_ch2_cw{:03}'.format(wave_id), Q_wave)

    def load_waveforms_onto_AWG_lookuptable(
            self,
            regenerate_waveforms: bool=True,
            stop_start: bool = True,
            # FIXME, force load should be False but is here now to hack around the _upload_updated_waveforms
            force_load_sequencer_program: bool=True
    ):
        # FIXME: handle this at the proper place
        # Uploading the codeword program (again) is needed too if the user
        # has changed the mode of the instrument.
        if force_load_sequencer_program:
            if self._mode == 'single_pulse':
                self.AWG.get_instr().awg_sequence_acquisition_and_pulse(
                    acquisition_delay=self.acquisition_delay()
                )
            else:
                self.AWG.get_instr().awg_sequence_acquisition_and_DIO_triggered_pulse(
                    cases=list(self.LutMap().keys()),
                    acquisition_delay=self.acquisition_delay(),
                    timeout=self.timeout()
                )

        super().load_waveforms_onto_AWG_lookuptable(
            regenerate_waveforms=regenerate_waveforms,
            stop_start=stop_start
        )

    ##########################################################################
    # Functions
    # FIXME: these provide an undesired backdoor
    ##########################################################################

    # FIXME: move to UHFQC driver?
    # FIXME: unused
    def set_mixer_offsets(self):
        UHFQC = self.AWG.get_instr()
        UHFQC.sigouts_0_offset(self.mixer_offs_I())
        UHFQC.sigouts_1_offset(self.mixer_offs_Q())

    # FIXME: seems unused
    def load_single_pulse_sequence_onto_UHFQC(
            self,
            pulse_name,
            regenerate_waveforms=True
    ):
        '''
        Load a single pulse to the lookuptable, it uses the lut_mapping to
            determine which lookuptable to load to.
        '''
        wf_idx = get_wf_idx_from_name(pulse_name, self.LutMap())
        if not wf_idx:
            raise KeyError(
                'Waveform named "{}" does not exist in the LutMap! Make sure that "pulse_type" "resonator_combinations" is set correctly.')

        self._mode = 'single_pulse'
        self._single_pulse_name = pulse_name
        self.load_waveforms_onto_AWG_lookuptable(regenerate_waveforms=regenerate_waveforms)

    def load_DIO_triggered_sequence_onto_UHFQC(
            self,
            regenerate_waveforms=True,
            timeout=5
    ):
        '''
        Load a single pulse to the lookuptable.
        '''
        self._mode = 'DIO_triggered'
        self.timeout(timeout)
        self.load_waveforms_onto_AWG_lookuptable(regenerate_waveforms=regenerate_waveforms)

def add_waves_different_length(a, b):
    """
    Helper method used to add two arrays of different lengths.
    """
    if len(a) < len(b):
        c = b.copy()
        c[:len(a)] += a
    else:
        c = a.copy()
        c[:len(b)] += b
    return c


text:
package ravtrix.backpackerbuddy.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import ravtrix.backpackerbuddy.activities.mainpage.UserMainPage;
import ravtrix.backpackerbuddy.activities.startingpage.WelcomeActivity;
import ravtrix.backpackerbuddy.models.UserLocalStore;

public class SplashActivity extends AppCompatActivity {
    private UserLocalStore userLocalStore;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        userLocalStore = new UserLocalStore(this);
        if (checkIsUserNotLoggedIn()) {
            // Non logged in user goes to logged in page
            Intent intent = new Intent(this, WelcomeActivity.class);
            startActivity(intent);
            finish();
        } else {
            // Non logged in user goes to logged in page
            Intent intent = new Intent(this, UserMainPage.class);
            startActivity(intent);
            finish();
        }
    }

    /**
     * Check to see if the user is already logged in. If not, go to log in page
     */
    private boolean checkIsUserNotLoggedIn() {
        return (userLocalStore.getLoggedInUser().getUserID() == 0);
    }
}


text:
package org.savantbuild.runtime;

/**
 * Thrown from the build script when the build fails.
 *
 * @author Brian Pontarelli
 */
public class BuildFailureException extends RuntimeException {
  public BuildFailureException() {
    super();
  }

  public BuildFailureException(String message) {
    super(message);
  }

  public BuildFailureException(String message, Throwable cause) {
    super(message, cause);
  }
}


text:
require 'test_helper'
require 'hanami/utils/io'

class IOTest
  TEST_CONSTANT = 'initial'
end

describe Hanami::Utils::IO do
  describe '.silence_warnings' do
    it 'lowers verbosity of stdout' do
      _, err = capture_io do
        Hanami::Utils::IO.silence_warnings do
          IOTest::TEST_CONSTANT = 'redefined'
        end
      end

      err.must_equal ""
    end
  end
end


text:
package com.planet_ink.coffee_mud.core.collections;

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

public class CMList<K> implements Serializable, Cloneable, Iterable<K>, Collection<K>, Deque<K>, List<K>, Queue<K>
{
	private static final long serialVersionUID = -4174213459327144471L;
	private static final Random rand=new Random(System.currentTimeMillis());
	private class CMListNode
	{
		public K obj;
		public boolean active=false;
		public CMListNode next=null;
		public CMListNode prev=null;
		public CMListNode randNext=null;
		public CMListNode randPrev=null;
		public CMListNode(K obj) { this.obj=obj;}
	}
	private volatile CMListNode randNode=null;
	private volatile CMListNode head=null;
	private volatile CMListNode tail=null;
	private volatile int size=0;

	public CMList()
	{
	}

	public CMList(final Enumeration<K> E)
	{
		if(E!=null)
			for(;E.hasMoreElements();)
				add(E.nextElement());
	}

	public CMList(final Iterator<K> E)
	{
		if(E!=null)
			for(;E.hasNext();)
				add(E.next());
	}

	public CMList(final Set<K> E)
	{
		if(E!=null)
			for(final K o : E)
				add(o);
	}

	public synchronized void addAll(Enumeration<K> E)
	{
		if(E!=null)
			for(;E.hasMoreElements();)
				add(E.nextElement());
	}

	public synchronized void addAll(K[] E)
	{
		if(E!=null)
			for(final K e : E)
				add(e);
	}

	public synchronized void addAll(Iterator<K> E)
	{
		if(E!=null)
			for(;E.hasNext();)
				add(E.next());
	}

	public synchronized void removeAll(Enumeration<K> E)
	{
		if(E!=null)
			for(;E.hasMoreElements();)
				remove(E.nextElement());
	}

	public synchronized void removeAll(Iterator<K> E)
	{
		if(E!=null)
			for(;E.hasNext();)
				remove(E.next());
	}

	public synchronized void removeAll(List<K> E)
	{
		if(E!=null)
			for(final K o : E)
				remove(o);
	}

	public LinkedList<K> toLinkedList()
	{
		final LinkedList<K> L=new LinkedList<K>();
		for (final K k : this)
			L.add(k);
		return L;
	}

	public Vector<K> toVector()
	{
		final Vector<K> V=new Vector<K>(size());
		for (final K k : this)
			V.add(k);
		return V;
	}

	private CMListNode findFirstNode(final Object arg0)
	{
		CMListNode curr=head;
		while(curr!=null)
		{
			if(curr.active)
			{
				if(arg0 == null)
				{
					if(curr.obj==null)
						return curr;
				}
				else
				if(arg0.equals(curr.obj))
					return curr;
			}
			curr=curr.next;
		}
		return null;
	}

	private CMListNode findLastNode(final Object arg0)
	{
		CMListNode curr=tail;
		while(curr!=null)
		{
			if(curr.active)
			{
				if(arg0 == null)
				{
					if(curr.obj==null)
						return curr;
				}
				else
				if(arg0.equals(curr.obj))
					return curr;
			}
			curr=curr.prev;
		}
		return null;
	}

	private synchronized void removeNode(final CMListNode here)
	{
		if((here == null)||(!here.active))
			return;
		here.active=false;
		size--;
		final CMListNode next=here.next;
		final CMListNode prev=here.prev;
		if(head == here) head=next;
		if(tail == here) tail=prev;
		if(prev != null) prev.next=next;
		if(next != null) next.prev=prev;
		final CMListNode randNext=here.randNext;
		final CMListNode randPrev=here.randPrev;
		if(randNode == here)
		{
			if(here.randNext == here)
				randNode = null;
			else
				randNode=here.randNext;
		}
		if(randPrev != null) randPrev.randNext=randNext;
		if(randNext != null) randNext.randPrev=randPrev;
		// in time, garbage collector will make all right again.
		// in time.
	}

	private synchronized CMListNode addAfter(final CMListNode here, final K arg1)
	{
		final CMListNode newNode=new CMListNode(arg1);
		if(here == null)
		{
			newNode.next=head;
			head=newNode;
			if(newNode.next!=null)
				newNode.next.prev=newNode;
			if(tail==null)
				tail=newNode;
		}
		else
		{
			newNode.next=here.next;
			here.next=newNode;
			newNode.prev=here;
			if(newNode.next!=null)
				newNode.next.prev=newNode;
			if(tail==here)
				tail=newNode;
		}
		if(randNode==null)
		{
			randNode=newNode;
			newNode.randNext=newNode;
			newNode.randPrev=newNode;
		}
		else
		if(rand.nextDouble()<0.5)
		{
			newNode.randNext=randNode;
			newNode.randPrev=randNode.randPrev;
			randNode.randPrev=newNode;
			newNode.randPrev.randNext=newNode;
			randNode = newNode;
		}
		else
		{
			newNode.randPrev=randNode;
			newNode.randNext=randNode.randNext;
			randNode.randNext.randPrev=newNode;
			randNode.randNext=newNode;
		}
		size++;
		newNode.active=true;
		return newNode;
	}

	private CMListNode nodeBefore(int arg0)
	{
		if((head == null) || (arg0 == 0))
			return null;
		else
		{
			CMListNode curr=head;
			for(int i=1;i<arg0;i++)
				if(curr.next!=null)
				{
					if(!curr.active)
						i--;
					curr=curr.next;
				}
			return curr;
		}
	}

	private CMListNode nodeAt(int arg0)
	{
		if((arg0<0)||(arg0>=size))
			return null;
		else
		{
			CMListNode curr;
			int i;
			int ch;
			if((arg0==size-1) || (arg0 > size/2))
			{
				curr=tail;
				i=size-1;
				ch=-1;
			}
			else
			{
				curr=head;
				i=0;
				ch=1;
			}
			while(curr != null)
			{
				if(i==arg0)
				{
					if(!curr.active)
						i=i+(ch*-1);
					else
						break;
				}
				else
					i=i+ch;
				curr=curr.next;
			}
			return curr;
		}
	}

	@Override
	public synchronized void add(int arg0, K arg1)
	{
		addAfter(nodeBefore(arg0),arg1);
	}

	@Override
	public synchronized boolean add(K arg0)
	{
		addAfter(tail,arg0);
		return true;
	}

	@Override
	public synchronized boolean addAll(Collection<? extends K> arg0)
	{
		for (final K name : arg0)
			if(!add(name))
				 return false;
		return true;
	}

	@Override
	public synchronized boolean addAll(int arg0, Collection<? extends K> arg1)
	{
		CMListNode curr=nodeBefore(arg0);
		for (final K name : arg1)
			curr=addAfter(curr,name);
		return true;
	}

	@Override
	public synchronized void addFirst(K arg0)
	{
		addAfter(null,arg0);
	}

	@Override
	public synchronized void addLast(K arg0)
	{
		addAfter(tail,arg0);
	}

	@Override
	public synchronized void clear()
	{
		head=null;
		tail=null;
		randNode=null;
		size=0;
	}

	public synchronized K getNextRandom()
	{
		final CMListNode node=randNode;
		if(node == null) return null;
		randNode=node.randNext;
		return node.obj;
	}

	public synchronized K getPreviousRandom()
	{
		final CMListNode node=randNode;
		if(node == null) return null;
		randNode=node.randPrev;
		return node.obj;
	}

	public synchronized CMList<K> copyOf()
	{
		final CMList<K> newList=new CMList<K>();
		CMListNode curr=tail;
		while(curr!=null)
		{
			if(curr.active)
				newList.addAfter(null, curr.obj);
			curr=curr.prev;
		}
		return newList;
	}

	@Override
	public boolean contains(Object arg0)
	{
		return findFirstNode(arg0) != null;
	}

	public boolean containsFromEnd(Object arg0)
	{
		return findLastNode(arg0) != null;
	}

	public Enumeration<K> elements()
	{
		final CMListNode firstNode=nodeAt(0);
		return new Enumeration<K>()
		{
			private CMListNode nextNode = firstNode;
			private void makeNext()
			{
				if(nextNode != null)
				{
					nextNode=nextNode.next;
					while((nextNode != null)&&(!nextNode.active))
						nextNode=nextNode.next;
				}
			}
			@Override public boolean hasMoreElements() { return nextNode != null; }
			@Override
			public K nextElement()
			{
				if(!hasMoreElements()) throw new NoSuchElementException();
				final K obj=nextNode.obj;
				makeNext();
				return obj;
			}
		};
	}

	@Override
	public Iterator<K> descendingIterator()
	{
		final CMListNode firstNode=nodeAt(size-1);
		return new Iterator<K>()
		{
			private CMListNode nextNode = firstNode;
			private CMListNode lastNode = null;
			private void makeNext()
			{
				if(nextNode != null)
				{
					nextNode=nextNode.prev;
					while((nextNode != null)&&(!nextNode.active))
						nextNode=nextNode.prev;
				}
			}
			@Override public boolean hasNext() { return nextNode != null; }
			@Override
			public K next()
			{
				if(!hasNext()) throw new NoSuchElementException();
				lastNode=nextNode;
				final K obj=nextNode.obj;
				makeNext();
				return obj;
			}
			@Override
			public void remove()
			{
				removeNode(lastNode);
			}
		};
	}

	@Override
	public K element()
	{
		return getFirst();
	}

	@Override
	public K get(int arg0)
	{
		final CMListNode node = nodeAt(arg0);
		if(node == null)   throw new NoSuchElementException();
		return node.obj;
	}

	@Override
	public K getFirst()
	{
		final CMListNode node = nodeAt(0);
		if(node != null)
			return node.obj;
		throw new NoSuchElementException();
	}

	@Override
	public K getLast()
	{
		final CMListNode node = nodeAt(size-1);
		if(node != null)
			return node.obj;
		throw new NoSuchElementException();
	}

	@Override
	public int indexOf(Object arg0)
	{
		for(final ListIterator<K> o=listIterator();o.hasNext();)
		{
			if(o.next()==arg0)
				return o.previousIndex();
		}
		return -1;
	}

	@Override
	public int lastIndexOf(Object arg0)
	{
		int i=size-1;
		for(final Iterator<K> o=descendingIterator();o.hasNext();)
		{
			if(o.next()==arg0) return i;
			i--;
		}
		return -1;
	}

	@Override
	public ListIterator<K> listIterator(final int arg0)
	{
		final CMListNode firstNode=nodeAt(arg0);
		return new ListIterator<K>()
		{
			private CMListNode lastNode = null;
			private CMListNode nextNode = firstNode;
			private int nextIndex = arg0;
			private CMListNode prevNode = null;

			private void makeNext()
			{
				if(nextNode != null)
				{
					prevNode=nextNode;
					nextIndex++;
					nextNode=nextNode.next;
					while((nextNode != null)&&(!nextNode.active))
						nextNode=nextNode.next;
				}
			}

			private void makePrev()
			{
				if(prevNode != null)
				{
					nextNode=prevNode;
					nextIndex--;
					prevNode=prevNode.prev;
					while((prevNode != null)&&(!prevNode.active))
						prevNode=prevNode.prev;
				}
			}

			@Override public boolean hasNext() { return nextNode != null; }
			@Override
			public K next()
			{
				if(!hasNext()) throw new NoSuchElementException();
				lastNode=nextNode;
				final K obj=nextNode.obj;
				makeNext();
				return obj;
			}
			@Override
			public void remove()
			{
				removeNode(lastNode);
			}
			@Override
			public void add(K arg0)
			{
				addAfter(prevNode,arg0);
			}
			@Override public boolean hasPrevious() { return prevNode != null; }
			@Override
			public int nextIndex()
			{
				if(!hasNext()) return size;
				return nextIndex;
			}
			@Override
			public K previous()
			{
				if(!hasPrevious()) throw new NoSuchElementException();
				lastNode=prevNode;
				final K obj=prevNode.obj;
				makePrev();
				return obj;
			}
			@Override
			public int previousIndex()
			{
				if(!hasPrevious()) return -1;
				return nextIndex-1;
			}
			@Override
			public void set(K arg0)
			{
				if(lastNode == null)
					throw new IllegalStateException();
				lastNode.obj=arg0;
			}
		};
	}

	@Override
	public synchronized boolean offer(K arg0)
	{
		return add(arg0);
	}

	@Override
	public synchronized boolean offerFirst(K arg0)
	{
		addFirst(arg0);
		return true;
	}

	@Override
	public synchronized boolean offerLast(K arg0)
	{
		addLast(arg0);
		return true;
	}

	@Override
	public K peek()
	{
		return peekFirst();
	}

	@Override
	public K peekFirst()
	{
		if(size == 0) return null;
		return head.obj;
	}

	@Override
	public K peekLast()
	{
		if(size == 0) return null;
		return head.obj;
	}

	@Override
	public synchronized K poll()
	{
		if(size == 0) return null;
		return removeFirst();
	}

	@Override
	public synchronized K pollFirst()
	{
		if(size == 0) return null;
		return removeFirst();
	}

	@Override
	public synchronized K pollLast()
	{
		if(size == 0) return null;
		return removeLast();
	}

	@Override
	public synchronized K pop()
	{
		return removeFirst();
	}

	@Override
	public synchronized void push(K arg0)
	{
		addFirst(arg0);
	}

	@Override
	public synchronized K remove()
	{
		return removeFirst();
	}

	@Override
	public synchronized K remove(int arg0)
	{
		final CMListNode node=nodeAt(arg0);
		if(node == null) throw new NoSuchElementException();
		removeNode(node);
		return node.obj;
	}

	@Override
	public synchronized boolean remove(Object arg0)
	{
		return removeFirstOccurrence(arg0);
	}

	@Override
	public synchronized K removeFirst()
	{
		final CMListNode node=nodeAt(0);
		if(node == null) throw new NoSuchElementException();
		removeNode(node);
		return node.obj;
	}

	@Override
	public synchronized boolean removeFirstOccurrence(Object arg0)
	{
		final CMListNode node = findFirstNode(arg0);
		if(node == null) return false;
		removeNode(node);
		return true;
	}

	@Override
	public synchronized K removeLast()
	{
		final CMListNode node=nodeAt(size-1);
		if(node == null) throw new NoSuchElementException();
		removeNode(node);
		return node.obj;
	}

	@Override
	public synchronized boolean removeLastOccurrence(Object arg0)
	{
		final CMListNode node = findLastNode(arg0);
		if(node == null) return false;
		removeNode(node);
		return true;
	}

	@Override
	public synchronized K set(int arg0, K arg1)
	{
		final CMListNode node = nodeAt(arg0);
		if(node == null) throw new NoSuchElementException();
		final K oldObj=node.obj;
		node.obj=arg1;
		return oldObj;
	}

	@Override
	public int size()
	{
		return size;
	}

	@Override
	public synchronized Object[] toArray()
	{
		final Object[] result = new Object[size];
		int i = 0;
		for (CMListNode e = head; e != null; e = e.next)
			result[i++] = e.obj;
		return result;
	}

	@SuppressWarnings("unchecked")
	@Override
	public synchronized <T> T[] toArray(T[] arg0)
	{
		if (arg0.length < size)
			arg0 = (T[])java.lang.reflect.Array.newInstance(arg0.getClass().getComponentType(), size);
		int i = 0;
		final Object[] result = arg0;
		for (CMListNode e = head; e != null; e = e.next)
			result[i++] = e.obj;
		if (arg0.length > size)
			arg0[size] = null;
		return arg0;
	}

	@Override
	public Iterator<K> iterator()
	{
		return listIterator();
	}

	@Override
	public boolean equals(Object arg0)
	{
		return this==arg0;
	}

	@Override
	public int hashCode()
	{
		int hashCode = 1;
		final Iterator<K> i = iterator();
		while (i.hasNext())
		{
			final K obj = i.next();
			hashCode = 31*hashCode + (obj==null ? 0 : obj.hashCode());
		}
		return hashCode;
	}

	@Override
	public ListIterator<K> listIterator()
	{
		return listIterator(0);
	}

	@Override
	public List<K> subList(int arg0, int arg1)
	{
		final CMList<K> newList=new CMList<K>();
		for(final ListIterator<K> l=listIterator();l.hasNext();)
		{
			final K obj=l.next();
			if((l.previousIndex() >=arg0) && (l.previousIndex() < arg1))
				newList.add(obj);
		}
		return newList;
	}

	@Override
	public boolean containsAll(Collection<?> c)
	{
		for(final Object o : c)
			if(!contains(o))
				return false;
		return true;
	}

	@Override
	public boolean isEmpty()
	{
		return size==0;
	}

	@Override
	public synchronized boolean removeAll(Collection<?> c)
	{
		if(c.size()==0) return true;
		boolean success=false;
		for (final Object name : c)
			success=remove(name)||success;
		return success;
	}

	@Override
	public synchronized boolean retainAll(Collection<?> c)
	{
		boolean modified = false;
		for(final Iterator<K> e = iterator();e.hasNext();)
		{
			final Object o=e.next();
			if((o!=null)&&(!c.contains(o)))
			{
				e.remove();
				modified=true;
			}
		}
		return modified;
	}

	@Override
	public String toString()
	{
		final Iterator<K> i = iterator();
		if (! i.hasNext())
			return "[]";
		final StringBuilder sb = new StringBuilder();
		sb.append('[');
		for (;;)
		{
			final K e = i.next();
			sb.append(e == this ? "(this Collection)" : e);
			if (! i.hasNext())
				return sb.append(']').toString();
			sb.append(", ");
		}
	}
}


text:
Shadow::Application.configure do
  config.cache_classes                      = true
  config.action_controller.perform_caching  = true
  config.action_dispatch.x_sendfile_header  = ''
  config.action_controller.logger           = Logger.new(STDOUT)
  config.serve_static_assets                = true

  config.cache_store = :dalli_store, { :expires_in => 1.day, :compress => true, :compress_threshold => 64*1024 }

  # Enable serving of images, stylesheets, and javascripts from an asset server
  config.action_controller.asset_host = Proc.new { |source|
      ["http://", [ENV['DOMAIN_ASSET_ID'], Shadow::Domains::Assets.subdomain].map(&:to_s).join('.')].join
  }

  config.active_support.deprecation = :notify
end