text:
module Unbounded
  # An unbounded (infinite) range extension for the standard Ruby Range class.
  class Range < ::Range
    include Formats

    RANGE_FORMATS[:humanized] = proc { |first, last| ::Unbounded::Range.humanized(first, last) }
    RANGE_FORMATS[:postgres]  = proc { |first, last| ::Unbounded::Range.postgres(first, last) }

    # @overload initialize(range_start, range_minimum, exclude_end = false)
    #   Create a range the traditional way, à la `Range.new`.
    #   @param [#succ] range_start
    #   @param [#succ] range_end
    #   @param [Boolean] exclude_end
    # @overload initialize(range_string)
    #   Create a range in the same manner as you would in PostgreSQL
    #   @param [String] range_string
    def initialize(*args)
      parsed = parse_for_range(args)

      @format = parsed.format

      super(parsed.minimum, parsed.maximum, parsed.exclude_end)
    end

    # @todo i18n support
    # @return [String] a more human-readable format
    def humanized
      case unbounded?
      when :infinite
        "infinite"
      when :maximum
        "#{self.begin}+"
      when :minimum
        exclude_end? ? "fewer than #{self.end}" : "#{self.end} or fewer"
      else
        super
      end
    end

    # @return [Boolean]
    def infinite?
      numeric? && ( ( unbounded_minimum | unbounded_maximum ) == 3 )
    end

    # @return [Boolean] whether this range is numeric
    def numeric?
      self.begin.kind_of?(Numeric) && self.end.kind_of?(Numeric)
    end

    # For compatibility with {Unbounded::RangeExtension#unbounded}
    # unded?
    # @return [self]
    def unbounded
      self
    end

    # Check whether this range is unbounded in some way.
    # @return [Symbol,nil] returns a symbol for the type of unboundedness, nil otherwise
    def unbounded?(unbounded_type = nil)
      return false unless numeric?

      unboundedness = case unbounded_minimum | unbounded_maximum
      when 3 then :infinite
      when 2 then :maximum
      when 1 then :minimum
      end

      return unbounded_type && unboundedness ? ( unboundedness == :infinite ) || ( unboundedness == unbounded_type ) : unboundedness
    end

    # @!group Enumerable Overrides
    # Same as `Enumerable#count`, except in cases where the collection is {Range#unbounded?}.
    # @note This would not be true in some cases, e.g. checking for negative
    #   numbers on a range of 0 to infinity.
    # @return [Integer, INFINITY] Infinity when unbounded, super otherwise
    def count(*args, &block)
      unbounded? ? INFINITY : super
    end

    # @overload first
    #   @return [Numeric] equivalent to `#min`
    # @overload first(n)
    #   @param [Integer] n
    #   @return [Array<#succ>] first n-elements of the range
    def first(*args)
      n = args.shift

      if unbounded_minimum? && (n.nil? || n.kind_of?(Integer))
        if n.nil?
          min
        else
          Array.new(n, min)
        end
      else
        return n.nil? ? super() : super(n)
      end
    end

    # @overload last
    #   @return [Numeric] equivalent to {#max}
    # @overload last(n)
    #   @param  [Integer] n
    #   @return [Array<#succ>] last n-elements of the range
    def last(*args)
      n = args.shift

      if unbounded? && (n.nil? || n.kind_of?(Integer))
        if n.nil?
          max
        elsif unbounded? == :minimum # To prevent `cannot iterate from Float`
          new_minimum = max - (n - 1)

          (new_minimum..max).to_a
        else
          Array.new(n, max) # Array of Infinity
        end
      else
        return n.nil? ? super() : super(n)
      end
    end

    # Overload for `Range#max` to account for "unbounded_maximum? && exclude_end?" edge case
    def max
      super
    rescue TypeError
      self.end
    end

    # The default implementation of `Range#minmax` for needlessly uses `#each`,
    # which can cause infinite enumeration.
    # @return [Array(Numeric, Numeric)]
    def minmax
      [min, unbounded? ? INFINITY : max]
    end
    # @!endgroup

    class << self
      # @param [Numeric] first
      # @param [Numeric] last
      # @return [String]
      def humanized(first, last)
        return new(first, last).humanized
      end

      private
      # @param [Symbol] type should be :min or :max
      # @param [Integer] int_to_return integer to return for bitwise comparison in {#unbounded?}
      # @return [void]
      # @!macro [attach] unbounded_endpoint
      #   @!method unbounded_$1imum
      #     Determine whether the $1 is unbounded.
      #     @!visibility private
      #     @return [$2,0] $2 if unbounded, 0 if otherwise
      #
      #   @!method unbounded_$1imum?
      #     Predicate method for {#unbounded_$1imum} that checks against zero
      #     @return [Integer,nil]
      #
      #   @!method finite_$1imum?
      #     Inverse complement of {#unbounded_$1imum?}
      #     @return [Boolean]
      def unbounded_endpoint(type, int_to_return)
        attr_name = type == :min ? "begin" : "end"

        class_eval <<-RUBY, __FILE__, __LINE__ + 1
          def unbounded_#{type}imum
            self.#{attr_name}.respond_to?(:infinite?) && self.#{attr_name}.infinite? ? #{int_to_return} : 0
          end

          def unbounded_#{type}imum?
            unbounded_#{type}imum.nonzero?
          end

          def finite_#{type}imum?
            !unbounded_#{type}imum?
          end

          private :unbounded_#{type}imum
        RUBY
      end
    end

    unbounded_endpoint :min, 1
    unbounded_endpoint :max, 2
  end
end


text:
using GeckoUBL.Ubl21.Udt;

namespace GeckoUBL.Ubl21.Cac
{
	/// <remarks/>
	[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "4.0.30319.33440")]
	[System.SerializableAttribute()]
	[System.Diagnostics.DebuggerStepThroughAttribute()]
	[System.ComponentModel.DesignerCategoryAttribute("code")]
	[System.Xml.Serialization.XmlTypeAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2")]
	[System.Xml.Serialization.XmlRootAttribute("ExceptionNotificationLine", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2", IsNullable=false)]
	public class ExceptionNotificationLineType {
		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public IdentifierType ID { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute("Note", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public TextType[] Note { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute("Description", Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public TextType[] Description { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType ExceptionStatusCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType CollaborationPriorityCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType ResolutionCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public MeasureType ComparedValueMeasure { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public MeasureType SourceValueMeasure { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public QuantityType VarianceQuantity { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType SupplyChainActivityTypeCode { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute(Namespace="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2")]
		public CodeType PerformanceMetricTypeCode { get; set; }

		/// <remarks/>
		public PeriodType ExceptionObservationPeriod { get; set; }

		/// <remarks/>
		[System.Xml.Serialization.XmlElementAttribute("DocumentReference")]
		public DocumentReferenceType[] DocumentReference { get; set; }

		/// <remarks/>
		public ForecastExceptionType ForecastException { get; set; }

		/// <remarks/>
		public ItemType SupplyItem { get; set; }
	}
}

redpajama_set_name: RedPajamaGithub


text:
package alterego.solutions.company_information.add_company;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.design.widget.Snackbar;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.crashlytics.android.Crashlytics;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;

import org.chromium.customtabsclient.CustomTabsActivityHelper;

import java.util.regex.Pattern;

import alterego.solutions.company_information.R;
import alterego.solutions.company_information.dbHelper.DBHelper;
import alterego.solutions.company_information.dbHelper.DbManagmentPresenter;
import alterego.solutions.company_information.runtime_permission.PermissionManager;
import alterego.solutions.company_information.search_company.SearchActivity;
import butterknife.Bind;
import butterknife.BindColor;
import butterknife.ButterKnife;
import io.fabric.sdk.android.Fabric;
import me.zhanghai.android.customtabshelper.CustomTabsHelperFragment;

public class AddActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener{

    /*@Bind(R.id.company_name)
    EditText name;

    @Bind(R.id.company_city)
    EditText city;

    @Bind(R.id.company_street)
    EditText street;

    @Bind(R.id.company_phone)
    EditText phone;

    @Bind(R.id.company_cell)
    EditText cell;

    @Bind(R.id.company_description)
    EditText description;*/

    @BindColor(R.color.colorPrimary)
    int mColorPrimary;

    DbManagmentPresenter mManagerPresenter;

    private CustomTabsHelperFragment mCustomTabsHelperFragment;

    private CustomTabsIntent mCustomTabsIntent;

    EditText name,city,street,phone,cell,description;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add);
        ButterKnife.bind(this);
        Fabric.with(this, new Crashlytics());
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_add_company);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        PermissionManager pm = new PermissionManager(this);
        pm.managingPermission();
        pm.managingPermission();

        name = (EditText) findViewById(R.id.company_name);
        city = (EditText) findViewById(R.id.company_city);
        street = (EditText) findViewById(R.id.company_street);
        phone = (EditText) findViewById(R.id.company_phone);
        cell = (EditText) findViewById(R.id.company_cell);
        description = (EditText) findViewById(R.id.company_description);

        mCustomTabsHelperFragment = CustomTabsHelperFragment.attachTo(this);

        mCustomTabsIntent = new CustomTabsIntent.Builder()
                .enableUrlBarHiding()
                .setToolbarColor(mColorPrimary)
                .setShowTitle(true)
                .build();

        mManagerPresenter = new DbManagmentPresenter(this);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.add_fab);
        fab.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View view) {

                if(!String.valueOf(name.getText()).isEmpty() && !String.valueOf(city.getText()).isEmpty() && !String.valueOf(street.getText()).isEmpty()
                        && !String.valueOf(phone.getText()).isEmpty()) {

                    AddPresenter mPresenter = new AddPresenter(String.valueOf(name.getText()), String.valueOf(city.getText()),
                            String.valueOf(street.getText()), String.valueOf(phone.getText()), String.valueOf(cell.getText()), String.valueOf(description.getText()),
                            getApplicationContext());

                    boolean isAdded = mPresenter.addCompany();

                    if(isAdded){
                        Snackbar.make(view, "Azienda già presente nel database", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                    }

                    if(!isAdded){
                        Snackbar.make(view, "Azienda aggiunta al database", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                        deleteField();
                    }
                }

                else{
                    Log.e("TEST EDITTEXT",String.valueOf(name.getText()));
                    Snackbar.make(view, "Campi obbligatori: Nome, Città, Strada, Telefono", Snackbar.LENGTH_LONG).setAction("Action", null).show();
                }
            }
        });

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id){

            case R.id.action_dump_db:
                mManagerPresenter.backupDB();
                return super.onOptionsItemSelected(item);

            case R.id.action_restore_db:
                //mManagerPresenter.restoreDB();
                getPathForDb();
                return super.onOptionsItemSelected(item);
            default:
                return super.onOptionsItemSelected(item);
        }

    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        int id = item.getItemId();

        switch (id){
            case R.id.search_company:
                Intent search = new Intent(this, SearchActivity.class);
                startActivity(search);
                break;
            case R.id.add_company:
                Intent add = new Intent(this, AddActivity.class);
                startActivity(add);
                break;
            case R.id.about_us:
                CustomTabsHelperFragment.open(this, mCustomTabsIntent, Uri.parse("http://alterego.solutions"), mCustomTabsFallback);
                break;
            default:
                break;

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout_add_company);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    public void deleteField(){
        name.setText("");
        city.setText("");
        street.setText("");
        phone.setText("");
        cell.setText("");
        description.setText("");
    }

    protected final CustomTabsActivityHelper.CustomTabsFallback mCustomTabsFallback =
            (activity, uri) -> {
                Toast.makeText(activity, R.string.custom_tab_error, Toast.LENGTH_SHORT).show();
                try {
                    activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
                } catch (ActivityNotFoundException e) {
                    e.printStackTrace();
                    Toast.makeText(activity, R.string.custom_tab_error_activity, Toast.LENGTH_SHORT)
                            .show();
                }
            };

    //Launch File Picker and get the path of the file for db.
    public void getPathForDb(){

        new MaterialFilePicker()
                .withActivity(this)
                .withRequestCode(1)
                .withFilter(Pattern.compile(".*\\.sqlite$")) // Filtering files and directories by file name using regexp
                .withFilterDirectories(false) // Set directories filterable (false by default)
                .withHiddenFiles(true) // Show hidden files and folders
                .start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {
            String filePath = data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH);
            // Do anything with file
            Log.e("PATH OF THE DB",filePath);
            mManagerPresenter.restoreDB(filePath);
        }
    }
}


text:
**NOTE: This is now the repository of *Icecite*, a research paper management
system. If you are looking for the PDF extraction tool (formerly also known as
Icecite), this project moved to [PdfAct](https://github.com/ad-freiburg/pdfact).**

## Demo
A **running demo** of Icecite can be found here: http://www.icecite.org.

## Literature
Read more about *Icecite* here:
[The Icecite Research Paper Management System](http://ad-publications.informatik.uni-freiburg.de/WISE_icecite_BK_2013.pdf)
*(Hannah Bast, Claudius Korzen, WISE 2013)*


text:
<?php
/**
 * Contains EWSType_ItemResponseShapeType.
 */

/**
 * Represents a set of properties to return in a GetItem operation, FindItem
 * operation, or SyncFolderItems operation response.
 *
 * @package php-ews\Types
 */
class EWSType_ItemResponseShapeType extends EWSType
{
    /**
     * Identifies additional properties to return in a response.
     *
     * @since Exchange 2007
     *
     * @var EWSType_NonEmptyArrayOfPathsToElementType
     */
    public $AdditionalProperties;

    /**
     * Identifies the basic configuration of properties to return in an item or
     * folder response.
     *
     * @since Exchange 2007
     *
     * @var EWSType_DefaultShapeNamesType
     */
    public $BaseShape;

    /**
     * Identifies how the body text is formatted in the response.
     *
     * @since Exchange 2007
     *
     * @var EWSType_BodyTypeResponseType
     */
    public $BodyType;

    /**
     * Indicates whether the item HTML body is converted to UTF8.
     *
     * @since Exchange 2010
     *
     * @var boolean
     */
    public $ConvertHtmlCodePageToUTF8;

    /**
     * Specifies whether HTML content filtering is enabled.
     *
     * @since Exchange 2010
     *
     * @var boolean
     */
    public $FilterHtmlContent;

    /**
     * Specifies whether the Multipurpose Internet Mail Extensions (MIME)
     * content of an item is returned in the response.
     *
     * @since Exchange 2007
     *
     * @var boolean
     */
    public $IncludeMimeContent;
}


text: define("dojox/form/nls/fi/Uploader",({label:"Valitse tiedostot..."}));


text:
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = y[op[0] & 2 ? "return" : op[0] ? "throw" : "next"]) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [0, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var _this = this;
var twitterConsumerKey = 'KEY';
var twitterConsumerSecret = 'SECRET';
var willGetOAuthAccessToken = function (twitterConsumerKey, twitterConsumerSecret) { return __awaiter(_this, void 0, void 0, function () {
    return __generator(this, function (_a) {
        return [2 /*return*/, new Promise(function (resolve, reject) {
                var OAuth2 = require('oauth').OAuth2;
                var oauth2 = new OAuth2(twitterConsumerKey, twitterConsumerSecret, 'https://api.twitter.com/', null, 'oauth2/token', null);
                oauth2.getOAuthAccessToken('', { 'grant_type': 'client_credentials' }, function (e, access_token, refresh_token, results) {
                    if (!access_token) {
                        return reject(new Error(results + ", " + JSON.stringify(e)));
                    }
                    return resolve(access_token);
                });
            })
            // Twitter API
        ];
    });
}); };
// Twitter API
require('isomorphic-fetch');
var option = function (token, method) {
    if (method === void 0) { method = 'GET'; }
    return ({
        method: method,
        headers: {
            Authorization: "Bearer " + token
        }
    });
};
var user_timeline = function (token, screen_name) {
    return fetch("https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=" + screen_name, option(token));
};
var update = function (token, status) {
    return fetch("https://api.twitter.com/1.1/statuses/update.json?status=" + status, option(token, 'POST'));
};
// Express
var express = require('express');
var app = express();
app.get('/', function (req, res) {
    return willGetOAuthAccessToken(twitterConsumerKey, twitterConsumerSecret)
        .then(function (access_token) {
        update(access_token, 'Test!')
            .then(function (response) { return response.json()
            .then(function (json) { return res.send(json); }); })
            .catch(function (err) { return console.error(err.message); });
    })
        .catch(function (err) { return console.error(err.message); });
});
// Export
var WebTask = require('webtask-tools');
module.exports = WebTask.fromExpress(app);


text:
This tests dragging text from a textarea element to an input element.

When the test is run, the follow textarea should be empty:

<textarea id="textarea" cols="50" rows="10">drag this text into the text field above</textarea>

And the following input should have text in it:

<input id="input" type="text" size="50">

If the test has completed this sentence should be replaced by a success message.


text:
package riff

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"reflect"
	"strconv"
)

// A Reader is a bytes reader with some helper functions to read IDs, Lens, and Data
// from RIFF files.
type Reader struct {
	*bytes.Reader
}

// NewReader returns an initial Reader
func NewReader(data []byte) *Reader {
	return &Reader{
		Reader: bytes.NewReader(data),
	}
}

// Print prints a reader without any knowledge of the structure of the reader,
// so all values will be []bytes.
// It assumes the reader has not advanced at all. Todo: Change that
func (r *Reader) Print() {
	deepPrint(r, " ", -1)
}

func deepPrint(r *Reader, prefix string, readLimit int) {
	var err error
	var typ string
	var l uint32
	var data []byte
	var isList bool
	var read int
	for err == nil && readLimit == -1 || read < readLimit {
		typ, l, isList, err = r.NextIDLen()
		// There will be a bogus byte at the end of some prints.
		if l%2 != 0 {
			l++
		}
		read += 8
		if err == nil {
			fmt.Print(prefix, typ, " Length:", l)
			if isList {
				typ2, err2 := r.NextID()
				read += 4
				if err2 == nil {
					fmt.Println(prefix+"  ", typ2)
					deepPrint(r, prefix+"    ", int(l)-4)
				} else {
					fmt.Println(prefix, err2)
				}
			} else if l < 40 {
				data = make([]byte, l)
				r.Read(data)
				fmt.Println(" Content:", data)
			} else {
				r.Seek(int64(l), io.SeekCurrent)
				fmt.Println(" Long Content")
			}
			read += int(l)
		}
	}
	if err != nil && err != io.EOF {
		fmt.Println(prefix, err)
	}
}

// Unmarshal is a mirror of json.Unmarshal, for RIFF files
func Unmarshal(data []byte, v interface{}) error {
	return NewReader(data).unmarshal(v)
}

func (r *Reader) unmarshal(v interface{}) error {
	// Mirrors json.unmarshal
	rv := reflect.ValueOf(v)
	if rv.Kind() != reflect.Ptr || rv.IsNil() {
		return errors.New("Invalid Unmarshal Struct")
	}
	// The first ID in the riff should be RIFF
	id, err := r.NextID()
	if err != nil {
		return err
	}
	if id != "RIFF" {
		return errors.New("RIFF format must begin with RIFF")
	}
	ln, err := r.NextLen()
	if err != nil {
		return err
	}
	// The next ID identifies this file type. We don't want it.
	_, err = r.NextID()
	if err != nil {
		return err
	}
	_, err = r.chunks(reflect.Indirect(rv), int(ln))
	return err
}

// NextID returns the next four byte sof the reader as a string
func (r *Reader) NextID() (string, error) {
	id := make([]byte, 4)
	l, err := r.Reader.Read(id)
	if l != 4 || err != nil {
		return "", errors.New("RIFF missing expected ID")
	}
	return string(id), nil
}

// NextIDLen returns NextID and NextLen
func (r *Reader) NextIDLen() (string, uint32, bool, error) {
	id, err := r.NextID()
	if err != nil {
		return "", 0, false, err
	}
	ln, err := r.NextLen()
	if err != nil {
		return "", 0, false, err
	}
	return id, ln, id == "LIST" || id == "RIFF", nil
}

// NextLen returns the next four bytes of the reader as a length.
func (r *Reader) NextLen() (uint32, error) {
	var ln uint32
	err := binary.Read(r.Reader, binary.LittleEndian, &ln)
	if err != nil {
		return ln, errors.New("RIFF missing expected length")
	}
	return ln, nil
}

func (r *Reader) chunks(rv reflect.Value, inLength int) (reflect.Value, error) {
	// Find chunkId in rv
	// If it can't be found, ignore it as a value the user does not want
	switch rv.Kind() {
	case reflect.Struct:
		return rv, r.structChunks(rv, inLength)
	case reflect.Slice:
		return r.sliceChunks(rv, inLength)
	default:
		return reflect.Value{}, errors.New("Unsupported unmarshal type")
	}
}

func (r *Reader) sliceChunks(rv reflect.Value, inLength int) (reflect.Value, error) {

	slTy := rv.Type()
	ty := slTy.Elem()
	newSlice := reflect.MakeSlice(slTy, 0, 10000)
	for inLength > 0 {
		_, ln, isList, err := r.NextIDLen()
		if err != nil {
			return reflect.Value{}, err
		}
		if !isList {
			return reflect.Value{}, errors.New("Slice structs need to be LISTs")
		}
		ln -= 4
		inLength -= 4
		if inLength <= 0 {
			break
		}
		_, err = r.NextID()
		if err != nil {
			return reflect.Value{}, err
		}

		inLength -= 8
		if inLength <= 0 {
			break
		}
		newStruct := reflect.New(ty)
		err = r.structChunks(reflect.Indirect(newStruct), int(ln))
		if err != nil {
			return reflect.Value{}, err
		}
		newSlice = reflect.Append(newSlice, reflect.Indirect(newStruct))
		if ln%2 != 0 {
			r.Reader.ReadByte()
			inLength--
		}
		inLength -= int(ln)
	}
	return newSlice, nil
}

// structChunks reads chunks and matches them to fields on rv (which is a struct)
// structChunks sets the fields of rv to be the output it gets
func (r *Reader) structChunks(rv reflect.Value, inLength int) error {
	chunkID, ln, isList, err := r.NextIDLen()
	if err != nil {
		return err
	}
	if isList {
		ln -= 4
		inLength -= 4
		chunkID, err = r.NextID()
		if err != nil {
			return err
		}
	}
	inLength -= 8
	ty := reflect.TypeOf(rv.Interface())
	fields := make([]reflect.Value, rv.NumField())
	fieldTags := make([]reflect.StructTag, rv.NumField())
	for i := range fields {
		fields[i] = rv.Field(i)
		fieldTags[i] = ty.Field(i).Tag
	}
	i := 0
	for inLength > 0 {
		tag := fieldTags[i].Get("riff")
		//spew.Dump(fields[i])
		if tag == chunkID {
			// get contents from recursive call
			var content reflect.Value
			if isList {
				content, err = r.chunks(fields[i], int(ln))
			} else {
				content, err = r.fieldValue(fields[i], ln)
			}
			if err != nil {
				return err
			}
			inLength -= int(ln)

			fields[i].Set(content)
			// if length is odd read one more
			if ln%2 != 0 {
				r.Reader.ReadByte()
				inLength--
			}
			if inLength <= 0 {
				return nil
			}
			// next id
			chunkID, ln, isList, err = r.NextIDLen()
			if err != nil {
				return err
			}
			if isList {
				ln -= 4
				inLength -= 4
				chunkID, err = r.NextID()
				if err != nil {
					return err
				}
			}
			inLength -= 8
			i = -1
		}
		if inLength <= 0 {
			return nil
		}
		i++
		if i >= len(fields) {
			// Skip this id
			// if length is odd read one more
			if ln%2 != 0 {
				ln++
			}
			_, err = r.Reader.Seek(int64(ln), io.SeekCurrent)
			if err != nil {
				return err
			}
			inLength -= int(ln)
			if inLength <= 0 {
				return nil
			}
			// next id
			chunkID, ln, isList, err = r.NextIDLen()
			if err != nil {
				return err
			}
			if isList {
				ln -= 4
				inLength -= 4
				chunkID, err = r.NextID()
				if err != nil {
					return err
				}
			}
			inLength -= 8
			i = 0
		}
	}
	return nil
}

// Todo: the switch here should change to some separate functions, there's some
// repetition here that is not necessary.
func (r *Reader) fieldValue(rv reflect.Value, ln uint32) (reflect.Value, error) {
	switch rv.Kind() {
	case reflect.Struct:
		st := rv.Addr().Interface()
		err := binary.Read(r.Reader, binary.LittleEndian, st)
		if err != nil {
			// Something on this struct has an undefined size
			// Read each field in part by part.
		}
		return reflect.Indirect(reflect.ValueOf(st)), err
	case reflect.String:
		data := make([]byte, ln)
		n, err := r.Reader.Read(data)
		if n != int(ln) {
			return reflect.Value{}, errors.New("Insufficient data found in RIFF data block")
		}
		return reflect.ValueOf(string(data)), err
	case reflect.Slice:
		switch rv.Type().Elem().Kind() {
		case reflect.Uint8:
			data := make([]byte, ln)
			n, err := r.Reader.Read(data)
			if n != int(ln) {
				return reflect.Value{}, errors.New("Insufficient data found in RIFF data block")
			}
			return reflect.ValueOf(data), err
		default:
			return reflect.Value{}, errors.New("Unsupported type in input struct")
		}
	case reflect.Uint32:
		if ln != 4 {
			return reflect.Value{}, errors.New("Invalid length for uint32: " + strconv.Itoa(int(ln)))
		}
		data := make([]byte, ln)
		n, err := r.Reader.Read(data)
		if n != int(ln) {
			return reflect.Value{}, errors.New("Insufficient data found in RIFF data block")
		}
		if err != nil {
			return reflect.Value{}, err
		}
		val, n := binary.Uvarint(data)
		if n <= 0 {
			return reflect.Value{}, errors.New("Unable to decode int64 from data")
		}
		val32 := uint32(val)
		return reflect.ValueOf(val32), nil
	case reflect.Int64:
		if ln != 8 {
			return reflect.Value{}, errors.New("Invalid length for int64: " + strconv.Itoa(int(ln)))
		}
		data := make([]byte, ln)
		n, err := r.Reader.Read(data)
		if n != int(ln) {
			return reflect.Value{}, errors.New("Insufficient data found in RIFF data block")
		}
		if err != nil {
			return reflect.Value{}, err
		}
		val, n := binary.Varint(data)
		if n <= 0 {
			return reflect.Value{}, errors.New("Unable to decode int64 from data")
		}
		return reflect.ValueOf(val), nil
	}
	return reflect.Value{}, nil
}


text:
package breeze.linalg.operators

import breeze.generic.UFunc
import breeze.linalg
import breeze.linalg.Axis.{_0, _1}
import breeze.linalg._
import breeze.linalg.support.{CanCollapseAxis, CanIterateAxis, CanSlice2, CanTraverseAxis, CanZipMapKeyValues, CanZipMapValues}
import breeze.macros.expand
import breeze.math.{Field, Semiring}
import breeze.storage.Zero
import breeze.util.{ArrayUtil, ReflectionUtil}
import dev.ludovic.netlib.blas.BLAS.{getInstance => blas}
import dev.ludovic.netlib.lapack.LAPACK.{getInstance => lapack}
import org.netlib.util.intW
import breeze.macros._
import breeze.macros._
import breeze.math.PowImplicits._

import scala.reflect.ClassTag
import scala.{specialized => spec}

trait DenseMatrixOps extends MatrixOps with DenseMatrixExpandedOps with DenseMatrix_ComparisonOps
  with DenseMatrixMultOps with DenseMatrixMultiplyOps with DenseMatrixOps_FloatSpecialized with DenseMatrix_SetOps {
  implicit val setMV_D: OpSet.InPlaceImpl2[DenseMatrix[Double], DenseVector[Double]] = new SetDMDVOp[Double]();
  implicit val setMV_F: OpSet.InPlaceImpl2[DenseMatrix[Float], DenseVector[Float]] = new SetDMDVOp[Float]();
  implicit val setMV_I: OpSet.InPlaceImpl2[DenseMatrix[Int], DenseVector[Int]] = new SetDMDVOp[Int]();

  /**
   * transforms each row into a new row, giving a new matrix.
   * @tparam V
   * @tparam R
   * @return
   */
  implicit def canMapRows_DM[V, R: ClassTag: Zero](implicit implSet: OpSet.InPlaceImpl2[DenseVector[R], DenseVector[R]])
  : CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], DenseVector[R], DenseMatrix[R]] =
    new CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], DenseVector[R], DenseMatrix[R]] {
      def apply(from: DenseMatrix[V], axis: Axis._0.type)(f: (DenseVector[V]) => DenseVector[R]): DenseMatrix[R] = {
        var result: DenseMatrix[R] = null
        cforRange (0 until from.cols) { c =>
          val col = f(from(::, c))
          if (result eq null) {
            result = DenseMatrix.zeros[R](col.length, from.cols)
          }
          // Scala 2.12 needs this
          implSet(result(::, c), col)
        }

        if (result eq null) {
          DenseMatrix.zeros[R](0, from.cols)
        } else {
          result
        }
      }
    }

  implicit def handholdCanMapRows_DM[V]: CanCollapseAxis.HandHold[DenseMatrix[V], Axis._0.type, DenseVector[V]] =
    new CanCollapseAxis.HandHold[DenseMatrix[V], Axis._0.type, DenseVector[V]]()

  implicit def canMapRowsBitVector_DM[V: ClassTag: Zero]
  : CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], BitVector, DenseMatrix[Boolean]] =
    new CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], BitVector, DenseMatrix[Boolean]] {
      def apply(from: DenseMatrix[V], axis: Axis._0.type)(f: (DenseVector[V]) => BitVector): DenseMatrix[Boolean] = {
        var result: DenseMatrix[Boolean] = null
        cforRange(0 until from.cols) { c =>
          val col = f(from(::, c))
          if (result eq null) {
            result = DenseMatrix.zeros[Boolean](col.length, from.cols)
          }
          result(::, c) := col
        }

        if (result eq null) {
          DenseMatrix.zeros[Boolean](0, from.cols)
        } else {
          result
        }
      }
    }

  /**
   * transforms each column into a new column, giving a new matrix.
   * @tparam V value type
   * @return
   */
  implicit def canMapCols_DM[V, Res: ClassTag: Zero](
                                                   implicit implSet: OpSet.InPlaceImpl2[DenseVector[Res], DenseVector[Res]])
  : CanCollapseAxis[DenseMatrix[V], _1.type, DenseVector[V], DenseVector[Res], DenseMatrix[Res]] = {
    new CanCollapseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V], DenseVector[Res], DenseMatrix[Res]] {
      def apply(from: DenseMatrix[V], axis: Axis._1.type)(f: (DenseVector[V]) => DenseVector[Res]): DenseMatrix[Res] = {
        var result: DenseMatrix[Res] = null
        import from.rows
        val t = from.t
        cforRange(0 until from.rows) { r =>
          val row = f(t(::, r))
          if (result eq null) {
            // scala has decided this method is overloaded, and needs a result type.
            // It has a result type, and is not overloaded.
            //          result = DenseMatrix.zeros[V](from.rows, row.length)
            val data = new Array[Res](rows * row.length)
            result = DenseMatrix.create(rows, row.length, data)
          }
          // 2.12 requires direct invocation here...
          implSet(result.t.apply(::, r), row)
        }

        if (result ne null) {
          result
        } else {
          val data = new Array[Res](0)
          result = DenseMatrix.create(rows, 0, data)
          result
        }
      }
    }
  }

  implicit def handholdCanMapCols_DM[V]: CanCollapseAxis.HandHold[DenseMatrix[V], Axis._1.type, DenseVector[V]] =
    new CanCollapseAxis.HandHold[DenseMatrix[V], Axis._1.type, DenseVector[V]]()

  implicit def canMapColsBitVector_DM[V: ClassTag: Zero]: CanCollapseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V], BitVector, DenseMatrix[Boolean]] =
    new CanCollapseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V], BitVector, DenseMatrix[Boolean]] {
      def apply(from: DenseMatrix[V], axis: Axis._1.type)(f: (DenseVector[V]) => BitVector): DenseMatrix[Boolean] = {
        var result: DenseMatrix[Boolean] = null
        import from.rows
        val t = from.t
        cforRange(0 until from.rows) { r =>
          val row = f(t(::, r))
          if (result eq null) {
            // scala has decided this method is overloaded, and needs a result type.
            // It has a result type, and is not overloaded.
            //          result = DenseMatrix.zeros[V](from.rows, row.length)
            val data = new Array[Boolean](rows * row.length)
            result = DenseMatrix.create(rows, row.length, data)
          }
          result.t.apply(::, r) := row
        }

        if (result ne null) {
          result
        } else {
          val data = new Array[Boolean](0)
          result = DenseMatrix.create(rows, 0, data)
          result
        }
      }
    }

  /**
   * Iterates over each columns
   * @return
   */
  implicit def canTraverseCols_DM[V]: CanTraverseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V]] = {
    new CanTraverseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V]] {
      def apply[A](from: DenseMatrix[V], axis: Axis._0.type)(f: (DenseVector[V]) => A): Unit = {
        cforRange(0 until from.cols) { c =>
          f(from(::, c))
        }
      }
    }
  }

  /**
   * iterates over each column
   * @tparam V
   * @return
   */
  implicit def canTraverseRows_DM[V]: CanTraverseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V]] = {
    new CanTraverseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V]] {
      def apply[A](from: DenseMatrix[V], axis: Axis._1.type)(f: (DenseVector[V]) => A): Unit = {
        val t = from.t
        cforRange(0 until from.rows) { r =>
          f(t(::, r))
        }
      }
    }
  }

  /**
   * Iterates over each columns
   * @return
   */
  implicit def canIterateCols_DM[V]: CanIterateAxis[DenseMatrix[V], Axis._0.type, DenseVector[V]] = {
    new CanIterateAxis[DenseMatrix[V], Axis._0.type, DenseVector[V]] {

      override def apply[A](from: DenseMatrix[V], axis: _0.type): Iterator[DenseVector[V]] = {
        (0 until from.cols).iterator.map(from(::, _))
      }
    }
  }

  /**
   * iterates over each column
   * @tparam V
   * @return
   */
  implicit def canIterateRows_DM[V]: CanIterateAxis[DenseMatrix[V], Axis._1.type, DenseVector[V]] = {
    new CanIterateAxis[DenseMatrix[V], Axis._1.type, DenseVector[V]] {

      override def apply[A](from: DenseMatrix[V], axis: _1.type): Iterator[DenseVector[V]] = {
        (0 until from.rows).iterator.map(from(_, ::).t)
      }

    }
  }

  //  implicit val setMM_D: OpSet] = new SetDMDMOp[Double.InPlaceImpl2[DenseMatrix[Double], DenseMatrix[Double]]
  //  implicit val setMM_F: OpSet]  = new SetDMDMOp[Float.InPlaceImpl2[DenseMatrix[Float], DenseMatrix[Float]]
  //  implicit val setMM_I: OpSet]  = new SetDMDMOp[Int.InPlaceImpl2[DenseMatrix[Int], DenseMatrix[Int]]

  // There's a bizarre error specializing float's here.
  class CanZipMapValuesDenseMatrix[@spec(Double, Int, Float, Long) V, @specialized(Int, Double) RV: ClassTag]
    extends CanZipMapValues[DenseMatrix[V], V, RV, DenseMatrix[RV]] {

    def create(rows: Int, cols: Int) = DenseMatrix.create(rows, cols, new Array[RV](rows * cols), 0, rows)

    /**Maps all corresponding values from the two collection. */
    def map(from: DenseMatrix[V], from2: DenseMatrix[V], fn: (V, V) => RV) = {
      require(from.rows == from2.rows, "Vector row dimensions must match!")
      require(from.cols == from2.cols, "Vector col dimensions must match!")
      val result = create(from.rows, from.cols)
      cforRange2 (0 until from.cols, 0 until from.rows) { (j, i) =>
        result(i, j) = fn(from(i, j), from2(i, j))
      }
      result
    }
  }

  implicit def zipMap_DM[V, R: ClassTag]: CanZipMapValuesDenseMatrix[V, R] = new CanZipMapValuesDenseMatrix[V, R]
  implicit val zipMap_DM_Double: CanZipMapValuesDenseMatrix[Double, Double] = new CanZipMapValuesDenseMatrix[Double, Double]
  implicit val zipMap_DM_Float: CanZipMapValuesDenseMatrix[Float, Float] = new CanZipMapValuesDenseMatrix[Float, Float]
  implicit val zipMap_DM_Int: CanZipMapValuesDenseMatrix[Int, Int] = new CanZipMapValuesDenseMatrix[Int, Int]

  class CanZipMapKeyValuesDenseMatrix[@spec(Double, Int, Float, Long) V, @specialized(Int, Double) RV: ClassTag]
    extends CanZipMapKeyValues[DenseMatrix[V], (Int, Int), V, RV, DenseMatrix[RV]] {

    def create(rows: Int, cols: Int) = DenseMatrix.create(rows, cols, new Array[RV](rows * cols), 0, rows)

    override def mapActive(
                            from: DenseMatrix[V],
                            from2: DenseMatrix[V],
                            fn: ((Int, Int), V, V) => RV): DenseMatrix[RV] = {
      map(from, from2, fn)
    }

    /**Maps all corresponding values from the two collection. */
    def map(from: DenseMatrix[V], from2: DenseMatrix[V], fn: ((Int, Int), V, V) => RV) = {
      require(from.rows == from2.rows, "Vector row dimensions must match!")
      require(from.cols == from2.cols, "Vector col dimensions must match!")
      val result = create(from.rows, from.cols)
      cforRange2 (0 until from.cols, 0 until from.rows) { (j, i) =>
        result(i, j) = fn((i, j), from(i, j), from2(i, j))
      }
      result
    }
  }

  implicit def zipMapKV_DM[V, R: ClassTag]: CanZipMapKeyValuesDenseMatrix[V, R] = new CanZipMapKeyValuesDenseMatrix[V, R]

  implicit def canDim_DM[E]: dim.Impl[DenseMatrix[E], (Int, Int)] = new dim.Impl[DenseMatrix[E], (Int, Int)] {
    def apply(v: DenseMatrix[E]): (Int, Int) = (v.rows, v.cols)
  }
}

trait DenseMatrixMultiplyOps extends DenseMatrixExpandedOps with DenseMatrixMultOps with DenseMatrix_SetOps {

  // <editor-fold defaultstate="collapsed" desc=" OpMulMatrix implementations ">

  implicit def impl_OpMulMatrix_DVTt_DMT_eq_DMT[T](
      implicit op: OpMulMatrix.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]])
    : OpMulMatrix.Impl2[Transpose[DenseVector[T]], DenseMatrix[T], Transpose[DenseVector[T]]] =
    new OpMulMatrix.Impl2[Transpose[DenseVector[T]], DenseMatrix[T], Transpose[DenseVector[T]]] {
      override def apply(v: Transpose[DenseVector[T]], v2: DenseMatrix[T]): Transpose[DenseVector[T]] = {
        (v.inner.asDenseMatrix * v2).apply(0, ::)
      }
    }

  implicit def impl_OpMulMatrix_DVT_DMT_eq_DMT[T](
      implicit op: OpMulMatrix.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]])
    : OpMulMatrix.Impl2[DenseVector[T], DenseMatrix[T], DenseMatrix[T]] =
    new OpMulMatrix.Impl2[DenseVector[T], DenseMatrix[T], DenseMatrix[T]] {
      def apply(v: DenseVector[T], v2: DenseMatrix[T]): DenseMatrix[T] = {
        require(v2.rows == 1)
        // as DenseMatrix comes out as a row, but we want a column
        op(v.asDenseMatrix.t, v2)
      }
    }

  // for BLAS.dgemm/dgemv
  private def transposeString(a: DenseMatrix[Double]): String = if (a.isTranspose) "T" else "N"

  implicit object impl_OpMulMatrix_DMD_DMD_eq_DMD
      extends OpMulMatrix.Impl2[DenseMatrix[Double], DenseMatrix[Double], DenseMatrix[Double]] {

    def apply(_a: DenseMatrix[Double], _b: DenseMatrix[Double]): DenseMatrix[Double] = {

      require(_a.cols == _b.rows, "Dimension mismatch!")

      val rv: DenseMatrix[Double] = DenseMatrix.zeros[Double](_a.rows, _b.cols)

      if (_a.rows == 0 || _b.rows == 0 || _a.cols == 0 || _b.cols == 0) return rv

      // if we have a weird stride...
      val a: DenseMatrix[Double] =
        if (_a.majorStride < math.max(if (_a.isTranspose) _a.cols else _a.rows, 1)) _a.copy else _a
      val b: DenseMatrix[Double] =
        if (_b.majorStride < math.max(if (_b.isTranspose) _b.cols else _b.rows, 1)) _b.copy else _b

      blas.dgemm(
        transposeString(a),
        transposeString(b),
        rv.rows,
        rv.cols,
        a.cols,
        1.0,
        a.data,
        a.offset,
        a.majorStride,
        b.data,
        b.offset,
        b.majorStride,
        0.0,
        rv.data,
        0,
        rv.rows)
      rv
    }
    implicitly[BinaryRegistry[Matrix[Double], Matrix[Double], OpMulMatrix.type, Matrix[Double]]].register(this)
    implicitly[BinaryRegistry[DenseMatrix[Double], Matrix[Double], OpMulMatrix.type, DenseMatrix[Double]]]
      .register(this)
  }

  implicit object impl_OpMulMatrix_DMD_DVD_eq_DVD
      extends OpMulMatrix.Impl2[DenseMatrix[Double], DenseVector[Double], DenseVector[Double]] {
    def apply(a: DenseMatrix[Double], b: DenseVector[Double]): DenseVector[Double] = {

      require(a.cols == b.length, "Dimension mismatch!")

      if (a.rows == 0 || a.cols == 0) {
        return DenseVector.zeros[Double](a.rows)
      }

      val rv = DenseVector.zeros[Double](a.rows)

      blas.dgemv(
        transposeString(a),
        if (a.isTranspose) a.cols else a.rows,
        if (a.isTranspose) a.rows else a.cols,
        1.0,
        a.data,
        a.offset,
        a.majorStride,
        b.data,
        b.offset,
        b.stride,
        0.0,
        rv.data,
        rv.offset,
        rv.stride
      )
      rv
    }
  }

  implicit val impl_OpMulMatrix_DVD_DMD_eq_DMD
    : OpMulMatrix.Impl2[DenseVector[Double], DenseMatrix[Double], DenseMatrix[Double]] = {
    new OpMulMatrix.Impl2[DenseVector[Double], DenseMatrix[Double], DenseMatrix[Double]] {
      def apply(a: DenseVector[Double], b: DenseMatrix[Double]): DenseMatrix[Double] = {
        require(b.rows == 1)
        //        val adata =  if(a.stride != 1) {
        //          val v = DenseVector.zeros[Double](a.length)
        //          v := a
        //          v.data
        //        } else {
        //          a.data
        //        }
        val rv = DenseMatrix.zeros[Double](a.length, b.cols)
        blas.dgemm(
          "T",
          transposeString(b),
          rv.rows,
          rv.cols,
          1,
          1.0,
          a.data,
          a.offset,
          a.stride,
          b.data,
          b.offset,
          b.majorStride,
          0.0,
          rv.data,
          0,
          rv.rows)
        rv

      }
    }
  }

  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" // <editor-fold defaultstate="collapsed" desc=" OpSolveMatrixBy implementations ">

  implicit object impl_OpSolveMatrixBy_DMD_DMD_eq_DMD
      extends OpSolveMatrixBy.Impl2[DenseMatrix[Double], DenseMatrix[Double], DenseMatrix[Double]] {

    override def apply(A: DenseMatrix[Double], V: DenseMatrix[Double]): DenseMatrix[Double] = {
      require(A.rows == V.rows, "Non-conformant matrix sizes")

      if (A.size == 0) {
        DenseMatrix.zeros[Double](0, 0)
      } else if (A.rows == A.cols) {
        // square: LUSolve
        val X = DenseMatrix.zeros[Double](V.rows, V.cols)
        X := V
        LUSolve(X, A)
        X
      } else {
        // non-square: QRSolve
        val X = DenseMatrix.zeros[Double](A.cols, V.cols)
        QRSolve(X, A, V)
        X
      }
    }

    /** X := A \ X, for square A */
    def LUSolve(X: DenseMatrix[Double], A: DenseMatrix[Double]): DenseMatrix[Double] = {

      val piv = new Array[Int](A.rows)
      val newA = A.copy
      assert(!newA.isTranspose)

      val info: Int = {
        val info = new intW(0)
        lapack.dgesv(
          A.rows,
          X.cols,
          newA.data,
          newA.offset,
          newA.majorStride,
          piv,
          0,
          X.data,
          X.offset,
          X.majorStride,
          info)
        info.`val`
      }

      if (info > 0)
        throw new MatrixSingularException()
      else if (info < 0)
        throw new IllegalArgumentException()

      X
    }

    /** X := A \ V, for arbitrary A */
    def QRSolve(X: DenseMatrix[Double], A: DenseMatrix[Double], V: DenseMatrix[Double]): DenseMatrix[Double] = {

      require(X.offset == 0)
      require(A.offset == 0)
      require(V.offset == 0)
      require(X.rows == A.cols, "Wrong number of rows in return value")
      require(X.cols == V.cols, "Wrong number of rows in return value")
      val transpose: Boolean = A.isTranspose

      val nrhs = V.cols

      // allocate temporary solution matrix
      val Xtmp = DenseMatrix.zeros[Double](math.max(A.rows, A.cols), nrhs)
      Xtmp(0 until A.rows, 0 until nrhs) := V(0 until A.rows, 0 until nrhs)

      val newData: Array[Double] = A.data.clone()

      // query optimal workspace
      val queryWork = new Array[Double](1)
      val queryInfo = new intW(0)
      lapack.dgels(
        if (!transpose) "N" else "T",
        if (!transpose) A.rows else A.cols,
        if (!transpose) A.cols else A.rows,
        nrhs,
        newData,
        A.majorStride,
        Xtmp.data,
        math.max(1, math.max(A.rows, A.cols)),
        queryWork,
        -1,
        queryInfo
      )

      // allocate workspace
      val work: Array[Double] = {
        val lwork = {
          if (queryInfo.`val` != 0)
            math.max(1, math.min(A.rows, A.cols) + math.max(math.min(A.rows, A.cols), nrhs))
          else
            math.max(queryWork(0).toInt, 1)
        }
        new Array[Double](lwork)
      }

      // compute factorization
      val info = new intW(0)
      lapack.dgels(
        if (!transpose) "N" else "T",
        if (!transpose) A.rows else A.cols,
        if (!transpose) A.cols else A.rows,
        nrhs,
        newData,
        A.majorStride,
        Xtmp.data,
        math.max(1, math.max(A.rows, A.cols)),
        work,
        work.length,
        info
      )

      if (info.`val` < 0)
        throw new IllegalArgumentException

      // extract solution
      X := Xtmp(0 until X.rows, 0 until nrhs)

      X
    }
  }

  implicit object impl_OpSolveMatrixBy_DMD_DVD_eq_DVD
      extends OpSolveMatrixBy.Impl2[DenseMatrix[Double], DenseVector[Double], DenseVector[Double]] {
    override def apply(a: DenseMatrix[Double], b: DenseVector[Double]): DenseVector[Double] = {
      val rv: DenseMatrix[Double] = a \ new DenseMatrix[Double](b.size, 1, b.data, b.offset, b.stride, true)
      new DenseVector[Double](rv.data)
    }
  }

  // </editor-fold>

}

// TODO: Rename/collapse trait
trait DenseMatrixOps_FloatSpecialized extends DenseMatrixExpandedOps with DenseMatrixMultOps with DenseMatrix_SlicingOps {

  // <editor-fold defaultstate="collapsed" desc=" OpMulMatrix implementations ">

  implicit val impl_OpMulMatrix_DM_DM_eq_DM_Float: OpMulMatrix.Impl2[DenseMatrix[Float], DenseMatrix[Float], DenseMatrix[Float]] = {
    (_a: DenseMatrix[Float], _b: DenseMatrix[Float]) => {
      require(_a.cols == _b.rows, "Dimension mismatch!")
      val rv = DenseMatrix.zeros[Float](_a.rows, _b.cols)

      if (_a.rows != 0 && _b.rows != 0  &&  _a.cols != 0  &&  _b.cols != 0) {
        // if we have a weird stride...
        val a: DenseMatrix[Float] =
          if (_a.majorStride < math.max(if (_a.isTranspose) _a.cols else _a.rows, 1)) _a.copy else _a
        val b: DenseMatrix[Float] =
          if (_b.majorStride < math.max(if (_b.isTranspose) _b.cols else _b.rows, 1)) _b.copy else _b
        blas.sgemm(
          transposeString(a),
          transposeString(b),
          rv.rows,
          rv.cols,
          a.cols,
          1.0f,
          a.data,
          a.offset,
          a.majorStride,
          b.data,
          b.offset,
          b.majorStride,
          0.0f,
          rv.data,
          0,
          rv.rows)
      }
      rv
    }
  }
  implicitly[BinaryRegistry[Matrix[Float], Matrix[Float], OpMulMatrix.type, Matrix[Float]]]
    .register(impl_OpMulMatrix_DM_DM_eq_DM_Float)
  implicitly[BinaryRegistry[DenseMatrix[Float], Matrix[Float], OpMulMatrix.type, DenseMatrix[Float]]]
    .register(impl_OpMulMatrix_DM_DM_eq_DM_Float)

  private def transposeString(a: DenseMatrix[Float]): String = {
    if (a.isTranspose) "T" else "N"
  }

  implicit object impl_OpMulMatrix_DMF_DVF_eq_DVF
      extends OpMulMatrix.Impl2[DenseMatrix[Float], DenseVector[Float], DenseVector[Float]] {
    def apply(a: DenseMatrix[Float], b: DenseVector[Float]): DenseVector[Float] = {

      require(a.cols == b.length, "Dimension mismatch!")
      val rv = DenseVector.zeros[Float](a.rows)
      blas.sgemv(
        transposeString(a),
        if (a.isTranspose) a.cols else a.rows,
        if (a.isTranspose) a.rows else a.cols,
        1.0f,
        a.data,
        a.offset,
        a.majorStride,
        b.data,
        b.offset,
        b.stride,
        0.0f,
        rv.data,
        rv.offset,
        rv.stride
      )
      rv
    }
  }

  implicit val impl_OpMulMatrix_DVF_DMF_eq_DMF
    : OpMulMatrix.Impl2[DenseVector[Float], DenseMatrix[Float], DenseMatrix[Float]] = {
    new OpMulMatrix.Impl2[DenseVector[Float], DenseMatrix[Float], DenseMatrix[Float]] {
      def apply(a: DenseVector[Float], b: DenseMatrix[Float]): DenseMatrix[Float] = {
        require(b.rows == 1)
        //        val adata =  if(a.stride != 1) {
        //          val v = DenseVector.zeros[Float](a.length)
        //          v := a
        //          v.data
        //        } else {
        //          a.data
        //        }
        val rv: DenseMatrix[Float] = DenseMatrix.zeros[Float](a.length, b.cols)
        blas.sgemm(
          "T",
          transposeString(b),
          rv.rows,
          rv.cols,
          1,
          1.0f,
          a.data,
          a.offset,
          a.stride,
          b.data,
          b.offset,
          b.majorStride,
          0.0f,
          rv.data,
          0,
          rv.rows)
        rv

      }
    }
  }

  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" // <editor-fold defaultstate="collapsed" desc=" OpSolveMatrixBy implementations ">

  implicit object impl_OpSolveMatrixBy_DMF_DMF_eq_DMF
      extends OpSolveMatrixBy.Impl2[DenseMatrix[Float], DenseMatrix[Float], DenseMatrix[Float]] {

    override def apply(A: DenseMatrix[Float], V: DenseMatrix[Float]) = {
      require(A.rows == V.rows, "Non-conformant matrix sizes")

      if (A.size == 0) {
        DenseMatrix.zeros[Float](0, 0)
      } else if (A.rows == A.cols) {
        // square: LUSolve
        val X = DenseMatrix.zeros[Float](V.rows, V.cols)
        X := V
        LUSolve(X, A)
        X
      } else {
        // non-square: QRSolve
        val X = DenseMatrix.zeros[Float](A.cols, V.cols)
        QRSolve(X, A, V)
        X
      }
    }

    /** X := A \ X, for square A */
    def LUSolve(X: DenseMatrix[Float], A: DenseMatrix[Float]): DenseMatrix[Float] = {

      require(X.offset == 0)
      require(A.offset == 0)
      val piv = new Array[Int](A.rows)
      val newA: DenseMatrix[Float] = A.copy
      assert(!newA.isTranspose)

      val info: Int = {
        val info = new intW(0)
        lapack.sgesv(A.rows, X.cols, newA.data, newA.majorStride, piv, X.data, X.majorStride, info)
        info.`val`
      }

      if (info > 0)
        throw new MatrixSingularException()
      else if (info < 0)
        throw new IllegalArgumentException()

      X
    }

    /** X := A \ V, for arbitrary A */
    def QRSolve(X: DenseMatrix[Float], A: DenseMatrix[Float], V: DenseMatrix[Float]): DenseMatrix[Float] = {

      require(X.offset == 0)
      require(A.offset == 0)
      require(V.offset == 0)
      require(X.rows == A.cols, "Wrong number of rows in return value")
      require(X.cols == V.cols, "Wrong number of rows in return value")

      val transpose: Boolean = X.isTranspose

      val nrhs = V.cols

      // allocate temporary solution matrix
      val Xtmp = DenseMatrix.zeros[Float](math.max(A.rows, A.cols), nrhs)
      val M = if (!transpose) A.rows else A.cols
      Xtmp(0 until M, 0 until nrhs) := V(0 until M, 0 until nrhs)

      val newData: Array[Float] = A.data.clone()

      // query optimal workspace
      val queryWork = new Array[Float](1)
      val queryInfo = new intW(0)
      lapack.sgels(
        if (!transpose) "N" else "T",
        A.rows,
        A.cols,
        nrhs,
        newData,
        A.majorStride,
        Xtmp.data,
        math.max(1, math.max(A.rows, A.cols)),
        queryWork,
        -1,
        queryInfo)

      // allocate workspace
      val work: Array[Float] = {
        val lwork: Int = {
          if (queryInfo.`val` != 0)
            math.max(1, math.min(A.rows, A.cols) + math.max(math.min(A.rows, A.cols), nrhs))
          else
            math.max(queryWork(0).toInt, 1)
        }
        new Array[Float](lwork)
      }

      // compute factorization
      val info = new intW(0)
      lapack.sgels(
        if (!transpose) "N" else "T",
        A.rows,
        A.cols,
        nrhs,
        newData,
        A.majorStride,
        Xtmp.data,
        math.max(1, math.max(A.rows, A.cols)),
        work,
        work.length,
        info)

      if (info.`val` < 0)
        throw new IllegalArgumentException

      // extract solution
      val N = if (!transpose) A.cols else A.rows
      X(0 until N, 0 until nrhs) := Xtmp(0 until N, 0 until nrhs)

      X
    }
  }

  implicit object impl_OpSolveMatrixBy_DMF_DVF_eq_DVF
      extends OpSolveMatrixBy.Impl2[DenseMatrix[Float], DenseVector[Float], DenseVector[Float]] {

    override def apply(a: DenseMatrix[Float], b: DenseVector[Float]): DenseVector[Float] = {
      val rv: DenseMatrix[Float] = a \ new DenseMatrix[Float](b.size, 1, b.data, b.offset, b.stride, true)
      new DenseVector[Float](rv.data)
    }
  }

  // </editor-fold>
}

trait DenseMatrixExpandedOps extends MatrixOps with DenseMatrix_GenericOps with DenseMatrix_TraversalOps {

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpXXX.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]] ">
  // don't remove

  @expand
  @expand.valify
  implicit def dm_dm_UpdateOp[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpAdd, OpSub, OpMulScalar, OpDiv, OpSet, OpMod, OpPow) Op <: OpType](implicit
          @expand.sequence[Op]({ _ + _ }, { _ - _ }, { _ * _ }, { _ / _ }, {  (__x, __y) => __y }, { _ % _ }, { _.pow(_) })
          op: Op.Impl2[T, T, T],
          @expand.sequence[Op]({ _ += _ }, { _ -= _ }, { _ :*= _ }, { _ :/= _ }, { _ := _ }, { _ %= _ }, { _ :^= _ })
          vecOp: Op.Impl2[T, T, T]): Op.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]] = {

    new Op.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]] {
      def apply(a: DenseMatrix[T], b: DenseMatrix[T]): Unit = {
        require(a.rows == b.rows, "Row dimension mismatch!")
        require(a.cols == b.cols, "Col dimension mismatch!")

        if ((a ne b) && a.overlaps(b)) {
          val ac = a.copy
          apply(ac, b)
          a := ac
          // gives a roughly 5-10x speedup
          // if a and b are both nicely and identically shaped, add them as though they were vectors
        } else if (a.isTranspose == b.isTranspose && a.isContiguous && b.isContiguous) {
          vecOp(new DenseVector(a.data, a.offset, 1, a.size), new DenseVector(b.data, b.offset, 1, b.size))
        } else {
          slowPath(a, b)
        }

      }

      private def slowPath(a: DenseMatrix[T], b: DenseMatrix[T]): Unit = {
        if (a.isTranspose) {
          apply(a.t, b.t)
        } else {
          val ad = a.data
          val bd = b.data
          cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
            ad(a.linearIndex(r, c)) = op(ad(a.linearIndex(r, c)), bd(b.linearIndex(r, c)))
          }
        }
      }

      implicitly[BinaryUpdateRegistry[Matrix[T], Matrix[T], Op.type]].register(this)
    }
  }

  @expand
  implicit def dm_dm_UpdateOp[
      @expand.args(OpAdd, OpSub, OpMulScalar, OpDiv, OpMod, OpPow) Op <: OpType,
      T: Field: Zero: ClassTag](
      implicit @expand.sequence[Op]({ f.+(_, _) }, { f.-(_, _) }, { f.*(_, _) }, { f./(_, _) }, { f.%(_, _) }, {
        f.pow(_, _)
      }) op: Op.Impl2[T, T, T]): Op.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]] = {
    val f = implicitly[Field[T]]
    new Op.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]] {
      def apply(a: DenseMatrix[T], b: DenseMatrix[T]): Unit = {
        val ad = a.data
        val bd = b.data

        if ((a ne b) && a.overlaps(b)) {
          val ac = a.copy
          apply(ac, b)
          a := ac
        } else {
          cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
            ad(a.linearIndex(r, c)) = op(ad(a.linearIndex(r, c)), bd(b.linearIndex(r, c)))
          }
        }

      }

      implicitly[BinaryUpdateRegistry[Matrix[T], Matrix[T], Op.type]].register(this)
    }
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpXXX.InPlaceImpl2[DenseMatrix[T], T] ">

  @expand
  @expand.valify
  implicit def dm_s_UpdateOp[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMulMatrix, OpDiv, OpSet, OpMod, OpPow) Op <: OpType](
      implicit @expand.sequence[Op]({ _ + _ }, { _ - _ }, { _ * _ }, { _ * _ }, { _ / _ }, {  (__x, __y) => __y }, { _ % _ }, { _.pow(_) }) op: Op.Impl2[T, T, T]): Op.InPlaceImpl2[DenseMatrix[T], T] =
    new Op.InPlaceImpl2[DenseMatrix[T], T] {
      def apply(a: DenseMatrix[T], b: T): Unit = {

        if (a.isContiguous) {
          fastPath(a, b)
        } else {
          slowPath(a, b)
        }

      }

      def fastPath(a: DenseMatrix[T], b: T): Unit = {
        val ad: Array[T] = a.data
        cforRange(a.offset until (a.offset + a.size)) { i =>
          ad(i) = op(ad(i), b)
        }
      }

      def slowPath(a: DenseMatrix[T], b: T): Unit = {
        val ad = a.data
        if (!a.isTranspose) {
          cforRange2(0 until a.cols, 0 until a.rows) { (c, r) =>
            ad(a.linearIndex(r, c)) = op(ad(a.linearIndex(r, c)), b)
          }
        } else {
          cforRange2(0 until a.rows, 0 until a.cols) { (r, c) =>
            ad(a.linearIndex(r, c)) = op(ad(a.linearIndex(r, c)), b)
          }
        }
      }

      implicitly[BinaryUpdateRegistry[Matrix[T], T, Op.type]].register(this)
    }

  @expand
  implicit def opUpdate_DM_S[
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMulMatrix, OpDiv, OpMod, OpPow) Op <: OpType,
      T: Field: Zero: ClassTag](
      implicit @expand.sequence[Op]({ f.+(_, _) }, { f.-(_, _) }, { f.*(_, _) }, { f.*(_, _) }, { f./(_, _) }, {
        f.%(_, _)
      }, { f.pow(_, _) }) op: Op.Impl2[T, T, T]): Op.InPlaceImpl2[DenseMatrix[T], T] = {
    val f = implicitly[Field[T]]
    new Op.InPlaceImpl2[DenseMatrix[T], T] {
      override def apply(a: DenseMatrix[T], b: T) = {
        val ad: Array[T] = a.data

        cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
          ad(a.linearIndex(r, c)) = op(ad(a.linearIndex(r, c)), b)
        }
      }
      implicitly[BinaryUpdateRegistry[Matrix[T], T, Op.type]].register(this)
    }
  }
  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpXXX.Impl2[DenseMatrix[T], T, DenseMatrix[T]] ">

  @expand
  @expand.valify
  implicit def op_DM_S[
      @expand.args(Int, Long, Float, Double) T,
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMulMatrix, OpMod, OpDiv, OpPow) Op]
    : Op.Impl2[DenseMatrix[T], T, DenseMatrix[T]] = {
    val uop = implicitly[Op.InPlaceImpl2[DenseMatrix[T], T]]
    new Op.Impl2[DenseMatrix[T], T, DenseMatrix[T]] {
      override def apply(a: DenseMatrix[T], b: T) = {
        val c = copy(a)
        uop(c, b)
        c
      }
      implicitly[BinaryRegistry[Matrix[T], T, Op.type, Matrix[T]]].register(this)
    }
  }

  @expand
  implicit def op_DM_S[
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMulMatrix, OpDiv, OpMod, OpPow) Op <: OpType,
      T: Field: Zero: ClassTag]:
//  (implicit @expand.sequence[Op]({f.+(_,_)}, {f.-(_,_)}, {f.*(_,_)}, {f.*(_,_)}, {f./(_,_)}, {f.%(_,_)},{f.pow(_,_)}) op: Op.Impl2[T,T,T]):
  Op.Impl2[DenseMatrix[T], T, DenseMatrix[T]] = {
    val uop = implicitly[Op.InPlaceImpl2[DenseMatrix[T], T]]
    new Op.Impl2[DenseMatrix[T], T, DenseMatrix[T]] {
      override def apply(a: DenseMatrix[T], b: T) = {
        val c = copy(a)
        uop(c, b)
        c
      }
      implicitly[BinaryRegistry[Matrix[T], T, Op.type, Matrix[T]]].register(this)
    }
  }

  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpXXX.Impl2[T, DenseMatrix[T], DenseMatrix[T]] ">

  @expand
  @expand.valify
  implicit def s_dm_op[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMulMatrix, OpDiv, OpMod, OpPow) Op <: OpType](implicit @expand.sequence[
    Op]({ _ + _ }, { _ - _ }, { _ * _ }, { _ * _ }, { _ / _ }, { _ % _ }, { _.pow(_) }) op: Op.Impl2[T, T, T])
    : Op.Impl2[T, DenseMatrix[T], DenseMatrix[T]] =
    new Op.Impl2[T, DenseMatrix[T], DenseMatrix[T]] {
      def apply(b: T, a: DenseMatrix[T]): DenseMatrix[T] = {
        val res: DenseMatrix[T] = DenseMatrix.zeros[T](a.rows, a.cols)
        val resd: Array[T] = res.data
        val ad: Array[T] = a.data
        var off = 0

        cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
          resd(off) = op(b, ad(a.linearIndex(r, c)))
          off += 1
        }

        res
      }

      implicitly[BinaryRegistry[T, Matrix[T], Op.type, Matrix[T]]].register(this)
    }

  implicit def s_dm_op[T, Op <: OpType, U](
      implicit opScalar: UFunc.UImpl2[Op, T, T, U],
      ct: ClassTag[U],
      zero: Zero[U]): UFunc.UImpl2[Op, T, DenseMatrix[T], DenseMatrix[U]] = {
    new UFunc.UImpl2[Op, T, DenseMatrix[T], DenseMatrix[U]] {
      def apply(b: T, a: DenseMatrix[T]): DenseMatrix[U] = {
        val res: DenseMatrix[U] = DenseMatrix.zeros[U](a.rows, a.cols)
        val resd: Array[U] = res.data
        val ad: Array[T] = a.data
        var off = 0

        cforRange2 (0 until a.cols, 0 until a.rows) { (c,r) =>
          resd(off) = opScalar(b, ad(a.linearIndex(r, c)))
          off += 1
        }

        res
      }
    }
  }

  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpXXX.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]] ">

  @expand
  @expand.valify
  implicit def op_DM_DM[
      @expand.args(Int, Long, Float, Double) T,
      @expand.args(OpAdd, OpSub, OpMulScalar, OpMod, OpDiv, OpPow) Op]
    : Op.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]] = {
    val uop = implicitly[Op.InPlaceImpl2[DenseMatrix[T], DenseMatrix[T]]]
    new Op.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]] {
      override def apply(a: DenseMatrix[T], b: DenseMatrix[T]): DenseMatrix[T] = {
        val c = copy(a)
        uop(c, b)

        c
      }

      implicitly[BinaryRegistry[Matrix[T], Matrix[T], Op.type, Matrix[T]]].register(this)
    }
  }

  // </editor-fold>

}

trait DenseMatrixOpsLowPrio extends MatrixOps {
}

trait DenseMatrixMultOps extends DenseMatrixExpandedOps with DenseMatrixOpsLowPrio {
  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for BinaryRegistry ">

  @expand
  @expand.valify
  implicit def impl_OpMulMatrix_DM_V_eq_DV[@expand.args(Int, Long, Float, Double) T]
    : BinaryRegistry[DenseMatrix[T], Vector[T], OpMulMatrix.type, DenseVector[T]] =
    new BinaryRegistry[DenseMatrix[T], Vector[T], OpMulMatrix.type, DenseVector[T]] {
      override def bindingMissing(a: DenseMatrix[T], b: Vector[T]): DenseVector[T] = {

        // TODO: this could probably be much faster?
        require(a.cols == b.length)
        val res: DenseVector[T] = DenseVector.zeros[T](a.rows)
        cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
          val v = a(r, c)
          res(r) += v * b(c)
        }

        res
      }

      implicitly[BinaryRegistry[Matrix[T], Vector[T], OpMulMatrix.type, Vector[T]]].register(this)
    }

  @expand
  @expand.valify
  implicit def impl_OpMulMatrix_DM_M_eq_DM[@expand.args(Int, Long, Float, Double) T]
    : BinaryRegistry[DenseMatrix[T], Matrix[T], OpMulMatrix.type, DenseMatrix[T]] =
    new BinaryRegistry[DenseMatrix[T], Matrix[T], OpMulMatrix.type, DenseMatrix[T]] {
      override def bindingMissing(a: DenseMatrix[T], b: Matrix[T]): DenseMatrix[T] = {
        // Martin Senne:
        // Accessing consequent areas in memory in the innermost loop ( a(i,l), a(i+1,l) ) is faster
        // than accessing ( b(c, j), b(c, j+1) as data layout in memory is column-like (Fortran), that is a(0,0), a(1,0), a(2,0), ...
        // Thus (adapted from dgemm in BLAS):
        //   - exchanged loop order
        //   - so to access consequent entries in the innermost loop and to hopefully avoid cache-misses
        val res: DenseMatrix[T] = DenseMatrix.zeros[T](a.rows, b.cols)
        require(a.cols == b.rows)

        val colsB = b.cols
        val colsA = a.cols
        val rowsA = a.rows
        // TODO: optimize in the case of isTranspose
        // TODO: consider a block impl

        cforRange (0 until colsB) { j =>
          cforRange (0 until colsA) { l =>
            val v = b(l, j)
            cforRange (0 until rowsA) { i =>
              res(i, j) += v * a(i, l)
            }
          }
        }
        res
      }

      implicitly[BinaryRegistry[Matrix[T], Matrix[T], OpMulMatrix.type, Matrix[T]]].register(this)
    }

  // </editor-fold>

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpMulMatrix ">

  @expand
  @expand.valify
  implicit def impl_OpMulMatrix_DM_DM_eq_DM[@expand.args(Int, Long) T]
    : OpMulMatrix.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]] =
    new OpMulMatrix.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[T]] {
      // amazingly, the bigger these are, the better.
      val blockSizeRow = 2000
      val blockSizeInner = 2000
      val blockSizeCol = 2000

      def multBlock(
          M: Int,
          N: Int,
          K: Int,
          aTrans: Array[T],
          b: Array[T],
          res: DenseMatrix[T],
          resRowOff: Int,
          resColOff: Int): Unit = {
        val rd = res.data
        val rOff = res.offset + resRowOff + resColOff * res.majorStride

        cforRange2(0 until M, 0 until K) { (i, k) =>
          var sum: T = 0
          cforRange(0 until N) { (j) =>
            sum += aTrans(i * N + j) * b(k * N + j)
          }
          rd(rOff + i + k * res.majorStride) += sum
        }
      }

      override def apply(a: DenseMatrix[T], b: DenseMatrix[T]): DenseMatrix[T] = {
        val res: DenseMatrix[T] = DenseMatrix.zeros[T](a.rows, b.cols)
        require(a.cols == b.rows)

        val aTrans = new Array[T](math.min(blockSizeRow * blockSizeInner, a.size))
        val bBuf = new Array[T](math.min(blockSizeInner * blockSizeCol, b.size))

        val numRowBlocks = (a.rows + blockSizeRow - 1) / blockSizeRow
        val numInnerBlocks = (a.cols + blockSizeCol - 1) / blockSizeCol
        val numColBlocks = (b.cols + blockSizeInner - 1) / blockSizeInner

        cforRange(0 until numRowBlocks) { r =>
          val mBegin = r * blockSizeRow
          val mEnd = math.min(mBegin + blockSizeRow, a.rows)
          val M = mEnd - mBegin
          cforRange(0 until numInnerBlocks) { i =>
            val nBegin = i * blockSizeInner
            val nEnd = math.min(nBegin + blockSizeInner, a.cols)
            val N = nEnd - nBegin

            if (a.isTranspose) {
              cforRange(0 until M) { m =>
                System.arraycopy(a.data, a.offset + (m + mBegin) * a.majorStride + nBegin, aTrans, m * N, N)
              }
            } else {
              cforRange2(0 until N, 0 until M) { (n, m) =>
                aTrans(m * N + n) = a(m + mBegin, n + nBegin)
              }
            }

            cforRange(0 until numColBlocks) { c =>
              val oBegin = c * blockSizeCol
              val oEnd = math.min(oBegin + blockSizeCol, b.cols)
              val O = oEnd - oBegin

              cforRange2(0 until O, 0 until N) { (o, n) =>
                bBuf(o * N + n) = b(n + nBegin, o + oBegin)
              }

              multBlock(M, N, O, aTrans, bBuf, res, mBegin, oBegin)

            }
          }
        }

        res
      }
      implicitly[BinaryRegistry[Matrix[T], Matrix[T], OpMulMatrix.type, Matrix[T]]].register(this)
      implicitly[BinaryRegistry[DenseMatrix[T], Matrix[T], OpMulMatrix.type, DenseMatrix[T]]].register(this)
    }

  // </editor-fold>

}

trait DenseMatrix_SetOps extends DenseMatrix_SlicingOps {

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpSet ">

  class SetDMDMOp[@spec(Double, Int, Float, Long) V] extends OpSet.InPlaceImpl2[DenseMatrix[V], DenseMatrix[V]] {

    def apply(a: DenseMatrix[V], b: DenseMatrix[V]): Unit = {
      require(a.rows == b.rows, "Matrixs must have same number of rows")
      require(a.cols == b.cols, "Matrixs must have same number of columns")

      if (a.isTranspose == b.isTranspose && a.isContiguous && b.isContiguous) {
        System.arraycopy(b.data, b.offset, a.data, a.offset, a.size)
      } else if (a.isTranspose == b.isTranspose) {
        cforRange(0 until a.majorSize) { j =>
          System.arraycopy(b.data, b.offset + j * b.majorStride, a.data, a.offset + j * a.majorStride, a.minorSize)
        }
      } else {
        cacheObliviousTranspose(0, a.majorSize, 0, b.majorSize, a.data, a.offset, a.majorStride, b.data, b.offset, b.majorStride)
      }
    }

    def cacheObliviousTranspose(
        rBegin: Int,
        rEnd: Int,
        cBegin: Int,
        cEnd: Int,
        dst: Array[V],
        dstOff: Int,
        aMajorStride: Int,
        src: Array[V],
        srcOff: Int,
        bMajorStride: Int): Unit = {
      val r = rEnd - rBegin
      val c = cEnd - cBegin
      if (r <= 16 && c <= 16) {
        cforRange2(rBegin until rEnd, cBegin until cEnd) { (j, i) =>
          dst(dstOff + j * aMajorStride + i) = src(srcOff + i * bMajorStride + j)
        }
      } else if (r >= c) {
        cacheObliviousTranspose(rBegin, rBegin + (r / 2), cBegin, cEnd, dst, dstOff, aMajorStride, src, srcOff, bMajorStride)
        cacheObliviousTranspose(rBegin + (r / 2), rEnd, cBegin, cEnd, dst, dstOff,aMajorStride, src, srcOff,bMajorStride)
      } else {
        cacheObliviousTranspose(rBegin, rEnd, cBegin, cBegin + (c / 2), dst, dstOff,aMajorStride, src, srcOff,bMajorStride)
        cacheObliviousTranspose(rBegin, rEnd, cBegin + (c / 2), cEnd, dst, dstOff,aMajorStride, src, srcOff,bMajorStride)
      }
    }
  }

  class SetDMDVOp[@spec(Double, Int, Float, Long) V] extends OpSet.InPlaceImpl2[DenseMatrix[V], DenseVector[V]] {

    def apply(a: DenseMatrix[V], b: DenseVector[V]): Unit = {
      require(
        a.rows == b.length && a.cols == 1 || a.cols == b.length && a.rows == 1,
        "DenseMatrix must have same number of rows, or same number of columns, as DenseVector, and the other dim must be 1."
      )

      val ad: Array[V] = a.data
      val bd: Array[V] = b.data
      var boff = b.offset
      cforRange2 (0 until a.cols, 0 until a.rows) { (c, r) =>
        ad(a.linearIndex(r, c)) = bd(boff)
        boff += b.stride
      }
    }
  }

  class SetMSOp[@spec(Double, Int, Float, Long) V] extends OpSet.InPlaceImpl2[DenseMatrix[V], V] {

    def apply(a: DenseMatrix[V], b: V): Unit = {
      if (a.isContiguous) {
        ArrayUtil.fill(a.data, a.offset, a.size, b)
      } else {
        slowPath(a, b)
      }
    }

    private def slowPath(a: DenseMatrix[V], b: V): Unit = {
      // slow path when we don't have a trivial matrix
      val ad: Array[V] = a.data
      var aoff = a.offset
      cforRange(0 until a.majorSize) { big =>
        cforRange(0 until a.minorSize) { little =>
          ad(aoff + little) = b
        }
        aoff += a.majorStride
      }
    }
  }

  implicit def impl_OpMulSet_InPlace_DM_DM[V]: OpSet.InPlaceImpl2[DenseMatrix[V], DenseMatrix[V]] = new SetDMDMOp[V]
  implicit def impl_OpMulSet_InPlace_DM_S[V]: OpSet.InPlaceImpl2[DenseMatrix[V], V] = new SetMSOp[V]

  // </editor-fold>

}

trait LowPriorityDenseMatrix1 {

  /**
   * Returns a 1xnumCols DenseMatrix
   * @tparam V
   * @tparam R
   * @return
   */
  implicit def canCollapseRows_DM[V, R: ClassTag]
    : CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], R, Transpose[DenseVector[R]]] =
    new CanCollapseAxis[DenseMatrix[V], Axis._0.type, DenseVector[V], R, Transpose[DenseVector[R]]] {
      def apply(from: DenseMatrix[V], axis: Axis._0.type)(f: (DenseVector[V]) => R): Transpose[DenseVector[R]] = {
        val result = new DenseVector[R](from.cols)
        cforRange(0 until from.cols) { c =>
          result(c) = f(from(::, c))
        }
        result.t
      }
    }

  /**
   * Returns a numRows DenseVector
   * @tparam V
   * @tparam R
   * @return
   */
  implicit def canCollapseCols_DM[V, R: ClassTag]: CanCollapseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V], R, DenseVector[R]] =
    new CanCollapseAxis[DenseMatrix[V], Axis._1.type, DenseVector[V], R, DenseVector[R]] {
      def apply(from: DenseMatrix[V], axis: Axis._1.type)(f: (DenseVector[V]) => R): DenseVector[R] = {
        val result = new DenseVector[R](from.rows)
        val t = from.t
        cforRange(0 until from.rows) { r =>
          result(r) = f(t(::, r))
        }
        result
      }
    }

  // <editor-fold defaultstate="collapsed" desc=" implicit implementations for OpSet ">

  implicit def impl_OpSet_InPlace_DM_M[@spec(Double, Int, Float, Long) V]: OpSet.InPlaceImpl2[DenseMatrix[V], Matrix[V]] = {
    (a: DenseMatrix[V], b: Matrix[V]) => {
      require(a.rows == b.rows, "Matrixs must have same number of rows")
      require(a.cols == b.cols, "Matrixs must have same number of columns")

      // TODO: detect b is a DM and dispatch
      // TODO: check isTranspose?

      val ad = a.data
      cforRange (0 until a.cols) { c =>
        cforRange (0 until a.rows) { r =>
          ad(a.linearIndex(r, c)) = b(r, c)
        }
      }
    }
  }

  // </editor-fold>

}

/**
 * Operators for comparisons among elements of a DenseMatrix
 *
 * @author dlwh
 **/
trait DenseMatrix_ComparisonOps extends DenseMatrixExpandedOps {

  @expand
  implicit def impl_Op_DM_DM_eq_DMBool[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpGT, OpGTE, OpLTE, OpLT, OpEq, OpNe) Op <: OpType](
      implicit @expand.sequence[Op]({ _ > _ }, { _ >= _ }, { _ <= _ }, { _ < _ }, { _ == _ }, { _ != _ })
      op: Op.Impl2[T, T, T]): Op.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[Boolean]] =
    new Op.Impl2[DenseMatrix[T], DenseMatrix[T], DenseMatrix[Boolean]] {
      def apply(a: DenseMatrix[T], b: DenseMatrix[T]): DenseMatrix[Boolean] = {
        if (a.isTranspose) {
          apply(a.t, b.t).t
        } else {
          if (a.rows != b.rows)
            throw new ArrayIndexOutOfBoundsException(s"Rows don't match for operator $Op ${a.rows} ${b.rows}")
          if (a.cols != b.cols)
            throw new ArrayIndexOutOfBoundsException(s"Cols don't match for operator $Op ${a.cols} ${b.cols}")
          val result = DenseMatrix.zeros[Boolean](a.rows, a.cols)

          cforRange2(0 until a.cols, 0 until a.rows) { (j, i) =>
            result(i, j) = op(a(i, j), b(i, j))
          }

          result
        }
      }
    }

  @expand
  implicit def impl_Op_DM_M_eq_DMBool_Comparison[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpGT, OpGTE, OpLTE, OpLT, OpEq, OpNe) Op <: OpType](
      implicit @expand.sequence[Op]({ _ > _ }, { _ >= _ }, { _ <= _ }, { _ < _ }, { _ == _ }, { _ != _ })
      op: Op.Impl2[T, T, Boolean]): Op.Impl2[DenseMatrix[T], Matrix[T], DenseMatrix[Boolean]] =
    new Op.Impl2[DenseMatrix[T], Matrix[T], DenseMatrix[Boolean]] {
      def apply(a: DenseMatrix[T], b: Matrix[T]): DenseMatrix[Boolean] = {
        if (a.rows != b.rows)
          throw new ArrayIndexOutOfBoundsException(s"Rows don't match for operator $Op ${a.rows} ${b.rows}")
        if (a.cols != b.cols)
          throw new ArrayIndexOutOfBoundsException(s"Cols don't match for operator $Op ${a.cols} ${b.cols}")
        val result = DenseMatrix.zeros[Boolean](a.rows, a.cols)

        cforRange2(0 until a.cols, 0 until a.rows) { (j, i) =>
          result(i, j) = op(a(i, j), b(i, j))
        }

        result
      }
    }

  @expand
  implicit def impl_Op_DM_S_eq_DMBool_Comparison[
      @expand.args(Int, Double, Float, Long) T,
      @expand.args(OpGT, OpGTE, OpLTE, OpLT, OpEq, OpNe) Op <: OpType](
      implicit @expand.sequence[Op]({ _ > _ }, { _ >= _ }, { _ <= _ }, { _ < _ }, { _ == _ }, { _ != _ })
      op: Op.Impl2[T, T, Boolean]): Op.Impl2[DenseMatrix[T], T, DenseMatrix[Boolean]] =
    new Op.Impl2[DenseMatrix[T], T, DenseMatrix[Boolean]] {
      def apply(a: DenseMatrix[T], b: T): DenseMatrix[Boolean] = {
        if (a.isTranspose) {
          apply(a.t, b).t
        } else {
          val result = DenseMatrix.zeros[Boolean](a.rows, a.cols)

          cforRange2 (0 until a.cols, 0 until a.rows) { (j, i) =>
            result(i, j) = op(a(i, j), b)
          }

          result
        }
      }
    }

}


text:
"""A script to publish a release of cli_helpers to PyPI."""

import io
from optparse import OptionParser
import re
import subprocess
import sys

import click

DEBUG = False
CONFIRM_STEPS = False
DRY_RUN = False

def skip_step():
    """
    Asks for user's response whether to run a step. Default is yes.
    :return: boolean
    """
    global CONFIRM_STEPS

    if CONFIRM_STEPS:
        return not click.confirm("--- Run this step?", default=True)
    return False

def run_step(*args):
    """
    Prints out the command and asks if it should be run.
    If yes (default), runs it.
    :param args: list of strings (command and args)
    """
    global DRY_RUN

    cmd = args
    print(" ".join(cmd))
    if skip_step():
        print("--- Skipping...")
    elif DRY_RUN:
        print("--- Pretending to run...")
    else:
        subprocess.check_output(cmd)

def version(version_file):
    _version_re = re.compile(
        r'__version__\s+=\s+(?P<quote>[\'"])(?P<version>.*)(?P=quote)'
    )

    with io.open(version_file, encoding="utf-8") as f:
        ver = _version_re.search(f.read()).group("version")

    return ver

def commit_for_release(version_file, ver):
    run_step("git", "reset")
    run_step("git", "add", version_file)
    run_step("git", "commit", "--message", "Releasing version {}".format(ver))

def create_git_tag(tag_name):
    run_step("git", "tag", tag_name)

def create_distribution_files():
    run_step("python", "setup.py", "clean", "--all", "sdist", "bdist_wheel")

def upload_distribution_files():
    run_step("twine", "upload", "dist/*")

def push_to_github():
    run_step("git", "push", "origin", "master")

def push_tags_to_github():
    run_step("git", "push", "--tags", "origin")

def checklist(questions):
    for question in questions:
        if not click.confirm("--- {}".format(question), default=False):
            sys.exit(1)

if __name__ == "__main__":
    if DEBUG:
        subprocess.check_output = lambda x: x

    checks = [
        "Have you updated the AUTHORS file?",
        "Have you updated the `Usage` section of the README?",
    ]
    checklist(checks)

    ver = version("cli_helpers/__init__.py")
    print("Releasing Version:", ver)

    parser = OptionParser()
    parser.add_option(
        "-c",
        "--confirm-steps",
        action="store_true",
        dest="confirm_steps",
        default=False,
        help=(
            "Confirm every step. If the step is not " "confirmed, it will be skipped."
        ),
    )
    parser.add_option(
        "-d",
        "--dry-run",
        action="store_true",
        dest="dry_run",
        default=False,
        help="Print out, but not actually run any steps.",
    )

    popts, pargs = parser.parse_args()
    CONFIRM_STEPS = popts.confirm_steps
    DRY_RUN = popts.dry_run

    if not click.confirm("Are you sure?", default=False):
        sys.exit(1)

    commit_for_release("cli_helpers/__init__.py", ver)
    create_git_tag("v{}".format(ver))
    create_distribution_files()
    push_to_github()
    push_tags_to_github()
    upload_distribution_files()


text:
from google.cloud import gke_backup_v1

def sample_get_restore_plan():
    # Create a client
    client = gke_backup_v1.BackupForGKEClient()

    # Initialize request argument(s)
    request = gke_backup_v1.GetRestorePlanRequest(
        name="name_value",
    )

    # Make the request
    response = client.get_restore_plan(request=request)

    # Handle the response
    print(response)

# [END gkebackup_v1_generated_BackupForGKE_GetRestorePlan_sync_16da5c9f]


text:
Title Slide
===========

----

Paragraphs
==========

.notes: notes

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultricies
tempus ultricies. Ut porta scelerisque viverra. Pellentesque aliquam metus
scelerisque dui ultricies, auctor dictum erat aliquet. Integer vehicula nunc
elit, vel iaculis lorem facilisis non.

.notes: more notes

Vivamus ante mauris, pellentesque et rhoncus ut, condimentum sed ipsum.
Nullam eu molestie sapien. Curabitur imperdiet, ligula id blandit sagittis,
libero quam consectetur felis, ac pharetra metus lectus vitae leo. Mauris
lacinia fermentum augue.

----

Blockquotes
===========

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris ultricies
    tempus ultricies. Ut porta scelerisque viverra. Pellentesque aliquam metus
    scelerisque dui ultricies, auctor dictum erat aliquet. Integer vehicula
    nunc elit, vel iaculis lorem facilisis non.

----

Subheadings and Emphasis
========================

Italic
------

*Lorem ipsum dolor sit amet*

Bold
----

**Lorem ipsum dolor sit amet**

----

First heading: *lorem ipsum* dolor sit
======================================

Second: *lorem ipsum* dolor sfi amet, consecte
----------------------------------------------

Third: *lorem ipsum* dolor sit amet, consectetur adipiscing
```````````````````````````````````````````````````````````

* 1
* 2
* 3
* 4
* 5
* 6
* 7

----

Lists
=====

Unordered List
--------------

- Markdown
- ReStructured Text
- Textile

Ordered List
------------

1. Python
2. JavaScript
3. HTML5

----

Second Title Slide
==================

----

Code
====

Single Word
-----------

Hello ``World``

Python
------

.. code-block:: python

    def multiply (x, y):
        return x * y

JavaScript
----------

.. code-block:: javascript

    multiply: function (x, y) {
      return x * y;
    }

HTML
----

.. code-block:: html

    <!doctype html>

----

Images
======

.. image:: ../_assets/landscape.jpg

----

View Presenter Notes
====================

This slide has presenter notes. Press ``p`` to view them.

Presenter Notes
===============

Hello from presenter notes

----

TOC and subsections
===================

A presentation supports multiple section levels. Subsections can be used to organize contents and generate local table of contents.

A table of content with depth 1:

.. contents::
   :local:
   :depth: 1

----

Subsection A
------------

This slide is a subsection of the section "Toc and subsections"

----

Subsection B
------------

This slide is a subsection of the section "Toc and subsections"

----

About the global TOC
--------------------

The global TOC includes sections and subsections.

The max-toc-level parameter allows the user to limit the number of subsections included in the global TOC.

----

Other features
==============

View other features in the help sidebar by pressing ``h``


text:
    .global name; \
    name:

#define ALIGN(x) \
    .align x

#define SECTION(sec) \
    .section sec

#else

#include <stddef.h>
#include <stdint.h>
#include <stdarg.h>

int vsprintf(char* buf, const char* fmt, va_list args);
int sprintf(char* buf, const char* fmt, ...);

inline constexpr void* operator new(size_t, void* address) {
    return address;
}

inline constexpr void* operator new[](size_t, void* address) {
    return address;
}

#ifdef __cplusplus
#define asmlinkage extern "C"
#else
#define asmlinkage
#endif

#define ALIGN(x) __attribute__((aligned(x)))
#define PACKED __attribute__((packed))
#define SECTION(x) __attribute__ ((section(#x)))
#define FASTCALL(x) __attribute__((regparm(3))) x
#define NORETURN __attribute__((noreturn))

#define EXPAND(x) x
#define PASTE(a, b) a##b

#define __STRINGIFY(x) #x
#define STRINGIFY(x) __STRINGIFY(x)

namespace yacppl {}

namespace utils = yacppl;

#define __off_t_defined
using off_t = int;

enum errno {
    err_no_error = 0,
    err_no_such_file,
    err_is_a_dir,
    err_exists,
    err_cannot_create,
    err_no_root,
};

#endif


text:
from django import forms
from django.forms import fields
from django.core.validators import validate_email
from .widgets import AutocompleteTextarea

class CSVListField(fields.CharField):
    """
        When you want a CharField that returns a list.
    """

    def to_python(self, value):
        if isinstance(value, list):
            return ", ".join(value)
        return [v.strip() for v in value.split(',')]

    def prepare_value(self, value):
        if isinstance(value, list):
            return ", ".join(value)
        return value

class MultiCharField(forms.Field):
    """
    A text field that expects a comma-separated list of inputs, and by default
    uses the AutocompleteTextarea widget, which uses a jQuery plugin to provide
    autocompletion (depends on Bootstrap) based on the 'choices' constructor
    argument.

    """
    widget = AutocompleteTextarea

    def __init__(self, initial=None, choices=(), *args, **kwargs):
        """
        choices - a list of choices to use as a source for autocompletion

        """
        if initial:
            initial = ', '.join(initial)
        super(MultiCharField, self).__init__(initial=initial, *args, **kwargs)

        self.choices = choices

    def _get_choices(self):
        return self._choices

    def _set_choices(self, value):
        self._choices = self.widget.choices = value

    choices = property(_get_choices, _set_choices)

    def to_python(self, value):
        if not value:
            return []

        return [val.strip() for val in value.split(',') if val.strip()]

    def run_validators(self, value):
        for val in value:
            if val not in self.choices:
                super(MultiCharField, self).run_validators(val)

class MultiEmailField(MultiCharField):
    """
    Validates that all provided emails are valid email addresses (or included
    in the 'choices' constructor argument).

    """
    default_validators = [validate_email]
    default_error_messages = {
        'invalid': 'Please enter only valid email addresses.'
    }


text:
Stats CLI
=========

[![crates.io](https://img.shields.io/crates/v/stats-cli)](https://crates.io/crates/stats-cli)
[![documentation](https://docs.rs/stats-cli/badge.svg)](https://docs.rs/stats-cli)
[![tests](https://github.com/erikbrinkman/stats/actions/workflows/rust.yml/badge.svg)](https://github.com/erikbrinkman/stats/actions/workflows/rust.yml)
![MIT License](https://img.shields.io/github/license/erikbrinkman/stats)

Rust package for efficiently computing statistics on floating point numbers from the command line.
This contains both a command line binary and a rust library with incremental statistics objects.
Currently only summary statistics (min, mean, variance), percentiles, and mode are supported.

See the rust documentation for the library api, or the cli help for usage.

To Do
-----

- [ ] Add sketches (many other crates do this)
- [ ] Add testing to cli
- [ ] Weigh tradeoffs behind `DerefCopy` trait vs `Borrow + Copy`


text:
/**
 * IS `true` for Node.js 10.10 and greater.
 */
export declare const IS_SUPPORT_READDIR_WITH_FILE_TYPES: boolean;
//# sourceMappingURL=constants.d.ts.map


text:
package com.mmnaseri.couteau.graph.node.impl;

import com.mmnaseri.couteau.basics.api.Stringifiable;
import com.mmnaseri.couteau.graph.node.MutableNode;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Milad Naseri (mmnaseri@programmer.net)
 * @since 1.0 (2013/7/24, 15:04)
 */
public class DirectedNode<N extends DirectedNode<N>> implements MutableNode<N> {

    /**
     * The stringifiable object associated with the node, to help facilitate
     * writing the node as a string value
     */
    private final Stringifiable<DirectedNode<N>> stringifiable;

    /**
     * The map containing all user data associated with the node
     */
    private final Map<String, Object> userData = new HashMap<String, Object>();

    /**
     * This nodes neighbors and link weights
     */
    private final Map<N, Double> neighbors = new HashMap<N, Double>();

    /**
     * The map of all attribute values
     */
    private final Map<String, String> attributes = new HashMap<String, String>();

    public DirectedNode() {
        this(null);
    }

    public DirectedNode(Stringifiable<DirectedNode<N>> stringifiable) {
        this.stringifiable = stringifiable;
    }

    /**
     * Will update the value of the given attribute. If this attribute has not been set
     * previously, it will be added to the node.
     * @param attributeName    the name of the attribute to be changed
     * @param value            the value of the attribute
     */
    @Override
    public void setAttribute(String attributeName, String value) {
        attributes.put(attributeName, value);
    }

    /**
     * This method adds a new neighbor to the node, with the weight being set to zero.
     * If the node is already a neighbor of this node, the weight of the connection between
     * the two will be set to zero.
     * @param neighbor    the node be added as a neighbor
     */
    @Override
    public void addNeighbor(N neighbor) {
        if (neighbors.containsKey(neighbor)) {
            neighbors.remove(neighbor);
        }
        neighbors.put(neighbor, 0d);
    }

    @Override
    public void removeNeighbor(N neighbor) {
        neighbors.remove(neighbor);
    }

    @Override
    public void removeAllNeighbors() {
        for (N node : neighbors.keySet()) {
            removeNeighbor(node);
        }
    }

    /**
     * Will change the weight of the connection between the two nodes. If no link exists
     * between the nodes, this method will not change anything.
     * @param neighbor    the neighboring node
     * @param weight      the new weight of the link
     */
    @Override
    public void setLinkWeight(N neighbor, double weight) {
        if (neighbors.containsKey(neighbor)) {
            neighbors.remove(neighbor);
            neighbors.put(neighbor, weight);
        }
    }

    /**
     * This method will set the user data with the given key and value
     * @param key      the key
     * @param value    the value
     */
    @Override
    public void setUserData(String key, Object value) {
        userData.put(key, value);
    }

    /**
     * This method returns a set of the names of all the attributes associated
     * and assigned with this node
     * @return the set of attribute names
     */
    @Override
    public Set<String> getAttributeNames() {
        return attributes.keySet();
    }

    /**
     * This method returns the value assigned to the given attribute for this node
     * @param attributeName    the name of the attribute being queried for
     * @return the value of the attribute, or {@code null} if no such attribute has
     * been set for this node.
     */
    @Override
    public String getAttribute(String attributeName) {
        return attributes.containsKey(attributeName) ? attributes.get(attributeName) : null;
    }

    /**
     * This method will return a set of all the neighbors adjacent to this node. Do
     * note that this does not necessarily bind nodes in a two-way relation. This is
     * to allow for modeling of directed graphs.
     * @return the set of nodes adjacent to this node.
     */
    @Override
    public Set<N> getNeighbors() {
        return neighbors.keySet();
    }

    /**
     * Returns the weight associated with the originating from this node to the
     * node being queried. If no link has been established between the two nodes,
     * the return value will be {@code 0}.
     * @param neighbour    the neighbor to be queried for
     * @return the weight of the link originating from this node and ending in the
     * neighboring node. If no such link exists, the value returned is {@code 0}.
     */
    @Override
    public double getLinkWeight(N neighbour) {
        return neighbors.containsKey(neighbour) ? neighbors.get(neighbour) : 0d;
    }

    /**
     * This method will query for user data associated with this node with the
     * given key
     * @param key    the key to the data
     * @return the user data if it exists, or {@code null} if not
     */
    @Override
    public Object getUserData(String key) {
        return userData.containsKey(key) ? userData.get(key) : null;
    }

    @Override
    public String toString() {
        if (stringifiable != null) {
            return stringifiable.toString(this);
        }
        return super.toString();
    }

}