text:
require File.dirname(__FILE__) +  '/test_helper'

# see db/schema.rb for 'events' attributes
class Event < ActiveRecord::Base
  attr_accessor :bar, :foo, :dude

  validates_presence_of :title, :unless => Proc.new { in_scenario? :disable_title }

  validates_presence_of :comment, :unless => Proc.new { in_scenarios? :disable_title, :more_disable_title }

  # instance based scenario validation
  validates_presence_of :short_description, :if => Proc.new { |e| e.in_scenario? :short_required }

  in_scenario :description_required do |me|
    me.validates_length_of :description, :in => 10..2000
  end

  in_scenario :bar_required_for_title_validation do |me|
    me.validates_length_of :title, :in => 10..2000, :if => Proc.new { |r| r.bar }
  end

  in_scenario :foo_required_for_title_validation do |me|
    me.validates_length_of :title, :in => 10..2000, :if => :foo
  end

  in_scenario :dude_required_for_title_validation do |me|
    me.validates_length_of :title, :in => 10..2000, :if => 'dude'
  end

  in_scenario :without_any_options do |me|
    me.validates_presence_of :description
  end
end

describe "Model with scenarios and an validation with no :if option" do
  before do
    @valid_event = create_valid_event
    @foo = Foo.new
  end

  it "should not be valid after instantiation" do
    Event.new.should.not.be.valid
  end

  it "should be valid after instantiation with a title" do
    @valid_event.valid?
    @valid_event.should.be.valid
  end

  it "should not be valid in the scenario without description" do
    @foo.with_scenario :description_required do
      @valid_event.should.not.be.valid
    end
  end

  it "should be valid in the scenario with a description" do
    @valid_event.description = 'This is a description'

    @foo.with_scenario :description_required do
      @valid_event.should.be.valid
    end
  end

  it "should not be valid in the scenario with a description but a missing title" do
    event = Event.new(:description => 'This is a description')

    @foo.with_scenario :description_required do
      event.should.not.be.valid
    end
  end

  it "should be valid again leaving the scenario scope caused by an exception" do
    begin
      @foo.with_scenario :description_required do
        @valid_event.should.not.be.valid
        raise Exception
      end
    rescue Exception
      @valid_event.should.be.valid
    end
  end
end

describe "Model in a scenario and a validation  on description without any further options" do
  before do
    @valid_event = create_valid_event
    @foo = Foo.new
  end

  it "should not be valid if description is missing" do
    @foo.with_scenario :without_any_options do
      @valid_event.should.not.be.valid
    end
  end

  it "should be valid if description is present" do
    @valid_event.description = 'found by gzigzigzeo'

    @foo.with_scenario :without_any_options do
      @valid_event.should.be.valid
    end
  end
end

describe "Model with scenarios and an validation with :if option as a proc" do
  before do
    @valid_event = create_valid_event
    @foo = Foo.new
  end

  it "should be valid in the scenario if the validation should not occur" do
    @valid_event.bar = nil

    @foo.with_scenario :bar_required_for_title_validation do
      @valid_event.should.be.valid
    end
  end

  it "should not be valid in the scenario if the validation should occur" do
    @valid_event.bar = 'bar'

    @foo.with_scenario :bar_required_for_title_validation do
      @valid_event.should.not.be.valid
    end
  end
end

describe "Model with scenarios and an validation with :if option as a symbol" do
  before do
    @valid_event = create_valid_event
    @foo = Foo.new
  end

  it "should be valid in the scenario if the validation should not occur" do
    @valid_event.foo = nil

    @foo.with_scenario :foo_required_for_title_validation do
      @valid_event.should.be.valid
    end
  end

  it "should not be valid in the scenario if the validation should occur" do
    @valid_event.foo = 'foo'

    @foo.with_scenario :foo_required_for_title_validation do
      @valid_event.should.not.be.valid
    end
  end
end

describe "Model with scenarios and an validation with :if option as a string" do
  before do
    @valid_event = create_valid_event
    @foo = Foo.new
  end

  it "should be valid in the scenario if the validation should not occur" do
    @valid_event.dude = nil

    @foo.with_scenario :dude_required_for_title_validation do
      @valid_event.should.be.valid
    end
  end

  it "should not be valid in the scenario if the validation should occur" do
    @valid_event.dude = 'dude'

    @foo.with_scenario :dude_required_for_title_validation do
      @valid_event.should.not.be.valid
    end
  end
end

describe "Model with scenarios and an validation skipping in a scenario" do
  before do
    @event = Event.new()
    @foo = Foo.new
  end

  it "should not be valid outside the scenario without title" do
    @event.should.not.be.valid
  end

  it "should be valid in the scenario without title" do
    @foo.with_scenario :disable_title do
      @event.should.be.valid
    end
  end
end

describe "Model with scenarios and an validation skipping in some scenarios" do
  before do
    @event = Event.new()
    @foo = Foo.new
  end

  it "should not be valid outside the scenario without title" do
    @event.should.not.be.valid
  end

  it "should be valid in one scenario without title and comment" do
    @foo.with_scenario :disable_title do
      @event.should.be.valid
    end
  end

  it "should be valid in another scenario without comment but title" do
    @event.title = 'dude'
    @foo.with_scenario :more_disable_title do
      @event.should.be.valid
    end
  end
end

describe "Model with instance-based scenario validation" do
  before do
    @event = create_valid_event
    @foo = Foo.new
  end

  it "should not be valid without 'short_description' in scenario :short_required" do
    @foo.with_scenario :short_required do
      @event.should.not.be.valid
    end
  end

  it "should be valid without 'short_description' in scenario :short_required" do
    @event.short_description = 'dude'

    @foo.with_scenario :short_required do
      @event.should.be.valid
    end
  end
end


text:
import React from 'react';
import PropTypes from 'prop-types';

declare const Welcome: {
    ({ showApp }: {
        showApp: () => void;
    }): JSX.Element;
    displayName: string;
    propTypes: {
        showApp: PropTypes.Requireable<(...args: any[]) => any>;
    };
    defaultProps: {
        showApp: any;
    };
};

declare const Button: {
    ({ children, onClick, }: {
        children: React.ReactNode;
        onClick: (event: React.MouseEvent<HTMLElement, MouseEvent>) => void;
    }): JSX.Element;
    displayName: string;
    propTypes: {
        children: PropTypes.Validator<PropTypes.ReactNodeLike>;
        onClick: PropTypes.Requireable<(...args: any[]) => any>;
    };
    defaultProps: {
        onClick: () => void;
    };
};

export { Welcome, Button };

redpajama_set_name: RedPajamaGithub


text:
USE `webutil` ;
INSERT INTO `webutil`.`group` (`id`, `name`) VALUES ('1', 'group');
INSERT INTO `webutil`.`member` (`id`, `name`, `group_id`) VALUES ('1', 'member', '1');


text:
from distutils.core import setup

setup(name='devlog',
      version='0.1.0',
      description="",
      author='Chris Loew',
      author_email='cloew123@gmail.com',
      packages=['devlog',
                'devlog.commands',
                'devlog.config',
                'devlog.dates',
                'devlog.files'],
      scripts=['devlog/scripts/devlog']
     )


text:
require 'rails_helper'

RSpec.describe "users/show", :type => :view do
  before(:each) do
    @user = assign(:user, User.create!(
      :username => "Username",
      :email => "Email"
    ))
  end

  it "renders attributes in <p>" do
    render
    expect(rendered).to match(/Username/)
    expect(rendered).to match(/Email/)
  end
end


text:
class TwoWayDict(dict):
    def __len__(self):
        return dict.__len__(self) / 2

    def __setitem__(self, key, value):
        dict.__setitem__(self, key, value)
        dict.__setitem__(self, value, key)


text:
layout: post
title:  "Object Oriented Programming with Classes"
date:   2014-05-04
categories: technical
tags: ruby oop classes attr
image: object_oriented_lego.png
---

The beauty of object oriented design comes from the ability to build more efficient code that can be re-used. When new objects are created, they start at an empty state. When objects are built through classes, they can have pre-defined characteristics. We're going to look at how classes are written using instance variables and instance methods.

Let's imagine that we're a dog breeder and we can create dogs using ruby!

{% highlight ruby linenos %}
class dog
  def initialize(name, type, gender, color )
    @name = name
    @type = type
    @species = species
    print "Your dog #{@name} has been created"
  end

  def name
    @name
  end

  def type
    @type
  end

  def gender
    @gender
  end

  def color
    @color
  end

  def name=(name)
    @name = new_name
  end
end
{% endhighlight %}

Instance Variables can be mistakened for normal variables. Just like normal variables you can assign them values, read them back and do stuff to them. However, when it comes to instance variables, they always start with the @ sign (also called the at sign) so you can quickly tell them apart from the common variable. Instance variables are also only visible to the object which they belong to. When an instance variable is defined in a class, they are accessible to all other methods within that class! How convenient!

When we build a class, such as our dog example, we start by defining the contents through initialize. We do this so that every time a new instance of this class is created, it will go through this class first. In our example, this initialize function will push the inputs (name, type, gender, color) into instance variables.

But looking at this code, it looks really repetitive. We like to keep things DRY. We can refactor these using attributes method family. Check out the refactored code below:

{% highlight ruby linenos %}
class dog
  attr_reader :type, :gender, :color
  attr_accessor :name

  def initialize(name, type, gender, color )
    @name = name
    @type = type
    @species = species
    print "Your dog #{@name} has been created"
  end
end
{% endhighlight %}

There are three commonly used attr_ functions. They must be placed in the beginning of the class definition. The attr_reader as shown in line 2 of the code above is the equivalent of

{% highlight ruby linenos %}
  def type
  @type
end
{% endhighlight %}

Any multiples of the attr_reader can be separated by commas. In line 3 we use the attr_accessor method which adds a method to read and write:

{% highlight ruby linenos %}
def name
  @name
end

def name=(name)
  @name = new_name
end
{% endhighlight %}

Should we only need a method to do write, we can use the attr_writer method.


text:
<?php

namespace Magento\Framework\View\Test\Unit\Element\Message;

use Magento\Framework\Message\MessageInterface;
use Magento\Framework\View\Element\Message\InterpretationMediator;
use Magento\Framework\View\Element\Message\InterpretationStrategy;

class InterpretationMediatorTest extends \PHPUnit_Framework_TestCase
{
    /**
     * @var InterpretationStrategy | \PHPUnit_Framework_MockObject_MockObject
     */
    private $interpretationStrategy;

    /**
     * @var MessageInterface | \PHPUnit_Framework_MockObject_MockObject
     */
    private $messageMock;

    /**
     * @var InterpretationMediator
     */
    private $interpretationMediator;

    protected function setUp()
    {
        $this->interpretationStrategy = $this->getMockBuilder(
            'Magento\Framework\View\Element\Message\InterpretationStrategy'
        )
            ->disableOriginalConstructor()
            ->getMock();
        $this->messageMock = $this->getMock(
            'Magento\Framework\Message\MessageInterface'
        );

        $this->interpretationMediator = new InterpretationMediator(
            $this->interpretationStrategy
        );
    }

    public function testInterpretNotIdentifiedMessage()
    {
        $messageText = 'Very awful message. Shame.';
        $this->messageMock->expects(static::once())
            ->method('getIdentifier')
            ->willReturn(null);
        $this->messageMock->expects(static::once())
            ->method('getText')
            ->willReturn($messageText);

        static::assertSame(
            $messageText,
            $this->interpretationMediator->interpret($this->messageMock)
        );
    }

    public function testInterpretIdentifiedMessage()
    {
        $messageInterpreted = 'Awesome message. An identified message is the one we appreciate.';

        $this->messageMock->expects(static::once())
            ->method('getIdentifier')
            ->willReturn('Great identifier');
        $this->interpretationStrategy->expects(static::once())
            ->method('interpret')
            ->with($this->messageMock)
            ->willReturn($messageInterpreted);

        static::assertSame(
            $messageInterpreted,
            $this->interpretationMediator->interpret($this->messageMock)
        );
    }

    public function testInterpretIdentifiedMessageNotConfigured()
    {
        $messageStillNotInterpreted = 'One step left to call it an awesome message.';

        $this->messageMock->expects(static::once())
            ->method('getIdentifier')
            ->willReturn('Great identifier');
        $this->messageMock->expects(static::once())
            ->method('getText')
            ->willReturn($messageStillNotInterpreted);
        $this->interpretationStrategy->expects(static::once())
            ->method('interpret')
            ->with($this->messageMock)
            ->willThrowException(new \LogicException());

        static::assertSame(
            $messageStillNotInterpreted,
            $this->interpretationMediator->interpret($this->messageMock)
        );
    }
}


text:
import scala.quoted.*

object scalatest {

  inline def assert(condition: => Boolean): Unit = ${ assertImpl('condition, '{""}) }

  def assertImpl(cond: Expr[Boolean], clue: Expr[Any])(using Quotes) : Expr[Unit] = {
    import quotes.reflect.*
    import util.*

    def isImplicitMethodType(tp: TypeRepr): Boolean = tp match
      case tp: MethodType => tp.isImplicit
      case _ => false

    cond.asTerm.underlyingArgument match {
      case t @ Apply(Select(lhs, op), rhs :: Nil) =>
        ValDef.let(Symbol.spliceOwner, lhs) { left =>
          ValDef.let(Symbol.spliceOwner, rhs) { right =>
            val app = Select.overloaded(left, op, Nil, right :: Nil)
            ValDef.let(Symbol.spliceOwner, app) { result =>
              val l = left.asExpr
              val r = right.asExpr
              val b = result.asExprOf[Boolean]
              val code = '{ scala.Predef.assert($b) }
              code.asTerm
            }
          }
        }.asExprOf[Unit]
      case Apply(f @ Apply(Select(Apply(qual, lhs :: Nil), op), rhs :: Nil), implicits)
        if isImplicitMethodType(f.tpe) =>
        ValDef.let(Symbol.spliceOwner, lhs) { left =>
          ValDef.let(Symbol.spliceOwner, rhs) { right =>
            val app = Select.overloaded(Apply(qual, left :: Nil), op, Nil, right :: Nil)
            ValDef.let(Symbol.spliceOwner, Apply(app, implicits)) { result =>
              val l = left.asExpr
              val r = right.asExpr
              val b = result.asExprOf[Boolean]
              val code = '{ scala.Predef.assert($b) }
              code.asTerm
            }
          }
        }.asExprOf[Unit]
    }
  }
}


text:
layout: page
title: Blue Studios Conference
date: 2016-05-24
author: Doris Carpenter
tags: weekly links, java
status: published
summary: Praesent placerat elit sed ipsum commodo accumsan. Phasellus.
banner: images/banner/office-01.jpg
booking:
  startDate: 01/22/2016
  endDate: 01/26/2016
  ctyhocn: LASSRHX
  groupCode: BSC
published: true
---
Sed egestas est ut consectetur commodo. Pellentesque venenatis vel lorem vitae rhoncus. Praesent et rutrum dolor. Vestibulum rutrum bibendum ligula, sit amet posuere enim gravida sit amet. Donec viverra justo tincidunt lorem ultricies pharetra. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras eu diam ornare, congue sapien sit amet, ultricies dolor. Pellentesque id congue arcu, in luctus lectus. Aenean accumsan facilisis lorem, in ultrices eros.

* Nullam et tortor at sem auctor laoreet
* Maecenas non purus sagittis, placerat mauris vel, maximus augue
* Vivamus vel ante tristique, ultricies augue eget, semper turpis
* Curabitur egestas quam vel molestie facilisis.

Proin elit tortor, dignissim ornare neque a, rhoncus faucibus metus. Proin ultrices tellus ut nulla pharetra, in tincidunt erat efficitur. Mauris blandit gravida tempor. Sed elementum, massa in egestas blandit, lectus augue porttitor ipsum, eu bibendum velit dolor in nisl. Vivamus libero dui, commodo gravida dapibus et, semper sit amet diam. Donec faucibus odio ipsum, quis feugiat lacus rhoncus non. Proin a accumsan justo, aliquam lobortis sem. Fusce feugiat enim ut urna fermentum, a sagittis odio egestas. Mauris eget justo ac elit vulputate fringilla. Maecenas ac aliquam arcu. In turpis elit, vulputate sit amet augue eget, ultrices tristique nulla. Morbi non quam tincidunt, egestas felis vel, pretium urna. Nullam laoreet nulla lorem, sit amet congue elit ullamcorper ac. In odio enim, euismod id iaculis luctus, imperdiet quis magna.
Aenean maximus vestibulum sapien, a aliquam magna varius eget. Donec condimentum auctor augue id dictum. Donec semper accumsan mauris, eget condimentum arcu consectetur non. Proin molestie volutpat vulputate. Duis tincidunt vitae magna in dictum. Vivamus malesuada sagittis leo non maximus. Morbi varius elit id sapien varius, eget scelerisque nisl condimentum. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean vitae venenatis leo. Duis ac leo neque.


text:
using OpenKh.Common;
using OpenKh.Tools.Common.Wpf;
using OpenKh.Tools.ModsManager.Models;
using OpenKh.Tools.ModsManager.Services;
using OpenKh.Tools.ModsManager.Views;
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using Xe.Tools;
using Xe.Tools.Wpf.Commands;
using static OpenKh.Tools.ModsManager.Helpers;

namespace OpenKh.Tools.ModsManager.ViewModels
{
    public interface IChangeModEnableState
    {
        void ModEnableStateChanged();
    }

    public class MainViewModel : BaseNotifyPropertyChanged, IChangeModEnableState
    {
        private static Version _version = Assembly.GetEntryAssembly()?.GetName()?.Version;
        private static string ApplicationName = Utilities.GetApplicationName();
        private static string ApplicationVersion = Utilities.GetApplicationVersion();
        private Window Window => Application.Current.Windows.OfType<Window>().FirstOrDefault(x => x.IsActive);

        private DebuggingWindow _debuggingWindow = new DebuggingWindow();
        private ModViewModel _selectedValue;
        private Pcsx2Injector _pcsx2Injector;
        private Process _runningProcess;
        private bool _isBuilding;

        public string Title => ApplicationName;
        public string CurrentVersion => ApplicationVersion;
        public ObservableCollection<ModViewModel> ModsList { get; set; }
        public RelayCommand ExitCommand { get; set; }
        public RelayCommand AddModCommand { get; set; }
        public RelayCommand RemoveModCommand { get; set; }
        public RelayCommand OpenModFolderCommand { get; set; }
        public RelayCommand MoveUp { get; set; }
        public RelayCommand MoveDown { get; set; }
        public RelayCommand BuildCommand { get; set; }
        public RelayCommand RunCommand { get; set; }
        public RelayCommand BuildAndRunCommand { get; set; }
        public RelayCommand StopRunningInstanceCommand { get; set; }
        public RelayCommand WizardCommand { get; set; }
        public RelayCommand OpenLinkCommand { get; set; }

        public ModViewModel SelectedValue
        {
            get => _selectedValue;
            set
            {
                _selectedValue = value;
                OnPropertyChanged();
                OnPropertyChanged(nameof(IsModSelected));
                OnPropertyChanged(nameof(IsModInfoVisible));
                OnPropertyChanged(nameof(IsModUnselectedMessageVisible));
                OnPropertyChanged(nameof(MoveUp));
                OnPropertyChanged(nameof(MoveDown));
                OnPropertyChanged(nameof(AddModCommand));
                OnPropertyChanged(nameof(RemoveModCommand));
                OnPropertyChanged(nameof(OpenModFolderCommand));
            }
        }

        public bool IsModSelected => SelectedValue != null;

        public Visibility IsModInfoVisible => IsModSelected ? Visibility.Visible : Visibility.Collapsed;
        public Visibility IsModUnselectedMessageVisible => !IsModSelected ? Visibility.Visible : Visibility.Collapsed;

        public bool IsBuilding
        {
            get => _isBuilding;
            set
            {
                _isBuilding = value;
                Application.Current.Dispatcher.Invoke(() =>
                {
                    OnPropertyChanged(nameof(BuildCommand));
                    OnPropertyChanged(nameof(BuildAndRunCommand));
                });
            }
        }

        public bool IsRunning => _runningProcess != null;

        public MainViewModel()
        {
            Log.OnLogDispatch += (long ms, string tag, string message) =>
                _debuggingWindow.Log(ms, tag, message);

            ReloadModsList();
            SelectedValue = ModsList.FirstOrDefault();

            ExitCommand = new RelayCommand(_ => Window.Close());
            AddModCommand = new RelayCommand(_ =>
            {
                var view = new InstallModView();
                if (view.ShowDialog() != true)
                    return;

                Task.Run(async () =>
                {
                    InstallModProgressWindow progressWindow = null;
                    try
                    {
                        var name = view.RepositoryName;
                        var isZipFile = view.IsZipFile;
                        progressWindow = Application.Current.Dispatcher.Invoke(() =>
                        {
                            var progressWindow = new InstallModProgressWindow
                            {
                                ModName = isZipFile ? Path.GetFileName(name) : name,
                                ProgressText = "Initializing",
                                ShowActivated = true
                            };
                            progressWindow.Show();
                            return progressWindow;
                        });

                        await ModsService.InstallMod(name, isZipFile, progress =>
                        {
                            Application.Current.Dispatcher.Invoke(() => progressWindow.ProgressText = progress);
                        }, nProgress =>
                        {
                            Application.Current.Dispatcher.Invoke(() => progressWindow.ProgressValue = nProgress);
                        });

                        var actualName = isZipFile ? Path.GetFileNameWithoutExtension(name) : name;
                        var mod = ModsService.GetMods(new string[] { actualName }).First();
                        Application.Current.Dispatcher.Invoke(() =>
                        {
                            progressWindow.Close();
                            ModsList.Insert(0, Map(mod));
                            SelectedValue = ModsList[0];
                        });
                    }
                    catch (Exception ex)
                    {
                        Handle(ex);
                    }
                    finally
                    {
                        Application.Current.Dispatcher.Invoke(() => progressWindow?.Close());
                    }
                });
            }, _ => true);
            RemoveModCommand = new RelayCommand(_ =>
            {
                var mod = SelectedValue;
                if (Question($"Do you want to delete the mod '{mod.Source}'?", $"Remove mod {mod.Source}"))
                {
                    Handle(() =>
                    {
                        foreach (var filePath in Directory.GetFiles(mod.Path, "*", SearchOption.AllDirectories))
                        {
                            var attributes = File.GetAttributes(filePath);
                            if (attributes.HasFlag(FileAttributes.ReadOnly))
                                File.SetAttributes(filePath, attributes & ~FileAttributes.ReadOnly);
                        }

                        Directory.Delete(mod.Path, true);
                        ReloadModsList();
                    });
                }
            }, _ => IsModSelected);
            OpenModFolderCommand = new RelayCommand(_ =>
            {
                using var process = Process.Start(new ProcessStartInfo
                {
                    FileName = SelectedValue.Path,
                    UseShellExecute = true
                });
            }, _ => IsModSelected);
            MoveUp = new RelayCommand(_ => MoveSelectedModUp(), _ => CanSelectedModMoveUp());
            MoveDown = new RelayCommand(_ => MoveSelectedModDown(), _ => CanSelectedModMoveDown());
            BuildCommand = new RelayCommand(async _ =>
            {
                ResetLogWindow();
                await BuildPatches();
                CloseAllWindows();
            }, _ => !IsBuilding);
            RunCommand = new RelayCommand(async _ =>
            {
                CloseRunningProcess();
                ResetLogWindow();
                await RunGame();
            });
            BuildAndRunCommand = new RelayCommand(async _ =>
            {
                CloseRunningProcess();
                ResetLogWindow();
                if (await BuildPatches())
                    await RunGame();
            }, _ => !IsBuilding);
            StopRunningInstanceCommand = new RelayCommand(_ =>
            {
                CloseRunningProcess();
                ResetLogWindow();
            }, _ => IsRunning);
            WizardCommand = new RelayCommand(_ =>
            {
                var dialog = new SetupWizardWindow()
                {
                    ConfigGameEdition = ConfigurationService.GameEdition,
                    ConfigGameDataLocation = ConfigurationService.GameDataLocation,
                    ConfigIsoLocation = ConfigurationService.IsoLocation,
                    ConfigOpenKhGameEngineLocation = ConfigurationService.OpenKhGameEngineLocation,
                    ConfigPcsx2Location = ConfigurationService.Pcsx2Location,
                    ConfigPcReleaseLocation = ConfigurationService.PcReleaseLocation,
                    ConfigRegionId = ConfigurationService.RegionId,
                };
                if (dialog.ShowDialog() == true)
                {
                    ConfigurationService.GameEdition = dialog.ConfigGameEdition;
                    ConfigurationService.GameDataLocation = dialog.ConfigGameDataLocation;
                    ConfigurationService.IsoLocation = dialog.ConfigIsoLocation;
                    ConfigurationService.OpenKhGameEngineLocation = dialog.ConfigOpenKhGameEngineLocation;
                    ConfigurationService.Pcsx2Location = dialog.ConfigPcsx2Location;
                    ConfigurationService.PcReleaseLocation = dialog.ConfigPcReleaseLocation;
                    ConfigurationService.RegionId = dialog.ConfigRegionId;
                    ConfigurationService.IsFirstRunComplete = true;
                }
            });
            OpenLinkCommand = new RelayCommand(url => Process.Start(new ProcessStartInfo(url as string)
            {
                UseShellExecute = true
            }));

            _pcsx2Injector = new Pcsx2Injector(new OperationDispatcher());
            FetchUpdates();

            if (!ConfigurationService.IsFirstRunComplete)
                WizardCommand.Execute(null);
        }

        public void CloseAllWindows()
        {
            CloseRunningProcess();
            Application.Current.Dispatcher.Invoke(_debuggingWindow.Close);
        }

        public void CloseRunningProcess()
        {
            if (_runningProcess == null)
                return;

            _pcsx2Injector.Stop();
            _runningProcess.CloseMainWindow();
            _runningProcess.Kill();
            _runningProcess.Dispose();
            _runningProcess = null;
            OnPropertyChanged(nameof(StopRunningInstanceCommand));
        }

        private void ResetLogWindow()
        {
            if (_debuggingWindow != null)
                Application.Current.Dispatcher.Invoke(_debuggingWindow.Close);
            _debuggingWindow = new DebuggingWindow();
            Application.Current.Dispatcher.Invoke(_debuggingWindow.Show);
            _debuggingWindow.ClearLogs();
        }

        private async Task<bool> BuildPatches()
        {
            IsBuilding = true;
            var result = await ModsService.RunPacherAsync();
            IsBuilding = false;

            return result;
        }

        private Task RunGame()
        {
            ProcessStartInfo processStartInfo;
            bool isPcsx2 = false;
            switch (ConfigurationService.GameEdition)
            {
                case 0:
                    Log.Info("Starting OpenKH Game Engine");
                    processStartInfo = new ProcessStartInfo
                    {
                        FileName = ConfigurationService.OpenKhGameEngineLocation,
                        WorkingDirectory = Path.GetDirectoryName(ConfigurationService.OpenKhGameEngineLocation),
                        Arguments = $"--data \"{ConfigurationService.GameDataLocation}\" --modpath \"{ConfigurationService.GameModPath}\"",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                    };
                    break;
                case 1:
                    Log.Info("Starting PCSX2");
                    _pcsx2Injector.RegionId = ConfigurationService.RegionId;
                    _pcsx2Injector.Region = Kh2.Constants.Regions[_pcsx2Injector.RegionId];
                    _pcsx2Injector.Language = Kh2.Constants.Languages[_pcsx2Injector.RegionId];

                    processStartInfo = new ProcessStartInfo
                    {
                        FileName = ConfigurationService.Pcsx2Location,
                        WorkingDirectory = Path.GetDirectoryName(ConfigurationService.Pcsx2Location),
                        Arguments = $"\"{ConfigurationService.IsoLocation}\"",
                        RedirectStandardOutput = true,
                        RedirectStandardError = true,
                        UseShellExecute = false,
                    };
                    isPcsx2 = true;
                    break;
                default:
                    processStartInfo = null;
                    break;
            }

            if (processStartInfo == null || !File.Exists(processStartInfo.FileName))
            {
                MessageBox.Show(
                    "Unable to locate the executable. Please run the Wizard by going to the Settings menu.",
                    "Run error", MessageBoxButton.OK, MessageBoxImage.Error);
                CloseAllWindows();
                return Task.CompletedTask;
            }

            _runningProcess = new Process() { StartInfo = processStartInfo };
            _runningProcess.OutputDataReceived += (sender, e) => CaptureLog(e.Data);
            _runningProcess.ErrorDataReceived += (sender, e) => CaptureLog(e.Data);
            _runningProcess.Start();
            _runningProcess.BeginOutputReadLine();
            _runningProcess.BeginErrorReadLine();
            if (isPcsx2)
                _pcsx2Injector.Run(_runningProcess, _debuggingWindow);

            OnPropertyChanged(nameof(StopRunningInstanceCommand));
            return Task.Run(() =>
            {
                _runningProcess.WaitForExit();
                CloseAllWindows();
            });
        }

        private void CaptureLog(string data)
        {
            if (data == null)
                return;
            else if (data.Contains("err", StringComparison.InvariantCultureIgnoreCase))
                Log.Err(data);
            else if (data.Contains("wrn", StringComparison.InvariantCultureIgnoreCase))
                Log.Warn(data);
            else if (data.Contains("warn", StringComparison.InvariantCultureIgnoreCase))
                Log.Warn(data);
            else
                Log.Info(data);
        }

        private void ReloadModsList()
        {
            ModsList = new ObservableCollection<ModViewModel>(
                ModsService.GetMods(ModsService.Mods).Select(Map));
            OnPropertyChanged(nameof(ModsList));
        }

        private ModViewModel Map(ModModel mod) => new ModViewModel(mod, this);

        public void ModEnableStateChanged()
        {
            ConfigurationService.EnabledMods = ModsList
                .Where(x => x.Enabled)
                .Select(x => x.Source)
                .ToList();
            OnPropertyChanged(nameof(BuildAndRunCommand));
        }

        private void MoveSelectedModDown()
        {
            var selectedIndex = ModsList.IndexOf(SelectedValue);
            if (selectedIndex < 0)
                return;

            var item = ModsList[selectedIndex];
            ModsList.RemoveAt(selectedIndex);
            ModsList.Insert(++selectedIndex, item);
            SelectedValue = ModsList[selectedIndex];
            ModEnableStateChanged();
        }

        private void MoveSelectedModUp()
        {
            var selectedIndex = ModsList.IndexOf(SelectedValue);
            if (selectedIndex < 0)
                return;

            var item = ModsList[selectedIndex];
            ModsList.RemoveAt(selectedIndex);
            ModsList.Insert(--selectedIndex, item);
            SelectedValue = ModsList[selectedIndex];
            ModEnableStateChanged();
        }

        private bool CanSelectedModMoveDown() =>
            SelectedValue != null && ModsList.IndexOf(SelectedValue) < ModsList.Count - 1;

        private bool CanSelectedModMoveUp() =>
            SelectedValue != null && ModsList.IndexOf(SelectedValue) > 0;

        private async Task FetchUpdates()
        {
            await Task.Delay(50); // fixes a bug where the UI wanted to refresh too soon
            await foreach (var modUpdate in ModsService.FetchUpdates())
            {
                var mod = ModsList.FirstOrDefault(x => x.Source == modUpdate.Name);
                if (mod == null)
                    continue;

                Application.Current.Dispatcher.Invoke(() =>
                    mod.UpdateCount = modUpdate.UpdateCount);
            }
        }
    }
}


text:
/* $Id$ */

package org.apache.fop.fo.properties;

import java.util.List;

import org.apache.fop.fo.FObj;
import org.apache.fop.fo.PropertyList;
import org.apache.fop.fo.expr.PropertyException;
import org.apache.fop.util.CompareUtil;

/**
 * Superclass for properties that are lists of other properties
 */
public class ListProperty extends Property {

    /**
     * Inner class for creating instances of {@code ListProperty}
     */
    public static class Maker extends PropertyMaker {

        /**
         * Create a maker for the given property id.
         * @param propId ID of the property for which Maker should be created
         */
        public Maker(int propId) {
            super(propId);
        }

        /** {@inheritDoc} */
        @Override
        public Property convertProperty(Property p,
                                        PropertyList propertyList, FObj fo)
                        throws PropertyException {
            if (p instanceof ListProperty) {
                return p;
            } else {
                return new ListProperty(p);
            }
        }

    }

    /** Vector containing the list of sub-properties */
    protected final List<Property> list = new java.util.Vector<Property>();

    /**
     * Simple constructor used by subclasses to do some special processing.
     */
    protected ListProperty() {
        //nop
    }

    /**
     * Create a new instance, using the given {@link Property} as the first
     * element in the list.
     * @param prop the first property to be added to the list
     */
    public ListProperty(Property prop) {
        this();
        addProperty(prop);
    }

    /**
     * Add a new property to the list
     * @param prop Property to be added to the list
     */
    public void addProperty(Property prop) {
        list.add(prop);
    }

    /**
     * Return the {@code java.util.List} of {@link Property} instances
     * contained in this property.
     * @return the list of properties contained in this instance
     */
    @Override
    public List<Property> getList() {
        return list;
    }

    /**
     * Return the {@code java.util.List} of {@link Property} instances,
     * cast as a {@code java.lang.Object}.
     * @return this.list cast as an Object
     */
    @Override
    public Object getObject() {
        return list;
    }

    @Override
    public int hashCode() {
        return list.hashCode();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof ListProperty)) {
            return false;
        }
        ListProperty other = (ListProperty) obj;
        return CompareUtil.equal(list, other.list);
    }
}


text:
namespace Stripe.Terminal
{
    using Newtonsoft.Json;

    public class ConfigurationCreateOptions : BaseOptions
    {
        /// <summary>
        /// An object containing device type specific settings for BBPOS WisePOS E readers.
        /// </summary>
        [JsonProperty("bbpos_wisepos_e")]
        public ConfigurationBbposWiseposEOptions BbposWiseposE { get; set; }

        /// <summary>
        /// Tipping configurations for readers supporting on-reader tips.
        /// </summary>
        [JsonProperty("tipping")]
        public ConfigurationTippingOptions Tipping { get; set; }

        /// <summary>
        /// An object containing device type specific settings for Verifone P400 readers.
        /// </summary>
        [JsonProperty("verifone_p400")]
        public ConfigurationVerifoneP400Options VerifoneP400 { get; set; }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>
  <parent>
    <groupId>com.webcohesion.enunciate</groupId>
    <artifactId>enunciate-parent</artifactId>
    <version>2.9.0-SNAPSHOT</version>
  </parent>

  <artifactId>enunciate-simple-archetype</artifactId>
  <packaging>maven-archetype</packaging>
  <name>Enunciate - Simple Archetype</name>

  <build>
    <extensions>
      <extension>
        <groupId>org.apache.maven.archetype</groupId>
        <artifactId>archetype-packaging</artifactId>
        <version>2.0</version>
      </extension>
    </extensions>
    <plugins>
      <plugin>
        <artifactId>maven-archetype-plugin</artifactId>
        <version>2.0</version>
        <extensions>true</extensions>
      </plugin>
    </plugins>
  </build>
</project>


text:
package com.intellij.packaging.ui;

public abstract class SourceItemPresentation extends TreeNodePresentation {
}


text:
package anchor

import (
	"bytes"
	"encoding/binary"
	"encoding/hex"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"path/filepath"
	"time"

	"github.com/btcsuitereleases/btcd/btcjson"
	"github.com/btcsuitereleases/btcd/chaincfg"
	"github.com/btcsuitereleases/btcd/txscript"
	"github.com/btcsuitereleases/btcd/wire"
	"github.com/btcsuitereleases/btcrpcclient"
	"github.com/btcsuitereleases/btcutil"
	"github.com/davecgh/go-spew/spew"

	"github.com/FactomProject/FactomCode/common"
	"github.com/FactomProject/FactomCode/database"
	"github.com/FactomProject/FactomCode/util"
	factomwire "github.com/FactomProject/btcd/wire"
)

var (
	balances            []balance // unspent balance & address & its WIF
	cfg                 *util.FactomdConfig
	dclient, wclient    *btcrpcclient.Client
	fee                 btcutil.Amount                  // tx fee for written into btc
	dirBlockInfoMap     map[string]*common.DirBlockInfo //dbHash string as key
	db                  database.Db
	walletLocked        bool
	reAnchorAfter       = 10 // hours. For anchors that do not get bitcoin callback info for over 10 hours, then re-anchor them.
	reAnchorCheckEvery  = 1  // hour. do re-anchor check every 1 hour.
	defaultAddress      btcutil.Address
	confirmationsNeeded int

	//Server Private key for milestone 1
	serverPrivKey common.PrivateKey

	//Server Entry Credit private key
	serverECKey common.PrivateKey
	//Anchor chain ID
	anchorChainID *common.Hash
	//InmsgQ for submitting the entry to server
	inMsgQ chan factomwire.FtmInternalMsg
)

type balance struct {
	unspentResult btcjson.ListUnspentResult
	address       btcutil.Address
	wif           *btcutil.WIF
}

//AnchorRecord is used to construct anchor chain
type AnchorRecord struct {
	AnchorRecordVer int
	DBHeight        uint32
	KeyMR           string
	RecordHeight    uint32

	Bitcoin struct {
		Address     string //"1HLoD9E4SDFFPDiYfNYnkBLQ85Y51J3Zb1",
		TXID        string //"9b0fc92260312ce44e74ef369f5c66bbb85848f2eddd5a7a1cde251e54ccfdd5", BTC Hash - in reverse byte order
		BlockHeight int32  //345678,
		BlockHash   string //"00000000000000000cc14eacfc7057300aea87bed6fee904fd8e1c1f3dc008d4", BTC Hash - in reverse byte order
		Offset      int32  //87
	}
}

// SendRawTransactionToBTC is the main function used to anchor factom
// dir block hash to bitcoin blockchain
func SendRawTransactionToBTC(hash *common.Hash, blockHeight uint32) (*wire.ShaHash, error) {
	anchorLog.Debug("SendRawTransactionToBTC: hash=", hash.String(), ", dir block height=", blockHeight) //strconv.FormatUint(blockHeight, 10))
	dirBlockInfo, err := sanityCheck(hash)
	if err != nil {
		return nil, err
	}
	return doTransaction(hash, blockHeight, dirBlockInfo)
}

func doTransaction(hash *common.Hash, blockHeight uint32, dirBlockInfo *common.DirBlockInfo) (*wire.ShaHash, error) {
	b := balances[0]
	balances = balances[1:]
	anchorLog.Info("new balances.len=", len(balances))

	msgtx, err := createRawTransaction(b, hash.Bytes(), blockHeight)
	if err != nil {
		return nil, fmt.Errorf("cannot create Raw Transaction: %s", err)
	}

	shaHash, err := sendRawTransaction(msgtx)
	if err != nil {
		return nil, fmt.Errorf("cannot send Raw Transaction: %s", err)
	}

	if dirBlockInfo != nil {
		dirBlockInfo.BTCTxHash = toHash(shaHash)
	}

	return shaHash, nil
}

func sanityCheck(hash *common.Hash) (*common.DirBlockInfo, error) {
	dirBlockInfo := dirBlockInfoMap[hash.String()]
	if dirBlockInfo == nil {
		s := fmt.Sprintf("Anchor Error: hash %s does not exist in dirBlockInfoMap.\n", hash.String())
		anchorLog.Error(s)
		return nil, errors.New(s)
	}
	if dirBlockInfo.BTCConfirmed {
		s := fmt.Sprintf("Anchor Warning: hash %s has already been confirmed in btc block chain.\n", hash.String())
		anchorLog.Error(s)
		return nil, errors.New(s)
	}
	//The re-anchoring is allowed now.
	//if !common.NewHash().IsSameAs(dirBlockInfo.BTCTxHash) {
	//s := fmt.Sprintf("Anchor Warning: hash %s has already been anchored but not confirmed. btc tx hash is %s\n", hash.String(), dirBlockInfo.BTCTxHash.String())
	//anchorLog.Error(s)
	//return nil, errors.New(s)
	//}
	if dclient == nil || wclient == nil {
		s := fmt.Sprintf("\n\n$$$ WARNING: rpc clients and/or wallet are not initiated successfully. No anchoring for now.\n")
		anchorLog.Warning(s)
		return nil, errors.New(s)
	}
	if len(balances) == 0 {
		anchorLog.Warning("len(balances) == 0, start rescan UTXO *** ")
		updateUTXO()
	}
	if len(balances) == 0 {
		s := fmt.Sprintf("\n\n$$$ WARNING: No balance in your wallet. No anchoring for now.\n")
		anchorLog.Warning(s)
		return nil, errors.New(s)
	}
	return dirBlockInfo, nil
}

func createRawTransaction(b balance, hash []byte, blockHeight uint32) (*wire.MsgTx, error) {
	msgtx := wire.NewMsgTx()

	if err := addTxOuts(msgtx, b, hash, blockHeight); err != nil {
		return nil, fmt.Errorf("cannot addTxOuts: %s", err)
	}

	if err := addTxIn(msgtx, b); err != nil {
		return nil, fmt.Errorf("cannot addTxIn: %s", err)
	}

	if err := validateMsgTx(msgtx, []btcjson.ListUnspentResult{b.unspentResult}); err != nil {
		return nil, fmt.Errorf("cannot validateMsgTx: %s", err)
	}

	return msgtx, nil
}

func addTxIn(msgtx *wire.MsgTx, b balance) error {
	output := b.unspentResult
	//anchorLog.Infof("unspentResult: %s\n", spew.Sdump(output))
	prevTxHash, err := wire.NewShaHashFromStr(output.TxID)
	if err != nil {
		return fmt.Errorf("cannot get sha hash from str: %s", err)
	}
	if prevTxHash == nil {
		anchorLog.Error("prevTxHash == nil")
	}

	outPoint := wire.NewOutPoint(prevTxHash, output.Vout)
	msgtx.AddTxIn(wire.NewTxIn(outPoint, nil))
	if outPoint == nil {
		anchorLog.Error("outPoint == nil")
	}

	// OnRedeemingTx
	err = dclient.NotifySpent([]*wire.OutPoint{outPoint})
	if err != nil {
		anchorLog.Error("NotifySpent err: ", err.Error())
	}

	subscript, err := hex.DecodeString(output.ScriptPubKey)
	if err != nil {
		return fmt.Errorf("cannot decode scriptPubKey: %s", err)
	}
	if subscript == nil {
		anchorLog.Error("subscript == nil")
	}

	sigScript, err := txscript.SignatureScript(msgtx, 0, subscript, txscript.SigHashAll, b.wif.PrivKey, true)
	if err != nil {
		return fmt.Errorf("cannot create scriptSig: %s", err)
	}
	if sigScript == nil {
		anchorLog.Error("sigScript == nil")
	}

	msgtx.TxIn[0].SignatureScript = sigScript
	return nil
}

func addTxOuts(msgtx *wire.MsgTx, b balance, hash []byte, blockHeight uint32) error {
	anchorHash, err := prependBlockHeight(blockHeight, hash)
	if err != nil {
		anchorLog.Errorf("ScriptBuilder error: %v\n", err)
	}

	builder := txscript.NewScriptBuilder()
	builder.AddOp(txscript.OP_RETURN)
	builder.AddData(anchorHash)

	// latest routine from Conformal btcsuite returns 2 parameters, not 1... not sure what to do for people with the old conformal libraries :(
	opReturn, err := builder.Script()
	msgtx.AddTxOut(wire.NewTxOut(0, opReturn))
	if err != nil {
		anchorLog.Errorf("ScriptBuilder error: %v\n", err)
	}

	amount, _ := btcutil.NewAmount(b.unspentResult.Amount)
	change := amount - fee

	// Check if there are leftover unspent outputs, and return coins back to
	// a new address we own.
	if change > 0 {

		// Spend change.
		pkScript, err := txscript.PayToAddrScript(b.address)
		if err != nil {
			return fmt.Errorf("cannot create txout script: %s", err)
		}
		msgtx.AddTxOut(wire.NewTxOut(int64(change), pkScript))
	}
	return nil
}

func validateMsgTx(msgtx *wire.MsgTx, inputs []btcjson.ListUnspentResult) error {
	flags := txscript.ScriptBip16 | txscript.ScriptStrictMultiSig //ScriptCanonicalSignatures
	bip16 := time.Now().After(txscript.Bip16Activation)
	if bip16 {
		flags |= txscript.ScriptBip16
	}

	for i := range msgtx.TxIn {
		scriptPubKey, err := hex.DecodeString(inputs[i].ScriptPubKey)
		if err != nil {
			return fmt.Errorf("cannot decode scriptPubKey: %s", err)
		}
		engine, err := txscript.NewEngine(scriptPubKey, msgtx, i, flags)
		if err != nil {
			anchorLog.Errorf("cannot create script engine: %s\n", err)
			return fmt.Errorf("cannot create script engine: %s", err)
		}
		if err = engine.Execute(); err != nil {
			anchorLog.Errorf("cannot execute script engine: %s\n  === UnspentResult: %s", err, spew.Sdump(inputs[i]))
			return fmt.Errorf("cannot execute script engine: %s", err)
		}
	}
	return nil
}

func sendRawTransaction(msgtx *wire.MsgTx) (*wire.ShaHash, error) {
	//anchorLog.Debug("sendRawTransaction: msgTx=", spew.Sdump(msgtx))
	buf := bytes.Buffer{}
	buf.Grow(msgtx.SerializeSize())
	if err := msgtx.BtcEncode(&buf, wire.ProtocolVersion); err != nil {
		return nil, err
	}

	// use rpc client for btcd here for better callback info
	// this should not require wallet to be unlocked
	shaHash, err := dclient.SendRawTransaction(msgtx, false)
	if err != nil {
		return nil, fmt.Errorf("failed in rpcclient.SendRawTransaction: %s", err)
	}
	anchorLog.Info("btc txHash returned: ", shaHash) // new tx hash
	return shaHash, nil
}

func createBtcwalletNotificationHandlers() btcrpcclient.NotificationHandlers {

	ntfnHandlers := btcrpcclient.NotificationHandlers{
		OnAccountBalance: func(account string, balance btcutil.Amount, confirmed bool) {
			//go newBalance(account, balance, confirmed)
			//anchorLog.Info("wclient: OnAccountBalance, account=", account, ", balance=",
			//balance.ToUnit(btcutil.AmountBTC), ", confirmed=", confirmed)
		},

		OnWalletLockState: func(locked bool) {
			anchorLog.Info("wclient: OnWalletLockState, locked=", locked)
			walletLocked = locked
		},

		OnUnknownNotification: func(method string, params []json.RawMessage) {
			//anchorLog.Info("wclient: OnUnknownNotification: method=", method, "\nparams[0]=",
			//string(params[0]), "\nparam[1]=", string(params[1]))
		},
	}

	return ntfnHandlers
}

func createBtcdNotificationHandlers() btcrpcclient.NotificationHandlers {

	ntfnHandlers := btcrpcclient.NotificationHandlers{

		OnBlockConnected: func(hash *wire.ShaHash, height int32) {
			//anchorLog.Info("dclient: OnBlockConnected: hash=", hash, ", height=", height)
			//go newBlock(hash, height)	// no need
		},

		OnRecvTx: func(transaction *btcutil.Tx, details *btcjson.BlockDetails) {
			//anchorLog.Info("dclient: OnRecvTx: details=%#v\n", details)
			//anchorLog.Info("dclient: OnRecvTx: tx=%#v,  tx.Sha=%#v, tx.index=%d\n",
			//transaction, transaction.Sha().String(), transaction.Index())
		},

		OnRedeemingTx: func(transaction *btcutil.Tx, details *btcjson.BlockDetails) {
			//anchorLog.Info("dclient: OnRedeemingTx: details=%#v\n", details)
			//anchorLog.Info("dclient: OnRedeemingTx: tx.Sha=%#v,  tx.index=%d\n",
			//transaction.Sha().String(), transaction.Index())

			if details != nil {
				// do not block OnRedeemingTx callback
				anchorLog.Info("Anchor: saveDirBlockInfo.")
				go saveDirBlockInfo(transaction, details)
			}
		},
	}

	return ntfnHandlers
}

// InitAnchor inits rpc clients for factom
// and load up unconfirmed DirBlockInfo from leveldb
func InitAnchor(ldb database.Db, q chan factomwire.FtmInternalMsg, serverKey common.PrivateKey) {
	anchorLog.Debug("InitAnchor")
	db = ldb
	inMsgQ = q
	serverPrivKey = serverKey

	var err error
	dirBlockInfoMap, err = db.FetchAllUnconfirmedDirBlockInfo()
	if err != nil {
		anchorLog.Error("InitAnchor error - " + err.Error())
		return
	}
	anchorLog.Debug("init dirBlockInfoMap.len=", len(dirBlockInfoMap))

	if err = initRPCClient(); err != nil {
		anchorLog.Error(err.Error())
		return
	}

	if err = initWallet(); err != nil {
		anchorLog.Error(err.Error())
		return
	}

	ticker := time.NewTicker(time.Hour * time.Duration(reAnchorCheckEvery))
	go func() {
		for _ = range ticker.C {
			// check init rpc client
			if dclient == nil || wclient == nil {
				if err = initRPCClient(); err != nil {
					anchorLog.Error(err.Error())
				}
			}
			checkForReAnchor()
		}
	}()
	return
}

func initRPCClient() error {
	anchorLog.Debug("init RPC client")
	cfg = util.ReadConfig()
	certHomePath := cfg.Btc.CertHomePath
	rpcClientHost := cfg.Btc.RpcClientHost
	rpcClientEndpoint := cfg.Btc.RpcClientEndpoint
	rpcClientUser := cfg.Btc.RpcClientUser
	rpcClientPass := cfg.Btc.RpcClientPass
	certHomePathBtcd := cfg.Btc.CertHomePathBtcd
	rpcBtcdHost := cfg.Btc.RpcBtcdHost
	confirmationsNeeded = cfg.Anchor.ConfirmationsNeeded

	//Added anchor parameters
	var err error
	serverECKey, err = common.NewPrivateKeyFromHex(cfg.Anchor.ServerECKey)
	if err != nil {
		panic("Cannot parse Server EC Key from configuration file: " + err.Error())
	}
	anchorChainID, err = common.HexToHash(cfg.Anchor.AnchorChainID)
	anchorLog.Debug("anchorChainID: ", anchorChainID)
	if err != nil || anchorChainID == nil {
		panic("Cannot parse Server AnchorChainID from configuration file: " + err.Error())
	}

	// Connect to local btcwallet RPC server using websockets.
	ntfnHandlers := createBtcwalletNotificationHandlers()
	certHomeDir := btcutil.AppDataDir(certHomePath, false)
	certs, err := ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert"))
	if err != nil {
		return fmt.Errorf("cannot read rpc.cert file: %s", err)
	}
	connCfg := &btcrpcclient.ConnConfig{
		Host:         rpcClientHost,
		Endpoint:     rpcClientEndpoint,
		User:         rpcClientUser,
		Pass:         rpcClientPass,
		Certificates: certs,
	}
	wclient, err = btcrpcclient.New(connCfg, &ntfnHandlers)
	if err != nil {
		return fmt.Errorf("cannot create rpc client for btcwallet: %s", err)
	}

	// Connect to local btcd RPC server using websockets.
	dntfnHandlers := createBtcdNotificationHandlers()
	certHomeDir = btcutil.AppDataDir(certHomePathBtcd, false)
	certs, err = ioutil.ReadFile(filepath.Join(certHomeDir, "rpc.cert"))
	if err != nil {
		return fmt.Errorf("cannot read rpc.cert file for btcd rpc server: %s", err)
	}
	dconnCfg := &btcrpcclient.ConnConfig{
		Host:         rpcBtcdHost,
		Endpoint:     rpcClientEndpoint,
		User:         rpcClientUser,
		Pass:         rpcClientPass,
		Certificates: certs,
	}
	dclient, err = btcrpcclient.New(dconnCfg, &dntfnHandlers)
	if err != nil {
		return fmt.Errorf("cannot create rpc client for btcd: %s", err)
	}

	return nil
}

func unlockWallet(timeoutSecs int64) error {
	err := wclient.WalletPassphrase(cfg.Btc.WalletPassphrase, int64(timeoutSecs))
	if err != nil {
		return fmt.Errorf("cannot unlock wallet with passphrase: %s", err)
	}
	walletLocked = false
	return nil
}

func initWallet() error {
	balances = make([]balance, 0, 200)
	fee, _ = btcutil.NewAmount(cfg.Btc.BtcTransFee)
	walletLocked = true
	err := updateUTXO()
	if err == nil && len(balances) > 0 {
		defaultAddress = balances[0].address
	}
	return err
}

func updateUTXO() error {
	anchorLog.Info("updateUTXO: walletLocked=", walletLocked)
	balances = make([]balance, 0, 200)
	//if walletLocked {
	err := unlockWallet(int64(6)) //600
	if err != nil {
		return fmt.Errorf("%s", err)
	}
	//}

	unspentResults, err := wclient.ListUnspentMin(confirmationsNeeded) //minConf=1
	if err != nil {
		return fmt.Errorf("cannot list unspent. %s", err)
	}
	anchorLog.Info("updateUTXO: unspentResults.len=", len(unspentResults))

	if len(unspentResults) > 0 {
		var i int
		for _, b := range unspentResults {
			if b.Amount > fee.ToBTC() {
				balances = append(balances, balance{unspentResult: b})
				i++
			}
		}
	}
	anchorLog.Info("updateUTXO: balances.len=", len(balances))

	for i, b := range balances {
		addr, err := btcutil.DecodeAddress(b.unspentResult.Address, &chaincfg.TestNet3Params)
		if err != nil {
			return fmt.Errorf("cannot decode address: %s", err)
		}
		balances[i].address = addr

		wif, err := wclient.DumpPrivKey(addr)
		if err != nil {
			return fmt.Errorf("cannot get WIF: %s", err)
		}
		balances[i].wif = wif
		//anchorLog.Infof("balance[%d]=%s \n", i, spew.Sdump(balances[i]))
	}

	//time.Sleep(1 * time.Second)
	return nil
}

func prependBlockHeight(height uint32, hash []byte) ([]byte, error) {
	// dir block genesis block height starts with 0, for now
	// similar to bitcoin genesis block
	h := uint64(height)
	if 0xFFFFFFFFFFFF&h != h {
		return nil, errors.New("bad block height")
	}

	header := []byte{'F', 'a'}
	big := make([]byte, 8)
	binary.BigEndian.PutUint64(big, h) //height)

	newdata := append(big[2:8], hash...)
	newdata = append(header, newdata...)
	return newdata, nil
}

func saveDirBlockInfo(transaction *btcutil.Tx, details *btcjson.BlockDetails) {
	anchorLog.Debug("in saveDirBlockInfo")
	var saved = false
	for _, dirBlockInfo := range dirBlockInfoMap {
		if bytes.Compare(dirBlockInfo.BTCTxHash.Bytes(), transaction.Sha().Bytes()) == 0 {
			dirBlockInfo.BTCTxOffset = int32(details.Index)
			dirBlockInfo.BTCBlockHeight = details.Height
			btcBlockHash, _ := wire.NewShaHashFromStr(details.Hash)
			dirBlockInfo.BTCBlockHash = toHash(btcBlockHash)
			dirBlockInfo.BTCConfirmed = true
			db.InsertDirBlockInfo(dirBlockInfo)
			delete(dirBlockInfoMap, dirBlockInfo.DBMerkleRoot.String())
			anchorLog.Infof("In saveDirBlockInfo, dirBlockInfo:%s saved to db\n", spew.Sdump(dirBlockInfo))
			saved = true

			anchorRec := new(AnchorRecord)
			anchorRec.AnchorRecordVer = 1
			anchorRec.DBHeight = dirBlockInfo.DBHeight
			anchorRec.KeyMR = dirBlockInfo.DBMerkleRoot.String()
			_, recordHeight, _ := db.FetchBlockHeightCache()
			anchorRec.RecordHeight = uint32(recordHeight)
			anchorRec.Bitcoin.Address = defaultAddress.String()
			anchorRec.Bitcoin.TXID = transaction.Sha().String()
			anchorRec.Bitcoin.BlockHeight = details.Height
			anchorRec.Bitcoin.BlockHash = details.Hash
			anchorRec.Bitcoin.Offset = int32(details.Index)
			anchorLog.Info("anchor.record saved: " + spew.Sdump(anchorRec))

			err := submitEntryToAnchorChain(anchorRec)
			if err != nil {
				anchorLog.Error("Error in writing anchor into anchor chain: ", err.Error())
			}
			break
		}
	}
	// This happends when there's a double spending (for dir block 122 and its btc tx)
	// (see https://www.blocktrail.com/BTC/tx/ac82f4173259494b22f4987f1e18608f38f1ff756fb4a3c637dfb5565aa5e6cf)
	// or tx mutation / malleated
	// In this case, it will end up being re-anchored.
	if !saved {
		anchorLog.Info("Not saved to db: btc.tx=%s\n blockDetails=%s\n", spew.Sdump(transaction), spew.Sdump(details))
	}
}

func toHash(txHash *wire.ShaHash) *common.Hash {
	h := new(common.Hash)
	h.SetBytes(txHash.Bytes())
	return h
}

// UpdateDirBlockInfoMap allows factom processor to update DirBlockInfo
// when a new Directory Block is saved to db
func UpdateDirBlockInfoMap(dirBlockInfo *common.DirBlockInfo) {
	anchorLog.Debug("UpdateDirBlockInfoMap: ", spew.Sdump(dirBlockInfo))
	dirBlockInfoMap[dirBlockInfo.DBMerkleRoot.String()] = dirBlockInfo
}

func checkForReAnchor() {
	timeNow := time.Now().Unix()
	time0 := 60 * 60 * reAnchorAfter
	for _, dirBlockInfo := range dirBlockInfoMap {
		if timeNow-dirBlockInfo.Timestamp > int64(time0) {
			anchorLog.Debug("re-anchor: ")
			SendRawTransactionToBTC(dirBlockInfo.DBMerkleRoot, dirBlockInfo.DBHeight)
		}
	}
}


text:
"""
Memory
------

Provides information about memory including swap usage, system memory usage,
and general capacity information.
"""

import psutil
from pyfarm.core.utility import convert

def used_ram():
    """Amount of physical memory currently in use by applications"""
    return total_ram() - free_ram()

def free_ram():
    """Amount of physical memory free for application use"""
    return int(convert.bytetomb(psutil.virtual_memory().available))

def total_ram():
    """Total physical memory installed on the system"""
    return int(convert.bytetomb(psutil.virtual_memory().total))

def process_memory():
    """Total amount of memory in use by this process"""
    process = psutil.Process()
    return int(convert.bytetomb(process.memory_info().rss))

def total_consumption():
    """
    Total amount of memory consumed by this process and any
    child process spawned by the parent process.  This includes
    any grandchild processes.
    """
    parent = psutil.Process()
    total = parent.memory_info().rss

    for child_process in parent.children(recursive=True):
        try:
            total += child_process.memory_info().rss

        # Catch possible race condition
        except psutil.NoSuchProcess:  # pragma: no cover
            pass

    return int(convert.bytetomb(total))


text:
#include <aws/appstream/AppStreamEndpointProvider.h>

namespace Aws
{
namespace AppStream
{
namespace Endpoint
{
} // namespace Endpoint
} // namespace AppStream
} // namespace Aws


text:
using System;
using System.Reflection;
using System.Diagnostics.Contracts;

namespace System
{

    public class AppDomain
    {

        public string RelativeSearchPath
        {
          get;
        }

        public AppDomainSetup SetupInformation
        {
          get;
        }

        public string FriendlyName
        {
          get;
        }

        public string BaseDirectory
        {
          get;
        }

        public System.Security.Policy.Evidence Evidence
        {
          get;
        }

        public bool ShadowCopyFiles
        {
          get;
        }

        public string DynamicDirectory
        {
          get;
        }

        public static AppDomain! CurrentDomain
        {
          get;
        }

        public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) {

          return default(object);
        }
        public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName, Object[] activationAttributes) {

          return default(object);
        }
        public object CreateInstanceFromAndUnwrap (string assemblyName, string typeName) {

          return default(object);
        }
        public object CreateInstanceAndUnwrap (string assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) {

          return default(object);
        }
        public object CreateInstanceAndUnwrap (string assemblyName, string typeName, Object[] activationAttributes) {

          return default(object);
        }
        public object CreateInstanceAndUnwrap (string assemblyName, string typeName) {

          return default(object);
        }
        public void SetDynamicBase (string path) {

        }
        public void SetShadowCopyFiles () {

        }
        public void SetShadowCopyPath (string path) {

        }
        public static AppDomain CreateDomain (string! friendlyName, System.Security.Policy.Evidence securityInfo, AppDomainSetup info) {
            CodeContract.Requires(friendlyName != null);

          return default(AppDomain);
        }
        public static AppDomain CreateDomain (string friendlyName) {

          return default(AppDomain);
        }
        public static AppDomain CreateDomain (string friendlyName, System.Security.Policy.Evidence securityInfo, string appBasePath, string appRelativeSearchPath, bool shadowCopyFiles) {

          return default(AppDomain);
        }
        public static AppDomain CreateDomain (string friendlyName, System.Security.Policy.Evidence securityInfo) {

          return default(AppDomain);
        }
        public void DoCallBack (CrossAppDomainDelegate! callBackDelegate) {
            CodeContract.Requires(callBackDelegate != null);

        }
        public object InitializeLifetimeService () {

          return default(object);
        }
        public void SetPrincipalPolicy (System.Security.Principal.PrincipalPolicy policy) {

        }
        public void SetThreadPrincipal (System.Security.Principal.IPrincipal! principal) {
            CodeContract.Requires(principal != null);

        }
        public void SetAppDomainPolicy (System.Security.Policy.PolicyLevel! domainPolicy) {
            CodeContract.Requires(domainPolicy != null);

        }
        public static void Unload (AppDomain! domain) {
            CodeContract.Requires(domain != null);

        }
        public static int GetCurrentThreadId () {

          return default(int);
        }
        public object GetData (string! name) {
            CodeContract.Requires(name != null);

          return default(object);
        }
        public void SetData (string! name, object data) {
            CodeContract.Requires(name != null);

        }
        public void SetCachePath (string path) {

        }
        public void ClearShadowCopyPath () {

        }
        public void ClearPrivatePath () {

        }
        public void AppendPrivatePath (string path) {

        }
        public bool IsFinalizingForUnload () {

          return default(bool);
        }
        public System.Reflection.Assembly[] GetAssemblies () {

          CodeContract.Ensures(CodeContract.Result<System.Reflection.Assembly[]>() != null);
          return default(System.Reflection.Assembly[]);
        }
        [Pure][Reads(ReadsAttribute.Reads.Owned)]
        public string ToString () {

          CodeContract.Ensures(CodeContract.Result<string>() != null);
          return default(string);
        }
        public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity, String[] args, Byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) {

          return default(int);
        }
        public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity, String[] args) {

          return default(int);
        }
        public int ExecuteAssembly (string assemblyFile) {

          return default(int);
        }
        public int ExecuteAssembly (string assemblyFile, System.Security.Policy.Evidence assemblySecurity) {

          return default(int);
        }
        public System.Reflection.Assembly Load (string assemblyString, System.Security.Policy.Evidence assemblySecurity) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef, System.Security.Policy.Evidence assemblySecurity) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore, System.Security.Policy.Evidence securityEvidence) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (Byte[] rawAssembly, Byte[] rawSymbolStore) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (Byte[] rawAssembly) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (string assemblyString) {

          return default(System.Reflection.Assembly);
        }
        public System.Reflection.Assembly Load (System.Reflection.AssemblyName assemblyRef) {

          return default(System.Reflection.Assembly);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) {
            CodeContract.Requires(this != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName, bool ignoreCase, System.Reflection.BindingFlags bindingAttr, System.Reflection.Binder binder, Object[] args, System.Globalization.CultureInfo culture, Object[] activationAttributes, System.Security.Policy.Evidence securityAttributes) {
            CodeContract.Requires(this != null);
            CodeContract.Requires(assemblyName != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName, Object[] activationAttributes) {
            CodeContract.Requires(this != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName, Object[] activationAttributes) {
            CodeContract.Requires(this != null);
            CodeContract.Requires(assemblyName != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom (string! assemblyFile, string typeName, Byte[] hashValue, System.Configuration.Assemblies.AssemblyHashAlgorithm hashAlgorithm) {
            CodeContract.Requires(this != null);
            CodeContract.Requires(assemblyFile != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateComInstanceFrom (string! assemblyName, string typeName) {
            CodeContract.Requires(this != null);
            CodeContract.Requires(assemblyName != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstanceFrom (string assemblyFile, string typeName) {
            CodeContract.Requires(this != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Runtime.Remoting.ObjectHandle CreateInstance (string! assemblyName, string typeName) {
            CodeContract.Requires(this != null);
            CodeContract.Requires(assemblyName != null);

          return default(System.Runtime.Remoting.ObjectHandle);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions, bool isSynchronized) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir, System.Security.Policy.Evidence evidence) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.PermissionSet requiredPermissions, System.Security.PermissionSet optionalPermissions, System.Security.PermissionSet refusedPermissions) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, System.Security.Policy.Evidence evidence) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access, string dir) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        public System.Reflection.Emit.AssemblyBuilder DefineDynamicAssembly (System.Reflection.AssemblyName name, System.Reflection.Emit.AssemblyBuilderAccess access) {

          return default(System.Reflection.Emit.AssemblyBuilder);
        }
        [Pure][Reads(ReadsAttribute.Reads.Nothing)][ResultNotNewlyAllocated]
        public Type GetType () {

          return default(Type);
        }
        public void remove_UnhandledException (UnhandledExceptionEventHandler value) {

        }
        public void add_UnhandledException (UnhandledExceptionEventHandler value) {

        }
        public void remove_AssemblyResolve (ResolveEventHandler value) {

        }
        public void add_AssemblyResolve (ResolveEventHandler value) {

        }
        public void remove_ResourceResolve (ResolveEventHandler value) {

        }
        public void add_ResourceResolve (ResolveEventHandler value) {

        }
        public void remove_TypeResolve (ResolveEventHandler value) {

        }
        public void add_TypeResolve (ResolveEventHandler value) {

        }
        public void remove_ProcessExit (EventHandler value) {

        }
        public void add_ProcessExit (EventHandler value) {

        }
        public void remove_AssemblyLoad (AssemblyLoadEventHandler value) {

        }
        public void add_AssemblyLoad (AssemblyLoadEventHandler value) {

        }
        public void remove_DomainUnload (EventHandler value) {

        }
        public void add_DomainUnload (EventHandler value) {
        }
    }
}


text:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.minanos</groupId>
	<artifactId>minano-parent</artifactId>
	<version>0.1.1-SNAPSHOT</version>
	<packaging>pom</packaging>
	<name>minano-webapp</name>
	<url>https://github.com/minanos/minano</url>
	<description>minano webapp</description>

	<build>

		<plugins>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-surefire-plugin</artifactId>
			</plugin>

			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
			</plugin>

		</plugins>

		<pluginManagement>
			<plugins>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-surefire-plugin</artifactId>
					<version>${maven-surefire-plugin.version}</version>
				</plugin>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-compiler-plugin</artifactId>
					<version>${maven-compiler-plugin.version}</version>
					<configuration>
						<source>1.7</source>
						<target>1.7</target>
						<compilerArgument>-proc:none</compilerArgument>
					</configuration>
				</plugin>

				<plugin>
					<groupId>org.apache.maven.plugins</groupId>
					<artifactId>maven-resources-plugin</artifactId>
					<version>${maven-resources-plugin.version}</version>
				</plugin>

			</plugins>
		</pluginManagement>

	</build>

	<properties>

		<querydsl>3.2.3</querydsl>
		<querydsl.version>3.2.3</querydsl.version>

		<dozer.version>5.4.0</dozer.version>

		<thymeleaf.version>2.1.2.RELEASE</thymeleaf.version>
		<thymeleaf-extras-tiles2-version>2.1.0.RELEASE</thymeleaf-extras-tiles2-version>
		<thymeleaf-extras-springsecurity3-version>2.1.0.RELEASE</thymeleaf-extras-springsecurity3-version>
		<thymeleaf-extras-conditionalcomments-version>2.1.0.RELEASE</thymeleaf-extras-conditionalcomments-version>
		<thymeleaf-extras-layout-version>1.2</thymeleaf-extras-layout-version>

		<ehcache.version>2.7.4</ehcache.version>
		<ehcache-core.version>2.6.6</ehcache-core.version>
		<ehcache-jcache.version>1.5.0-0.5</ehcache-jcache.version>

		<!-- Spring related -->
		<spring.version>4.0.0.RELEASE</spring.version>
		<spring-security.version>3.2.0.RELEASE</spring-security.version> <!--  -->
		<javassist.version>3.18.1-GA</javassist.version>
		<aspectjweaver.version>1.7.4</aspectjweaver.version>

		<!-- web -->
		<javax.servlet-api.version>3.0.1</javax.servlet-api.version>

		<!-- marshalling -->
		<jackson.version>2.2.3</jackson.version>
		<jaxb-api.version>2.2.11</jaxb-api.version>
		<xstream.version>1.4.6</xstream.version>

		<!-- commons and utils -->
		<commons-lang3.version>3.2</commons-lang3.version>
		<guava.version>16.0-rc1</guava.version>

		<!-- UNSORTED -->
		<commons-codec.version>1.9</commons-codec.version>

		<!-- persistence -->
		<mysql-connector-java.version>5.1.28</mysql-connector-java.version> <!-- latest version on: 02.01.2014 - http://dev.mysql.com/downloads/connector/j/ -->
		<hibernate.version>4.3.0.Final</hibernate.version>
		<hibernate-jpamodelgen.version>4.3.0.Final</hibernate-jpamodelgen.version>
		<commons-dbcp.version>1.4</commons-dbcp.version>
		<querydsl.version>3.3.0</querydsl.version>
		<spring-data-jpa.version>1.4.3.RELEASE</spring-data-jpa.version>

		<h2.version>1.3.174</h2.version>
		<hsqldb.version>2.3.1</hsqldb.version>

		<validation-api.version>1.1.0.Final</validation-api.version>
		<hibernate-validator.version>5.0.2.Final</hibernate-validator.version>

		<!-- logging -->
		<org.slf4j.version>1.7.3</org.slf4j.version>
		<logback.version>1.0.11</logback.version>

		<!-- testing -->
		<org.hamcrest.version>1.3</org.hamcrest.version>
		<junit.version>4.11</junit.version>
		<mockito.version>1.9.5</mockito.version>

		<httpcore.version>4.3.1</httpcore.version>
		<httpclient.version>4.3.1</httpclient.version>

		<rest-assured.version>2.1.0</rest-assured.version>

		<!-- maven plugins -->
		<maven-surefire-plugin.version>2.16</maven-surefire-plugin.version>
		<maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>
		<maven-resources-plugin.version>2.6</maven-resources-plugin.version>
		<jrebel-maven-plugin.version>1.1.5</jrebel-maven-plugin.version>
		<cargo-maven2-plugin.version>1.4.6</cargo-maven2-plugin.version>

	</properties>

	<repositories>

		<repository>
			<id>apache-snapshot</id>
			<name>Apache Maven Snapshot Repository</name>
			<url>https://repository.apache.org/content/groups/snapshots/</url>
			<snapshots>
				<enabled>true</enabled>
			</snapshots>
		</repository>

		<repository>
			<id>repository.springsource.milestone</id>
			<name>SpringSource Milestone Repository</name>
			<url>http://repo.springsource.org/milestone</url>
		</repository>

	</repositories>

	<modules>
		<module>modules/common-client</module>
		<module>modules/common</module>
		<module>modules/test</module>
		<module>modules/api</module>
		<module>modules/runtime</module>

	</modules>

	<issueManagement>
		<url>https://github.com/minanos/minano/issues</url>
		<system>GitHub Issues</system>
	</issueManagement>

	<licenses>
		<license>
			<name>MIT License</name>
			<url>http://www.opensource.org/licenses/mit-license.php</url>
			<distribution>repo</distribution>
		</license>
	</licenses>

	<developers>
		<developer>
			<email>entation@qq.com</email>
			<name>Ent ation</name>
			<url>https://github.com/entation</url>
			<id>entation</id>
		</developer>
		<developer>
			<email>6208317@qq.com</email>
			<name>Cheng nuo</name>
			<url>https://github.com/im-qq</url>
			<id>Chengnuo</id>
		</developer>
	</developers>

	<ciManagement>
		<system>Jenkins</system>
		<url>https://minano-security.ci.cloudbees.com/</url>
	</ciManagement>

	<scm>
		<connection>scm:git:git://github.com/minanos/minano.git</connection>
		<url>scm:git:git://github.com/minanos/minano.git</url>
		<developerConnection>scm:git:git://github.com/minanos/minano.git</developerConnection>
	</scm>

</project>


text:
var logger = require('logger');
var config = require('config/config');
var util = require('util');
var events = require('events');
var playlistManager = require('./playlist');
var audioDeck = require('./audioDeck');
var stream = require('stream');
var fs = require('fs');

var Player = function(streamer) {
	events.EventEmitter.call(this);
	var self = this;
	this.streamer = streamer;
	this.connection = undefined;
	this.audioDecks = [];
	this.audioDecks.push(this.createDeck(0));
	this.audioDecks.push(this.createDeck(1));
	this.playlistManager = new playlistManager();
	this.playlistManager.on('stop', function() {
		logger.debug('Audioplayer has been stopped');
		self.stop();
		self.emit('stop');
	});
	this.interval = setInterval(function() {
		self.mainLoop();
	}, 1000);
	this.retryCount = 0;
	this.outBuffer = new Buffer(0);
	this.sentData = 0;
	this.outOfSyncCounter = 0;
	/*
		Pre compute how big is 60 seconds PCM data.
	*/
	this.preData = this.timeToData(60000);
	logger.info('Audioplayer started');
};

util.inherits(Player, events.EventEmitter);

Player.prototype.createDeck = function(id) {
	var deck = new audioDeck(this.streamer);
	deck.id = id;
	var self = this;
	deck.on('position', function(position) {
		if (this.state == 1 && (!this.song.commercial || config.commercial.crossfade)
			&& this.frameIndex >= this.frames.length - this.corssfadedFrames - 30) {

			this.fadeOut();
			if (!self.playlistManager.nextCommercial() || config.commercial.crossfade) {
				var nextDeck = self.getNextDeck(this.id);
				self.playNext(nextDeck);
			}
		}
	});
	deck.on('end', function() {
		var nextDeck = self.getNextDeck(this.id);
		self.playNext(nextDeck);
	});
	return deck;
};

Player.prototype.start = function() {
	if (undefined === this.encoder) {
		this.encoder = this.streamer.getEncoderInstance();
		this.encoder.pipe(this.connection, {end: false});
	}

	var song = this.playlistManager.getNextSong();
	this.audioDecks[0].play(song, true);
	this.startTime = Date.now();
	this.emit('songStart', song);
};

Player.prototype.mainLoop = function() {
	var min, i, j, e;
	/* 	c = Audiodeck count which have outbuff.length > 0
		p = Not idling audiodecks
	*/
	var c = 0, p = 0;
	for (i = this.audioDecks.length - 1; i >= 0; i--) {
		var d = this.audioDecks[i];
		var len = d.outBuffer.length;
		if (len > 0) {
			min = min === undefined ? len : Math.min(min, len);
			c++;
		}
		if (d.state > 0) {
			p++;
		}
	}
	if (min > 0) {
		if (p > c && this.retryCount < 2) {
			// Some audiodecks are still processing audio
			this.retryCount++;
			var self = this;
			logger.debug('c %d p %d r %d', c, p, this.retryCount);
			setTimeout(function() {
				self.mainLoop();
			}, 150);
			return;
		}
		if (this.retryCount > 0) {
			logger.debug('retry reset');
			this.retryCount = 0;
		}
		if (c == 1) {
			for (i = this.audioDecks.length - 1; i >= 0; i--) {
				e = this.audioDecks[i].outBuffer;
				if (e.length > 0) {
					this.encoder.write(e);
					this.sentData += e.length;
					this.audioDecks[i].outBuffer = new Buffer(0);
					break;
				}
			}
		}
		else {
			var tmpBuff = new Buffer(min);
			for (i = 0; i < min/2; i++) {
				var value = 0;
				for (j = this.audioDecks.length - 1; j >= 0; j--) {
					var buff = this.audioDecks[j].outBuffer;
					if (buff.length > 0) {
						value += buff.readInt16LE(i*2);
					}
				}
				// Clipping
				if (value < -32768) value = -32768;
				if (value > 32767) value = 32767;
				tmpBuff.writeInt16LE(value, i*2);
			}
			for (j = this.audioDecks.length - 1; j >= 0; j--) {
				e = this.audioDecks[j];
				if (e.outBuffer.length > 0) {
					e.outBuffer = new Buffer(e.outBuffer.slice(min));
				}
			}
			this.sentData += tmpBuff.length;
			this.encoder.write(tmpBuff);
		}

		var diff = this.timeToData(Date.now() - this.startTime);
		log.debug(util.format('Data sent %d, should be sent %d, diff %d', this.sentData, a, this.sentData - diff));
		/*
			Check if we are sending data too slow, if necessary ask AudioDeck to send more
		*/
		if (this.sentData - diff < 0) {
			this.outOfSyncCounter++;
			if (this.outOfSyncCounter > 10) {
				this.getActiveDeck().getMore(500);
				this.outOfSyncCounter = 0;
			}
		}
		else {
			this.outOfSyncCounter = 0;
		}
		// U shall not reach max int
		if (this.sentData > this.preData) {
			this.sentData -= this.preData;
			this.startTime += 60000;
		}
	}
};

Player.prototype.timeToData = function(time) {
	return Math.floor(2 * 16 * 44100 / 1000 / 8 * time);
}

Player.prototype.dataToTime = function(data) {
	return data / 2 / 16 / 44100 * 1000 * 8;
}

Player.prototype.playNext = function(deck) {
	if (deck.state === 0) {
		var song = this.playlistManager.getNextSong();
		deck.play(song, !song.commercial);
		this.emit('songStart', song);
	}
};

Player.prototype.next = function() {
	logger.debug('Next called');
	var deck = this.getActiveDeck();
	var e = {
		crossfading: deck.state == 1,
		offset: config.crossfade
	};
	if (deck.state == 1) {
		deck.fadeOut();
		if (!this.playlistManager.nextCommercial() || config.commercial.crossfade) {
			var nextDeck = this.getNextDeck(deck.id);
			this.playNext(nextDeck);
		}
	}
	else {
		deck.stop();
	}

	return e;
};

Player.prototype.getActiveDeck = function() {
	var closingDeck;
	for (var i = this.audioDecks.length - 1; i >= 0; i--) {
		var e = this.audioDecks[i];
		if (e.state === 1 || e.state === 2) return e;
		if (e.state === 3) closingDeck = e;
	}
	return closingDeck;
};

Player.prototype.getNextDeck = function(id) {
	var nextId = id + 1;
	if (nextId >= this.audioDecks.length) {
		nextId = 0;
	}
	return this.audioDecks[nextId];
};

Player.prototype.stop = function() {
	for (var i = this.audioDecks.length - 1; i >= 0; i--) {
		this.audioDecks[i].stop();
	}
};

module.exports = Player;


text:
package org.sbtidea

object SystemProps {
  val jdkName = System.getProperty("java.version").substring(0, 3)
  val languageLevel = "JDK_" + jdkName.replace(".", "_")
  val runsOnWindows = System.getProperty("os.name").contains("Windows")
  val userHome = {
    val system = System.getProperty("user.home")
    if (system.endsWith(java.io.File.separator)) system.dropRight(1) else system
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#ffffff">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <ImageView
            android:layout_width="200dp"
            android:layout_height="200dp"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:src="@drawable/loading"/>
    </RelativeLayout>
</LinearLayout>


text:
package org.projectfloodlight.openflow.protocol;

import org.projectfloodlight.openflow.protocol.*;
import org.projectfloodlight.openflow.protocol.action.*;
import org.projectfloodlight.openflow.protocol.actionid.*;
import org.projectfloodlight.openflow.protocol.bsntlv.*;
import org.projectfloodlight.openflow.protocol.errormsg.*;
import org.projectfloodlight.openflow.protocol.meterband.*;
import org.projectfloodlight.openflow.protocol.instruction.*;
import org.projectfloodlight.openflow.protocol.instructionid.*;
import org.projectfloodlight.openflow.protocol.match.*;
import org.projectfloodlight.openflow.protocol.oxm.*;
import org.projectfloodlight.openflow.protocol.queueprop.*;
import org.projectfloodlight.openflow.types.*;
import org.projectfloodlight.openflow.util.*;
import org.projectfloodlight.openflow.exceptions.*;
import org.jboss.netty.buffer.ChannelBuffer;

public interface OFPortDescPropOptical extends OFObject, OFPortDescProp {
    int getType();
    long getSupported();
    long getTxMinFreqLmda();
    long getTxMaxFreqLmda();
    long getTxGridFreqLmda();
    long getRxMinFreqLmda();
    long getRxMaxFreqLmda();
    long getRxGridFreqLmda();
    long getTxPwrMin();
    long getTxPwrMax();
    OFVersion getVersion();

    void writeTo(ChannelBuffer channelBuffer);

    Builder createBuilder();
    public interface Builder extends OFPortDescProp.Builder {
        OFPortDescPropOptical build();
        int getType();
        long getSupported();
        Builder setSupported(long supported);
        long getTxMinFreqLmda();
        Builder setTxMinFreqLmda(long txMinFreqLmda);
        long getTxMaxFreqLmda();
        Builder setTxMaxFreqLmda(long txMaxFreqLmda);
        long getTxGridFreqLmda();
        Builder setTxGridFreqLmda(long txGridFreqLmda);
        long getRxMinFreqLmda();
        Builder setRxMinFreqLmda(long rxMinFreqLmda);
        long getRxMaxFreqLmda();
        Builder setRxMaxFreqLmda(long rxMaxFreqLmda);
        long getRxGridFreqLmda();
        Builder setRxGridFreqLmda(long rxGridFreqLmda);
        long getTxPwrMin();
        Builder setTxPwrMin(long txPwrMin);
        long getTxPwrMax();
        Builder setTxPwrMax(long txPwrMax);
        OFVersion getVersion();
    }
}


text:
require 'spec_helper'
require 'dynamo/function'
require 'dynamo/function_dict_generator'
require 'dynamo/file'
require 'dynamo/project_scanner'
require 'dynamo/class_dict_generator'
require 'nokogiri'

module Dynamo
  describe ClassDictGenerator do
    let(:generator) { ClassDictGenerator.new }

    it 'can store classes' do
      klass1 = double()
      klass2 = double()
      file = double()

      generator.update('class', [klass1, file])
      generator.update('class', [klass2, file])

      expect(generator.classes.length).to eq(2)
    end

    it 'can convert filename to viml key' do
      expect(generator.filename_to_key('post.php')).to eq('wp_post')
    end

    it 'can convert pathname to viml key' do
      expect(generator.filename_to_key('foo/bar/post.php')).to eq('wp_post')
    end

    it 'can build viml variable for file' do
      expect(generator.viml_variable('wp_post')).to eq(
        "g:phpcomplete_builtin['classes']['wp_post']"
      )
    end

    it 'can build list of modules' do
      generator.modules = ['lorem', 'ipsum', 'dolor']
      output = generator.build_module_list

      expected = "let g:wordpress_active_class_extensions = [
\\ 'lorem',
\\ 'ipsum',
\\ 'dolor',
\\]"

      expect(output).to eq(expected)
    end

    it 'can build dict from file with classes' do
      node_text = <<-eos
      <project title='foo'>
        <file path="post.php" generated-path="post.html" hash="ce9edb6b7b49b028dd320ca7f72049f6" package="foo">
        <class final="false" abstract="false" namespace="" line="9" package="WordPress\\Customize">
          <extends/>
          <name>WP_Customize_Setting</name>
          <full_name>\\WP_Customize_Setting</full_name>
          <docblock line="9">
            <description>Customize Setting Class.</description>
            <long-description></long-description>
            <tag name="package" line="9" description="WordPress"/>
            <tag name="subpackage" line="9" description="Customize"/>
            <tag name="since" line="9" description="3.4.0"/>
          </docblock>
          <property static="false" visibility="public" namespace="" line="10" package="WordPress\\Customize">
            <name>$manager</name>
            <full_name>\\WP_Customize_Setting::manager</full_name>
            <default></default>
            <docblock line="10">
              <description></description>
              <long-description></long-description>
            </docblock>
          </property>
          <property static="false" visibility="public" namespace="" line="11" package="WordPress\\Customize">
            <name>$id</name>
            <full_name>\\WP_Customize_Setting::id</full_name>
            <default></default>
            <docblock line="11">
              <description></description>
              <long-description></long-description>
            </docblock>
          </property>
          <method final="false" abstract="false" static="false" visibility="public" namespace="" line="69" package="WordPress\\Customize">
            <name>preview</name>
            <full_name>\\WP_Customize_Setting::preview()</full_name>
            <docblock line="69">
              <description>Handle previewing the setting.</description>
              <long-description></long-description>
              <tag name="since" line="69" description="3.4.0"/>
            </docblock>
          </method>
          <method final="false" abstract="false" static="false" visibility="public" namespace="" line="96" package="WordPress\\Customize">
            <name>_preview_filter</name>
            <full_name>\\WP_Customize_Setting::_preview_filter()</full_name>
            <docblock line="96">
              <description>Callback function to filter the theme mods and options.</description>
              <long-description></long-description>
              <tag name="since" line="96" description="3.4.0"/>
              <tag name="uses" line="96" description="" link="WP_Customize_Setting::multidimensional_replace()"/>
              <tag name="param" line="96" description="the param" type="mixed" variable="$original">
                <type>mixed</type>
              </tag>
              <tag name="return" line="96" description="New or old value." type="mixed">
                <type>mixed</type>
              </tag>
            </docblock>
            <argument line="0" by_reference="false">
              <name>$original</name>
              <default></default>
              <type>mixed</type>
            </argument>
          </method>
        </class>
        </file>
      </project>
      eos

      xml = Nokogiri::XML.parse(node_text) do |config|
        config.noblanks
      end

      node = xml.root

      project = Project.new
      project.parse(node)

      scanner = ProjectScanner.new
      scanner.add_observer(generator)
      scanner.scan(project)

      expected = "let g:phpcomplete_builtin['functions']['wp_post'] = {
\\ 'get_extended(': 'string $post | array',
\\}"

      expected = "let g:phpcomplete_builtin['classes']['wp_post'] = {
\\'wp_customize_setting': {
\\  'name': 'WP_Customize_Setting',
\\  'properties': {
\\    '$manager': {'initializer': '', 'type': ''},
\\    '$id': {'initializer': '', 'type': ''},
\\  },
\\  'methods': {
\\    'preview': { 'signature': 'void', 'return_type': 'void'},
\\    '_preview_filter': { 'signature': 'mixed $original', 'return_type': 'mixed'},
\\  },
\\},
\\}\n"

      output = generator.build

      expect(output).to eq(expected)
      expect(generator.modules).to eq(['wp_post'])
    end
  end
end


text:
{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances #-}
{-# OPTIONS_HADDOCK hide #-}
-----------------------------------------------------------------------------
-- |
-- Module     : Data.Matrix.Class.ISolveBase
-- Copyright  : Copyright (c) , Patrick Perry <patperry@stanford.edu>
-- License    : BSD3
-- Maintainer : Patrick Perry <patperry@stanford.edu>
-- Stability  : experimental
--
-- An overloaded interface for solving immutable matrix systems.  The
-- matrices can operate via inverse multiplication on immutable dense
-- vectors and matrices.
--

module Data.Matrix.Class.ISolveBase (
    -- * The IMatrix type class
    ISolve(..),

    -- * Operators
    (<\>),
    (<\\>),

    -- * Solving linear systems
    solveVector,
    solveMatrix,
    ssolveVector,
    ssolveMatrix,

    ) where

import Data.Elem.BLAS
import BLAS.Internal ( checkMatVecSolv, checkMatMatSolv )
import Data.Matrix.Class
import Data.Matrix.Class.MSolveBase

import Data.Tensor.Class.ITensor( (*>) )
import Data.Vector.Dense ( Vector, dim )
import Data.Vector.Dense.ST ( runSTVector )
import Data.Matrix.Dense ( Matrix, shape )
import Data.Matrix.Dense.ST ( runSTMatrix )
import Data.Matrix.TriBase

infixr 7 <\>, <\\>

-- | A type class for immutable matrices with inverses.  The member
-- functions of the type class do not perform any checks on the validity
-- of shapes or indices, so in general their safe counterparts should be
-- preferred.
class (MatrixShaped a) => ISolve a where
    unsafeSolveVector :: (BLAS2 e)
                   => a e -> Vector e -> Vector e
    unsafeSolveVector = unsafeSSolveVector 1
    {-# INLINE unsafeSolveVector #-}

    unsafeSolveMatrix :: (BLAS3 e)
                   => a e -> Matrix e -> Matrix e
    unsafeSolveMatrix = unsafeSSolveMatrix 1
    {-# INLINE unsafeSolveMatrix #-}

    unsafeSSolveVector :: (BLAS2 e)
                    => e -> a e -> Vector e -> Vector e

    unsafeSSolveMatrix :: (BLAS3 e)
                    => e -> a e -> Matrix e -> Matrix e

-- | Solve for a vector.
solveVector :: (ISolve a, BLAS2 e) => a e -> Vector e -> Vector e
solveVector a y =
    checkMatVecSolv (shape a) (dim y) $
        unsafeSolveVector a y
{-# INLINE solveVector #-}

-- | Solve for a matrix.
solveMatrix :: (ISolve a, BLAS3 e) => a e -> Matrix e -> Matrix e
solveMatrix a b =
    checkMatMatSolv (shape a) (shape b) $
        unsafeSolveMatrix a b
{-# INLINE solveMatrix #-}

-- | Solve for a vector and scale.
-- @ssolveVector k a y@ is equal to @a `solveVector` (k *> y)@ but is often faster.
ssolveVector :: (ISolve a, BLAS2 e) => e -> a e -> Vector e -> Vector e
ssolveVector alpha a y =
    checkMatVecSolv (shape a) (dim y) $
        unsafeSSolveVector alpha a y
{-# INLINE ssolveVector #-}

-- | Solve for a matrix and scale.
-- @ssolveMatrix k a c@ is equal to @a `solveMatrix` (k *> c)@ but is often faster.
ssolveMatrix :: (ISolve a, BLAS3 e) => e -> a e -> Matrix e -> Matrix e
ssolveMatrix alpha a b =
    checkMatMatSolv (shape a) (shape b) $
        unsafeSSolveMatrix alpha a b
{-# INLINE ssolveMatrix #-}

instance ISolve (Tri Matrix) where
    unsafeSSolveVector alpha a y = runSTVector $ unsafeGetSSolveVector alpha a y
    {-# INLINE unsafeSSolveVector #-}
    unsafeSSolveMatrix alpha a c = runSTMatrix $ unsafeGetSSolveMatrix alpha a c
    {-# INLINE unsafeSSolveMatrix #-}

-- | Operator form of solving for a vector.
(<\>) :: (ISolve a, BLAS2 e) => a e -> Vector e -> Vector e
(<\>) = solveVector
{-# INLINE (<\>) #-}

-- | Operator form of solving for a matrix.
(<\\>) :: (ISolve a, BLAS3 e) => a e -> Matrix e -> Matrix e
(<\\>) = solveMatrix
{-# INLINE (<\\>) #-}

{-# RULES
"scale.solve/ssolveVector"       forall k a y. a <\>  (k *> y) = ssolveVector k a y
"scale.solveMatrix/ssolveMatrix" forall k a c. a <\\> (k *> c) = ssolveMatrix k a c
 #-}