text:
package org.nd4j.linalg.ops.transforms;

import org.nd4j.linalg.api.complex.IComplexNDArray;
import org.nd4j.linalg.api.complex.IComplexNumber;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.ops.BaseElementWiseOp;

/**
 *
 * Max out activation:
 * http://arxiv.org/pdf/1302.4389.pdf
 *
 *
 * @author Adam Gibson
 *
 */
public class MaxOut extends BaseElementWiseOp {

    /**
     * Apply the transformation
     */
    @Override
    public void exec() {
        INDArray linear = from.linearView();
        if(linear instanceof IComplexNDArray) {
            IComplexNDArray cLinear = (IComplexNDArray) linear;
            int max = Nd4j.getBlasWrapper().iamax(cLinear);
            IComplexNumber max2 = cLinear.getComplex(max);
            for(int i = 0; i < cLinear.length(); i++) {
                cLinear.putScalar(i,max2);
            }

        }

        else {
            int max = Nd4j.getBlasWrapper().iamax(linear);
            double maxNum = linear.getFloat(max);
            for(int i = 0; i < linear.length(); i++) {
                from.putScalar(i,maxNum);
            }
        }
    }

    /**
     * The transformation for a given value (a scalar)
     *
     * @param origin the origin ndarray
     * @param value  the value to apply (a scalar)
     * @param i      the index of the element being acted upon
     * @return the transformed value based on the input
     */
    @Override
    public <E> E apply(INDArray origin, Object value, int i) {
        return null;
    }
}


text:
@interface StrobeViewController () {
    NSMutableArray * usableColors;
}

@end

@implementation StrobeViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)changeSpeed:(id)sender {
    [refreshTimer invalidate];
    refreshTimer = [NSTimer scheduledTimerWithTimeInterval:slider.value target:self selector:@selector(changeBackgroundColor) userInfo:nil repeats:YES];
}

- (void) viewWillAppear:(BOOL)animated {

    usableColors = [[NSMutableArray alloc]init];
    [usableColors removeAllObjects];

    NSArray * array = [[NSArray alloc]init];
    array = [[NSUserDefaults standardUserDefaults] valueForKey:@"colors"];

    for (NSString * string in array) {
        int index = (int)[string integerValue];
        if (index == 0) {
            [usableColors addObject:@"Black"];
        }
        else if (index == 1) {
            [usableColors addObject:@"White"];
        }
        else if (index == 2) {
            [usableColors addObject:@"Red"];
        }
        else if (index == 3) {
            [usableColors addObject:@"Green"];
        }
        else if (index == 4) {
            [usableColors addObject:@"Blue"];
        }
        else if (index == 5) {
            [usableColors addObject:@"Brown"];
        }
        else if (index == 6) {
            [usableColors addObject:@"Dark Gray"];
        }
        else if (index == 7) {
            [usableColors addObject:@"Gray"];
        }
        else if (index == 8) {
            [usableColors addObject:@"Light Gray"];
        }
        else if (index == 9) {
            [usableColors addObject:@"Magenta"];
        }
        else if (index == 10) {
            [usableColors addObject:@"Orange"];
        }
        else if (index == 11) {
            [usableColors addObject:@"Purple"];
        }
        else if (index == 12) {
            [usableColors addObject:@"Yellow"];
        }
    }

    if (usableColors.count == 0) {
        [usableColors addObject:@"Black"];
        [usableColors addObject:@"White"];
    }

    refreshTimer = [NSTimer scheduledTimerWithTimeInterval:slider.value target:self selector:@selector(changeBackgroundColor) userInfo:nil repeats:YES];

}
- (void) viewWillDisappear:(BOOL)animated {
    [refreshTimer invalidate];
}

- (void) changeBackgroundColor {
    for (BOOL newColor = NO; newColor == NO; nil) {
         UIColor * newBackround = [self colorForString:usableColors[arc4random() % usableColors.count]];
        if (![newBackround isEqual:self.view.backgroundColor]) {
            colorView.backgroundColor = newBackround;
            newColor = YES;
        }
        else if (usableColors.count == 1) {
            return;
        }
    }
}

- (UIColor *)colorForString:(NSString *)string {
    if ([string isEqualToString:@"Black"]) {
        return [UIColor blackColor];
    }
    else if ([string isEqualToString:@"Black"]) {
        return [UIColor blackColor];
    }
    else if ([string isEqualToString:@"White"]) {
        return [UIColor whiteColor];
    }
    else if ([string isEqualToString:@"Red"]) {
        return [UIColor redColor];
    }
    else if ([string isEqualToString:@"Green"]) {
        return [UIColor greenColor];
    }
    else if ([string isEqualToString:@"Blue"]) {
        return [UIColor blueColor];
    }
    else if ([string isEqualToString:@"Brown"]) {
        return [UIColor brownColor];
    }
    else if ([string isEqualToString:@"Dark Gray"]) {
        return [UIColor darkGrayColor];
    }
    else if ([string isEqualToString:@"Gray"]) {
        return [UIColor grayColor];
    }
    else if ([string isEqualToString:@"Light Gray"]) {
        return [UIColor lightGrayColor];
    }
    else if ([string isEqualToString:@"Magenta"]) {
        return [UIColor magentaColor];
    }
    else if ([string isEqualToString:@"Orange"]) {
        return [UIColor orangeColor];
    }
    else if ([string isEqualToString:@"Purple"]) {
        return [UIColor purpleColor];
    }
    else if ([string isEqualToString:@"Yellow"]) {
        return [UIColor yellowColor];
    }
    return nil;
}

@end

redpajama_set_name: RedPajamaGithub


text:
/*
 * File:   ModPort.h
 * Author: alain
 *
 * Created on January 31, 2020, 9:46 PM
 */

#ifndef SURELOG_MODPORT_H
#define SURELOG_MODPORT_H
#pragma once

#include <Surelog/Common/SymbolId.h>
#include <Surelog/Design/Signal.h>

#include <string_view>
#include <vector>

namespace SURELOG {

class ModuleDefinition;
class FileContent;

class ModPort final {
 public:
  ModPort(ModuleDefinition* parent, std::string_view name,
          const FileContent* const fC, NodeId nodeId)
      : m_parent(parent), m_name(name), m_fileContent(fC), m_nodeId(nodeId) {}

  const std::string& getName() const { return m_name; }
  void addSignal(const Signal& sig) { m_ports.push_back(sig); }
  const std::vector<Signal>& getPorts() const { return m_ports; }
  const Signal* getPort(const std::string& name) const;
  ModuleDefinition* getParent() const { return m_parent; }
  const FileContent* getFileContent() const { return m_fileContent; }
  NodeId getNodeId() const { return m_nodeId; }

 private:
  ModuleDefinition* const m_parent;
  const std::string m_name;
  const FileContent* const m_fileContent;
  const NodeId m_nodeId;

  std::vector<Signal> m_ports;
};
}  // namespace SURELOG

#endif /* SURELOG_MODPORT_H */


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;

/* @var $this yii\web\View */
/* @var $model app\models\CpuAttributeValueSearch */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
        'action' => ['index'],
        'method' => 'get',
    ]); ?>

    <?= $form->field($model, 'cpu_attribute_value_id') ?>

    <?= $form->field($model, 'value') ?>

    <?= $form->field($model, 'cpu_id') ?>

    <?= $form->field($model, 'cpu_attribute_id') ?>

        <?= Html::submitButton(Yii::t('app', 'Search'), ['class' => 'btn btn-primary']) ?>
        <?= Html::resetButton(Yii::t('app', 'Reset'), ['class' => 'btn btn-default']) ?>

    <?php ActiveForm::end(); ?>


text:
require_relative '../diagram_converter'
require_relative '../util/cli_generator'
require_relative '../util/platform'

module Asciidoctor
  module Diagram
    # @private
    class GnuplotConverter
      include DiagramConverter
      include CliGenerator

      def supported_formats
        [:png, :svg, :gif, :txt, :literal]
      end

      def collect_options(source)
        {
            :width => source.attr('width'),
            :height => source.attr('height'),
            :transparent => source.attr('transparent'),
            :crop => source.attr('crop'),
            :font => source.attr('font'),
            :fontscale => source.attr('fontscale'),
            :background => source.attr('background'),
        }
      end

      def convert(source, format, options)
        if format == :txt || format == :literal
          terminal = 'dumb'
        else
          terminal = format.to_s
        end
        code = "set term #{terminal}"

        width = options[:width]
        height = options[:height]
        code << " size #{width},#{height}" unless width.nil? or height.nil?

        transparent = options[:transparent]
        code << (transparent ? " transparent" : " notransparent") unless transparent.nil?

        crop = options[:crop]
        code << (crop ? " crop" : " nocrop") unless crop.nil?

        font = options[:font]
        code << %( font "#{font}") unless font.nil?

        font_scale = options[:fontscale]
        code << " fontscale #{font_scale}" unless font_scale.nil?

        background = options[:background]
        code << %( background "#{background}") unless background.nil?

        code << "\n"
        code << source.to_s

        generate_stdin_stdout(source.find_command('gnuplot'), code)
      end
    end
  end
end


text:
from json import loads
from pika import BlockingConnection, ConnectionParameters

RABBIT_MQ_HOST = '54.76.183.35'
RABBIT_MQ_PORT = 5672

def announce(ch, method, properties, body):
    product = loads(body)
    print "New product! %s" % (product,)

connection = BlockingConnection(ConnectionParameters(host=RABBIT_MQ_HOST,
                                                     port=RABBIT_MQ_PORT))
channel = connection.channel()

channel.exchange_declare(exchange='alex2', type='topic')

result = channel.queue_declare(exclusive=True)
queue = result.method.queue

channel.queue_bind(exchange='alex2', queue=queue, routing_key='new_products')

channel.basic_consume(announce, queue=queue, no_ack=True)
channel.start_consuming()


text:
import createBaseForm from './createBaseForm';

export const mixin = {
  getForm() {
    return {
      getFieldsValue: this.fieldsStore.getFieldsValue,
      getFieldValue: this.fieldsStore.getFieldValue,
      getFieldInstance: this.getFieldInstance,
      setFieldsValue: this.setFieldsValue,
      setFields: this.setFields,
      setFieldsInitialValue: this.fieldsStore.setFieldsInitialValue,
      getFieldDecorator: this.getFieldDecorator,
      getFieldProps: this.getFieldProps,
      getFieldsError: this.fieldsStore.getFieldsError,
      getFieldError: this.fieldsStore.getFieldError,
      isFieldValidating: this.fieldsStore.isFieldValidating,
      isFieldsValidating: this.fieldsStore.isFieldsValidating,
      isFieldsTouched: this.fieldsStore.isFieldsTouched,
      isFieldTouched: this.fieldsStore.isFieldTouched,
      isSubmitting: this.isSubmitting,
      submit: this.submit,
      validateFields: this.validateFields,
      resetFields: this.resetFields,
    };
  },
};

function createForm(options) {
  return createBaseForm(options, [mixin]);
}

export default createForm;


text:
using System.Collections.Generic;

namespace I_Solution_3
{
    public class DinnerUnitIterator : Iterator
    {
        private List<MenuItem> menuItems;
        private int current;

        public DinnerUnitIterator(List<MenuItem> menuItems)
        {
            this.menuItems = menuItems;
        }

        public bool hasNext()
        {
            return current < menuItems.Count;
        }

        public MenuItem next()
        {
            return menuItems[current++];
        }
    }
}


text:
package com.thoughtworks.go.serverhealth;

import java.util.List;

import com.thoughtworks.go.domain.BaseCollection;

/**
 * @understands a collection of server health states
 */
public class ServerHealthStates extends BaseCollection<ServerHealthState> {
    public ServerHealthStates(List<ServerHealthState> serverHealthStates) {
        super(serverHealthStates);
    }

    public ServerHealthStates() {
    }

    public ServerHealthStates(ServerHealthState... states) {
        super(states);
    }

    public int errorCount() {
        int errors = 0;
        for (ServerHealthState serverHealthState : this) {
            if (!serverHealthState.isSuccess()) {
                errors++;
            }
        }
        return errors;
    }

    public int warningCount() {
        int warnings = 0;
        for (ServerHealthState serverHealthState : this) {
            if (serverHealthState.isWarning()) {
                warnings++;
            }
        }
        return warnings;
    }

    public boolean isRealSuccess() {
        return errorCount() == 0 && warningCount() == 0;
    }
}


text:
class UploadsController < ApplicationController
  # GET /uploads
  # GET /uploads.json
  def index
  end

  # GET /uploads/1
  # GET /uploads/1.json
  def show
    @upload = Upload.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @upload }
    end
  end

  # GET /uploads/new
  # GET /uploads/new.json
  def new
    @upload = Upload.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @upload }
    end
  end

  # GET /uploads/1/edit
  def edit
    @upload = Upload.find(params[:id])
  end

  # POST /uploads
  # POST /uploads.json
  def create
    @upload = Upload.new(params[:upload].permit(:upload_file_name, :upload_content_type, :upload_file_size, :upload, :document_set_key))

    respond_to do |format|
      if @upload.save
        format.html {
          render :json => [@upload.to_jq_upload].to_json,
          :content_type => 'text/html',
          :layout => false
        }
        format.json { render json: {files: [@upload.to_jq_upload]}, status: :created, location: @upload }
      else
        format.html { render action: "new" }
        format.json { render json: @upload.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /uploads/1
  # PUT /uploads/1.json
  def update
    @upload = Upload.find(params[:id])

    respond_to do |format|
      if @upload.update_attributes(params[:upload])
        format.html { redirect_to @upload, notice: 'Upload was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @upload.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /uploads/1
  # DELETE /uploads/1.json
  def destroy
    @upload = Upload.find(params[:id])
    @upload.destroy

    respond_to do |format|
      format.html { redirect_to uploads_url }
      format.json { head :no_content }
    end
  end
end


text:
<?php

/**
 * Helper class to generate human-readable stack traces.
 */
class yTest_Stack {
    private static $enableDetailledMode = false;
    private static $removeAnnoyingFrames = true; // remove annoying frames

    public static function setDetailledMode($enable) {
        self::$enableDetailledMode = $enable;
    }

    public static function keepAnnoyingFrames($enableKeep) {
        self::$removeAnnoyingFrames = $enableKeep;
    }

    public static function getStackLineMaxLength() {
        return YTEST_STACK_LINE_MAX_LENGTH;
    }

    public static function getCurrentStack($maxLineLen = null) {
        if (self::$enableDetailledMode) {
            return self::getDetailledCurrentStack($maxLineLen);
        } else {
            return self::getAbbreviatedCurrentStack($maxLineLen);
        }
    }

    public static function getAbbreviatedCurrentStack($maxLineLen = null) {
        if ($maxLineLen === null) {
            $maxLineLen = self::getStackLineMaxLength();
        }
        $bt = debug_backtrace();

        $preSkip = true;
        $removedPhpUnitFrames = false;
        $lines = array();
        foreach ($bt as $frame) {

            if (self::$removeAnnoyingFrames) {
                if ($preSkip && array_key_exists('class', $frame) && ($frame['class'] == 'yTest_Stack')) {
                    continue;
                } else {
                    $preSkip = false;
                    if (array_key_exists('class', $frame)
                        && $frame['class'] == 'PHPUnit_Framework_TestCase'
                        && $frame['function'] == 'runTest') {
                        $removedPhpUnitFrames = true;
                        break;
                    }
                }

            }

            $callPart = " ";
            if (isset($frame['class'])) {
                $callPart .= $frame['class']  . $frame['type'];
            }
            $callPart .= $frame['function'];

            if (isset($frame['file'])) {
                $filePart = str_replace(yTest_getBaseDir(), '', $frame['file']) . ":" . $frame['line'];
            } else {
                $filePart = "<no file info>";
            }

            $lines[] = array($callPart, $filePart);
        }

        if (self::$removeAnnoyingFrames && $removedPhpUnitFrames) {
            // We remove two extra frames on top of PHPUnit ones:
            //
            //  <TestCaseName>-><TestMethodName> <no file info>
            //  ReflectionMethod->invokeArgs     /test/libs/phpunit/PHPUnit/Framework/TestCase.php:822

            $lines = array_slice($lines, 0, count($lines) - 2);
        }

        return $lines;
    }

    public static function getDetailledCurrentStack($maxLineLen = null) {
        ob_start();
        debug_print_backtrace();
        $trace = ob_get_contents();
        ob_end_clean();
        $lines = explode("\n", $trace);
        $res = array();
        foreach ($lines as $line) {
            $res[] = array($line);
        }
        return $res;
    }

    /**
     * Format stacks returned by getCurrentStack() and friends.
     * Returns an array of strings.
     */
    public static function formatStack($stack, $maxLineLen = null) {
        if ($maxLineLen === null) {
            $maxLineLen = self::getStackLineMaxLength();
        }

        if (count($stack) == 0) {
            return $stack;
        }

        $numParts = count($stack[0]);
        if ($numParts == 0) {
            return $stack;
        }

        // Find the max length of each part
        $maxLens = array();
        for ($i = 0; $i < $numParts; ++$i) {
            $max = 0;
            foreach ($stack as $parts) {
                $part = $parts[$i];
                $l = strlen($part);
                if (strlen($part) > $max) {
                    $max = strlen($part);
                }
            }
            $maxLens[$i] = $max;
        }

        // Build each line of the result by indenting the parts
        $lines = array();
        foreach ($stack as $parts) {
            $line = "";
            for ($i = 0; $i < $numParts; ++$i) {
                $part = $parts[$i];
                $line .= $part;
                $pad = $maxLens[$i] - strlen($part);
                $pad = max($pad, 0);
                $line .= str_repeat(' ', $pad + 1);
            }
            $lines[] = $line;
        }

        // Truncate the lines if necessary
        $cutLines = array();
        foreach ($lines as $line) {
            if (strlen($line) > $maxLineLen) {
                $cutLines[] = substr($line, 0, $maxLineLen) . " ...<CUT!>...";
            } else {
                $cutLines[] = $line;
            }
        }

        return $cutLines;
    }

}


text:
/* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE369_Divide_by_Zero__float_rand_82_goodG2B.cpp
Label Definition File: CWE369_Divide_by_Zero__float.label.xml
Template File: sources-sinks-82_goodG2B.tmpl.cpp
*/
/*
 * @description
 * CWE: 369 Divide by Zero
 * BadSource: rand Set data to result of RAND32(), which may be zero
 * GoodSource: A hardcoded non-zero number (two)
 * Sinks:
 *    GoodSink: Check value of or near zero before dividing
 *    BadSink : Divide a constant by data
 * Flow Variant: 82 Data flow: data passed in a parameter to an virtual method called via a pointer
 *
 * */
#ifndef OMITGOOD

#include "std_testcase.h"
#include "CWE369_Divide_by_Zero__float_rand_82.h"

namespace CWE369_Divide_by_Zero__float_rand_82
{

void CWE369_Divide_by_Zero__float_rand_82_goodG2B::action(float data)
{
    {
        /* POTENTIAL FLAW: Possibly divide by zero */
        int result = (int)(100.0 / data);
        printIntLine(result);
    }
}

}
#endif /* OMITGOOD */


text:
using System.Collections.Generic;
using System.Windows;
using OsEngine.Entity;
using System.Windows.Forms.Integration;
using System.Windows.Forms;

namespace OsEngine.OsOptimizer.OptEntity
{
    /// <summary>
    /// Логика взаимодействия для OptimizerBotParametersSimpleUi.xaml
    /// </summary>
    public partial class OptimizerBotParametersSimpleUi : Window
    {
        public OptimizerBotParametersSimpleUi(OptimizerReport report, OptimazerFazeReport faze, string botType)
        {
            InitializeComponent();
            _report = report;
            _faze = faze;

            string label = " StrategyType: " + botType;

            label += " Faze Start :" + _faze.Faze.TimeStart.Date.ToShortDateString();

            label += " Faze End :" + _faze.Faze.TimeEnd.Date.ToShortDateString();

            label += " Aver profit % in faze " + report.AverageProfitPercent;

            Title = Title + label;

            List<IIStrategyParameter> parameters = _report.GetParameters();

            if (parameters.Count < 8)
            {
                PaintParams(parameters, HostParams1);
                return;
            }

            List<IIStrategyParameter> parameters2 = new List<IIStrategyParameter>();

            int breakNum = parameters.Count / 2;

            for (int i = breakNum; i < parameters.Count;)
            {
                parameters2.Add(parameters[i]);
                parameters.RemoveAt(i);
            }

            PaintParams(parameters, HostParams1);
            PaintParams(parameters2, HostParams2);
        }

        OptimizerReport _report;

        OptimazerFazeReport _faze;

        private void PaintParams(List<IIStrategyParameter> parameters, WindowsFormsHost host)
        {
            DataGridView grid = GetGrid();

            for (int i = 0; i < parameters.Count; i++)
            {
                if(parameters[i].Type == StrategyParameterType.Button ||
                    parameters[i].Type == StrategyParameterType.Label)
                {
                    continue;
                }
                DataGridViewRow row = GetRow(parameters[i]);
                grid.Rows.Add(row);
            }

            host.Child = grid;
        }

        private DataGridViewRow GetRow(IIStrategyParameter parameter)
        {
            DataGridViewRow nRow = new DataGridViewRow();

            nRow.Cells.Add(new DataGridViewTextBoxCell());
            nRow.Cells[0].Value = parameter.Name;

            nRow.Cells.Add(new DataGridViewTextBoxCell());

            if (parameter.Type == StrategyParameterType.Bool)
            {
                nRow.Cells[1].Value = ((StrategyParameterBool)parameter).ValueBool;
            }
            if (parameter.Type == StrategyParameterType.Decimal)
            {
                nRow.Cells[1].Value = ((StrategyParameterDecimal)parameter).ValueDecimal;
            }
            if (parameter.Type == StrategyParameterType.Int)
            {
                nRow.Cells[1].Value = ((StrategyParameterInt)parameter).ValueInt;
            }
            if (parameter.Type == StrategyParameterType.String)
            {
                nRow.Cells[1].Value = ((StrategyParameterString)parameter).ValueString;
            }
            if (parameter.Type == StrategyParameterType.TimeOfDay)
            {
                nRow.Cells[1].Value = ((StrategyParameterTimeOfDay)parameter).Value.ToString();
            }

            return nRow;
        }

        private DataGridView GetGrid()
        {
            DataGridView grid = DataGridFactory.GetDataGridView(DataGridViewSelectionMode.FullRowSelect, DataGridViewAutoSizeRowsMode.AllCells);

            DataGridViewCellStyle style = grid.DefaultCellStyle;

            DataGridViewTextBoxCell cell0 = new DataGridViewTextBoxCell();
            cell0.Style = style;

            DataGridViewColumn colum0 = new DataGridViewColumn();
            colum0.CellTemplate = cell0;
            colum0.HeaderText = "Param name";
            colum0.ReadOnly = true;
            colum0.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            grid.Columns.Add(colum0);

            DataGridViewColumn colum01 = new DataGridViewColumn();
            colum01.CellTemplate = cell0;
            colum01.HeaderText = "Value";
            colum01.ReadOnly = true;
            colum01.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            grid.Columns.Add(colum01);

            return grid;
        }
    }
}


text:
/*global __dirname:false*/

define(['underscore', 'fs', 'moment', 'os', 'path', 'util'], function (_, fs, moment, os, path, util) {

    var DEFAULT_FILE_NAME = 'lazojs.log';

    var DEFAULT_FILE_PATH = path.join(process.cwd(), DEFAULT_FILE_NAME);

    var MB = 1024 * 1024;

    var DEFAULT_MAX_SIZE = 10 * MB;

    var DEFAULT = {
        filePath: DEFAULT_FILE_PATH,
        maxFiles: 10,
        maxSize: DEFAULT_MAX_SIZE,
        roll: true
    };

    var dateChanged = function (a, b) {
        return a === null || b === null ||
            a.getUTCFullYear() !== b.getUTCFullYear() ||
            a.getUTCMonth() !== b.getUTCMonth() ||
            a.getUTCDate() !== b.getUTCDate();
    };

    var getFilename = function (filePath) {
        return _.last(filePath.split(path.sep));
    };

    var getNextFilePath = function (filePath, maxFiles) {
        var dirPath = path.dirname(filePath);
        var files = fs.readdirSync(dirPath);
        var fileName = getFilename(filePath);
        var regExp = new RegExp('^' + fileName + '\\.(\\d+)$');
        var filtered = _.filter(files, function (file) {
            return regExp.test(file);
        });
        var last = _.max(filtered, function (fileName) {
            var filePath = path.join(dirPath, fileName);
            return fs.existsSync(filePath) ? fs.statSync(filePath).mtime : 0;
        });
        var match = last && regExp.exec(last);
        var pointer = match && match[1] ? parseInt(match[1]) : 0;
        var sequence = pointer >= 1 && pointer < maxFiles ? pointer + 1 : 1;

        return util.format('%s.%d', filePath, sequence);
    };

    var rollFileSync = function (filePath, maxFiles) {
        try {
            if (!fs.existsSync(filePath)) {
                return;
            }

            var nextFilePath = getNextFilePath(filePath, maxFiles);
            fs.renameSync(filePath, nextFilePath);
        } catch (error) {
            console.error(util.format('FileSink, error while rolling file "%s": %s', filePath, error.message));
        }
    };

    var FileSink = function (options) {

        var _options = _.defaults({}, options, DEFAULT);

        // Check if directory exists

        var dirPath = path.dirname(_options.filePath);

        if (!fs.existsSync(dirPath)) {
            throw new Error(util.format('FileSink, given path does not exist: %s', dirPath));
        }

        // Check if can write file

        fs.closeSync(fs.openSync(_options.filePath, 'a'));

        // Initial status

        var stats = fs.statSync(_options.filePath);
        var fileSize = stats.size;
        var lastModified = stats.mtime;

        // Sink function

        return function (message) {
            var now = new Date();
            var messageBuffer = new Buffer(message + os.EOL);
            var messageLength = messageBuffer.length;

            if ((fileSize + messageLength) > _options.maxSize || (_options.roll && dateChanged(lastModified, now))) {
                rollFileSync(_options.filePath, _options.maxFiles);
                fileSize = 0;
            }

            fs.appendFile(_options.filePath, messageBuffer, function (error) {
                if (error) {
                    return console.error(util.format('FileSink, error while appending to "%s": %s', _options.filePath, error.message));
                }

                fileSize += messageLength;
                lastModified = now;
            });
        };
    };

    return FileSink;

});


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2014.12.06 at 02:16:35 PM EST
//

package com.grndctl.model.airsigmet;

import javax.xml.bind.annotation.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;

/**
 *

 * Java class for anonymous complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within
 * this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{}point" maxOccurs="unbounded"/>
 *       </sequence>
 *       <attribute name="num_points" type="{http://www.w3.org/2001/XMLSchema}integer" />
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = { "point" })
@XmlRootElement(name = "area")
public class Area {

    @XmlElement(required = true)
    protected List<Point> point;
    @XmlAttribute(name = "num_points")
    protected BigInteger numPoints;

    /**
     * Gets the value of the point property.
     *
     *

     * This accessor method returns a reference to the live list, not a
     * snapshot. Therefore any modification you make to the returned list will
     * be present inside the JAXB object. This is why there is not a
     * set method for the point property.
     *
     *

     * For example, to add a new item, do as follows:
     *
     *

     * getPoint().add(newItem);
     *

     *
     *
     *

     * Objects of the following type(s) are allowed in the list {@link Point }
     *
     *
     */
    public List<Point> getPoint() {
        if (point == null) {
            point = new ArrayList<Point>();
        }
        return this.point;
    }

    /**
     * Gets the value of the numPoints property.
     *
     * @return possible object is {@link java.math.BigInteger }
     *
     */
    public BigInteger getNumPoints() {
        return numPoints;
    }

    /**
     * Sets the value of the numPoints property.
     *
     * @param value
     *            allowed object is {@link java.math.BigInteger }
     *
     */
    public void setNumPoints(BigInteger value) {
        this.numPoints = value;
    }

}


text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const get_unit_1 = require("./get-unit");
const systems_1 = require("./systems");
class UnitConverter {
    constructor(value, unitSymbol) {
        this.toBase = () => this.to();
        this.unitSymbol = unitSymbol || get_unit_1.getUnit(value.toString());
        if (this.unitSymbol) {
            this.system = this.systemFromUnitSymbol(this.unitSymbol);
            this.unit = this.getUnitFromSystem(this.unitSymbol, this.system);
        }
        this.baseValue =
            parseFloat(String(value).replace(this.unitSymbol, '')) *
                ((this.unit && this.unit.ratio) || 1);
    }
    systemFromUnitSymbol(unitSymbol) {
        for (const name of Object.keys(systems_1.systems)) {
            const system = systems_1.systems[name];
            if (system.units[unitSymbol] || system.aliases[unitSymbol]) {
                return system;
            }
        }
        throw new Error('unknown system for unit ' + unitSymbol);
    }
    getUnitFromSystem(unitSymbol, system) {
        const _system = system || this.systemFromUnitSymbol(unitSymbol);
        const units = _system.units;
        return units[unitSymbol] || units[_system.aliases[unitSymbol]] || null;
    }
    getUnitSymbol() {
        return this.unitSymbol;
    }
    to(unitSymbol) {
        if (!this.system && !unitSymbol) {
            throw new Error(`you must specify at least one unit (in constructor or in 'to' method)`);
        }
        const system = this.system || this.systemFromUnitSymbol(unitSymbol);
        let toUnit = null;
        try {
            toUnit = this.getUnitFromSystem(unitSymbol || system.baseUnit, system);
        }
        catch (err) {
            toUnit = { ratio: 1 };
        }
        if (!toUnit) {
            throw new Error('unknown unit ' + unitSymbol + ' for ' + system.name + ' system');
        }
        const value = this.baseValue;
        return value / toUnit.ratio;
    }
}
exports.UnitConverter = UnitConverter;
//# sourceMappingURL=UnitConverter.js.map


text:
<!--- master only -->
> ![warning](./images/warning.png) This document applies to the HEAD of the calico-containers source tree.
>
> View the calico-containers documentation for the latest release [here](https://github.com/projectcalico/calico-containers/blob/v0.14.0/README.md).
<!--- else
> You are viewing the calico-containers documentation for release **release**.
<!--- end of master only -->

# Using Calico with a secure etcd cluster

Calico supports insecure and TLS/certificate-enabled etcd clusters.

## Etcd with client and server verification

To use TLS-enabled etcd, the following environment variables need to be set
before running any `calicoctl` command:

- **`ETCD_AUTHORITY`**: The `<ip_address>:<port_number>` pair representing the
 access point to the cluster. **Default**: 127.0.0.1:2379
- **`ETCD_SCHEME`**: The http or https protocol used by the etcd datastore.
 **Default**: http
- **`ETCD_CA_CERT_FILE`**: The full path to the CA certificate file for the
 Certificate Authority that signed the etcd server key/certificate pair.
- **`ETCD_CERT_FILE`**: The full path to the client certificate file for
 accessing the etcd cluster.
- **`ETCD_KEY_FILE`**: The full path to the client key file for accessing the
 etcd cluster.

For example:

```
export ETCD_AUTHORITY=127.0.0.1:2379
export ETCD_SCHEME=https
export ETCD_CA_CERT_FILE=/path/to/ca.crt
export ETCD_CERT_FILE=/path/to/cert.crt
export ETCD_KEY_FILE=/path/to/key.pem
```

> NOTE: The file extensions are not important, the files just need to exist and
> be readable.

### Commands that require root
Some commands are required to be run as root.  The user's environment variables
specified above will not be recognized by the root user, so the variables must
be passed into the Calico command.

For example, to run `calicoctl node`, you would call something like this:

```
sudo ETCD_SCHEME=https ETCD_KEY_FILE=/path/to/client.key \
     ETCD_CA_CERT_FILE=/path/to/ca.crt ETCD_CERT_FILE=/path/to/client.crt \
     ETCD_AUTHORITY=127.0.0.1:2379 calicoctl node
```

Alternatively, if you have previously defined/exported your environment
variables, you can run `sudo` with the `-E` flag to pass in your environment:

```
sudo -E calicoctl node
```

Here's a list of commands that must be run as root:

- `calicoctl node`
- `calicoctl node stop`
- `calicoctl node remove`
- `calicoctl container add`
- `calicoctl container remove`
- `calicoctl container ip add`
- `calicoctl container ip remove`

See the [calicoctl reference guide](./calicoctl.md) for details on specific
calicoctl commands.

### Calico as a Docker network plugin

If you are using Calico as a Docker network plugin, the Docker daemon requires
a KV store for its inbuilt multi-host networking support.  In our tutorials
recommend using etcd for this KV store so that you can have a single store
used by both Docker and Calico.

To run Docker daemon with TLS-enabled etcd, supply the following additional
command line options to the Docker daemon.

     --cluster-store-opt kv.cacertfile=/path/to/ca.crt
     --cluster-store-opt kv.certfile=/path/to/cert.crt
     --cluster-store-opt kv.keyfile=/path/to/key.pem

[![Analytics](https://ga-beacon.appspot.com/UA-52125893-3/calico-containers/docs/EtcdSecureCluster.md?pixel)](https://github.com/igrigorik/ga-beacon)


text:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="@integer/anim_length"
        android:fromXDelta="0%"
        android:toXDelta="100%" >
    </translate>
</set>


text:
#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM

#include "tensorflow/core/kernels/cwise_ops_gpu_common.cu.h"

namespace tensorflow {
namespace functor {
DEFINE_BINARY4(pow, Eigen::half, float, double, int64);
}  // namespace functor
}  // namespace tensorflow

#endif  // GOOGLE_CUDA || TENSORFLOW_USE_ROCM


text:
/*
Package runner contains a utility to run Docker containers

Create a RunHelper with NewRunHelper and then create new run
instances with New()
*/
package run


text:
mod generic;

use std::thread;
use std::sync::Arc;
use std::sync::RwLock;
use std::sync::mpsc::Receiver;

use buffer::Buffer;
use event::InputEvent;
pub use self::generic::GenericClient;

pub trait Client {
    fn new(Arc<RwLock<Vec<Buffer>>>, Receiver<InputEvent>) -> Self;

    fn handle_input(&self, InputEvent);
    fn reciever(&self) -> Receiver<InputEvent>;

    fn listen(&self) {
        thread::spawn(|| {
            loop {
                match self.reciever().recv() {
                    Err(e) => break,
                    Ok(event) => self.handle_input(event),
                }
            }
        });
        return
    }
}


text:
class Api::V2::TasksController < ApplicationController
  def index
    tasks = Task.where(user_id: current_user.id)

    if params[:date]
      tasks = tasks.where(scheduled_date: params[:date])
    end

    render :json => tasks
  end

  def show
    task = Task.where(user_id: current_user.id, id: params[:id])
  end

  def create
    task = Task.new(task_params)
    task.user_id = current_user.id
    if task.save
      render :json => task, :status => 200
    else
      render :json => task.errors, :status => 400
    end
  end

  def update
    task = Task.find(params[:id])

    if task.update_attributes(task_params)
      render :json => task, :status => 200
    else
      render :json => task.errors, :status => 400
    end
  end

  def destroy
    task = Task.find(params[:id])
    task.destroy
  end

  protected
    def task_params
      params.require(:task).permit(:title,:description,:scheduled_date,:scheduled_hour,:location)
    end
end


text:
#include "lib.h"
#include "str.h"
#include "ioloop.h"
#include "ostream.h"
#include "connection.h"
#include "http-date.h"
#include "http-request-parser.h"

static struct connection_list *clients;
static int fd_listen;
struct io *io_listen;

struct client {
	struct connection conn;
	struct http_request_parser *parser;
};

static void client_destroy(struct connection *conn)
{
	struct client *client = (struct client *)conn;

	http_request_parser_deinit(&client->parser);
	connection_deinit(&client->conn);
	i_free(client);
}

static int
client_handle_request(struct client *client, struct http_request *request)
{
	string_t *str = t_str_new(128);

	if (strcmp(request->method, "GET") != 0) {
		o_stream_send_str(client->conn.output, "HTTP/1.1 501 Not Implemented\r\nAllow: GET\r\n\r\n");
		return 0;
	}
	str_append(str, "HTTP/1.1 200 OK\r\n");
	str_printfa(str, "Date: %s\r\n", http_date_create(ioloop_time));
	str_printfa(str, "Content-Length: %d\r\n", (int)strlen(request->target_raw));
	str_append(str, "Content-Type: text/plain\r\n");
	str_append(str, "\r\n");
	str_append(str, request->target_raw);
	o_stream_send(client->conn.output, str_data(str), str_len(str));
	return 0;
}

static void client_input(struct connection *conn)
{
	struct client *client = (struct client *)conn;
	struct http_request request;
	enum http_request_parse_error error_code;
	const char *error;
	int ret;

	while ((ret = http_request_parse_next
		(client->parser, NULL, &request, &error_code, &error)) > 0) {
		if (client_handle_request(client, &request) < 0 ||
		    request.connection_close) {
			client_destroy(conn);
			return;
		}
	}
	if (ret < 0) {
		i_error("Client sent invalid request: %s", error);
		client_destroy(conn);
	}
}

static struct connection_settings client_set = {
	.input_max_size = (size_t)-1,
	.output_max_size = (size_t)-1,
	.client = FALSE
};

static const struct connection_vfuncs client_vfuncs = {
	.destroy = client_destroy,
	.input = client_input
};

static void client_init(int fd)
{
	struct client *client;
	struct http_request_limits req_limits;

	memset(&req_limits, 0, sizeof(req_limits));
	req_limits.max_target_length = 4096;

	client = i_new(struct client, 1);
	connection_init_server(clients, &client->conn,
			       "(http client)", fd, fd);
	client->parser = http_request_parser_init(client->conn.input, &req_limits);
}

static void client_accept(void *context ATTR_UNUSED)
{
	int fd;

	fd = net_accept(fd_listen, NULL, NULL);
	if (fd == -1)
		return;
	if (fd == -2)
		i_fatal("accept() failed: %m");

	client_init(fd);
}

int main(int argc, char *argv[])
{
	struct ip_addr my_ip;
	struct ioloop *ioloop;
	unsigned int port;

	lib_init();
	if (argc < 2 || str_to_uint(argv[1], &port) < 0)
		i_fatal("Port parameter missing");
	if (argc < 3)
		net_get_ip_any4(&my_ip);
	else if (net_addr2ip(argv[2], &my_ip) < 0)
		i_fatal("Invalid IP parameter");

	ioloop = io_loop_create();
	clients = connection_list_init(&client_set, &client_vfuncs);

	fd_listen = net_listen(&my_ip, &port, 128);
	if (fd_listen == -1)
		i_fatal("listen(port=%u) failed: %m", port);
	io_listen = io_add(fd_listen, IO_READ, client_accept, (void *)NULL);

	io_loop_run(ioloop);

	io_remove(&io_listen);
	i_close_fd(&fd_listen);
	connection_list_deinit(&clients);
	io_loop_destroy(&ioloop);
	lib_deinit();
}


text:
<?php

namespace Blog\NewsBundle\Services;

class TestService
{
    public function toUpper($str)
    {
        return strtoupper($str);
    }

    public function toLower($str)
    {
        return strtolower($str);
    }

    public function getGoodTitle()
    {
        return 'hello';
    }
}


text:
/* eslint-disable import/prefer-default-export */
export { default as createAction } from './create-action';
export { default as createReducer } from './create-reducer';
export { default as identity } from './identity';
export { default as nextState } from './next-state';
/* eslint-enable import/prefer-default-export */


text:
// Project: https://github.com/c0b41/musixmatch, https://www.npmjs.com/package/musicmatch
// Definitions by: Aleksei Klimenko <https://github.com/DadUndead>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped

import Musicmatch, {
    AlbumParams,
    AlbumTracksParams,
    ArtistAlbumsParams,
    ArtistParams,
    ArtistRelatedParams,
    ArtistSearchParams,
    ChartArtistsParams,
    MatcherLyricsParams,
    MatcherSubtitleParams,
    MatcherTrackParams,
    TrackLyricsAddParams,
    TrackLyricsFeedbackParams,
    TrackLyricsParams,
    TrackParams,
    TrackSearchParams,
    TrackSearchResult,
    TrackSnippetParams,
    TrackSubtitleParams
} from 'musicmatch';

const musicmatch = new Musicmatch({ apikey: 'api_key', format: '' });

const COUNTRY = 'USA';
const Q_ARTIST = 'artist name';
const Q_TRACK = 'track title';

const trackSearchParams: TrackSearchParams = {
    f_music_genre_id: 18,
    page_size: 100,
    page: 1,
    s_track_rating: 'desc',
    f_lyrics_language: 'en',
};

const albumParams: AlbumParams = {
    album_id: 1,
};

const albumTrackParams: AlbumTracksParams = {
    album_id: 1,
    album_mbid: 1,
    format: 'json',
};

const artisParams: ArtistParams = {
    artist_id: 1,
    artist_mbid: 1,
};

const artistAlbumsParams: ArtistAlbumsParams = {
    artist_mbid: 1,
    artist_id: 1,
    g_album_name: 1,
    page: 1,
    page_size: 10,
    s_release_date: 'desc',
};

const artistRelatedParams: ArtistRelatedParams = {
    page_size: 10,
    page: 1,
    artist_id: 1,
    artist_mbid: 1,
};

const artistSearchParams: ArtistSearchParams = {
    page: 1,
    page_size: 10,
    f_artist_id: 1,
    f_artist_mbid: 1,
    q_artist: Q_ARTIST
};

const chartArtistsParams: ChartArtistsParams = {
    page: 1,
    page_size: 10,
    country: COUNTRY
};

const chartTracksParams: ChartArtistsParams = {
    page: 1,
    page_size: 10,
    country: COUNTRY,
};

const matcherLyricsParams: MatcherLyricsParams = {
    q_artist: Q_ARTIST,
    q_track: Q_TRACK,
};

const matcherSubtitleParams: MatcherSubtitleParams = {
    q_artist: Q_ARTIST,
    q_track: Q_TRACK,
    f_subtitle_length: 100,
    f_subtitle_length_max_deviation: 10,
};

const matcherTrackParams: MatcherTrackParams = {
    q_artist: Q_ARTIST,
    q_track: Q_TRACK,
    f_has_lyrics: 1,
    f_has_subtitle: 1,
};

const trackParams: TrackParams = {
    track_id: 1,
    track_mbid: 1,
};

const trackLyricsParams: TrackLyricsParams = {
    track_id: 1,
    track_mbid: 1,
};

const trackLyricsAddParams: TrackLyricsAddParams = {
    lyrics_body: 'Lyrics',
    lyrics_id: 1,
};

const trackLyricsFeedbackParams: TrackLyricsFeedbackParams = {
    feedback: 'bad_characters',
    lyrics_id: 1,
    track_id: 1,
};

const trackSnippetParams: TrackSnippetParams = {
    track_id: 1,
};

const trackSubtitleParams: TrackSubtitleParams = {
    f_subtitle_length: 100,
    f_subtitle_length_max_deviation: 10,
    subtitle_format: 'dfxp',
    track_id: 1,
    track_mbid: 1,
};

/**
 * Example of track search result
 */
const trackSearchResult: TrackSearchResult = {
    message: {
        header: { status_code: 200, execute_time: 0.27148103713989, available: 10000 }, body: {
            track_list: [{
                track: {
                    track_id: 164289228,
                    track_name: '7 rings',
                    track_name_translation_list: [],
                    track_rating: 100,
                    commontrack_id: 91473047,
                    instrumental: 0,
                    explicit: 1,
                    has_lyrics: 1,
                    has_subtitles: 1,
                    has_richsync: 1,
                    num_favourite: 2130,
                    album_id: 31234760,
                    album_name: 'thank u, next',
                    artist_id: 13958599,
                    artist_name: 'Ariana Grande',
                    track_share_url: 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546',
                    track_edit_url: 'https:\/\/www.musixmatch.com\/lyrics\/Ariana-Grande\/7-rings\/edit?utm_source=application&utm_campaign=api&utm_medium=FruitSarcop%3A1409618278546',
                    restricted: 0,
                    updated_time: '2019-03-22T15:28:01Z',
                    primary_genres: {
                        music_genre_list: [{
                            music_genre: {
                                music_genre_id: 14,
                                music_genre_parent_id: 34,
                                music_genre_name: 'Pop',
                                music_genre_name_extended: 'Pop',
                                music_genre_vanity: 'Pop'
                            }
                        }]
                    }
                }
            }]
        }
    }
};

Promise
    .all([
        musicmatch.album(albumParams),                                  //  0
        musicmatch.albumTracks(albumTrackParams),                       //  1
        musicmatch.artist(artisParams),                                 //  2
        musicmatch.artistAlbums(artistAlbumsParams),                    //  3
        musicmatch.artistRelated(artistRelatedParams),                  //  4
        musicmatch.artistSearch(artistSearchParams),                    //  5
        musicmatch.chartArtists(chartArtistsParams),                    //  6
        musicmatch.chartTracks(chartTracksParams),                      //  7
        musicmatch.matcherLyrics(matcherLyricsParams),                  //  8
        musicmatch.matcherSubtitle(matcherSubtitleParams),              //  9
        musicmatch.matcherTrack(matcherTrackParams),                    //  10
        musicmatch.track(trackParams),                                  //  11
        musicmatch.trackLyrics(trackLyricsParams),                      //  12
        musicmatch.trackLyricsAdd(trackLyricsAddParams),                //  13
        musicmatch.trackLyricsFeedback(trackLyricsFeedbackParams),      //  14
        musicmatch.trackSearch(trackSearchParams),                      //  15
        musicmatch.trackSnippet(trackSnippetParams),                    //  16
        musicmatch.trackSubtitle(trackSubtitleParams),                  //  17
    ])
    .then((results) => {
        const trackSearchResult: TrackSearchResult = results[15];

        console.log('No. of tracks found by search:', trackSearchResult.message.body.track_list.length);
    });


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

namespace Neemo.Tax
{
    public static class TaxCostExtensions
    {
        /// <summary>
        /// Returns the sum of multiple tax amounts
        /// </summary>
        public static TaxCost TaxCostSum(this IEnumerable<TaxCost> taxes)
        {
            var taxesToSum = taxes.ToList();

            if (taxesToSum.Count == 0)
                return null;

            // Take the first tax cost
            var total = new TaxCost(taxesToSum.First().TaxType);

            return taxesToSum.Aggregate(total, (current, tax) => current + tax);
        }
    }
}


text:
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <title>Word Tower</title>
  <meta property="og:title" content="Word Tower" />
  <meta property="og:image" content="https://www.simontiu.com/img/profilepic.jpg" />
  <meta name="description" content="Associate at Valia Ventures, Strategy at Google Cloud, Growth at Google Fiber, Consultant at Deloitte">
  <meta property="og:description" content="Associate at Valia Ventures, Strategy at Google Cloud, Growth at Google Fiber, Consultant at Deloitte" />
  <meta name="author" content="Simon Tiu">

  <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet">

  <link href="https://fonts.googleapis.com/css?family=Saira+Extra+Condensed:100,200,300,400,500,600,700,800,900" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css?family=Open+Sans:300,300i,400,400i,600,600i,700,700i,800,800i" rel="stylesheet">
  <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <link href='https://cdnjs.cloudflare.com/ajax/libs/devicons/1.8.0/css/devicons.min.css' rel='stylesheet'>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/simple-line-icons/2.4.1/css/simple-line-icons.min.css" rel="stylesheet">

  <link href="https://www.simontiu.com/css/resume.css" rel="stylesheet">
  <link href="https://www.simontiu.com/css/tweaks.css" rel="stylesheet">
  <meta name="generator" content="Hugo 0.37.1" />

    Simon Tiu

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">

  </button>

        About

            Experience

            Education

            Skills

            Projects

            Photos + Vids

            Musings

  Simon

  Projects

  Creations

  Word Tower

Word Tower

This is a fun game that I made entirely in Matlab (apparently it can do full OOP programming). You can choose popular songs and the program will load the lyrics and track your typing speed as you attempt to “type along.”

I had a lot of fun building this. Definitely feel free to check it out. You’ll need Matlab to run it.

Project link: https://github.com/Psymen/WordTower

game

matlab

app


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Cahiers Pacif. 11: 106 (1967)

#### Original name
Oidium phyllanthi var. phyllanthi

### Remarks
null


text:
from __future__ import unicode_literals

from .sh import wrap, cmd, ShellError, ShellOutput, set_env

from kids.test import Test
from kids.cache import cache

class BaseShTest(Test):

    COMMAND = ""
    DEFAULT_ENV = {
    }

    @cache
    @property
    def cmd(self):
        return set_env(**self.DEFAULT_ENV)(cmd)

    @cache
    @property
    def w(self):
        return set_env(**self.DEFAULT_ENV)(wrap)


text:
#include "third_party/blink/renderer/core/dom/shadow_root.h"

#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_get_inner_html_options.h"
#include "third_party/blink/renderer/core/css/resolver/style_resolver.h"
#include "third_party/blink/renderer/core/css/style_change_reason.h"
#include "third_party/blink/renderer/core/css/style_engine.h"
#include "third_party/blink/renderer/core/css/style_sheet_list.h"
#include "third_party/blink/renderer/core/dom/element_traversal.h"
#include "third_party/blink/renderer/core/dom/events/event_dispatch_forbidden_scope.h"
#include "third_party/blink/renderer/core/dom/slot_assignment.h"
#include "third_party/blink/renderer/core/dom/slot_assignment_engine.h"
#include "third_party/blink/renderer/core/dom/text.h"
#include "third_party/blink/renderer/core/dom/whitespace_attacher.h"
#include "third_party/blink/renderer/core/editing/serializers/serialization.h"
#include "third_party/blink/renderer/core/html/html_slot_element.h"
#include "third_party/blink/renderer/core/trustedtypes/trusted_types_util.h"
#include "third_party/blink/renderer/platform/bindings/exception_state.h"
#include "third_party/blink/renderer/platform/wtf/size_assertions.h"

namespace blink {

struct SameSizeAsShadowRoot : public DocumentFragment, public TreeScope {
  Member<void*> member[2];
  unsigned flags[1];
};

ASSERT_SIZE(ShadowRoot, SameSizeAsShadowRoot);

ShadowRoot::ShadowRoot(Document& document, ShadowRootType type)
    : DocumentFragment(nullptr, kCreateShadowRoot),
      TreeScope(*this, document),
      style_sheet_list_(nullptr),
      child_shadow_root_count_(0),
      type_(static_cast<unsigned>(type)),
      registered_with_parent_shadow_root_(false),
      delegates_focus_(false),
      slot_assignment_mode_(static_cast<unsigned>(SlotAssignmentMode::kNamed)),
      needs_dir_auto_attribute_update_(false),
      unused_(0) {}

ShadowRoot::~ShadowRoot() = default;

SlotAssignment& ShadowRoot::EnsureSlotAssignment() {
  if (!slot_assignment_)
    slot_assignment_ = MakeGarbageCollected<SlotAssignment>(*this);
  return *slot_assignment_;
}

HTMLSlotElement* ShadowRoot::AssignedSlotFor(const Node& node) {
  if (!slot_assignment_)
    return nullptr;
  return slot_assignment_->FindSlot(node);
}

void ShadowRoot::DidAddSlot(HTMLSlotElement& slot) {
  EnsureSlotAssignment().DidAddSlot(slot);
}

void ShadowRoot::DidChangeHostChildSlotName(const AtomicString& old_value,
                                            const AtomicString& new_value) {
  if (!slot_assignment_)
    return;
  slot_assignment_->DidChangeHostChildSlotName(old_value, new_value);
}

Node* ShadowRoot::Clone(Document&, CloneChildrenFlag) const {
  NOTREACHED() << "ShadowRoot nodes are not clonable.";
  return nullptr;
}

void ShadowRoot::SetSlotAssignmentMode(SlotAssignmentMode assignment_mode) {
  slot_assignment_mode_ = static_cast<unsigned>(assignment_mode);
}

String ShadowRoot::innerHTML() const {
  return CreateMarkup(this, kChildrenOnly);
}

String ShadowRoot::getInnerHTML(const GetInnerHTMLOptions* options) const {
  ClosedRootsSet include_closed_roots;
  if (options->hasClosedRoots()) {
    for (auto& shadow_root : options->closedRoots()) {
      include_closed_roots.insert(shadow_root);
    }
  }
  return CreateMarkup(
      this, kChildrenOnly, kDoNotResolveURLs,
      options->includeShadowRoots() ? kIncludeShadowRoots : kNoShadowRoots,
      include_closed_roots);
}

void ShadowRoot::setInnerHTML(const String& html,
                              ExceptionState& exception_state) {
  if (DocumentFragment* fragment = CreateFragmentForInnerOuterHTML(
          html, &host(), kAllowScriptingContent, "innerHTML",
          /*include_shadow_roots=*/false, exception_state)) {
    ReplaceChildrenWithFragment(this, fragment, exception_state);
    if (auto* element = DynamicTo<HTMLElement>(host()))
      element->AdjustDirectionalityIfNeededAfterShadowRootChanged();
  }
}

void ShadowRoot::RebuildLayoutTree(WhitespaceAttacher& whitespace_attacher) {
  DCHECK(!NeedsReattachLayoutTree());
  DCHECK(!ChildNeedsReattachLayoutTree());
  RebuildChildrenLayoutTrees(whitespace_attacher);
}

void ShadowRoot::DetachLayoutTree(bool performing_reattach) {
  ContainerNode::DetachLayoutTree(performing_reattach);

  // Shadow host may contain unassigned light dom children that need detaching.
  // Assigned nodes are detached by the slot element.
  for (Node& child : NodeTraversal::ChildrenOf(host())) {
    if (!child.IsSlotable() || child.AssignedSlotWithoutRecalc())
      continue;

    if (child.GetDocument() == GetDocument())
      child.DetachLayoutTree(performing_reattach);
  }
}

Node::InsertionNotificationRequest ShadowRoot::InsertedInto(
    ContainerNode& insertion_point) {
  DocumentFragment::InsertedInto(insertion_point);

  if (!insertion_point.isConnected())
    return kInsertionDone;

  GetDocument().GetStyleEngine().ShadowRootInsertedToDocument(*this);

  GetDocument().GetSlotAssignmentEngine().Connected(*this);

  // FIXME: When parsing <video controls>, InsertedInto() is called many times
  // without invoking RemovedFrom().  For now, we check
  // registered_with_parent_shadow_root. We would like to
  // DCHECK(!registered_with_parent_shadow_root) here.
  // https://bugs.webkit.org/show_bug.cig?id=101316
  if (registered_with_parent_shadow_root_)
    return kInsertionDone;

  if (ShadowRoot* root = host().ContainingShadowRoot()) {
    root->AddChildShadowRoot();
    registered_with_parent_shadow_root_ = true;
  }

  return kInsertionDone;
}

void ShadowRoot::RemovedFrom(ContainerNode& insertion_point) {
  if (insertion_point.isConnected()) {
    if (NeedsSlotAssignmentRecalc())
      GetDocument().GetSlotAssignmentEngine().Disconnected(*this);
    GetDocument().GetStyleEngine().ShadowRootRemovedFromDocument(this);
    if (registered_with_parent_shadow_root_) {
      ShadowRoot* root = host().ContainingShadowRoot();
      if (!root)
        root = insertion_point.ContainingShadowRoot();
      if (root)
        root->RemoveChildShadowRoot();
      registered_with_parent_shadow_root_ = false;
    }
  }

  DocumentFragment::RemovedFrom(insertion_point);
}

void ShadowRoot::SetNeedsAssignmentRecalc() {
  if (!slot_assignment_)
    return;
  return slot_assignment_->SetNeedsAssignmentRecalc();
}

bool ShadowRoot::NeedsSlotAssignmentRecalc() const {
  return slot_assignment_ && slot_assignment_->NeedsAssignmentRecalc();
}

void ShadowRoot::ChildrenChanged(const ChildrenChange& change) {
  ContainerNode::ChildrenChanged(change);

  if (change.IsChildElementChange()) {
    CheckForSiblingStyleChanges(
        change.type == ChildrenChangeType::kElementRemoved
            ? kSiblingElementRemoved
            : kSiblingElementInserted,
        To<Element>(change.sibling_changed), change.sibling_before_change,
        change.sibling_after_change);
  }
}

StyleSheetList& ShadowRoot::StyleSheets() {
  if (!style_sheet_list_)
    SetStyleSheets(MakeGarbageCollected<StyleSheetList>(this));
  return *style_sheet_list_;
}

void ShadowRoot::Trace(Visitor* visitor) const {
  visitor->Trace(style_sheet_list_);
  visitor->Trace(slot_assignment_);
  TreeScope::Trace(visitor);
  DocumentFragment::Trace(visitor);
}

std::ostream& operator<<(std::ostream& ostream, const ShadowRootType& type) {
  switch (type) {
    case ShadowRootType::kUserAgent:
      ostream << "UserAgent";
      break;
    case ShadowRootType::kOpen:
      ostream << "Open";
      break;
    case ShadowRootType::kClosed:
      ostream << "Closed";
      break;
  }
  return ostream;
}

}  // namespace blink


text:
using System.Runtime.InteropServices;

[assembly: ComVisible(false)]
[assembly: Guid("f25aec4f-5aa3-4157-8827-690ebb49e078")]


text:
class Rspec < Yamadera::Command
  usage 'rspec [OPTIONS]'

  class_option :fixture_replacement, type: :string, default: 'factory_girl'

  def install_rspec
    install_gems 'rspec', 'rspec-rails', group: %i[development test]
  end

  def generate_rspec_install
    generate 'rspec:install'
    uncomment_lines 'spec/rails_helper.rb', %r[spec/support/\*\*/\*\.rb]
    git_add and git_commit message: '$ rails generate rspec:install'
  end

  def install_spring_commands_rspec
    install_gems 'spring-commands-rspec', group: :development
  end

  def spring_binstub_rspec
    run 'spring binstub rspec', with: 'bundle exec'
    git_add and git_commit message: 'Add spring wrapper for rspec'
  end

  invoke_from_option :fixture_replacement, test_framework: 'rspec'
end


text:
<?php

// use yii\db\Schema;
use console\components\Migration;

class m160906_125951_competition extends Migration
{
    public function getOperations()
    {
//        return ["Controller:Action" => ["role1", "role2"]];
        return [];
    }

    public function safeUp()
    {
        $this->addColumn("competition", "organizer", $this->string()->notNull());
        $this->addColumn("competition", "organizer_url", $this->string());
        $this->addColumn("competition", "created_date", $this->dateTime());

        $this->createTable("competition_sponsor", [
            "id" => $this->primaryKey(),
            "competition_id" => $this->integer()->notNull(),
            "name" => $this->string()->notNull(),
            "url" => $this->string()
        ]);
        $this->addForeignKey("competition_sponsor_competition_fk", "competition_sponsor", "competition_id", "competition", "id");

        $this->createTable("competition_condition", [
            "id" => $this->primaryKey(),
            "competition_id" => $this->integer()->notNull(),
            "name" => $this->string(),
        ]);
        $this->addForeignKey("competition_condition_competition_fk", "competition_condition", "competition_id", "competition", "id");

        $this->createTable("competition_prize", [
            "id" => $this->primaryKey(),
            "competition_id" => $this->integer()->notNull(),
            "name" => $this->string()->notNull(),
            "url" => $this->string()
        ]);
        $this->addForeignKey("competition_prize_competition_fk", "competition_prize", "competition_id", "competition", "id");
    }

    public function safeDown()
    {
        $this->dropColumn("competition", "organizer");
        $this->dropColumn("competition", "organizer_url");
        $this->dropColumn("competition", "created_date");

        $this->dropTable("competition_sponsor");

        $this->dropTable("competition_condition");

        $this->dropTable("competition_prize");
    }

    /*
    // Use up/down to run migration code without a transaction
    public function up()
    {
    }

    public function down()
    {
    }
    */
}


text:
import { Component, Input, AfterContentInit } from '@angular/core';

import { ShellLists } from '../DB/ShellLists';

import { FourDCollection } from 'js44d';

@Component({
    selector: 'mglist-dropdown',
    styles: [`.mglistDropdown {
                margin: inherit;
                width: inherit;
                padding: inherit;
                font-size: inherit;
                border: 1px solid #ccc;
                height: inherit;
                }
            `],
    template: `
        <select  #selector class='mglistDropdown' (change)='selectedValue = $event.target.value' [(value)]='selectedValue'>
            <option *ngFor='let item of listOptions' value='{{item}}' [selected]='isItemSelected(item)'>{{item}}</option>
        </select>
       `
})

export class MGListDropDown implements AfterContentInit {
    @Input() public listName: string;
    @Input() public selectedValue: string;
    @Input() public listOptions: Array<string> = [];

    private shellList: ShellLists;

    private static _listCache: any = {};

    ngAfterContentInit() {
        if (this.listName) {
            if (MGListDropDown._listCache[this.listName]) {
                // list is cached, reuse it
                this.listOptions = MGListDropDown._listCache[this.listName];
            } else {
                this.shellList = new ShellLists();
                let query = { query: [ShellLists.kListName + ';=;' + this.listName] };
                this.shellList.getRecords(query)
                    .then((recs: FourDCollection) => {
                        this.listOptions = [''];
                        recs.models.forEach((rec: ShellLists) => {
                            this.listOptions.push(rec.ElementShortValue);
                        });
                        MGListDropDown._listCache[this.listName] = this.listOptions; // cache list
                    })
                    .catch((reason) => { console.log('error', reason); });
            }
        }
    }

    isItemSelected(item: string): string {
        return (item === this.selectedValue) ? 'selected' : '';
    }

}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Student
{
    class Program
    {
        static void Main(string[] args)
        {
            Student newStudent = new Student();

            Type type = newStudent.GetType();

            foreach (var item in type.GetProperties())
            {
                Console.WriteLine(item);
            }
        }
    }
}


text:
"""Version Module

So we only have to maintain version information in one place!
"""

version_info = (3, 4, 1, "dev")  # (major, minor, patch, dev?)
version = ".".join(map(str, version_info))


text:
package io.opensec.oval.model.linux;

import io.opensec.oval.model.OvalObject;

/**
 * The RpmInfoBehaviors defines a set of behaviors for controlling what data,
 * for installed rpms, is collected.
 *
 * @author  Akihito Nakamura, AIST
 * @see OVAL Language
 */
public class RpmInfoBehaviors
    implements OvalObject
{

    public static final Boolean  DEFAULT_FILEPATHS = Boolean.FALSE;

    private Boolean  filepaths;
    //{optional, default='false'}

    /**
     * Constructor.
     */
    public RpmInfoBehaviors()
    {
    }

    /**
     */
    public void setFilepaths(
                    final Boolean filepaths
                    )
    {
        this.filepaths = filepaths;
    }

    public Boolean getFilepaths()
    {
        return filepaths;
    }

    public static final Boolean filepaths(
                    final RpmInfoBehaviors obj
                    )
    {
        Boolean  filepaths = obj.getFilepaths();
        return (filepaths == null ? DEFAULT_FILEPATHS : filepaths);
    }

    //**************************************************************
    //  java.lang.Object
    //**************************************************************

    @Override
    public int hashCode()
    {
        final int  prime = 37;
        int  result = 17;

        result = prime * result + filepaths( this ).hashCode();

        return result;
    }

    @Override
    public boolean equals(
                    final Object obj
                    )
    {
        if (this == obj) {
            return true;
        }

        if (!(obj instanceof RpmInfoBehaviors)) {
            return false;
        }

        if (super.equals( obj )) {
            RpmInfoBehaviors  other = (RpmInfoBehaviors)obj;
            if (filepaths( this ) == filepaths( other )) {
                return true;
            }
        }

        return false;
    }

    @Override
    public String toString()
    {
        return super.toString()
                        + ", filepaths="    + getFilepaths()
                        ;
    }

}
//RpmInfoBehaviors


text:
namespace chrono {

// This file contains a number of ready-to-use loads (ChLoad inherited classes and
// their embedded ChLoader classes) that can be applied to objects of ChNodeXYZ (and
// inherited classes) type.
// These are 'simplified' tools, that save you from inheriting your custom
// loads.
// Or just look at these classes and learn how to implement some special type of load.

// A first example, mostly an exercise, that inherits from ChLoaderUVWatomic:

/// FORCE AT XYZ NODE
/// Loader for a constant force applied at a XYZ node.
/// Note that an equivalent shortcut is to set directly the node's own force member data
/// as mynode->SetForce(), but this other approach is more object-oriented (es. you can
/// apply multiple forces at a single node, etc)
/// Another option is to use ChLoadXYZnodeForceAbsolute
class ChLoaderXYZnode : public ChLoaderUVWatomic {
  private:
    ChVector<> force;

  public:
    // Useful: a constructor that also sets ChLoadable
    ChLoaderXYZnode(std::shared_ptr<ChLoadableUVW> mloadable) : ChLoaderUVWatomic(mloadable, 0, 0, 0), force(VNULL) {}

    // Compute F=F(u,v,w)
    // Implement it from base class.
    virtual void ComputeF(const double U,        ///< parametric coordinate -not used
                          const double V,        ///< parametric coordinate -not used
                          const double W,        ///< parametric coordinate -not used
                          ChVectorDynamic<>& F,  ///< Result F vector here, size must be = n.field coords.of loadable
                          ChVectorDynamic<>* state_x,  ///< if != 0, update state (pos. part) to this, then evaluate F
                          ChVectorDynamic<>* state_w   ///< if != 0, update state (speed part) to this, then evaluate F
                          ) {
        F.segment(0, 3) = force.eigen();
    }

    /// Set the force, assumed to be constant in space and time and assumed applied at the node.
    void SetForce(const ChVector<>& mf) { force = mf; }

    /// Get the applied force.
    const ChVector<>& GetForce() const { return force; }
};

/// Force at XYZ node (ready to use load)
class ChLoadXYZnode : public ChLoad<ChLoaderXYZnode> {
  public:
    ChLoadXYZnode(std::shared_ptr<ChNodeXYZ> mloadable) : ChLoad<ChLoaderXYZnode>(mloadable) {}
};

////////////////////////////////////////////////////////////////////////////
//
//  LOADS ON:   ChNodeXYZ

/// Base class for loads representing a concentrated force acting on a ChNodeXYZ.
/// Users should inherit from this and implement custom ComputeForce(), this is enough
/// to have the load working.
/// Note: there are already some predefined examples, ie. children classes
/// with common concrete implementations, such as ChLoadXYZnodeForceAbsolute ;
/// take inspiration from those example to inherit your own load if they are not enough.
class ChApi ChLoadXYZnodeForce : public ChLoadCustom {
  public:
    ChLoadXYZnodeForce(std::shared_ptr<ChNodeXYZ> body  ///< node to apply load to
    );

    /// Compute the force on the node, in absolute coordsystem,
    /// given position of node as abs_pos.
    /// Inherited classes MUST IMPLEMENT THIS.
    virtual void ComputeForce(const ChVector<>& abs_pos,
									 const ChVector<>& abs_vel,
                                           ChVector<>& abs_force) = 0;

	// Optional: inherited classes could implement this to avoid the
    // default numerical computation of jacobians:
    //   virtual void ComputeJacobian(...) // see ChLoad

    /// Compute Q, the generalized load.
    /// Called automatically at each Update().
    virtual void ComputeQ(ChState* state_x,      ///< state position to evaluate Q
                          ChStateDelta* state_w  ///< state speed to evaluate Q
                          ) override;

	/// For diagnosis purposes, this can return the actual last computed value of
    /// the applied force, expressed in absolute coordinate system, assumed applied to node
    ChVector<> GetForce() const { return computed_abs_force; }

  protected:

	/// Inherited classes could override this and return true, if the load benefits from a jacobian
	/// when using implicit integrators.
    virtual bool IsStiff() override { return false; }

    virtual void Update(double time) override;

	ChVector<> computed_abs_force;
};

 // Example:
/// Load representing a concentrated force acting on a ChNodeXYZ,
/// as a constant force, or it provides a function to modulate
/// it with time.
class ChApi ChLoadXYZnodeForceAbsolute : public ChLoadXYZnodeForce {
  public:
    ChLoadXYZnodeForceAbsolute(std::shared_ptr<ChNodeXYZ> node,  ///< node to apply load to
                    const ChVector<>& force        ///< force to apply, assumed in absolute coordsys,
    );

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadXYZnodeForceAbsolute* Clone() const override { return new ChLoadXYZnodeForceAbsolute(*this); }

	/// Compute the force on the node, in absolute coordsystem,
    /// given position of node as abs_pos.
    virtual void ComputeForce(const ChVector<>& abs_pos,
									 const ChVector<>& abs_vel,
                                           ChVector<>& abs_force) override;

    /// Set the applied force vector: it is assumed constant, unless a
	/// non-constant scaling time function is provided.
    /// It is expressed in absolute coordinates.
    void SetForceBase(const ChVector<>& force);

    /// Return the current force vector (scaled by the current modulation value).
    ChVector<> GetForce() const;

    /// Set modulation function.
    /// This is a function of time which (optionally) modulates the specified applied force.
    /// By default the modulation is a constant function, always returning a value of 1.
    void SetModulationFunction(std::shared_ptr<ChFunction> modulation) { m_modulation = modulation; }

  protected:
    ChVector<> m_force_base;  ///< base force value

	std::shared_ptr<ChFunction> m_modulation;  ///< modulation function of time
    double m_scale;                            ///< scaling factor (current modulation value)

    virtual bool IsStiff() override { return false; }

    virtual void Update(double time) override;
};

////////////////////////////////////////////////////////////////////////////
//
//  LOADS ON:   ChNodeXYZ ---- ChNodeXYZ

/// Base class for loads representing a concentrated force acting between two ChNodeXYZ.
/// Users should inherit from this and implement a custom ComputeForce(), this is enough
/// to have the load working.
/// Note: there are already some predefined examples, ie. children classes
/// with common concrete implementations, such as ChLoadXYZnodeXYZnodeSpring ChLoadXYZnodeXYZnodeBushing etc.;
/// take inspiration from those example to inherit your own load if they are not enough.
class ChApi ChLoadXYZnodeXYZnode : public ChLoadCustomMultiple {
  public:
    ChLoadXYZnodeXYZnode(std::shared_ptr<ChNodeXYZ> mnodeA,  ///< node A to apply load to
						 std::shared_ptr<ChNodeXYZ> mnodeB   ///< node B to apply load to, as reaction
    );

    /// Compute the force on the node A, in absolute coordsystem,
    /// given position and speed of node respect to the other. Node B gets the opposite.
    /// Inherited classes MUST IMPLEMENT THIS.
    virtual void ComputeForce(const ChVector<>& rel_pos,
							  const ChVector<>& rel_vel,
                              ChVector<>& abs_force) = 0;

	// Optional: inherited classes could implement this to avoid the
    // default numerical computation of jacobians:
    //   virtual void ComputeJacobian(...) // see ChLoad

    /// Compute Q, the generalized load.
    /// Called automatically at each Update().
    virtual void ComputeQ(ChState* state_x,      ///< state position to evaluate Q
                          ChStateDelta* state_w  ///< state speed to evaluate Q
                          ) override;

	/// For diagnosis purposes, this can return the actual last computed value of
    /// the applied force, expressed in absolute coordinate system, assumed applied to node
    ChVector<> GetForce() const { return computed_abs_force; }

  protected:

	/// Inherited classes could override this and return true, if the load benefits from a jacobian
	/// when using implicit integrators.
    virtual bool IsStiff() override { return false; }

    virtual void Update(double time) override;

	ChVector<> computed_abs_force;
};

 // Example:
/// Load representing a spring between two ChNodeXYZ, with given damping and spring constants,
/// directed as the distance between the two.
class ChApi ChLoadXYZnodeXYZnodeSpring : public ChLoadXYZnodeXYZnode {
  public:
    ChLoadXYZnodeXYZnodeSpring(std::shared_ptr<ChNodeXYZ> mnodeA,  ///< node to apply load to
                               std::shared_ptr<ChNodeXYZ> mnodeB,  ///< node to apply load to as reaction
                               double mK,                          ///< stiffness,
                               double mR,                          ///< damping,
                               double mD0 = 0                      ///< initial rest length
    );

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadXYZnodeXYZnodeSpring* Clone() const override { return new ChLoadXYZnodeXYZnodeSpring(*this); }

	/// Compute the force on the nodeA, in absolute coordsystem,
    /// given relative position of nodeA respect to B, in absolute basis
    virtual void ComputeForce(const ChVector<>& rel_pos,
									 const ChVector<>& rel_vel,
                                           ChVector<>& abs_force) override;

    /// Set stiffness, along direction, es [N/m]
    void SetStiffness(const double mstiffness) { K = mstiffness; }
    double GetStiffness() const { return K; }

    /// Set damping, along direction, es [Ns/m]
    void SetDamping(const double mdamping) { R = mdamping; }
    double GetDamping() const { return R; }

	/// Set initial spring length, es [m]
    void SetRestLength(const double mrest) { d_0 = mrest; }
    double GetRestLength() const { return d_0; }

	/// Use this to enable the stiff force computation (i.e. it enables the
	/// automated computation of the jacobian by numerical differentiation to
	/// elp the convergence of implicit integrators, but adding CPU overhead).
	void SetStiff(bool ms) { this->is_stiff = ms; }

  protected:
	  double K;
	  double R;
	  double d_0;
	  bool is_stiff;

	  virtual bool IsStiff() override { return is_stiff; }
};

 // Example:
/// Load representing a XYZ bushing between two ChNodeXYZ, with given
/// with spring stiffness as a ChFunction of displacement, for each X,Y,Z direction.
class ChApi ChLoadXYZnodeXYZnodeBushing : public ChLoadXYZnodeXYZnode {
  public:
    ChLoadXYZnodeXYZnodeBushing(std::shared_ptr<ChNodeXYZ> mnodeA,  ///< node to apply load to
                                std::shared_ptr<ChNodeXYZ> mnodeB   ///< node to apply load to as reaction
    );

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadXYZnodeXYZnodeBushing* Clone() const override { return new ChLoadXYZnodeXYZnodeBushing(*this); }

	/// Compute the force on the nodeA, in absolute coordsystem,
    /// given relative position of nodeA respect to B, in absolute basis
    virtual void ComputeForce(const ChVector<>& rel_pos,
									 const ChVector<>& rel_vel,
                                           ChVector<>& abs_force) override;

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceX(std::shared_ptr<ChFunction> fx) { force_dX = fx; }

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceY(std::shared_ptr<ChFunction> fy) { force_dY = fy; }

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceZ(std::shared_ptr<ChFunction> fz) { force_dZ = fz; }

	/// Set xyz constant damping coefficients [Ns/m]
	/// along the three absolute directions xyz
    void SetDamping(const ChVector<> mdamping) { R = mdamping; }
    ChVector<> GetDamping() const { return R; }

	/// Use this to enable the stiff force computation (i.e. it enables the
	/// automated computation of the jacobian by numerical differentiation to
	/// elp the convergence of implicit integrators, but adding CPU overhead).
	void SetStiff(bool ms) { this->is_stiff = ms; }

  protected:
	  std::shared_ptr<ChFunction> force_dX;
	  std::shared_ptr<ChFunction> force_dY;
	  std::shared_ptr<ChFunction> force_dZ;

	  ChVector<> R;

	  bool is_stiff;

	  virtual bool IsStiff() override { return is_stiff; }
};

////////////////////////////////////////////////////////////////////////////
//
//  LOADS ON:   ChNodeXYZ ---- ChBody

/// Base class for loads representing a concentrated force acting between a ChNodeXYZ and a ChBody
/// Users should inherit from this and implement a custom ComputeForce(), this is enough
/// to have the load working.
/// Note: there are already some predefined examples, ie. children classes
/// with common concrete implementations, such as ChLoadXYZnodeBodySpring ChLoadXYZnodeBodyBushing etc.;
/// take inspiration from those example to inherit your own load if they are not enough.
class ChApi ChLoadXYZnodeBody : public ChLoadCustomMultiple {
  public:
    ChLoadXYZnodeBody   (std::shared_ptr<ChNodeXYZ> nodeA,    ///< node
						 std::shared_ptr<ChBody> bodyB        ///< body
    );

    /// Compute the force on the nodeA, in local coordsystem of SetApplicationFrameB (the
	/// auxiliary frame attached to body) given relative position of nodeA respect to B
    /// Body will receive the reaction force.
    /// Inherited classes MUST IMPLEMENT THIS.
    virtual void ComputeForce(const ChFrameMoving<>& rel_AB,
                               ChVector<>& loc_force) = 0;

    // Optional: inherited classes could implement this to avoid the
    // default numerical computation of jacobians:
    //   virtual void ComputeJacobian(...) // see ChLoad

    /// For diagnosis purposes, this can return the actual last computed value of
    /// the applied force, expressed in coordinate system of loc_application_B, assumed applied to node.
    ChVector<> GetForce() const { return computed_loc_force; }

    /// Set the application frame of bushing on bodyB
    void SetApplicationFrameB(const ChFrame<>& mpB) { loc_application_B = mpB; }
    ChFrame<> GetApplicationFrameB() const { return loc_application_B; }

    /// Get absolute coordinate of frame B (last computed)
    ChFrameMoving<> GetAbsoluteFrameB() const { return frame_Bw; }

    std::shared_ptr<ChNodeXYZ> GetNodeA() const;
    std::shared_ptr<ChBody> GetBodyB() const;

  protected:
    ChFrame<> loc_application_B;  ///< application point on body B (local)
    ChVector<> computed_loc_force;  ///< store computed values here
    ChFrameMoving<> frame_Aw;     ///< for results
    ChFrameMoving<> frame_Bw;     ///< for results

    /// Compute Q, the generalized load. It calls ComputeBodyBodyForceTorque, so in
    /// children classes you do not need to implement it.
    /// Called automatically at each Update().
    virtual void ComputeQ(ChState* state_x,      ///< state position to evaluate Q
                          ChStateDelta* state_w  ///< state speed to evaluate Q
                          ) override;
};

 // Example:
/// Load representing a spring between a ChNodeXYZ and a ChBody, where the
/// anchoring to body can be set via SetApplicationFrameB().
class ChApi ChLoadXYZnodeBodySpring : public ChLoadXYZnodeBody {
  public:
	  ChLoadXYZnodeBodySpring    (std::shared_ptr<ChNodeXYZ> mnodeA,  ///< node to apply load to
								  std::shared_ptr<ChBody> mbodyB,   ///< node to apply load to as reaction
								  double mK,	///< stiffness,
								  double mR,	///< damping,
								  double mD0=0	///< initial rest length
    );

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadXYZnodeBodySpring* Clone() const override { return new ChLoadXYZnodeBodySpring(*this); }

	/// Compute the force on the nodeA, in local coordsystem of SetApplicationFrameB (the
	/// auxiliary frame attached to body) given relative position of nodeA respect to B
    virtual void ComputeForce(const ChFrameMoving<>& rel_AB,
                               ChVector<>& loc_force) override;

    /// Set stiffness, along direction, es [N/m]
    void SetStiffness(const double mstiffness) { K = mstiffness; }
    double GetStiffness() const { return K; }

    /// Set damping, along direction, es [Ns/m]
    void SetDamping(const double mdamping) { R = mdamping; }
    double GetDamping() const { return R; }

	/// Set initial spring length, es [m]
    void SetRestLength(const double mrest) { d_0 = mrest; }
    double GetRestLength() const { return d_0; }

	/// Use this to enable the stiff force computation (i.e. it enables the
	/// automated computation of the jacobian by numerical differentiation to
	/// elp the convergence of implicit integrators, but adding CPU overhead).
	void SetStiff(bool ms) { this->is_stiff = ms; }

  protected:
	  double K;
	  double R;
	  double d_0;
	  bool is_stiff;

	  virtual bool IsStiff() override { return is_stiff; }
};

 // Example:
/// Load representing a XYZ bushing between a ChNodeXYZ and a ChBody application point, with given
/// with spring stiffness as a ChFunction of displacement, for each X,Y,Z direction along the
/// auxiliary frame at the attachment point. You can set the attachment point via SetApplicationFrameB().
class ChApi ChLoadXYZnodeBodyBushing : public ChLoadXYZnodeBody {
  public:
	  ChLoadXYZnodeBodyBushing   (std::shared_ptr<ChNodeXYZ> mnodeA,  ///< node to apply load
								  std::shared_ptr<ChBody> mbodyB);   ///< body to apply load

    /// "Virtual" copy constructor (covariant return type).
    virtual ChLoadXYZnodeBodyBushing* Clone() const override { return new ChLoadXYZnodeBodyBushing(*this); }

	/// Compute the force on the nodeA, in local coordsystem of SetApplicationFrameB (the
	/// auxiliary frame attached to body) given relative position of nodeA respect to B
    virtual void ComputeForce(const ChFrameMoving<>& rel_AB,
                               ChVector<>& loc_force) override;

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceX(std::shared_ptr<ChFunction> fx) { force_dX = fx; }

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceY(std::shared_ptr<ChFunction> fy) { force_dY = fy; }

	/// Set force as a function of displacement on X. Default was constant zero.
	void SetFunctionForceZ(std::shared_ptr<ChFunction> fz) { force_dZ = fz; }

	/// Set xyz constant damping coefficients [Ns/m] along the three directions xyz, assuming
	/// local xyz directions of the frame attached to body via SetApplicationFrameB.
    void SetDamping(const ChVector<> mdamping) { R = mdamping; }
    ChVector<> GetDamping() const { return R; }

	/// Use this to enable the stiff force computation (i.e. it enables the
	/// automated computation of the jacobian by numerical differentiation to
	/// elp the convergence of implicit integrators, but adding CPU overhead).
	void SetStiff(bool ms) { this->is_stiff = ms; }

  protected:
	  std::shared_ptr<ChFunction> force_dX;
	  std::shared_ptr<ChFunction> force_dY;
	  std::shared_ptr<ChFunction> force_dZ;

	  ChVector<> R;

	  bool is_stiff;

	  virtual bool IsStiff() override { return is_stiff; }
};

}  // end namespace chrono

#endif