text:
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.DocAsCode.Common.Tests
{
    using System.Collections.Generic;
    using System.Collections.Immutable;
    using System.IO;
    using System.Linq;

    using Xunit;

    using Microsoft.DocAsCode.Common;
    using Microsoft.DocAsCode.Tests.Common;

    [Trait("Owner", "vwxyzh")]
    public class FileAbstractLayerTest : TestBase
    {
        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldReadFileCorrectlyWhenInputNoFallback()
        {
            var input = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "👍");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(new PathMapping((RelativePath)"~/", input))
                .Create();
            Assert.True(fal.Exists("~/temp.txt"));
            Assert.True(fal.Exists("temp.txt"));
            Assert.False(fal.Exists("~/temp.jpg"));
            Assert.False(fal.Exists("temp.jpg"));
            Assert.Equal("👍", fal.ReadAllText("temp.txt"));
            Assert.Equal(new[] { (RelativePath)"~/temp.txt" }, fal.GetAllInputFiles());
            Assert.Equal(
                new[]
                {
                    new KeyValuePair<RelativePath, string>(
                        (RelativePath)"~/temp.txt",
                        Path.Combine(input, "temp.txt")),
                },
                fal.GetAllPhysicalPaths());
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldGetPropertiesCorrectly()
        {
            var input = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "👍");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(
                    new PathMapping((RelativePath)"~/", input)
                    {
                        Properties = ImmutableDictionary<string, string>.Empty.Add("test", "true")
                    })
                .Create();
            Assert.True(fal.Exists("temp.txt"));
            Assert.Equal("true", fal.GetProperties("temp.txt")["test"]);
            Assert.True(fal.HasProperty("temp.txt", "test"));
            Assert.Equal("true", fal.GetProperty("temp.txt", "test"));
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldReadFileCorrectlyWhenInputWithFallbackForSameLogicalFolder()
        {
            var input1 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input1, "temp1.txt"), "😎");
            var input2 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input2, "temp1.txt"), "😈");
            File.WriteAllText(Path.Combine(input2, "temp2.txt"), "💂");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(
                    new PathMapping((RelativePath)"~/", input1),
                    new PathMapping((RelativePath)"~/", input2))
                .Create();
            Assert.True(fal.Exists("~/temp1.txt"));
            Assert.True(fal.Exists("temp1.txt"));
            Assert.True(fal.Exists("~/temp2.txt"));
            Assert.True(fal.Exists("temp2.txt"));
            Assert.False(fal.Exists("~/temp.jpg"));
            Assert.Equal("😎", fal.ReadAllText("temp1.txt"));
            Assert.Equal("💂", fal.ReadAllText("temp2.txt"));
            Assert.Equal(
                new[]
                {
                    "~/temp1.txt",
                    "~/temp2.txt",
                },
                from r in fal.GetAllInputFiles()
                select r.ToString() into p
                orderby p
                select p);
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldReadFileCorrectlyWhenInputWithFallbackForDifferentLogicalFolder()
        {
            var input1 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input1, "temp.txt"), "😎");
            var input2 = GetRandomFolder();
            Directory.CreateDirectory(Path.Combine(input2, "a"));
            Directory.CreateDirectory(Path.Combine(input2, "b"));
            File.WriteAllText(Path.Combine(input2, "a/temp.txt"), "😈");
            File.WriteAllText(Path.Combine(input2, "b/temp.txt"), "💂");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(
                    new PathMapping((RelativePath)"~/a/", input1),
                    new PathMapping((RelativePath)"~/", input2))
                .Create();
            Assert.True(fal.Exists("~/a/temp.txt"));
            Assert.True(fal.Exists("~/b/temp.txt"));
            Assert.False(fal.Exists("~/temp.txt"));
            Assert.Equal("😎", fal.ReadAllText("a/temp.txt"));
            Assert.Equal("💂", fal.ReadAllText("b/temp.txt"));
            Assert.Equal(
                new[]
                {
                    "~/a/temp.txt",
                    "~/b/temp.txt",
                },
                from r in fal.GetAllInputFiles()
                select r.ToString() into p
                orderby p
                select p);
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldCopyFileCorrectly()
        {
            var input = GetRandomFolder();
            var output = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "😈");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(new PathMapping((RelativePath)"~/", input))
                .WriteToLink(output)
                .Create();
            fal.Copy("temp.txt", "copy.txt");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("copy.txt"));
            Assert.False(fal2.Exists("temp.txt"));
            Assert.Equal("😈", fal2.ReadAllText("copy.txt"));
            Assert.Equal(new[] { (RelativePath)"~/copy.txt" }, fal2.GetAllInputFiles());
            Assert.False(File.Exists(Path.Combine(output, "copy.txt")));
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldCreateTwiceForSameFileCorrectly()
        {
            var output = GetRandomFolder();
            var fal = FileAbstractLayerBuilder.Default
                .WriteToLink(output)
                .Create();
            fal.WriteAllText("temp.txt", "😱");
            fal.WriteAllText("temp.txt", "😆");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("temp.txt"));
            Assert.Equal("😆", fal2.ReadAllText("temp.txt"));
            Assert.Equal(new[] { (RelativePath)"~/temp.txt" }, fal2.GetAllInputFiles());
            Assert.False(File.Exists(Path.Combine(output, "temp.txt")));
        }

        [Fact]
        public void TestFileAbstractLayerWithLinkImplementsShouldCopyThenCreateForSameFileCorrectly()
        {
            var input = GetRandomFolder();
            var output = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "😄");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromLink(new PathMapping((RelativePath)"~/", input))
                .WriteToLink(output)
                .Create();
            fal.Copy("temp.txt", "copy.txt");
            fal.WriteAllText("copy.txt", "😁");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("copy.txt"));
            Assert.Equal("😁", fal2.ReadAllText("copy.txt"));
            Assert.Equal(new[] { (RelativePath)"~/copy.txt" }, fal2.GetAllInputFiles());
            Assert.False(File.Exists(Path.Combine(output, "copy.txt")));
            Assert.Equal(File.ReadAllText(Path.Combine(input, "temp.txt")), "😄");
        }

        [Fact]
        public void TestFileAbstractLayerWithRealImplementsShouldReadFileCorrectlyWhenInputNoFallback()
        {
            var input = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "👍");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input)
                .Create();
            Assert.True(fal.Exists("~/temp.txt"));
            Assert.True(fal.Exists("temp.txt"));
            Assert.False(fal.Exists("~/temp.jpg"));
            Assert.False(fal.Exists("temp.jpg"));
            Assert.Equal("👍", fal.ReadAllText("temp.txt"));
            Assert.Equal(new[] { (RelativePath)"~/temp.txt" }, fal.GetAllInputFiles());
        }

        [Fact]
        public void TestFileAbstractLayerWithRealImplementsShouldCopyFileCorrectly()
        {
            var input = GetRandomFolder();
            var output = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "😈");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input)
                .WriteToRealFileSystem(output)
                .Create();
            fal.Copy("temp.txt", "copy.txt");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("copy.txt"));
            Assert.False(fal2.Exists("temp.txt"));
            Assert.Equal("😈", fal2.ReadAllText("copy.txt"));
            Assert.Equal(new[] { (RelativePath)"~/copy.txt" }, fal2.GetAllInputFiles());
            Assert.True(File.Exists(Path.Combine(output, "copy.txt")));
        }

        [Fact]
        public void TestFileAbstractLayerWithRealImplementsShouldCreateTwiceForSameFileCorrectly()
        {
            var output = GetRandomFolder();
            var fal = FileAbstractLayerBuilder.Default
                .WriteToRealFileSystem(output)
                .Create();
            fal.WriteAllText("temp.txt", "😱");
            fal.WriteAllText("temp.txt", "😆");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("temp.txt"));
            Assert.Equal("😆", fal2.ReadAllText("temp.txt"));
            Assert.Equal(new[] { (RelativePath)"~/temp.txt" }, fal2.GetAllInputFiles());
            Assert.True(File.Exists(Path.Combine(output, "temp.txt")));
        }

        [Fact]
        public void TestFileAbstractLayerWithRealImplementsShouldCopyThenCreateForSameFileCorrectly()
        {
            var input = GetRandomFolder();
            var output = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "😄");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input)
                .WriteToRealFileSystem(output)
                .Create();
            fal.Copy("temp.txt", "copy.txt");
            fal.WriteAllText("copy.txt", "😁");

            var fal2 = FileAbstractLayerBuilder.Default
                .ReadFromOutput(fal)
                .Create();
            Assert.True(fal2.Exists("copy.txt"));
            Assert.Equal("😁", fal2.ReadAllText("copy.txt"));
            Assert.Equal(new[] { (RelativePath)"~/copy.txt" }, fal2.GetAllInputFiles());
            Assert.True(File.Exists(Path.Combine(output, "copy.txt")));
            Assert.Equal(File.ReadAllText(Path.Combine(input, "temp.txt")), "😄");
        }

        [Fact]
        public void TestFileAbstractLayerWithRealImplementsShouldGetPropertiesCorrectly()
        {
            var input = GetRandomFolder();
            File.WriteAllText(Path.Combine(input, "temp.txt"), "👍");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(
                    input,
                    ImmutableDictionary<string, string>.Empty.Add("test", "true"))
                .Create();
            Assert.True(fal.Exists("temp.txt"));
            Assert.Equal("true", fal.GetProperties("temp.txt")["test"]);
            Assert.True(fal.HasProperty("temp.txt", "test"));
            Assert.Equal("true", fal.GetProperty("temp.txt", "test"));
        }

        [Fact]
        public void TestFileAbstractLayerWithFallbackShouldReadFileCorrectly()
        {
            var input1 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input1, "temp1.txt"), "👍");
            var input2 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input2, "temp1.txt"), "😈");
            File.WriteAllText(Path.Combine(input2, "temp2.txt"), "😎");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input1)
                .FallbackReadFromInput(
                    FileAbstractLayerBuilder.Default
                    .ReadFromRealFileSystem(input2)
                    .Create())
                .Create();
            Assert.True(fal.Exists("temp1.txt"));
            Assert.True(fal.Exists("temp2.txt"));
            Assert.False(fal.Exists("temp3.txt"));
            Assert.Equal("👍", fal.ReadAllText("temp1.txt"));
            Assert.Equal("😎", fal.ReadAllText("temp2.txt"));
            Assert.Equal(
                new[] { "~/temp1.txt", "~/temp2.txt" },
                from r in fal.GetAllInputFiles()
                select (string)r into p
                orderby p
                select p);
        }

        [Fact]
        public void TestFileAbstractLayerWithFallbackShouldGetPropertiesCorrectly()
        {
            var input1 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input1, "temp1.txt"), "👍");
            var input2 = GetRandomFolder();
            File.WriteAllText(Path.Combine(input2, "temp1.txt"), "😈");
            File.WriteAllText(Path.Combine(input2, "temp2.txt"), "😎");
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input1, ImmutableDictionary<string, string>.Empty.Add("from", "1"))
                .FallbackReadFromInput(
                    FileAbstractLayerBuilder.Default
                    .ReadFromRealFileSystem(input2, ImmutableDictionary<string, string>.Empty.Add("from", "2"))
                    .Create())
                .Create();
            Assert.True(fal.Exists("temp1.txt"));
            Assert.Equal("1", fal.GetProperty("temp1.txt", "from"));
            Assert.Equal("2", fal.GetProperty("temp2.txt", "from"));
        }

        [Fact]
        public void TestFileAbstractLayerWithRedirectionFolder()
        {
            // arrange
            var input = GetRandomFolder();
            Directory.CreateDirectory(Path.Combine(input, "structured"));
            Directory.CreateDirectory(Path.Combine(input, "authored"));
            Directory.CreateDirectory(Path.Combine(input, "standalone"));
            File.WriteAllText(Path.Combine(input, "structured/temp1.yml"), "I pair with authored/temp1.yml.md");
            File.WriteAllText(Path.Combine(input, "authored/temp1.yml.md"), "I am paired by structured/temp1.yml");
            File.WriteAllText(Path.Combine(input, "structured/temp2.yml"), "I pair with authored/temp2.yml.md");
            File.WriteAllText(Path.Combine(input, "structured/temp2.yml.md"), "I am not paired by authored/temp2.yml.md");
            File.WriteAllText(Path.Combine(input, "standalone/temp3"), "I am not affected by folder redirection rules");
            var fdm = new FolderRedirectionManager(new[] { new FolderRedirectionRule("structured", "authored") });

            // act
            var fal = FileAbstractLayerBuilder.Default
                .ReadFromRealFileSystem(input)
                .ReadWithFolderRedirection(fdm)
                .Create();

            // assert
            Assert.True(fal.Exists("structured/temp1.yml.md"));
            Assert.Equal("I am paired by structured/temp1.yml", fal.ReadAllText("structured/temp1.yml.md"));
            Assert.False(fal.Exists("structured/temp2.yml.md"));
            Assert.True(fal.Exists("standalone/temp3"));
            Assert.Equal("I am not affected by folder redirection rules", fal.ReadAllText("standalone/temp3"));
        }
    }
}


text:
This rule catches generator functions that does not have `yield`, then warns those.

## Rule details

The following patterns are considered warnings:

```js
function* foo() {
  return 10;
}
```

The following patterns are not considered warnings:

```js
function* foo() {
  yield 5;
  return 10;
}
```

```js
function foo() {
  return 10;
}
```

```js
// This rule does not warn just empty generator functions.
function* foo() { }
```

redpajama_set_name: RedPajamaGithub


text:
using System.Threading.Tasks;
using Shouldly;
using Xunit;

namespace Jasper.Testing.Transports.Tcp.Protocol
{
    public class error_in_receiver : ProtocolContext
    {
        public error_in_receiver()
        {
            theReceiver.ThrowErrorOnReceived = true;
        }

        [Fact]
        public async Task did_not_succeed()
        {
            await afterSending();
            theSender.Succeeded.ShouldBeFalse();
        }

        [Fact]
        public async Task logs_processing_failure_in_sender()
        {
            await afterSending();
            theSender.ProcessingFailed.ShouldBeTrue();
        }

    }
}


text:
package game;

import org.newdawn.slick.*;

import javax.swing.*;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;

/**
 * A separate program needed to create beatmap for the game BeatBitBeat
 *
 * Writes lines to a text file at a rate of 15ms
 * The fixed rate is achieved by setting a fixed delta time
 * Delta time is the time in between calls of update() method
 *
 * Each line represents the beat map information
 * Each line contains 4 columns, represented by Red, Green, Blue, Yellow, respectively
 * Possible lines are the ff:
 * 0000     - no beat
 * 1000     - red note beat
 * 0100     - green note beat
 * 0010     - green blue beat
 * 0001     - green yellow beat
 *
 *
 * The BeatBitBeat beat map reader will then read this file at the same rate -- 15ms
 * The reader drops notes according to the fetched line from the beat map text file
 *
 */

public class BeatBitBeatMapCreator extends BasicGame implements KeyListener {

    private static final String gameName = "Beat Map Creator - BeatBitBeat";

    private BufferedWriter bw;
    private FileWriter fw;

    private Music music;

    private boolean pressedBlue;
    private boolean pressedRed;
    private boolean pressedYellow;
    private boolean pressedGreen;

    private String fileName;
    private String fileDir;

    // Beat map information stored in a LinkedList
    // each node in the link represents a single line
    private List<String> beatMapLines = new LinkedList<>();

    private static final int displayWidth = 600;
    private static final int displayHeight = 400;

    public BeatBitBeatMapCreator(String title) {
        super(title);
    }

    public static void main(String[] args) throws SlickException {
        AppGameContainer app = new AppGameContainer(new BeatBitBeatMapCreator(gameName));

        app.setTitle(gameName);                // Title for top bar
        app.setDisplayMode(displayWidth, displayHeight, false);     // fullscreen false for now
        app.setVSync(true);                         // matches monitor refresh rate. or use app.setTargetFrameRate(60);
        app.setMinimumLogicUpdateInterval(15);      // minimum delta of 15 ms
        app.setMaximumLogicUpdateInterval(15);      // maximum delta of 15 ms

        app.start();
    }

    @Override
    public void init(GameContainer gameContainer) throws SlickException {
        // Use JFileChooser to open a file
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
        int returnVal = fc.showOpenDialog(new JFrame());    // receive response from the dialog, represented by integer

        if (returnVal == JFileChooser.APPROVE_OPTION) {     // if user opened a file
            fileName = fc.getSelectedFile().getName();
            fileDir = fc.getSelectedFile().getAbsolutePath();
            music = new Music(fileDir);     // load selected music

            try {
                File file = new File("Beat Map 2.txt");
                bw = new BufferedWriter(new FileWriter(file));

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(GameContainer gameContainer, int i) throws SlickException {
        if (music.playing()) {      // must only write if music is playing
                if (pressedRed) {
                    pressedRed = false;
                    beatMapLines.add("1000\n");
                }
                else if (pressedGreen) {
                    pressedGreen = false;
                    beatMapLines.add("0100\n");
                }
                else if (pressedBlue) {
                    pressedBlue = false;
                    beatMapLines.add("0010\n");
                }
                else if (pressedYellow) {
                    pressedYellow = false;
                    beatMapLines.add("0001\n");
                }
                else {
                    beatMapLines.add("0000\n");
                }
            System.out.println(beatMapLines.size());
        }
    }

    @Override
    public void render(GameContainer gameContainer, Graphics graphics) throws SlickException {
        graphics.drawString("Time", (displayWidth / 2) - 20, 10);
        graphics.drawString(String.valueOf(music.getPosition()), ((displayWidth / 2 ) - String.valueOf(music.getPosition()).length() * 10), 20);
        graphics.drawString(fileName.substring(0, fileName.length() - 4), (displayWidth / 2) - (fileName.length() * 10), 30);

        graphics.drawString("U - Red | I - Green | O - Blue | P - Yellow", (displayWidth / 2) - 50, 70);
        graphics.drawString("S - Start | Space - Pause/Play | Left - Step back", (displayWidth / 2) - 45, 80);
        graphics.drawString("Esc - Save Beat Map and Exit", (displayWidth / 2) - 30, 90);
    }

    @Override
    public void keyPressed(int key, char pressedKey) {
        if (key == Input.KEY_U) {
            pressedRed = true;
        }
        if (key == Input.KEY_I) {
            pressedGreen = true;
        }
        if (key == Input.KEY_O) {
            pressedBlue = true;
        }
        if (key == Input.KEY_P) {
            pressedYellow = true;
        }

        // Write beat map from linkedlist to file
        if (key == Input.KEY_ESCAPE) {
            try {
                for (String line : beatMapLines) {
                    bw.write(line);
                }

                bw.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            System.exit(0);
        }

        // Pause/Play music
        if (key == Input.KEY_SPACE) {
            if (music.playing()) {
                music.pause();
            } else {
                music.resume();
            }
        }

        if (key == Input.KEY_S) {
            music.play();
        }

        if (key == Input.KEY_LEFT) {
            if (music.playing()) {

                // check if can still backtrack by 2 seconds
                if (music.getPosition() - 2 >= 0 || beatMapLines.size() == 0) {
                    for (int i = 0; i <= 120; i ++) {
                        beatMapLines.remove(beatMapLines.size() - 1);
                    }
                    music.setPosition(music.getPosition() - 2f);    // set music position to 2 seconds before
                } else {
                    music.setPosition(0);
                    beatMapLines.clear();
                }

            } else {
                music.resume();
                if (music.getPosition() - 2 >= 0 || beatMapLines.size() == 0) {
                    for (int i = 0; i <= 120; i ++) {
                        beatMapLines.remove(beatMapLines.size() - 1);
                    }
                    music.setPosition(music.getPosition() - 2f);
                } else {
                    music.setPosition(0);
                    beatMapLines.clear();
                }
                music.pause();
            }
        }

    }

    @Override
    public void keyReleased(int key, char pressedKey) {

    }
}


text:
import { Indicator, IndicatorInput } from '../indicator/indicator';
/**
 * Created by AAravindan on 5/8/16.
 */
"use strict";
export class MDMInput extends IndicatorInput {
}
;
export class MDM extends Indicator {
    constructor(input) {
        super(input);
        var lows = input.low;
        var highs = input.high;
        var format = this.format;
        if (lows.length != highs.length) {
            throw ('Inputs(low,high) not of equal size');
        }
        this.result = [];
        this.generator = (function* () {
            var minusDm;
            var current = yield;
            var last;
            while (true) {
                if (last) {
                    let upMove = (current.high - last.high);
                    let downMove = (last.low - current.low);
                    minusDm = format((downMove > upMove && downMove > 0) ? downMove : 0);
                }
                last = current;
                current = yield minusDm;
            }
        })();
        this.generator.next();
        lows.forEach((tick, index) => {
            var result = this.generator.next({
                high: highs[index],
                low: lows[index]
            });
            if (result.value !== undefined)
                this.result.push(result.value);
        });
    }
    ;
    static calculate(input) {
        Indicator.reverseInputs(input);
        var result = new MDM(input).result;
        if (input.reversedInput) {
            result.reverse();
        }
        Indicator.reverseInputs(input);
        return result;
    }
    ;
    nextValue(price) {
        return this.generator.next(price).value;
    }
    ;
}


text:
'use strict'
const cssUrlRewrite = require('css-url-rewrite')
const urlResolver = require('url').resolve
const R = require('ramda')

function fullCssUrl (params) {
  const filePath = (params.pkg.filePath[0] === '/' ? '' : '/') +
    params.pkg.filePath
  const basePath = '/raw/' + params.pkg.name + '@' + params.pkg.version +
    filePath

  function replace (url) {
    if (url.match(/^https?:/)) {
      return url
    }
    return urlResolver(basePath, url)
  }

  const replaced = cssUrlRewrite(params.content, replace)
  return R.merge(params, {
    content: replaced,
  })
}

module.exports = fullCssUrl


text:
class Note < ActiveRecord::Base
  include ChangesTracker

  self.inheritance_column = nil

  TYPE_SALARY = 'Salary'
  TYPE_PERFORMANCE_REVIEW = 'Performance Review'
  TYPE_EXIT_INTERVIEW = 'Exit Interview'
  TYPES = [
    "Recruiter's Note",
    'CV Review',
    'Message From Candidate',
    'Conversation / Call',
    'Initial Interview',
    'Tech Interview',
    'Additional Interview',
    'Test Assignment',
    'CEO Opinion',
    'Decision',
    'Recommended',
    TYPE_SALARY,
    "Manager's Note",
    TYPE_PERFORMANCE_REVIEW,
    TYPE_EXIT_INTERVIEW,
    'Other'
  ]
  FINANCE_TYPES = [TYPE_SALARY, TYPE_PERFORMANCE_REVIEW, TYPE_EXIT_INTERVIEW]

  belongs_to :person, counter_cache: true, touch: true

  validates :type, :person, :value, presence: true
  validates :type, inclusion: { in: TYPES }
end


text:
class SmartEditor < ActiveRecord::Base
  attr_accessible :image
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NewRelic.Platform.Sdk;
using NewRelic.Platform.Sdk.Processors;

namespace uniqPlugin
{
    class Program
    {
        static int Main(string[] args)
        {
            try
            {
                Runner run = new Runner();
                run.Add(new UniqAgentFactory());
                run.SetupAndRun();

            }
            catch (Exception e) {
                Console.WriteLine("Exception occurred, unable to continue.\n"+e.Message);
                return -1;
            }

            return 0;
        }

    }

    class UniqAgent : Agent
    {
        private string name;
        private string host;
        private int port;
        private string user;
        private string password;

        //Processors
        private IProcessor connectionsProcessor = new EpochProcessor();

        public override string Guid
        {
            get { return "ru.pravo.uniqplugin"; }
        }

        public override string Version
        {
            get { return "0.0.1"; }
        }

        public UniqAgent(string name, string host, int port)
        {
            this.name = name;
            this.host = host;
            this.port = port;
        }

        public override string GetAgentName()
        {
            return this.name;
        }

        public override void PollCycle()
        {
            int conn = 1;
            ReportMetric("Connections/Count", "connections", conn);
            ReportMetric("Connections/Rate", "connections/sec", connectionsProcessor.Process(conn));
        }
    }

    class UniqAgentFactory : AgentFactory
    {

        public override Agent CreateAgentWithConfiguration(IDictionary<string, object> properties)
        {
            string name = (string)properties["name"];
            string host = (string)properties["host"];
            //int port = (int)properties["port"];
            int port = Convert.ToInt32(properties["port"]);

            return new UniqAgent(name, host, port);
        }
    }
}


text:
package org.owasp.security.logging.filter;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import org.junit.Test;
import org.owasp.security.logging.SecurityMarkers;
import org.slf4j.LoggerFactory;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.spi.FilterReply;

public class MarkerFilterTest {

	@Test
	public void testDecideILoggingEvent() {
		LoggerContext lc = (LoggerContext) LoggerFactory.getILoggerFactory();

		// create a new marker filter
		MarkerFilter mkt = new MarkerFilter();
		mkt.setContext(lc);
		mkt.setMarker(SecurityMarkers.CONFIDENTIAL_MARKER_NAME);
		mkt.setOnMatch(FilterReply.ACCEPT);
		mkt.setOnMismatch(FilterReply.DENY);
		mkt.start();
		assertTrue(mkt.isStarted());

		// test a logging event with no markers
		ILoggingEvent nulEvent = new LoggingEvent();
		assertEquals(FilterReply.DENY, mkt.decide(nulEvent));

		// test a logging event with the CONFIDENTIAL marker
		LoggingEvent confidentialEvent = new LoggingEvent();
		confidentialEvent.setMarker(SecurityMarkers.CONFIDENTIAL);
		assertEquals(FilterReply.ACCEPT, mkt.decide(confidentialEvent));

		// test a logging event without the CONFIDENTIAL marker
		LoggingEvent normalEvent = new LoggingEvent();
		normalEvent.setMarker(SecurityMarkers.EVENT_SUCCESS);
		assertEquals(FilterReply.DENY, mkt.decide(nulEvent));

		Logger LOGGER = lc.getLogger(MarkerFilterTest.class);
		LOGGER.debug(SecurityMarkers.TOP_SECRET, "You should not see this!");
		LOGGER.debug(SecurityMarkers.CONFIDENTIAL,
				"Look at this confidential information!");
	}
}


text:
#include "CManager.hpp"
namespace libm2 {

    building::CManager::CManager() {
        ((void(*)(building::CManager * const))Addr::building::CManager::CManager)(this);
    }

    void building::CManager::ClearLand(DWORD dwLandID) {
        ((void(*)(building::CManager * const, DWORD))Addr::building::CManager::ClearLand__DWORD)(this, dwLandID);
    }

    void building::CManager::ClearLandByGuildID(DWORD dwGuildID) {
        ((void(*)(building::CManager * const, DWORD))Addr::building::CManager::ClearLandByGuildID__DWORD)(this, dwGuildID);
    }

    void building::CManager::DeleteObject(DWORD dwID) {
        ((void(*)(building::CManager * const, DWORD))Addr::building::CManager::DeleteObject__DWORD)(this, dwID);
    }

    void building::CManager::Destroy() {
        ((void(*)(building::CManager * const))Addr::building::CManager::Destroy)(this);
    }

    void building::CManager::FinalizeBoot() {
        ((void(*)(building::CManager * const))Addr::building::CManager::FinalizeBoot)(this);
    }

    building::CLand * building::CManager::FindLand(long lMapIndex, long x, long y) {
        return ((building::CLand * (*)(building::CManager * const, long, long, long))Addr::building::CManager::FindLand__long_long_long)(this, lMapIndex, x, y);
    }

    building::CLand * building::CManager::FindLand(DWORD dwID) {
        return ((building::CLand * (*)(building::CManager * const, DWORD))Addr::building::CManager::FindLand__DWORD)(this, dwID);
    }

    building::CLand * building::CManager::FindLandByGuild(DWORD GID) {
        return ((building::CLand * (*)(building::CManager * const, DWORD))Addr::building::CManager::FindLandByGuild__DWORD)(this, GID);
    }

    building::LPOBJECT building::CManager::FindObjectByVID(DWORD dwVID) {
        return ((building::LPOBJECT(*)(building::CManager * const, DWORD))Addr::building::CManager::FindObjectByVID__DWORD)(this, dwVID);
    }

    building::TObjectProto * building::CManager::GetObjectProto(DWORD dwVnum) {
        return ((building::TObjectProto * (*)(building::CManager * const, DWORD))Addr::building::CManager::GetObjectProto__DWORD)(this, dwVnum);
    }

    bool building::CManager::LoadLand(building::TLand * pTable) {
        return ((bool(*)(building::CManager * const, building::TLand *))Addr::building::CManager::LoadLand__building_CLand_TLand_)(this, pTable);
    }

    bool building::CManager::LoadObject(building::TObject * pTable, bool isBoot) {
        return ((bool(*)(building::CManager * const, building::TObject *, bool))Addr::building::CManager::LoadObject__building_CObject_TObject__bool)(this, pTable, isBoot);
    }

    bool building::CManager::LoadObjectProto(const building::TObjectProto * pProto, int size) {
        return ((bool(*)(building::CManager * const, const building::TObjectProto *, int))Addr::building::CManager::LoadObjectProto__const_building_CObject_TObjectProto__int)(this, pProto, size);
    }

    void building::CManager::SendLandList(LPDESC d, long lMapIndex) {
        ((void(*)(building::CManager * const, LPDESC, long))Addr::building::CManager::SendLandList__LPDESC_long)(this, d, lMapIndex);
    }

    void building::CManager::UnregisterObject(building::LPOBJECT pkObj) {
        ((void(*)(building::CManager * const, building::LPOBJECT))Addr::building::CManager::UnregisterObject__building_CLand_LPOBJECT)(this, pkObj);
    }

    void building::CManager::UpdateLand(building::TLand * pTable) {
        ((void(*)(building::CManager * const, building::TLand *))Addr::building::CManager::UpdateLand__building_CLand_TLand_)(this, pTable);
    }

    building::CManager::~CManager() {
        ((void(*)(building::CManager * const))Addr::building::CManager::__CManager)(this);
    }
}


text:
import copy
import time
from unittest import mock

import fixtures
from keystoneauth1 import exceptions as kc_exceptions
from oslo_log import log as logging

from heat.common import exception
from heat.common import template_format
from heat.common import timeutils
from heat.engine.clients.os import keystone
from heat.engine.clients.os.keystone import fake_keystoneclient as fake_ks
from heat.engine.clients.os.keystone import heat_keystoneclient as hkc
from heat.engine import scheduler
from heat.engine import stack
from heat.engine import template
from heat.objects import snapshot as snapshot_object
from heat.objects import stack as stack_object
from heat.objects import user_creds as ucreds_object
from heat.tests import common
from heat.tests import generic_resource as generic_rsrc
from heat.tests import utils

empty_template = template_format.parse('''{
  "HeatTemplateFormatVersion" : "2012-12-12",
}''')

class StackTest(common.HeatTestCase):
    def setUp(self):
        super(StackTest, self).setUp()

        self.tmpl = template.Template(copy.deepcopy(empty_template))
        self.ctx = utils.dummy_context()

    def test_delete(self):
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_with_snapshot(self):
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()
        snapshot_fake = {
            'tenant': self.ctx.tenant_id,
            'name': 'Snapshot',
            'stack_id': stack_id,
            'status': 'COMPLETE',
            'data': self.stack.prepare_abandon()
        }
        snapshot_object.Snapshot.create(self.ctx, snapshot_fake)

        self.assertIsNotNone(snapshot_object.Snapshot.get_all(
            self.ctx, stack_id))

        self.stack.delete()
        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual([], snapshot_object.Snapshot.get_all(
            self.ctx, stack_id))

    def test_delete_with_snapshot_after_stack_add_resource(self):
        tpl = {'heat_template_version': 'queens',
               'resources':
                   {'A': {'type': 'ResourceWithRestoreType'}}}
        self.stack = stack.Stack(self.ctx, 'stack_delete_with_snapshot',
                                 template.Template(tpl))
        stack_id = self.stack.store()
        self.stack.create()

        data = copy.deepcopy(self.stack.prepare_abandon())
        data['resources']['A']['resource_data']['a_string'] = 'foo'
        snapshot_fake = {
            'tenant': self.ctx.tenant_id,
            'name': 'Snapshot',
            'stack_id': stack_id,
            'status': 'COMPLETE',
            'data': data
        }
        snapshot_object.Snapshot.create(self.ctx, snapshot_fake)

        self.assertIsNotNone(snapshot_object.Snapshot.get_all(
            self.ctx, stack_id))

        new_tmpl = {'heat_template_version': 'queens',
                    'resources':
                        {'A': {'type': 'ResourceWithRestoreType'},
                         'B': {'type': 'ResourceWithRestoreType'}}}
        updated_stack = stack.Stack(self.ctx, 'update_stack_add_res',
                                    template.Template(new_tmpl))
        self.stack.update(updated_stack)
        self.assertEqual(2, len(self.stack.resources))

        self.stack.delete()
        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        self.assertEqual([], snapshot_object.Snapshot.get_all(
            self.ctx, stack_id))

    def test_delete_user_creds(self):
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)
        self.assertIsNotNone(db_s.user_creds_id)
        user_creds_id = db_s.user_creds_id
        db_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, db_s.user_creds_id)
        self.assertIsNotNone(db_creds)

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        db_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertIsNone(db_creds)
        del_db_s = stack_object.Stack.get_by_id(self.ctx,
                                                stack_id,
                                                show_deleted=True)
        self.assertIsNone(del_db_s.user_creds_id)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_user_creds_gone_missing(self):
        '''Do not block stack deletion if user_creds is missing.

        It may happen that user_creds were deleted when a delete operation was
        stopped. We should be resilient to this and still complete the delete
        operation.
        '''
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)
        self.assertIsNotNone(db_s.user_creds_id)
        user_creds_id = db_s.user_creds_id
        db_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, db_s.user_creds_id)
        self.assertIsNotNone(db_creds)

        ucreds_object.UserCreds.delete(self.ctx, user_creds_id)

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        db_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertIsNone(db_creds)
        del_db_s = stack_object.Stack.get_by_id(self.ctx,
                                                stack_id,
                                                show_deleted=True)
        self.assertIsNone(del_db_s.user_creds_id)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_user_creds_fail(self):
        '''Do not stop deleting stacks even failed deleting user_creds.

        It may happen that user_creds were incorrectly saved (truncated) and
        thus cannot be correctly retrieved (and decrypted). In this case,
        stack delete should not be stopped.
        '''
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)
        self.assertIsNotNone(db_s.user_creds_id)
        exc = exception.Error('Cannot get user credentials')
        self.patchobject(ucreds_object.UserCreds,
                         'get_by_id').side_effect = exc

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_trust(self):
        self.stub_keystoneclient()

        self.stack = stack.Stack(self.ctx, 'delete_trust', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_trust_trustor(self):
        self.stub_keystoneclient(user_id='thetrustor')
        trustor_ctx = utils.dummy_context(user_id='thetrustor')

        self.stack = stack.Stack(trustor_ctx, 'delete_trust_nt', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        user_creds_id = db_s.user_creds_id
        self.assertIsNotNone(user_creds_id)
        user_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertEqual('thetrustor', user_creds.get('trustor_user_id'))

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(trustor_ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_trust_not_trustor(self):
        # Stack gets created with trustor_ctx, deleted with other_ctx
        # then the trust delete should be with stored_ctx
        trustor_ctx = utils.dummy_context(user_id='thetrustor')
        other_ctx = utils.dummy_context(user_id='nottrustor')
        stored_ctx = utils.dummy_context(trust_id='thetrust')

        mock_kc = self.patchobject(hkc, 'KeystoneClient')
        self.stub_keystoneclient(user_id='thetrustor')

        mock_sc = self.patchobject(stack.Stack, 'stored_context')
        mock_sc.return_value = stored_ctx

        self.stack = stack.Stack(trustor_ctx, 'delete_trust_nt', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        user_creds_id = db_s.user_creds_id
        self.assertIsNotNone(user_creds_id)
        user_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertEqual('thetrustor', user_creds.get('trustor_user_id'))

        mock_kc.return_value = fake_ks.FakeKeystoneClient(user_id='nottrustor')

        loaded_stack = stack.Stack.load(other_ctx, self.stack.id)
        loaded_stack.delete()
        mock_sc.assert_called_with()

        db_s = stack_object.Stack.get_by_id(other_ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         loaded_stack.state)

    def test_delete_trust_backup(self):
        class FakeKeystoneClientFail(fake_ks.FakeKeystoneClient):
            def delete_trust(self, trust_id):
                raise Exception("Shouldn't delete")

        mock_kcp = self.patchobject(keystone.KeystoneClientPlugin, '_create',
                                    return_value=FakeKeystoneClientFail())

        self.stack = stack.Stack(self.ctx, 'delete_trust', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete(backup=True)

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual(self.stack.state,
                         (stack.Stack.DELETE, stack.Stack.COMPLETE))
        mock_kcp.assert_called_once_with()

    def test_delete_trust_nested(self):
        class FakeKeystoneClientFail(fake_ks.FakeKeystoneClient):
            def delete_trust(self, trust_id):
                raise Exception("Shouldn't delete")

        self.stub_keystoneclient(fake_client=FakeKeystoneClientFail())

        self.stack = stack.Stack(self.ctx, 'delete_trust_nested', self.tmpl,
                                 owner_id='owner123')
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)
        user_creds_id = db_s.user_creds_id
        self.assertIsNotNone(user_creds_id)
        user_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertIsNotNone(user_creds)

        self.stack.delete()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        user_creds = ucreds_object.UserCreds.get_by_id(
            self.ctx, user_creds_id)
        self.assertIsNotNone(user_creds)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_trust_fail(self):
        class FakeKeystoneClientFail(fake_ks.FakeKeystoneClient):
            def delete_trust(self, trust_id):
                raise kc_exceptions.Forbidden("Denied!")

        mock_kcp = self.patchobject(keystone.KeystoneClientPlugin, '_create',
                                    return_value=FakeKeystoneClientFail())

        self.stack = stack.Stack(self.ctx, 'delete_trust', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete()

        mock_kcp.assert_called_with()
        self.assertEqual(2, mock_kcp.call_count)

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_deletes_project(self):
        fkc = fake_ks.FakeKeystoneClient()
        fkc.delete_stack_domain_project = mock.Mock()

        mock_kcp = self.patchobject(keystone.KeystoneClientPlugin, '_create',
                                    return_value=fkc)

        self.stack = stack.Stack(self.ctx, 'delete_trust', self.tmpl)
        stack_id = self.stack.store()

        self.stack.set_stack_user_project_id(project_id='aproject456')

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete()

        mock_kcp.assert_called_with()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.COMPLETE),
                         self.stack.state)
        fkc.delete_stack_domain_project.assert_called_once_with(
            project_id='aproject456')

    def test_delete_rollback(self):
        self.stack = stack.Stack(self.ctx, 'delete_rollback_test',
                                 self.tmpl, disable_rollback=False)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete(action=self.stack.ROLLBACK)

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNone(db_s)
        self.assertEqual((stack.Stack.ROLLBACK, stack.Stack.COMPLETE),
                         self.stack.state)

    def test_delete_badaction(self):
        self.stack = stack.Stack(self.ctx, 'delete_badaction_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        self.stack.delete(action="wibble")

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)
        self.assertEqual((stack.Stack.DELETE, stack.Stack.FAILED),
                         self.stack.state)

    def test_stack_delete_timeout(self):
        self.stack = stack.Stack(self.ctx, 'delete_test', self.tmpl)
        stack_id = self.stack.store()

        db_s = stack_object.Stack.get_by_id(self.ctx, stack_id)
        self.assertIsNotNone(db_s)

        def dummy_task():
            while True:
                yield

        start_time = time.time()
        mock_tg = self.patchobject(scheduler.DependencyTaskGroup, '__call__',
                                   return_value=dummy_task())
        mock_wallclock = self.patchobject(timeutils, 'wallclock')
        mock_wallclock.side_effect = [
            start_time,
            start_time + 1,
            start_time + self.stack.timeout_secs() + 1
        ]

        self.stack.delete()

        self.assertEqual((stack.Stack.DELETE, stack.Stack.FAILED),
                         self.stack.state)
        self.assertEqual('Delete timed out', self.stack.status_reason)

        mock_tg.assert_called_once_with()
        mock_wallclock.assert_called_with()
        self.assertEqual(3, mock_wallclock.call_count)

    def test_stack_delete_resourcefailure(self):
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}

        mock_rd = self.patchobject(generic_rsrc.GenericResource,
                                   'handle_delete',
                                   side_effect=Exception('foo'))

        self.stack = stack.Stack(self.ctx, 'delete_test_fail',
                                 template.Template(tmpl))

        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)

        self.stack.delete()

        mock_rd.assert_called_once_with()
        self.assertEqual((self.stack.DELETE, self.stack.FAILED),
                         self.stack.state)
        self.assertEqual('Resource DELETE failed: Exception: '
                         'resources.AResource: foo',
                         self.stack.status_reason)

    def test_delete_stack_with_resource_log_is_clear(self):
        debug_logger = self.useFixture(
            fixtures.FakeLogger(level=logging.DEBUG,
                                format="%(levelname)8s [%(name)s] "
                                       "%(message)s"))
        tmpl = {'HeatTemplateFormatVersion': '2012-12-12',
                'Resources': {'AResource': {'Type': 'GenericResourceType'}}}
        self.stack = stack.Stack(self.ctx, 'delete_log_test',
                                 template.Template(tmpl))
        self.stack.store()
        self.stack.create()
        self.assertEqual((self.stack.CREATE, self.stack.COMPLETE),
                         self.stack.state)
        self.stack.delete()
        self.assertNotIn("destroy from None running",
                         debug_logger.output)

    def test_stack_user_project_id_delete_fail(self):

        class FakeKeystoneClientFail(fake_ks.FakeKeystoneClient):
            def delete_stack_domain_project(self, project_id):
                raise kc_exceptions.Forbidden("Denied!")

        mock_kcp = self.patchobject(keystone.KeystoneClientPlugin, '_create',
                                    return_value=FakeKeystoneClientFail())

        self.stack = stack.Stack(self.ctx, 'user_project_init',
                                 self.tmpl,
                                 stack_user_project_id='aproject1234')
        self.stack.store()
        self.assertEqual('aproject1234', self.stack.stack_user_project_id)
        db_stack = stack_object.Stack.get_by_id(self.ctx, self.stack.id)
        self.assertEqual('aproject1234', db_stack.stack_user_project_id)

        self.stack.delete()

        mock_kcp.assert_called_with()
        self.assertEqual((stack.Stack.DELETE, stack.Stack.FAILED),
                         self.stack.state)
        self.assertIn('Error deleting project', self.stack.status_reason)


text:
@implementation UIView (NSLayoutConstraints)

- (void)clappr_addSubviewMatchingFrameOfView:(UIView *)view
{
    [self addSubview:view];

    view.translatesAutoresizingMaskIntoConstraints = NO;

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"|[view]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];

    [self addConstraints:[NSLayoutConstraint constraintsWithVisualFormat:@"V:|[view]|"
                                                                      options:0
                                                                      metrics:nil
                                                                        views:NSDictionaryOfVariableBindings(view)]];
}

@end


text:
              {{ user.firstName + " " + user.lastName }}

              {{user.roles.toString()}}

            <button type="button" class="btn btn-success btn-sm">Follow</button>
            <button type="button" class="btn btn-danger btn-sm ">Message</button>

                  Overview

                  Account Settings

                  Tasks

                  Help

First Name

Last Name

Email

Provider

Created

Roles


text:
require 'pattern_deployer'

##~ @file = source2swagger.namespace("uploaded_file")
##~ @file.basePath = "<%= request.protocol + request.host_with_port %>/api"
##~ @file.resourcePath = "/uploaded_files"
##~ @file.swaggerVersion = "1.1"
##~ @file.apiVersion = "0.2"
##
##~ errors = []
##~ errors << {:reason => "user provided invalid parameter(s)", :code => 400}
##~ errors << {:reason => "user haven't logined", :code => 401}
##~ errors << {:reason => "user doesnot have permission for this operation", :code => 403}
##~ errors << {:reason => "some weird error occurs, possibly due to bug(s)", :code => 500}
##
##~ @clouds = ["ec2", "openstack"]
##~ @types_descs = {}
##~ @types_descs["identity_file"] = "Identity file contains private key that is used to ssh to the deployed instance. An identity file should match a keypair of the cloud and should have an suffix '.pem'"
##~ @types_descs["war_file"] = "Java application archive. An war file should have suffix '.war'"
##~ @types_descs["sql_script_file"] = "An sql script file which is used to setup the schema/tables of database"
##~ @file_type_desc = "
File types

type	description

" + @types_descs.sort.map{|key, value| "
#{key}	#{value}
"}.join + "
"
##
## * Model UploadedFile
##
##~ model = @file.models.UploadedFile
##~ model.id = "UploadedFile"
##~ fields = model.properties
##
##~ field = fields.id
##~ field.set :type => "int", :description => "The id of the uploaded file"
##
##~ field = fields.fileName
##~ field.set :type => "string", :description => "The name of the uploaded file"
##
##~ field = fields.fileType
##~ field.set :type => "string", :description => "The type of the uploaded file"
##~ field.allowableValues = {:valueType => "LIST", :values => @types_descs.keys}
##
##~ field = fields.forCloud
##~ field.set :type => "string", :description => "The cloud that the identity file belongs to"
##~ field.allowableValues = {:valueType => "LIST", :values => @clouds}
##
##~ field = fields.keyPairId
##~ field.set :type => "string", :description => "The key pair id of the identity file"
##
##~ field = fields.link
##~ field.set :type => "string", :description => "The link of the uploaded file"
##
## * Model UploadedFiles
##
##~ model = @file.models.UploadedFiles
##~ model.id = "UploadedFiles"
##~ fields = model.properties
##
##~ field = fields.all
##~ field.set :type => "List", :description => "The information of the uploaded files", :items => {:$ref => "UploadedFile"}
##
class UploadedFilesController < RestfulController

  include PatternDeployer::Errors

  ####
  ##~ api = @file.apis.add
  ##~ api.path = "/uploaded_files"
  ##~ api.description = "Show a list of uploaded files"
  ##~ op = api.operations.add
  ##~ op.set :httpMethod => "GET", :nickname => "getFiles", :deprecated => false, :responseClass => "UploadedFiles"
  ##~ op.summary = api.description
  ##
  ##~ errors.each{|err| op.errorResponses.add err if err[:code] != 400}
  ##
  def index
    @files = get_resources_readable_by_me(UploadedFile.all)
    render :formats => "json"
  end

  ####
  ##~ api = @file.apis.add
  ##~ api.path = "/uploaded_files"
  ##~ api.description = "Upload a file"
  ##~ op = api.operations.add
  ##~ op.set :httpMethod => "POST", :nickname => "createFile", :deprecated => false, :responseClass => "UploadedFile"
  ##~ op.summary = api.description
  ##~ op.notes = "User need to provide a name for the created file. Depending on file type, user may need to fill additional parameter(s)" + @file_type_desc
  ##
  ##~ errors.each{|err| op.errorResponses.add err}
  ##
  ##  * declaring parameters
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "file", :dataType => "file", :allowMultiple => false, :required => true, :paramType => "body"
  ##~ param.description = "The uploaded file"
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "file_type", :dataType => "string", :allowMultiple => false, :required => true, :paramType => "query"
  ##~ param.allowableValues = {:valueType => "LIST", :values => @types_descs.keys}
  ##~ param.description = "The type of the uploaded file"
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "file_name", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
  ##~ param.description = "The name of the uploaded file. Use this parameter if user want a name different from the orignal file name."
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "key_pair_id", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
  ##~ param.description = "The key pair id of the identify file"
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "for_cloud", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
  ##~ param.allowableValues = {:valueType => "LIST", :values => @clouds}
  ##~ param.description = "The cloud where this key pair belongs to"
  ##
  def create
    if file_type = params[:file_type]
      file_type = file_type.downcase
    else
      err_msg = "The request doesnot container parameter 'file_type'."
      fail ParametersValidationError, err_msg
    end

    if file_io = params[:file]
      default_file_name = file_io.original_filename
    else
      err_msg = "The request doesnot container parameter 'file'."
      fail ParametersValidationError, err_msg
    end

    if file_type == "identity_file"
      @file = IdentityFile.new(:file_name => params[:file_name] || default_file_name,
                               :key_pair_id => params[:key_pair_id],
                               :for_cloud => params[:for_cloud] && params[:for_cloud].downcase,
                               :owner => current_user)
    elsif file_type == "war_file"
      @file = WarFile.new(:file_name => params[:file_name] || default_file_name,
                          :owner => current_user)
    elsif file_type == "sql_script_file"
      @file = SqlScriptFile.new(:file_name => params[:file_name] || default_file_name,
                                :owner => current_user)
    else
      err_msg = "Unsupported type of file #{file_type}, only 'identity_file', 'war_file', or 'sql_script_file' is supported."
      fail ParametersValidationError, err_msg
    end

    @file.upload(file_io)

    if @file.save
      render :formats => "json", :action => "show"
    else
      error = ParametersValidationError.new
      error.active_record = @file
      fail error
    end
  end

  ####
  ##~ api = @file.apis.add
  ##~ api.set :path => "/uploaded_files/{id}"
  ##~ api.description = "Delete the uploaded file by id"
  ##~ op = api.operations.add
  ##~ op.set :httpMethod => "GET", :nickname => "getFileById", :deprecated => false, :responseClass => "UploadedFile"
  ##~ op.summary = api.description
  ##
  ##~ errors.each{|err| op.errorResponses.add err}
  ##
  ##  * declaring parameters
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "id", :dataType => "int", :allowMultiple => false, :required => true, :paramType => "path"
  ##~ param.description = "The unique id of the uploaded file"
  ##
  def show
    @file = UploadedFile.find(params[:id])
    render :formats => "json"
  end

  ####
  ##~ api = @file.apis.add
  ##~ api.set :path => "/uploaded_files/{id}"
  ##~ api.description = "Delete the uploaded file by id"
  ##~ op = api.operations.add
  ##~ op.set :httpMethod => "DELETE", :nickname => "deleteFileById", :deprecated => false, :responseClass => "UploadedFiles"
  ##~ op.summary = api.description
  ##
  ##~ errors.each{|err| op.errorResponses.add err}
  ##
  ##  * declaring parameters
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "id", :dataType => "int", :allowMultiple => false, :required => true, :paramType => "path"
  ##~ param.description = "The unique id of uploaded file"
  ##
  def destroy
    UploadedFile.find(params[:id]).destroy

    @files = get_resources_readable_by_me(UploadedFile.all)
    render :formats => "json", :action => "index"
  end

  module FileOp
    RENAME = "rename"
    REUPLOAD = "reupload"
  end

  ####
  ##~ api = @file.apis.add
  ##~ api.set :path => "/uploaded_files/{id}"
  ##~ api.description = "Modify the uploaded file by id"
  ##~ op = api.operations.add
  ##~ op.set :httpMethod => "PUT", :nickname => "modifyFileById", :deprecated => false, :responseClass => "UploadedFile"
  ##~ op.summary = api.description
  ##
  ##~ errors.each{|err| op.errorResponses.add err}
  ##
  ##  * declaring parameters
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "id", :dataType => "int", :allowMultiple => false, :required => true, :paramType => "path"
  ##~ param.description = "The unique id of uploaded file"
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "operation", :dataType => "string", :allowMultiple => false, :required => true, :paramType => "query"
  ##~ param.description = "The operation to execute"
  ##~ param.allowableValues = {:valueType => "LIST", :values => ["rename", "reupload"]}
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "file", :dataType => "file", :allowMultiple => false, :required => false, :paramType => "body"
  ##~ param.description = "The new file. Used with 'reupload' operation"
  ##
  ##~ param = op.parameters.add
  ##~ param.set :name => "file_name", :dataType => "string", :allowMultiple => false, :required => false, :paramType => "query"
  ##~ param.description = "The new file name. Used with 'rename' operation"
  ##
  def update
    operation = params[:operation]
    if operation.nil?
      err_msg = "Parameter 'operation' is missing."
      fail ParametersValidationError, err_msg
    end

    @file = UploadedFile.find(params[:id])

    case operation
    when FileOp::RENAME
      fail ParametersValidationError, "parameter 'file_name' is missing." unless params[:file_name]
      @file.rename(params[:file_name])
    when FileOp::REUPLOAD
      fail ParametersValidationError, "parameter 'file' is missing." unless params[:file]
      @file.reupload(params[:file])
    else
      err_msg = "Invalid operation. Supported operations are #{get_operations(FileOp).join(',')}."
      fail ParametersValidationError, err_msg
    end

    render :formats => "json", :action => "show"
  end
end


text:
<link rel="import" href="..\..\bower_components/polymer/polymer.html">
<link rel="import" href="../../bower_components/paper-icon-button/paper-icon-button.html">
<link rel="import" href="../../bower_components/paper-input/paper-input.html">
<link rel="import" href="../../bower_components/paper-item/paper-item.html">
<link rel="import" href="../../bower_components/paper-button/paper-button.html">
<link rel="import" href="../../bower_components/paper-styles/paper-styles.html">
<link rel="import" href="../../bower_components/paper-listbox/paper-listbox.html">
<link rel="import" href="../../bower_components/paper-tabs/paper-tabs.html">
<link rel="import" href="../../bower_components/paper-tabs/paper-tab.html">
<link rel="import" href="../transport-service/transport-service.html">
<link rel="import" href="../summary-item-card/summary-item-card.html">
<link rel="import" href="../summarydrop-item-card/summarydrop-item-card.html">
<link rel="stylesheet" type="text/css" href="../styles/styles.css">

<dom-module id="summary-report">
  <template>

<paper-item>
Pick Up
</paper-item>

        <paper-tabs selected="0">
          <paper-tab>Route</paper-tab>
          <paper-tab>Total No Students</paper-tab>
          <paper-tab>Fee Paid</paper-tab>
          <paper-tab>Total Fee</paper-tab>
        </paper-tabs>

      <template  is="dom-repeat" items="{{summaryarr}}" as="view">

      </template>

<paper-item>
Drop
</paper-item>

        <paper-tabs selected="0">
          <paper-tab>Route</paper-tab>
          <paper-tab>Total No Students</paper-tab>
          <paper-tab>Fee Paid</paper-tab>
          <paper-tab>Total Fee</paper-tab>
        </paper-tabs>

      <template  is="dom-repeat" items="{{summarydroparr}}" as="views">
        <summarydrop-item-card routes="{{views.route_name}}" totalstus="{{views.total_students}}" feepaids="{{views.fee_paid}}" feess="{{views.total_fee}}"></summarydrop-item-card>
      </template>

        <paper-button class="button" style="margin-top: 0%; height: 35px;" id="print" on-click="print">Print</paper-button>

      <transport-service id="service"></transport-service>

  </template>

</dom-module>


text:
package com.jhlabs.image;

import java.awt.Point;
import java.awt.Rectangle;

/**
 * A filter which rotates an image. These days this is easier done with Java2D, but this filter remains.
 */
public class RotateFilter extends TransformFilter {

  private float angle;
  private float cos, sin;
  private boolean resize = true;

  /**
   * Construct a RotateFilter.
   */
  public RotateFilter() {
    this(ImageMath.PI);
  }

  /**
   * Construct a RotateFilter.
   *
   * @param angle the angle to rotate
   */
  public RotateFilter(float angle) {
    this(angle, true);
  }

  /**
   * Construct a RotateFilter.
   *
   * @param angle  the angle to rotate
   * @param resize true if the output image should be resized
   */
  public RotateFilter(float angle, boolean resize) {
    setAngle(angle);
    this.resize = resize;
  }

  /**
   * Specifies the angle of rotation.
   *
   * @param angle the angle of rotation.
   * @angle
   * @see #getAngle
   */
  public void setAngle(float angle) {
    this.angle = angle;
    cos = (float) Math.cos(this.angle);
    sin = (float) Math.sin(this.angle);
  }

  /**
   * Returns the angle of rotation.
   *
   * @return the angle of rotation.
   * @see #setAngle
   */
  public float getAngle() {
    return angle;
  }

  @Override
  protected void transformSpace(Rectangle rect) {
    if (resize) {
      Point out = new Point(0, 0);
      int minx = Integer.MAX_VALUE;
      int miny = Integer.MAX_VALUE;
      int maxx = Integer.MIN_VALUE;
      int maxy = Integer.MIN_VALUE;
      int w = rect.width;
      int h = rect.height;
      int x = rect.x;
      int y = rect.y;

      for (int i = 0; i < 4; i++) {
        switch (i) {
          case 0:
            transform(x, y, out);
            break;
          case 1:
            transform(x + w, y, out);
            break;
          case 2:
            transform(x, y + h, out);
            break;
          case 3:
            transform(x + w, y + h, out);
            break;
        }
        minx = Math.min(minx, out.x);
        miny = Math.min(miny, out.y);
        maxx = Math.max(maxx, out.x);
        maxy = Math.max(maxy, out.y);
      }

      rect.x = minx;
      rect.y = miny;
      rect.width = maxx - rect.x;
      rect.height = maxy - rect.y;
    }
  }

  private void transform(int x, int y, Point out) {
    out.x = (int) ((x * cos) + (y * sin));
    out.y = (int) ((y * cos) - (x * sin));
  }

  @Override
  protected void transformInverse(int x, int y, float[] out) {
    out[0] = (x * cos) - (y * sin);
    out[1] = (y * cos) + (x * sin);
  }

  public String toString() {
    return "Rotate " + (int) (angle * 180 / Math.PI);
  }
}


text:
package cmd

import (
	"fmt"
	"time"

	restapi "github.com/cilium/cilium/api/v1/server/restapi/metrics"
	"github.com/cilium/cilium/pkg/api"
	"github.com/cilium/cilium/pkg/metrics"
	"github.com/cilium/cilium/pkg/option"
	"github.com/cilium/cilium/pkg/spanstat"

	"github.com/go-openapi/runtime/middleware"
	"github.com/prometheus/client_golang/prometheus"
)

type getMetrics struct {
	daemon *Daemon
}

// NewGetMetricsHandler returns the metrics handler
func NewGetMetricsHandler(d *Daemon) restapi.GetMetricsHandler {
	return &getMetrics{daemon: d}
}

func (h *getMetrics) Handle(params restapi.GetMetricsParams) middleware.Responder {
	metrics, err := metrics.DumpMetrics()
	if err != nil {
		return api.Error(
			restapi.GetMetricsInternalServerErrorCode,
			fmt.Errorf("Cannot gather metrics from daemon"))
	}

	return restapi.NewGetMetricsOK().WithPayload(metrics)
}

func initMetrics() <-chan error {
	var errs <-chan error

	if option.Config.PrometheusServeAddr != "" {
		log.Infof("Serving prometheus metrics on %s", option.Config.PrometheusServeAddr)
		errs = metrics.Enable(option.Config.PrometheusServeAddr)
	}

	return errs
}

type bootstrapStatistics struct {
	overall         spanstat.SpanStat
	earlyInit       spanstat.SpanStat
	k8sInit         spanstat.SpanStat
	restore         spanstat.SpanStat
	healthCheck     spanstat.SpanStat
	initAPI         spanstat.SpanStat
	initDaemon      spanstat.SpanStat
	cleanup         spanstat.SpanStat
	bpfBase         spanstat.SpanStat
	clusterMeshInit spanstat.SpanStat
	ipam            spanstat.SpanStat
	daemonInit      spanstat.SpanStat
	mapsInit        spanstat.SpanStat
	workloadsInit   spanstat.SpanStat
	proxyStart      spanstat.SpanStat
	fqdn            spanstat.SpanStat
	enableConntrack spanstat.SpanStat
	kvstore         spanstat.SpanStat
}

func (b *bootstrapStatistics) updateMetrics() {
	for scope, stat := range b.getMap() {
		if stat.SuccessTotal() != time.Duration(0) {
			metricBootstrapTimes.WithLabelValues(scope, metrics.LabelValueOutcomeSuccess).Observe(stat.SuccessTotal().Seconds())
		}
		if stat.FailureTotal() != time.Duration(0) {
			metricBootstrapTimes.WithLabelValues(scope, metrics.LabelValueOutcomeFail).Observe(stat.FailureTotal().Seconds())
		}
	}
}

func (b *bootstrapStatistics) getMap() map[string]*spanstat.SpanStat {
	return map[string]*spanstat.SpanStat{
		"overall":         &b.overall,
		"earlyInit":       &b.earlyInit,
		"k8sInit":         &b.k8sInit,
		"restore":         &b.restore,
		"healthCheck":     &b.healthCheck,
		"initAPI":         &b.initAPI,
		"initDaemon":      &b.initDaemon,
		"cleanup":         &b.cleanup,
		"bpfBase":         &b.bpfBase,
		"clusterMeshInit": &b.clusterMeshInit,
		"ipam":            &b.ipam,
		"daemonInit":      &b.daemonInit,
		"mapsInit":        &b.mapsInit,
		"workloadsInit":   &b.workloadsInit,
		"proxyStart":      &b.proxyStart,
		"fqdn":            &b.fqdn,
		"enableConntrack": &b.enableConntrack,
		"kvstore":         &b.kvstore,
	}
}

var (
	metricBootstrapTimes prometheus.ObserverVec
)

func init() {
	metricBootstrapTimes = prometheus.NewHistogramVec(prometheus.HistogramOpts{
		Namespace: metrics.Namespace,
		Subsystem: metrics.SubsystemAgent,
		Name:      "bootstrap_seconds",
		Help:      "Duration of bootstrap sequence",
	}, []string{metrics.LabelScope, metrics.LabelOutcome})

	if err := metrics.Register(metricBootstrapTimes); err != nil {
		log.WithError(err).Fatal("unable to register prometheus metric")
	}
}


text:
COMPILER_JAR="/c/Program Files/closure-compiler/compiler.jar"
src=`sed -E -n "s/^.*\"(\w+\.js)\".*$/--js ..\/src\/\1/p" ../src/chess.include.js`
java -jar "$COMPILER_JAR" \
	--language_in ECMASCRIPT5_STRICT \
	--compilation_level ADVANCED_OPTIMIZATIONS \
	--output_wrapper "(function(){%output%})();" \
	--use_types_for_optimization \
	--summary_detail_level 3 \
	--warning_level VERBOSE \
	--js_output_file ../chess.min.js \
	--externs extern-jquery-1.9.js \
	--externs extern-jquery-ui.js \
	$src \
	--js export.js
cp ../src/chess.css ..
cp ../src/chess.ico ..
sed "s/chess\.include\.js/chess.min.js/" ../src/chess.html > ../chess.html


text:
package io.github.binaryfoo.lagotto.output

object Xsv {

  def toCsv(m: Seq[String]): String = toXsv(",", m)

  def toTsv(m: Seq[String]): String = toXsv("\t", m)

  def toXsv(separator: String, m: Seq[String]): String = m.mkString(separator)

  implicit class SeqToXsv(val m: Seq[String]) extends AnyVal {
    def toCsv: String = Xsv.toCsv(m)
    def toTsv: String = Xsv.toTsv(m)
  }

  implicit class IteratorSeqToXsv(val m: Iterator[Seq[String]]) extends AnyVal {
    def toCsv: String = m.map(Xsv.toCsv).mkString("\n")
    def toTsv: String = m.map(Xsv.toTsv).mkString("\n")
  }

}


text:
/**
 * (c) 2014 Vincenzo Cappello
 * This projected is licensed under the terms of the MIT license,
 * refer to the file LICENSE.txt.
 */

#ifndef WIN_PROPERTY_H
#define WIN_PROPERTY_H

#include <win/event.h>

#include <vector>
#include <algorithm>

namespace win {

/**
 * A simple property, fire the changedEvent event when the value change
 */
template<class T>
class Property {
public:
	Property() {
	}
	explicit Property(const T& value) :
		mValue( value ) {
	}

	virtual ~Property() {
	}

public:
	/**
     * Property getter
	 * @return the property value
	 */
    const T& operator()() const {
        return mValue;
    }

    T& operator()() {
        return mValue;
    }

	/**
     * Property setter, if the value change the changedEvent
	 * is fired.
	 * @param value the new property value
	 */
    void operator()(const T& value) {
		if (value != mValue) {
			mValue = value;
			changedEvent.fire();
		}
    }

public:
	/**
	 * Event fired when the property value is changed
	 */
	Event<> changedEvent;

protected:
	T mValue;
};

/**
 * An array of properties with type T
 */
template<class T>
class PropertyArray {
public:
	using childPropertyT = Property<T>;
	using containerT = std::vector<childPropertyT>;
	using iteratorT = typename containerT::iterator;
	using constIteratorT = typename containerT::const_iterator;

public:
	PropertyArray() {
	}
	PropertyArray(std::initializer_list<T> initList) {
		for (auto item : initList) {
			add (item);
		}
	}
	virtual ~PropertyArray() {
	}

public:
	childPropertyT& operator[](std::size_t index) {
		return mArray[index];
	}

	const childPropertyT& operator[](std::size_t index) const {
		return const_cast<childPropertyT>(mArray[index]);
	}

	void add(const T& value) {
		childPropertyT property;
		property() = value;
		mArray.push_back (property);

		itemAddedEvent.fire (value);
	}

	void remove(std::size_t index) {
		childPropertyT property = mArray[index];
		itemRemovedEvent.fire (property());

		mArray.erase (index);
	}

	iteratorT begin() {
		return mArray.begin();
	}

	constIteratorT begin() const {
		return mArray.begin();
	}

	iteratorT end() {
		return mArray.end();
	}

	constIteratorT end() const {
		return mArray.end();
	}

public:
	Event<T> itemAddedEvent;
	Event<T> itemRemovedEvent;

protected:
	containerT mArray;
};

}

#endif // WIN_PROPERTY_H


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class PaymentModel extends CI_Model {

    public function __construct() {
        parent::__construct();
    }

    public function insert($paymentdata, $reservationdata) {
        $this->db->insert('reservations', $reservationdata);
        $query = $this->db->insert('payments', $paymentdata);
        return $query;
    }

    public function eventCancelation($data) {
        $query = $this->db->insert('other_payments', $data);
        return $query;
    }

    public function guestEventCancelation($token) {
        $date = date("Y-m-d H:i:s");
        $data = array('payment_status' => 'refunded', 'updated_on' => $date);
        $query = $this->db->update('payments', $data, array('reservation_token' => $token));
        return $query;
    }

    public function guestEventApproval($token) {
        $date = date("Y-m-d H:i:s");
        $data = array('payment_status' => 'success', 'updated_on' => $date);
        $query = $this->db->update('payments', $data, array('reservation_token' => $token));
        return $query;
    }

    /**
     * @name useCoupon
     * @description Expires a coupon code
     * @param type $code
     */
    public function useCoupon($code) {
        $this->db->update('discount_coupons', array('used' => 1), array('code' => $code));
    }

    public function getPaymentId($token) {
        $sql = "SELECT payment_id, total FROM payments where reservation_token = '$token'";
        $query = $this->db->query($sql);
        return $query->result();
    }

}


text:
var logger = require('../logger/logger').logger;

module.exports.CountryEnum = {
  PL: 'PL',
  UNKNOWN: 'UNKNOWN',

  getCountry: function (country) {

    if (!this.hasOwnProperty(country)) {
      logger.warn('CountryEnum.getCountry: Unable to get country from "' + country + '"');

      return null;
    }

    return module.exports.CountryEnum[country];
  }
};