text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Document</title>
  <meta name="description" content="Description">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="//unpkg.com/docsify/lib/themes/vue.css">


text:
"use strict";
/*global alert: true, BST, ODSA, PARAMS */
$(document).ready(function () {
  // Process about button: Pop up a message with an Alert
  function about() {
    alert(ODSA.AV.aboutstring(interpret(".avTitle"), interpret("av_Authors")));
  }

  // Set click handlers
  $("#about").click(about);

  function initialize() {
    BST.turnAnimationOff();
    if (stack) {
      stack.clear();
    }
    stack = av.ds.stack({center: true, xtransition: 5, ytransition: -3});

    function dataTest(array) {
      var bst = av.ds.binarytree();
      bst.insert(array);
      var result = bst.height() <= maxHeight;
      bst.clear();
      return result;
    }

    //clear old binary tree
    if (jsavTree) {
      jsavTree.clear();
    }
    //generate random tree
    jsavTree = av.ds.binarytree({center: true, visible: true, nodegap: 15});
    do {
      initialArray = [];
      perfectBinTree(initialArray, 1, 10, 100, 3, 1);
      initialArray = initialArray.concat(JSAV.utils.rand.numKeys(10, 100, treeSize - 7));
    } while (!dataTest(initialArray));
    jsavTree.insert(initialArray);
    jsavTree.click(clickHandler);
    jsavTree.layout();

    //pick the values to delete and push them in the stack
    for (var i = 0; i < deleteSize; i++) {
      deleteValues[i] = initialArray[Math.floor(treeSize - 1 - i * (treeSize - 1) / (deleteSize - 1))];
      stack.addLast(deleteValues[i]);
    }
    stack.first().highlight();
    stack.layout();

    BST.restoreAnimationState();

    return jsavTree;
  }

  function modelSolution(av) {
    //helper function for finding the node
    //naive because path and node are guaranteed to exist
    function find(val) {
      var node = modelTree.root();
      while (node.value() !== val) {
        if (val < node.value()) {
          node = node.left();
        } else {
          node = node.right();
        }
      }
      return node;
    }

    //helper function for finding replacing node
    //if no left child the function will return undefined
    function findReplacingNode(root) {
      if (!root.left() !== !root.right()) {
        //only one child -> return child
        if (root.left()) {
          return root.left();
        } else {
          return root.right();
        }
      }
      var node = root.left();
      if (!node) {
        return undefined;
      }
      while (node.right()) {
        node = node.right();
      }
      return node;
    }

    //higlights and unhighlights a path between root and node
    function highlightPath(root, node, undo) {
      var n = node;
      var css;
      while (n !== root) {
        if (undo) {
          n.edgeToParent().removeClass("blueline");
	} else {
          n.edgeToParent().addClass("blueline");
	}
        n = n.parent();
      }
    }

    var modelStack = av.ds.stack({center: true});
    var i;
    for (i = 0; i < deleteSize; i++) {
      modelStack.addLast(deleteValues[i]);
    }
    modelStack.layout();

    var modelTree = av.ds.binarytree({center: true, visible: true, nodegap: 10});

    modelTree.insert(initialArray);
    modelTree.layout();

    av._undo = [];

    for (i = 0; i < deleteSize; i++) {
      //highlight the value which should be deleted
      modelStack.first().highlight();
      //node which should be deleted
      var node = find(deleteValues[i]);
      //highlight node
      node.highlight();
      //add step
      av.step();

      while (node) {
        //find possible empty node between node and root
        var empty = node;
        while (empty !== null && empty.value() !== "") {
          empty = empty.parent();
        }

        //if an empty node is found with only one child, replace the empty node with node
        //if the empty node has two children move the value of node into the empty node
        if (empty) {
          //unhighlight path
          highlightPath(empty, node, true);
          if (!empty.right() !== !empty.left()) {
            //replace node with node
            if (empty.parent().left() === empty) {
              empty.parent().left(node.remove({hide: false}));
            } else {
              empty.parent().right(node.remove({hide: false}));
            }
            modelTree.layout();
            av.stepOption("grade", true);
            av.step();
            break;
          } else {
            //insert value of node into empty node
            av.effects.moveValue(node, empty);
            empty.unhighlight();
          }
        }
        //empty this node
        node.value("");
        //if no children, remove node and move on
        if (!node.left() && !node.right()) {
          node.remove();
          modelTree.layout();
          node = null;
        } else {
          var rep = findReplacingNode(node);
          if (rep) {
            highlightPath(node, rep);
          }
          node = rep;
        }
        av.stepOption("grade", true);
        av.step();

      }

      //remove node from stack
      modelStack.removeFirst();
    }

    return modelTree;
  }

  function highlightNext() {
    stack.removeFirst();
    stack.layout();
    //higlight the next one
    if (stack.size()) {
      stack.first().highlight();
    }
  }

  var clickHandler = function () {
    if (stack.size() && !this.hasClass("jsavnullnode")) {
      //find possible empty node between this and root
      var empty = this;
      while (empty !== null && empty.value() !== "") {
        empty = empty.parent();
      }

      //if an empty node is found with only one child, replace the empty node with this
      //if the empty node has two children move the value of this into the empty node
      if (empty) {
        if (!empty.right() !== !empty.left()) {
          //replace node with this
          BST.turnAnimationOff();
          if (empty.parent().left() === empty) {
            empty.parent().left(this);
          } else {
            empty.parent().right(this);
          }
          this.show();
          BST.restoreAnimationState();
          jsavTree.layout();
          highlightNext();
          exercise.gradeableStep();
          return;
        } else {
          //insert value of this into empty node
          av.effects.moveValue(this, empty);
        }
      }
      //empty this node
      this.value("");
      //if no children, remove node and move on
      if (!this.left() && !this.right()) {
        this.remove();
        jsavTree.layout();
        highlightNext();
      }
      exercise.gradeableStep();
    }
  };

  // helper function for creating a perfect binary tree
  function perfectBinTree(arr, level, min, max, levelsInTotal, arrayIndex) {
    var diff = max - min;
    var value = JSAV.utils.rand.numKey(min + Math.floor(diff / 3), max - Math.floor(diff / 3));
    arr[arrayIndex - 1] = value;
    if (level < levelsInTotal) {
      perfectBinTree(arr, level + 1, min, value - 1, levelsInTotal, 2 * arrayIndex);
      perfectBinTree(arr, level + 1, value + 1, max, levelsInTotal, 2 * arrayIndex + 1);
    }
  }

  //////////////////////////////////////////////////////////////////
  // Start processing here
  //////////////////////////////////////////////////////////////////

  // AV variables
  var initialArray = [],
      deleteValues = [],
      jsavTree,
      stack,
      deleteSize = 5,          //delete 5 values/nodes
      treeSize = 20,          //20 nodes
      maxHeight = 6,
      pseudo,

      // Load the configurations created by odsaAV.js
      config = ODSA.UTILS.loadConfig({default_code: "none"}),
      interpret = config.interpreter,
      code = config.code,
      codeOptions = {after: {element: $(".instructions")}, visible: true},

      // Settings for the AV
      settings = config.getSettings(),

      // Create a JSAV instance
      av = new JSAV($(".avcontainer"));

  av.recorded(); // we are not recording an AV with an algorithm

  // show a JSAV code instance only if the code is defined in the parameter
  // and the parameter value is not "none"
  if (code) {
    pseudo = av.code($.extend(codeOptions, code));
  }

  var exercise = av.exercise(modelSolution, initialize,
                             {controls: $(".jsavexercisecontrols"),
                              modelDialog: {width: 700}});
  exercise.reset();
});

redpajama_set_name: RedPajamaGithub


text:
package sinfo.ufrn.br.japi.interfaces;

import ca.mimic.oauth2library.OAuthResponse;

/**
 * Created by victor on 28/09/17.
 */

public interface AsyncResponse {

    void processAuthorization(OAuthResponse response);

}


text:
MQHorizontalFlowLayout inherites from UICollectionViewFlowLayout!
Based on the WWDC 2012 videos on UICollectionView, it appears that if you use Flow Layout with vertical scrolling, your layout lines are horizontal, and if you scroll horizontally, your layout lines are vertical. If you want **horizontal layout lines** in a **horizontally-scrolling** collection view. ***OK, that's the MQHorizontalFlowLayout!***

##Supported OS & SDK Versions

* Supported build target - iOS 7.0

NOTE: 'Supported' means that the library has been tested with this version. 'Compatible' means that the library should work on this OS version (i.e. it doesn't rely on any unavailable SDK features) but is no longer being tested for compatibility and may require tweaking or bug fixes to run correctly.

##Installation

To use the MQHorizontalFlowLayout class in an app, just drag the MQHorizontalFlowLayout class files into your project.

##Property
###The MQHorizontalFlowLayout only has the following two properties:

    @property (assign, nonatomic) NSInteger rowCount;
 This property defines the number of rows per page! And default is 3!

    @property (assign, nonatomic) NSInteger columnCount;
 This property defines the number of column per page! And default is 3!

##Contact

If you have any problem, just contact with me: xu20121013@gmail.com! I would pleasure for that!
And here is one of my app used MQHorizontalFlowLayout: [SweetSounds](https://itunes.apple.com/app/id952649748)


text:
package org.apache.taglibs.bsf;

import javax.servlet.jsp.tagext.*;

import org.apache.bsf.*;

public class bsftag extends BodyTagSupport implements BodyTag
{
    protected static String language;
    protected static int lineNo = 0;
    protected static BSFManager mgr;

    public void setLanguage(String value) {
        language = value;
    }

    protected void register(BSFManager mgr, String name, Object bean)
                     throws Exception {
        if (bean == null) return;
        try {
            mgr.declareBean(name, bean, bean.getClass());
    }
        catch(Exception e) {
        throw e;
        }
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item android:id="@+id/menu_sort"
        android:icon="@android:drawable/ic_menu_sort_by_size"
        android:title="@string/menu_sort"
        app:showAsAction="ifRoom" />
    <item android:id="@+id/menu_notify"
        android:icon="@drawable/ic_notifications_active_white_24dp"
        android:title="@string/menu_notify"
        app:showAsAction="ifRoom"/>
    <item android:id="@+id/menu_add"
        android:icon="@android:drawable/ic_menu_add"
        android:title="@string/menu_add"
        app:showAsAction="ifRoom"/>
    <!--<item android:id="@+id/menu_refresh"
        android:icon="@android:drawable/ic_popup_sync"
        android:title="@string/menu_refresh" />-->
    <item android:id="@+id/menu_settings"
        android:icon="@android:drawable/ic_menu_preferences"
        android:title="@string/menu_settings" />
    <item android:id="@+id/menu_help"
        android:icon="@android:drawable/ic_menu_help"
        android:title="@string/menu_help" />
    <!--<item android:id="@+id/menu_about"-->
        <!--android:icon="@android:drawable/ic_menu_info_details"-->
        <!--android:title="@string/menu_about" />-->
</menu>


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

using DocumentFormat.OpenXml.Framework;
using DocumentFormat.OpenXml.Framework.Metadata;
using System;
using System.Collections.Generic;
using System.Xml;

namespace DocumentFormat.OpenXml.Features
{
    internal class NoDataNamespaceResolver : IOpenXmlNamespaceResolver
    {
        public IDictionary<string, string> GetNamespacesInScope(XmlNamespaceScope scope) => new Dictionary<string, string>();

        public FileFormatVersions GetVersion(OpenXmlNamespace ns) => FileFormatVersions.Office2007;

        public string? LookupNamespace(string prefix) => null;

        public string? LookupPrefix(string namespaceName) => null;

        public bool TryGetExtendedNamespace(OpenXmlNamespace ns, out OpenXmlNamespace extNamespaceUri)
        {
            extNamespaceUri = default;
            return false;
        }

        public bool TryGetTransitionalNamespace(OpenXmlNamespace ns, out OpenXmlNamespace transitionalNamespace)
        {
            transitionalNamespace = default;
            return false;
        }

        public bool TryGetTransitionalRelationship(OpenXmlNamespace ns, out OpenXmlNamespace transitionalRelationship)
        {
            transitionalRelationship = default;
            return false;
        }
    }
}


text:
<!DOCTYPE html>

<meta charset="UTF-8">
<link href="style.css" type="text/css" rel="stylesheet">
<title>MAXSD—Return Maximum Scalar Double-Precision Floating-Point Value </title>

MAXSD—Return Maximum Scalar Double-Precision Floating-Point Value

Opcode/Instruction
Op/En
64/32-bit Mode
CPUID Feature Flag
Description

F2 0F 5F /r

MAXSD xmm1, xmm2/m64

RM
V/V
SSE2
Return the maximum scalar double-precision floating-point value between xmm2/mem64 and xmm1.

VEX.NDS.LIG.F2.0F.WIG 5F /r

VMAXSD xmm1, xmm2, xmm3/m64

RVM
V/V
AVX
Return the maximum scalar double-precision floating-point value between xmm3/mem64 and xmm2.

Instruction Operand Encoding

Op/En
Operand 1
Operand 2
Operand 3
Operand 4

RM
ModRM:reg (r, w)
ModRM:r/m (r)
NA
NA

RVM
ModRM:reg (w)
VEX.vvvv (r)
ModRM:r/m (r)
NA

Description

Compares the low double-precision floating-point values in the first source operand and second the source operand, and returns the maximum value to the low quadword of the destination operand. The second source operand can be an XMM register or a 64-bit memory location. The first source and destination operands are XMM registers. When the second source operand is a memory operand, only 64 bits are accessed. The high quadword of the destination operand is copied from the same bits of first source operand.

If the values being compared are both 0.0s (of either sign), the value in the second source operand is returned. If a value in the second source operand is an SNaN, that SNaN is returned unchanged to the destination (that is, a QNaN version of the SNaN is not returned).

If only one value is a NaN (SNaN or QNaN) for this instruction, the second source operand, either a NaN or a valid floating-point value, is written to the result. If instead of this behavior, it is required that the NaN of either source operand be returned, the action of MAXSD can be emulated using a sequence of instructions, such as, a comparison followed by AND, ANDN and OR.

The second source operand can be an XMM register or a 64-bit memory location. The first source and destination operands are XMM registers.

In 64-bit mode, use of the REX.R prefix permits this instruction to access additional registers (XMM8-XMM15).

128-bit Legacy SSE version: The destination and first source operand are the same. Bits (VLMAX-1:64) of the corresponding YMM destination register remain unchanged.

VEX.128 encoded version: Bits (127:64) of the XMM register destination are copied from corresponding bits in the first source operand. Bits (VLMAX-1:128) of the destination YMM register are zeroed.

Operation

MAX(SRC1, SRC2)

{
    IF ((SRC1 = 0.0) and (SRC2 = 0.0)) THEN DEST ← SRC2;
         ELSE IF (SRC1 = SNaN) THEN DEST ← SRC2; FI;
         ELSE IF SRC2 = SNaN) THEN DEST ← SRC2; FI;
         ELSE IF (SRC1 > SRC2) THEN DEST ← SRC1;
         ELSE DEST ← SRC2;
    FI;
}

MAXSD (128-bit Legacy SSE version)

DEST[63:0] ←MAX(DEST[63:0], SRC[63:0])
DEST[VLMAX-1:64] (Unmodified)

VMAXSD (VEX.128 encoded version)

DEST[63:0] ←MAX(SRC1[63:0], SRC2[63:0])
DEST[127:64] ←SRC1[127:64]
DEST[VLMAX-1:128] ← 0

Intel C/C++ Compiler Intrinsic Equivalent

MAXSD:

 __m128d _mm_max_sd(__m128d a, __m128d b)

SIMD Floating-Point Exceptions

Invalid (including QNaN source operand), Denormal.

Other Exceptions

See Exceptions Type 3.


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information

using System;
using System.Data.Entity;
using Microsoft.AspNet.WebHooks.Storage;

namespace Microsoft.AspNet.WebHooks
{
    /// <summary>
    /// Defines a <see cref="DbContext"/> which contains the set of WebHook <see cref="Registration"/> instances.
    /// </summary>
    public class WebHookStoreContext : DbContext
    {
        internal const string ConnectionStringName = "MS_SqlStoreConnectionString";
        private const string ConnectionStringNameParameter = "name=" + ConnectionStringName;

        /// <summary>
        /// Initializes a new instance of the <see cref="WebHookStoreContext"/> class.
        /// </summary>
        public WebHookStoreContext() : base(ConnectionStringNameParameter)
        {
        }

        /// <summary>
        /// Gets or sets the current collection of <see cref="Registration"/> instances.
        /// </summary>
        public virtual DbSet<Registration> Registrations { get; set; }

        /// <inheritdoc />
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            if (modelBuilder == null)
            {
                throw new ArgumentNullException(nameof(modelBuilder));
            }

            modelBuilder.HasDefaultSchema("WebHooks");
        }
    }
}


text:
ACCEPTED

#### According to
International Plant Names Index

#### Published in
null

#### Original name
Chaetanthera pulvinata var. achenohirsuta Tombesi

### Remarks
null


text:
require 'logger'
require 'dalli'
require 'net/telnet'

module Dallish
  class Client

    attr_accessor :servers, :log, :dalli

    def initialize(params)
      raise ArgumentError.new('`params` should be a Hash value.') unless params.is_a? Hash

      # log settings
      @log = Logger.new(params[:log_output] || STDOUT)
      @log.level = params[:log_level] || Logger::INFO

      # memcached server settings
      if params[:servers] and params[:servers].is_a?(String)
        @servers = [params[:servers]]
      else
        @servers = params[:servers] || ['127.0.0.1:11211']
      end
      @dalli_options = params[:options] || {}
      @dalli = Dalli::Client.new(@servers, @dalli_options)

      # cannot support memcached 1.6 or higher
      self.servers.each { |server|
        version = telnet_connect(server, :prompt => /\n/).cmd('version')
        self.log.debug "version: #{version}"

        /VERSION (?<major_version>\d+\.\d+).*/ =~ version
        if major_version and major_version.to_f >= 1.6
          raise ArgumentError.new("Sorry, Dallish doesn't support memcached 1.6 or higher version.")
        end
      }
    end

    def telnet_connect(server, options = {})
      (host, port) = server.split(':')
      self.log.debug "target memcahced server: #{host}:#{port}"
      Net::Telnet::new(
          'Host' => host,
          'Port' => port,
          'Prompt' => options[:prompt] || /(^END$)/,
          'Timeout' => options[:timeout] || 3
      )
    end

    def all_keys()
      self.servers.flat_map { |server|
        telnet = telnet_connect(server)
        begin
          slab_ids = telnet.cmd("stats slabs").split("\n").map { |line|
            /STAT (?<slab_id>\d+):.+/ =~ line
            slab_id
          }.reject { |e| e.nil? }.uniq

          slab_ids.flat_map { |slab_id|
            telnet.cmd("stats cachedump #{slab_id} 10000000").split("\n").map { |line|
              /ITEM (?<key>.+) \[\d+ b; \d+ s\]/ =~ line
              key
            }
          }
        rescue Exception => e
          self.log.info "Failed to get keys because #{e.to_s}"
          []
        ensure
          telnet.close()
        end
      }.reject { |e| e.nil? }.uniq
    end

    def find_keys_by(regexp)
      all_keys.select { |key| regexp.match(key) }
    end

    def delete_all_by(regexp)
      find_keys_by(regexp).each do |key|
        self.dalli.delete(key)
      end
      nil
    end

    def find_all_by(regexp)
      find_keys_by(regexp).inject({}) { |result, key|
        result[key] = self.dalli.get(key)
        result
      }
    end

    def method_missing(name, *args, &block)
      self.dalli.send(name, *args, &block)
    end

  end
end


text:
require_relative "../../spec_helper"
require "./lib/duolingo/user"

describe Duolingo::User do
  let(:username) { "Novohispano" }
  let(:user) { described_class.new(username) }

  it "returns the  total points for all languages" do
    VCR.use_cassette("user") do
      expect(user.total_points).to eq(2285)
    end
  end

  it "all the studied languages" do
    VCR.use_cassette("user") do
      expect(user.languages_studied).to eq(["Portuguese"])
    end
  end

  it "languages that are currently being studied" do
    VCR.use_cassette("user") do
      expect(user.current_languages).to eq(["Portuguese"])
    end
  end

  it "points for a particular language" do
    VCR.use_cassette("user") do
      expect(user.points_for("Portuguese")).
        to eq("#{username} has 2285 points for Portuguese")
    end
  end

  it "gets number of followers" do
    VCR.use_cassette("user") do
      expect(user.number_of_followers).to eq(23)
    end
  end

  it "the date account was created" do
    VCR.use_cassette("user") do
      expect(user.created_at).to eq("9 months ago")
    end
  end

  it "number of people they are following" do
    VCR.use_cassette("user") do
      expect(user.num_following).to eq(47)
    end
  end

  it "has a full name" do
    VCR.use_cassette("user") do
      expect(user.full_name).to eq("Jorge Téllez")
    end
  end

  it "returns all the users information" do
    VCR.use_cassette("user") do
      expect(user.get_all_info).to include("Jorge Téllez")
    end
  end

  it "return a lot of info for that language" do
    VCR.use_cassette("user") do
      expect(user.stats_for_languages_studied.count).to eq 1
    end
  end

  it "returns all of the friends" do
    VCR.use_cassette("user") do
      expect(user.friends.count).to eq 47
    end
  end

  it "returns stats for all friends" do
    VCR.use_cassette("user") do
      expect(user.friends_stats).to include { "renechs" }
    end
  end

  it "returns the rank" do
    VCR.use_cassette("user") do
      expect(user.rank).to eq(3)
    end
  end
end


text:
package org.wikipedia.random;

import android.support.annotation.NonNull;

import com.google.gson.JsonParseException;

import org.junit.Test;
import org.wikipedia.dataclient.WikiSite;
import org.wikipedia.dataclient.restbase.page.RbPageSummary;
import org.wikipedia.page.PageTitle;
import org.wikipedia.random.RandomSummaryClient.Callback;
import org.wikipedia.random.RandomSummaryClient.Service;
import org.wikipedia.test.MockWebServerTest;

import java.io.IOException;

import retrofit2.Call;

import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isA;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;

public class RandomSummaryClientTest extends MockWebServerTest {
    @NonNull private RandomSummaryClient client = new RandomSummaryClient();

    @Test
    public void testRequestEligible() throws Throwable {
        enqueueFromFile("rb_page_summary_valid.json");

        Callback cb = mock(Callback.class);
        Call<RbPageSummary> call = request(cb);

        server().takeRequest();
        assertCallbackSuccess(call, cb);
    }

    @Test public void testRequestMalformed() throws Throwable {
        enqueueFromFile("rb_page_summary_malformed.json");

        Callback cb = mock(Callback.class);
        Call<RbPageSummary> call = request(cb);

        server().takeRequest();
        assertCallbackFailure(call, cb, JsonParseException.class);
    }

    @Test public void testRequestFailure() throws Throwable {
        enqueue404();

        Callback cb = mock(Callback.class);
        Call<RbPageSummary> call = request(cb);

        server().takeRequest();
        assertCallbackFailure(call, cb, IOException.class);
    }

    @NonNull private Call<RbPageSummary> request(@NonNull Callback cb) {
        return client.request(service(Service.class), WikiSite.forLanguageCode("test"), cb);
    }

    private void assertCallbackSuccess(@NonNull Call<RbPageSummary> call,
                                       @NonNull Callback cb) {
        verify(cb).onSuccess(eq(call), any(PageTitle.class));
        //noinspection unchecked
        verify(cb, never()).onError(any(Call.class), any(Throwable.class));
    }

    private void assertCallbackFailure(@NonNull Call<RbPageSummary> call,
                                       @NonNull Callback cb,
                                       @NonNull Class<? extends Throwable> expectedThrowable) {
        //noinspection unchecked
        verify(cb, never()).onSuccess(any(Call.class), any(PageTitle.class));
        verify(cb).onError(eq(call), isA(expectedThrowable));
    }
}


text:
package job

import (
	"fmt"
	"math/rand"
	"sync"

	"github.com/elastic/beats/libbeat/common"

	"techtoolkit.ickey.cn/cockimport/worker"
)

// Job represents the job to be run
type Job struct {
	Name       string
	Wg         *sync.WaitGroup
	Rnd        *rand.Rand
	Event      *common.MapStr
	JobQueue   chan worker.Job
	RandomFail bool
	Retries    int
	Attempts   int
}

func (j Job) String() string {
	return j.Name
}

func (j Job) Process() error {
	// fmt.Printf("Processing job %s  event: %v\n", j.String(), j.Event)
	fmt.Printf("Processing job %s  event: %v\n", j.String(), *j.Event)
	if !j.RandomFail || j.Rnd.Intn(2) == 0 {
		return nil
	}
	return fmt.Errorf("Some kind of error")
}

func (j Job) Result(err error) {
	if err != nil {
		fmt.Printf("Processing job %s failed: %s\n", j.String(), err)
		if j.Attempts < j.Retries {
			j.Attempts++
			fmt.Printf("Retrying job %s [Retries:%d]\n", j.String(), j.Attempts)
			j.JobQueue <- j
			return
		} else {
			fmt.Printf("Giving up job %s [Retries:%d]\n", j.String(), j.Attempts)
		}
	} else {
		fmt.Printf("Processed job %s successfully\n", j.String())
	}
	j.Wg.Done()
}


text:
<?php

namespace Coyote\Repositories\Criteria\Microblog;

use Coyote\Microblog;
use Coyote\Tag;
use Coyote\Repositories\Contracts\RepositoryInterface as Repository;
use Coyote\Repositories\Contracts\RepositoryInterface;
use Coyote\Repositories\Criteria\Criteria;

class WithTag extends Criteria
{
    /**
     * @var string
     */
    private $tag;

    /**
     * WithTag constructor.
     * @param string $tag
     */
    public function __construct($tag)
    {
        $this->tag = $tag;
    }

    /**
     * @param $model
     * @param RepositoryInterface $repository
     * @return mixed
     */
    public function apply($model, Repository $repository)
    {
        $query = $model->whereIn('microblogs.id', function ($sub) {
            $sub->selectRaw('(CASE WHEN parent_id IS NOT NULL THEN parent_id ELSE microblogs.id END)')
                ->from((new Tag())->getTable())
                ->join('tag_resources', 'tag_resources.tag_id', '=', 'tags.id')
                ->join('microblogs', 'microblogs.id', '=', 'tag_resources.resource_id')
                ->where('name', $this->tag)
                ->where('tag_resources.resource_type', Microblog::class);
        });

        return $query;
    }
}


text:
<?php
/**
 * WordPress Administration Generic POST Handler.
 *
 * @package WordPress
 * @subpackage Administration
 */

/** We are located in WordPress Administration Screens */
define('WP_ADMIN', true);

if ( defined('ABSPATH') )
	require_once(ABSPATH . 'wp-load.php');
else
	require_once('../wp-load.php');

require_once(ABSPATH . 'wp-admin/includes/admin.php');

nocache_headers();

do_action('admin_init');

$action = 'admin_post';

if ( !wp_validate_auth_cookie() )
	$action .= '_nopriv';

if ( !empty($_REQUEST['action']) )
	$action .= '_' . $_REQUEST['action'];

do_action($action);

?>


text:
// Copyright 2022 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.api.ads.admanager.jaxws.v202205;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

/**
 *
 *             Creates a new blank network for testing purposes using the current login.
 *

 *             Each login(i.e. email address) can only have one test network. Data from
 *             any of your existing networks will not be transferred to the new test network.
 *             Once the test network is created, the test network can be used in the API
 *             by supplying the {@link Network#networkCode} in the SOAP header or by
 *             logging into the Ad Manager UI.
 *

 *             Test networks are limited in the following ways:
 *

 *
Test networks cannot serve ads.

 *
Because test networks cannot serve ads, reports will always come
 *             back without data.

 *
Since forecasting requires serving history, forecast service results
 *             will be faked. See {@link ForecastService} for more info.

 *
Test networks are, by default, Ad Manager networks and don't have any features
 *             from Ad Manager 360. To have additional features turned on, please contact your
 *             account manager.

 *
Test networks are limited to 10,000 objects per entity type.

 *

 *

 *
 *
 *
Java class for makeTestNetwork element declaration.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <element name="makeTestNetwork">
 *   <complexType>
 *     <complexContent>
 *       <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *         <sequence>
 *         </sequence>
 *       </restriction>
 *     </complexContent>
 *   </complexType>
 * </element>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
@XmlRootElement(name = "makeTestNetwork")
public class NetworkServiceInterfacemakeTestNetwork {

}


text:
package com.intellij.codeInsight.completion;

import com.intellij.codeInsight.lookup.LookupElementBuilder;
import com.intellij.patterns.XmlPatterns;
import com.intellij.psi.PsiElement;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.psi.xml.XmlAttribute;
import com.intellij.psi.xml.XmlElementType;
import com.intellij.util.ProcessingContext;
import com.intellij.xml.XmlAttributeDescriptor;
import org.jetbrains.annotations.NotNull;

import static com.intellij.codeInsight.completion.XmlCompletionContributor.hasEnumerationReference;
import static com.intellij.patterns.PlatformPatterns.psiElement;
import static com.intellij.patterns.XmlPatterns.xmlAttribute;
import static com.intellij.patterns.XmlPatterns.xmlTag;
import static com.intellij.psi.filters.getters.XmlAttributeValueGetter.getEnumeratedValues;

public class XmlNonFirstCompletionContributor extends CompletionContributor {
  public XmlNonFirstCompletionContributor() {
    extend(CompletionType.BASIC, psiElement().inside(xmlAttribute()), new XmlAttributeReferenceCompletionProvider());
    extend(CompletionType.BASIC, psiElement().inside(xmlTag()), new TagNameReferenceCompletionProvider());
    extend(CompletionType.BASIC, psiElement().inside(XmlPatterns.xmlAttributeValue()), new CompletionProvider<>() {
      @Override
      protected void addCompletions(@NotNull CompletionParameters parameters,
                                    @NotNull ProcessingContext context,
                                    @NotNull CompletionResultSet result) {
        PsiElement position = parameters.getPosition();
        if (position.getNode().getElementType() != XmlElementType.XML_ATTRIBUTE_VALUE_TOKEN) return;
        XmlAttribute attr = PsiTreeUtil.getParentOfType(position, XmlAttribute.class);
        if (attr != null && !hasEnumerationReference(parameters, result)) {
          final XmlAttributeDescriptor descriptor = attr.getDescriptor();

          if (descriptor != null) {
            if (descriptor.isFixed() && descriptor.getDefaultValue() != null) {
              result.addElement(LookupElementBuilder.create(descriptor.getDefaultValue()));
              return;
            }
            for (String value : getEnumeratedValues(attr)) {
              result.addElement(LookupElementBuilder.create(value));
            }
          }
        }
      }
    });

  }
}


text:
//Generated code by table2java.py, do not modify.
package com.transmem.data.db;

import java.util.logging.Logger;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

/**
 * Users preferences as item key/value.
 *
 * @version 0.1
 * @author Ted Wen
 * @date Jan.2007
 */
public class Preferences implements java.io.Serializable
{
	protected static final long serialVersionUID = 111L;
	private Logger log_ = Logger.getLogger(Preferences.class.getName());

	private boolean[] setreg_ = new boolean[4];

	private Connection con_;
	private int preid_; ///auto-increment id
	private int user_; ///User ID
	private String item_; ///Item name to configure
	private String value_; ///Value of the item

	/**
	 * Construct an empty Preferences object.
	 *
	 */
	public Preferences()
	{
	}

	/**
	 * Construct a Preferences object with a Connection instance.
	 *
	 * @param con - Connection object
	 */
	public Preferences(Connection con)
	{
		con_ = con;
	}

	/**
	 * Construct with a query on primary key(s)
	 *
	 */
	public Preferences(Connection con, int _preid) throws SQLException
	{
		con_ = con;
		queryByPrimaryKey(_preid);
	}

	/**
	 * Setter for Connection object
	 *
	 */
	public void setConnection(Connection con)
	{
		this.con_ = con;
	}

	/**
	 * Getter for F_PreID
	 *
	 */
	public int getPreID()
	{
		return preid_;
	}

	/**
	 * Setter for F_PreID
	 *
	 */
	public void setPreID(int _preid)
	{
		preid_ = _preid;
		setreg_[0] = true;
	}

	/**
	 * Getter for F_User
	 *
	 */
	public int getUser()
	{
		return user_;
	}

	/**
	 * Setter for F_User
	 *
	 */
	public void setUser(int _user)
	{
		user_ = _user;
		setreg_[1] = true;
	}

	/**
	 * Getter for F_Item
	 *
	 */
	public String getItem()
	{
		return item_;
	}

	/**
	 * Setter for F_Item
	 *
	 */
	public void setItem(String _item)
	{
		item_ = _item;
		setreg_[2] = true;
	}

	/**
	 * Getter for F_Value
	 *
	 */
	public String getValue()
	{
		return value_;
	}

	/**
	 * Setter for F_Value
	 *
	 */
	public void setValue(String _value)
	{
		value_ = _value;
		setreg_[3] = true;
	}

	/**
	 * Clear all update tags
	 *
	 */
	public void clearUpdates()
	{
		for (int i=0; i<setreg_.length; i++)
		{
			setreg_[i] = false;
		}
	}

	/**
	 * Query by primary key(s), and populate current instance.
	 *
	 * @param _preid - int
	 */
	public void queryByPrimaryKey(int _preid) throws SQLException
	{
		if (this.con_ == null)
		{
			log_.severe("Connetion object null");
			throw new SQLException("Connection object not set.");
		}
		String sql = "select * from T_Preferences where F_PreID=?";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			stmt = con_.prepareStatement(sql);
			stmt.setInt(1,_preid);
			rs = stmt.executeQuery();
			if (rs.next())
			{
				setPreID(rs.getInt(1));
				setUser(rs.getInt(2));
				setItem(rs.getString(3));
				setValue(rs.getString(4));
			}
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
			throw e;
		}
		finally
		{
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
	}

	/**
	 * Get all preference settings for a user.
	 *
	 * @param user - int
	 */
	public ArrayList<UserPrefs> queryPreferencesByUser(int user) throws SQLException
	{
		if (this.con_ == null)
		{
			log_.severe("Connetion object null");
			throw new SQLException("Connection object not set.");
		}
		String sql = "select F_Item,F_Value from T_Preferences where F_User=?";
		ArrayList<UserPrefs> result = new ArrayList<UserPrefs>();
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			stmt = con_.prepareStatement(sql);
			stmt.setInt(1,user);
			rs = stmt.executeQuery();
			while (rs.next())
			{
				UserPrefs s = new UserPrefs();
				s.setItem(rs.getString(1));
				s.setValue(rs.getString(2));
				result.add(s);
			}
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
		}
		finally
		{
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
		return result;
	}

	/**
	 * Insert record in table with current data object.
	 *
	 */
	public void insert(Connection con) throws SQLException
	{
		String sql = "select * from T_Preferences where F_PreID=?";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			stmt = con.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
			stmt.setInt(1, preid_);
			stmt.setFetchSize(1);
			rs = stmt.executeQuery();
			rs.moveToInsertRow();
			if (setreg_[0]) rs.updateInt(1,preid_);
			if (setreg_[1]) rs.updateInt(2,user_);
			if (setreg_[2]) rs.updateString(3,item_);
			if (setreg_[3]) rs.updateString(4,value_);
			rs.insertRow();
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
			throw e;
		}
		finally
		{
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
	}

	public void insert() throws SQLException
	{
		if (this.con_ == null)
		{
			log_.severe("Connetion object null");
			throw new SQLException("Connection object not set.");
		}
		insert(this.con_);
	}

	/**
	 * Update record in table with current data object.
	 * All fields must be set, better query in first.
	 *
	 */
	public void update(Connection con) throws SQLException
	{
		String sql = "select * from T_Preferences where F_PreID=?";
		PreparedStatement stmt = null;
		ResultSet rs = null;
		try
		{
			stmt = con.prepareStatement(sql,ResultSet.TYPE_FORWARD_ONLY,ResultSet.CONCUR_UPDATABLE);
			stmt.setInt(1, preid_);
			rs = stmt.executeQuery();
			if (rs.next())
			{
				if (setreg_[1]) rs.updateInt(2,user_);
				if (setreg_[2]) rs.updateString(3,item_);
				if (setreg_[3]) rs.updateString(4,value_);
				rs.updateRow();
			}
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
			throw e;
		}
		finally
		{
			try {
				if (rs != null) rs.close();
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
	}

	public void update() throws SQLException
	{
		if (this.con_ == null)
		{
			log_.severe("Connetion object null");
			throw new SQLException("Connection object not set.");
		}
		update(this.con_);
	}

	/**
	 * Delete record by primary key(s).
	 *
	 * @param _preid - int
	 */
	public void delete(int _preid) throws SQLException
	{
		if (this.con_ == null)
		{
			log_.severe("Connetion object null");
			throw new SQLException("Connection object not set.");
		}
		String sql = "delete from T_Preferences where F_PreID=?";
		PreparedStatement stmt = null;
		try
		{
			stmt = con_.prepareStatement(sql);
			stmt.setInt(1,_preid);
			stmt.executeUpdate();
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
			throw e;
		}
		finally
		{
			try {
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
	}

	/**
	 * Delete current record by PK with a connection.
	 *
	 */
	public void delete(Connection _con) throws SQLException
	{
		String sql = "delete from T_Preferences where F_PreID=?";
		PreparedStatement stmt = null;
		try
		{
			stmt = con_.prepareStatement(sql);
			stmt.setInt(1,preid_);
			stmt.executeUpdate();
		}
		catch (SQLException e)
		{
			log_.severe(e.toString());
			throw e;
		}
		finally
		{
			try {
				if (stmt != null) stmt.close();
			}
			catch (SQLException x)
			{
			}
		}
	}

}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>org.apache.cassandra.repair (apache-cassandra API)</title>
<meta name="date" content="2015-06-05">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

org.apache.cassandra.repair

Interfaces

IRepairJobEventListener

IRequestCoordinator

IRequestProcessor

Classes

AnticompactionTask

AnticompactionTask.AnticompactionCallback

DatacenterAwareRequestCoordinator

Differencer

NodePair

NodePair.NodePairSerializer

ParallelRequestCoordinator

RepairFuture

RepairJob

RepairJobDesc

RepairMessageVerbHandler

RepairSession

SequentialRequestCoordinator

SnapshotTask

StreamingRepairTask

TreeResponse

Validator

Enums

RepairParallelism


text:
title: npm Update Error
tags:
  - npm
  - linux
  - nodejs
categories:
  - notes
header:
  overlay_filter: "0.5"
  overlay_color: "#000"
  teaser: /assets/the-most-terrifying.png
  overlay_image: /assets/the-most-terrifying.png
excerpt: npm Update Error
---

## Problem

```bash
$ sudo npm i -g npm to update
npm ERR! code 1
npm ERR! Command failed: /usr/bin/git clone -q git://github.com/jonschlinkert/resolve-file.git /home/jp/.npm/_cacache/tmp/git-clone-6677f267
npm ERR! /home/jp/.npm/_cacache/tmp/git-clone-6677f267/.git: Permission denied
npm ERR!

npm ERR! A complete log of this run can be found in:
npm ERR!     /home/jp/.npm/_logs/2018-04-11T09_43_12_553Z-debug.log
```

## Solution

```bash
$ wget -O- https://www.npmjs.com/install.sh | sudo bash
```


text:
package org.jbpm.shared.services.impl.commands;

import org.drools.core.command.impl.GenericCommand;
import org.jbpm.shared.services.impl.JpaPersistenceContext;
import org.kie.internal.command.Context;

public class FindObjectCommand<T> implements GenericCommand<T> {

	private static final long serialVersionUID = -4014807273522465028L;

	private Object identifer;
	private Class<T> clazz;

	public FindObjectCommand(Object identifer, Class<T> clazz) {
		this.identifer = identifer;
		this.clazz = clazz;
	}

	@Override
	public T execute(Context context) {
		JpaPersistenceContext ctx = (JpaPersistenceContext) context;
		return ctx.find(clazz, identifer);
	}

}


text:
package com.codificando.jbehavei18n;

import org.jbehave.scenario.PropertyBasedConfiguration;
import org.jbehave.scenario.Scenario;
import org.jbehave.scenario.definition.KeyWords;
import org.jbehave.scenario.parser.ClasspathScenarioDefiner;
import org.jbehave.scenario.parser.PatternScenarioParser;
import org.jbehave.scenario.parser.ScenarioDefiner;
import org.jbehave.scenario.parser.UnderscoredCamelCaseResolver;

public class I18nScenario extends Scenario {
	public I18nScenario() {
		 super(new PropertyBasedConfiguration() {
			 	public ScenarioDefiner forDefiningScenarios() {
	                return new ClasspathScenarioDefiner(
	                    new UnderscoredCamelCaseResolver(".scenario"),
	                    new PatternScenarioParser(this), Thread.currentThread().getContextClassLoader());
	            }

	            public KeyWords keywords() {
	            	return new KeyWords(
	            			I18nKeywords.getInstance().getScenario(),
	            			I18nKeywords.getInstance().getGiven(),
	            			I18nKeywords.getInstance().getWhen(),
	            			I18nKeywords.getInstance().getThen(),
	            			I18nKeywords.getInstance().getAnd());
	            }
		 });
	}
}


text:
<?php

namespace Zoop\Shard\Test\Freeze;

use Zoop\Shard\Freeze\Events;
use Zoop\Shard\Manifest;
use Zoop\Shard\Test\BaseTest;
use Zoop\Shard\Test\Freeze\TestAsset\Document\AccessControlled;
use Zoop\Shard\Test\TestAsset\RoleAwareUser;

class AccessControlAllowTest extends BaseTest
{
    protected $calls = array();

    public function setUp()
    {
        $manifest = new Manifest(
            [
                'models' => [
                    __NAMESPACE__ . '\TestAsset\Document' => __DIR__ . '/TestAsset/Document'
                ],
                'extension_configs' => [
                    'extension.freeze' => true,
                    'extension.accessControl' => true,
                    'extension.odmcore' => true
                ],
                'service_manager_config' => [
                    'factories' => [
                        'user' => function () {
                            $user = new RoleAwareUser();
                            $user->setUsername('toby');
                            $user->addRole('admin');

                            return $user;
                        }
                    ]
                ]
            ]
        );

        $this->documentManager = $manifest->getServiceManager()->get('modelmanager');
        $this->freezer = $manifest->getServiceManager()->get('freezer');
    }

    public function testFreezeAllow()
    {
        $this->calls = array();

        $documentManager = $this->documentManager;
        $eventManager = $documentManager->getEventManager();

        $eventManager->addEventListener(Events::FREEZE_DENIED, $this);

        $testDoc = new AccessControlled();
        $metadata = $documentManager->getClassMetadata(get_class($testDoc));

        $testDoc->setName('version 1');

        $documentManager->persist($testDoc);
        $documentManager->flush();
        $id = $testDoc->getId();
        $documentManager->clear();

        $repository = $documentManager->getRepository(get_class($testDoc));
        $testDoc = $repository->find($id);

        $this->freezer->freeze($testDoc, $metadata);

        $documentManager->flush();
        $documentManager->clear();

        $testDoc = $repository->find($id);
        $this->assertTrue($this->freezer->isFrozen($testDoc, $metadata));
        $this->assertFalse(isset($this->calls[Events::FREEZE_DENIED]));
    }

    public function testThawGrant()
    {
        $this->calls = array();

        $documentManager = $this->documentManager;
        $eventManager = $documentManager->getEventManager();

        $eventManager->addEventListener(Events::THAW_DENIED, $this);

        $testDoc = new AccessControlled();
        $metadata = $documentManager->getClassMetadata(get_class($testDoc));
        $this->freezer->freeze($testDoc, $metadata);
        $testDoc->setName('version 1');

        $documentManager->persist($testDoc);
        $documentManager->flush();
        $id = $testDoc->getId();
        $documentManager->clear();

        $repository = $documentManager->getRepository(get_class($testDoc));
        $testDoc = $repository->find($id);

        $this->freezer->thaw($testDoc, $metadata);

        $documentManager->flush();
        $documentManager->clear();

        $testDoc = $repository->find($id);
        $this->assertFalse($this->freezer->isFrozen($testDoc, $metadata));
        $this->assertFalse(isset($this->calls[Events::THAW_DENIED]));
    }

    public function __call($name, $arguments)
    {
        $this->calls[$name] = $arguments;
    }
}


text:
from functools import partial
from itertools import cycle
import logging
import numpy as np
import os
import pickle
from scipy import sparse as sp
import tensorflow as tf

from .errors import (
    ModelNotBiasedException, ModelNotFitException, ModelWithoutAttentionException, BatchNonSparseInputException,
    TfVersionException
)
from .input_utils import create_tensorrec_iterator, get_dimensions_from_tensorrec_dataset
from .loss_graphs import AbstractLossGraph, RMSELossGraph
from .prediction_graphs import AbstractPredictionGraph, DotProductPredictionGraph
from .recommendation_graphs import (
    project_biases, split_sparse_tensor_indices, bias_prediction_dense, bias_prediction_serial, rank_predictions,
    densify_sampled_item_predictions, collapse_mixture_of_tastes, predict_similar_items
)
from .representation_graphs import AbstractRepresentationGraph, LinearRepresentationGraph
from .session_management import get_session
from .util import sample_items, calculate_batched_alpha, datasets_from_raw_input

class TensorRec(object):

    def __init__(self,
                 n_components=100,
                 n_tastes=1,
                 user_repr_graph=LinearRepresentationGraph(),
                 item_repr_graph=LinearRepresentationGraph(),
                 attention_graph=None,
                 prediction_graph=DotProductPredictionGraph(),
                 loss_graph=RMSELossGraph(),
                 biased=True,):
        """
        A TensorRec recommendation model.
        :param n_components: Integer
        The dimension of a single output of the representation function. Must be >= 1.
        :param n_tastes: Integer
        The number of tastes/reprs to be calculated for each user. Must be >= 1.
        :param user_repr_graph: AbstractRepresentationGraph
        An object which inherits AbstractRepresentationGraph that contains a method to calculate user representations.
        See tensorrec.representation_graphs for examples.
        :param item_repr_graph: AbstractRepresentationGraph
        An object which inherits AbstractRepresentationGraph that contains a method to calculate item representations.
        See tensorrec.representation_graphs for examples.
        :param attention_graph: AbstractRepresentationGraph or None
        Optional. An object which inherits AbstractRepresentationGraph that contains a method to calculate user
        attention. Any valid repr_graph is also a valid attention graph. If None, no attention process will be applied.
        :param prediction_graph: AbstractPredictionGraph
        An object which inherits AbstractPredictionGraph that contains a method to calculate predictions from a pair of
        user/item reprs.
        See tensorrec.prediction_graphs for examples.
        :param loss_graph: AbstractLossGraph
        An object which inherits AbstractLossGraph that contains a method to calculate the loss function.
        See tensorrec.loss_graphs for examples.
        :param biased: bool
        If True, a bias value will be calculated for every user feature and item feature.
        """

        # Check TensorFlow version
        major, minor, patch = tf.__version__.split(".")
        if int(major) < 1 or int(major) == 1 and int(minor) < 7:
            raise TfVersionException(tf_version=tf.__version__)

        # Arg Check
        if (n_components is None) or (n_tastes is None) or (user_repr_graph is None) or (item_repr_graph is None) \
                or (prediction_graph is None) or (loss_graph is None):
            raise ValueError("All arguments to TensorRec() must be non-None")
        if n_components < 1:
            raise ValueError("n_components must be >= 1")
        if n_tastes < 1:
            raise ValueError("n_tastes must be >= 1")
        if not isinstance(user_repr_graph, AbstractRepresentationGraph):
            raise ValueError("user_repr_graph must inherit AbstractRepresentationGraph")
        if not isinstance(item_repr_graph, AbstractRepresentationGraph):
            raise ValueError("item_repr_graph must inherit AbstractRepresentationGraph")
        if not isinstance(prediction_graph, AbstractPredictionGraph):
            raise ValueError("prediction_graph must inherit AbstractPredictionGraph")
        if not isinstance(loss_graph, AbstractLossGraph):
            raise ValueError("loss_graph must inherit AbstractLossGraph")
        if attention_graph is not None:
            if not isinstance(attention_graph, AbstractRepresentationGraph):
                raise ValueError("attention_graph must be None or inherit AbstractRepresentationGraph")
            if n_tastes == 1:
                raise ValueError("attention_graph must be None if n_tastes == 1")

        self.n_components = n_components
        self.n_tastes = n_tastes
        self.user_repr_graph_factory = user_repr_graph
        self.item_repr_graph_factory = item_repr_graph
        self.attention_graph_factory = attention_graph
        self.prediction_graph_factory = prediction_graph
        self.loss_graph_factory = loss_graph
        self.biased = biased

        # A list of the attr names of every graph hook attr
        self.graph_tensor_hook_attr_names = [

            # Top-level API nodes
            'tf_user_representation', 'tf_item_representation', 'tf_prediction_serial', 'tf_prediction', 'tf_rankings',
            'tf_predict_similar_items', 'tf_rank_similar_items',

            # Training nodes
            'tf_basic_loss', 'tf_weight_reg_loss', 'tf_loss',

            # Feed placeholders
            'tf_learning_rate', 'tf_alpha', 'tf_sample_indices', 'tf_n_sampled_items', 'tf_similar_items_ids',
        ]
        if self.biased:
            self.graph_tensor_hook_attr_names += ['tf_projected_user_biases', 'tf_projected_item_biases']
        if self.attention_graph_factory is not None:
            self.graph_tensor_hook_attr_names += ['tf_user_attention_representation']

        self.graph_operation_hook_attr_names = [
            # AdamOptimizer
            'tf_optimizer',
        ]
        self.graph_iterator_hook_attr_names = [
            # Input data iterators
            'tf_user_feature_iterator', 'tf_item_feature_iterator', 'tf_interaction_iterator',
        ]

        # Calling the break routine during __init__ creates all the attrs on the TensorRec object with an initial value
        # of None
        self._break_graph_hooks()

        # A map of every graph hook attr name to the node name after construction
        # Tensors and operations are stored separated because they are handled differently by TensorFlow
        self.graph_tensor_hook_node_names = {}
        self.graph_operation_hook_node_names = {}
        self.graph_iterator_hook_node_names = {}

    def _break_graph_hooks(self):
        for graph_tensor_hook_attr_name in self.graph_tensor_hook_attr_names:
            self.__setattr__(graph_tensor_hook_attr_name, None)
        for graph_operation_hook_attr_name in self.graph_operation_hook_attr_names:
            self.__setattr__(graph_operation_hook_attr_name, None)
        for graph_iterator_hook_attr_name in self.graph_iterator_hook_attr_names:
            self.__setattr__(graph_iterator_hook_attr_name, None)

    def _attach_graph_hooks(self):
        session = get_session()

        for graph_tensor_hook_attr_name in self.graph_tensor_hook_attr_names:
            graph_tensor_hook_node_name = self.graph_tensor_hook_node_names[graph_tensor_hook_attr_name]
            node = session.graph.get_tensor_by_name(name=graph_tensor_hook_node_name)
            self.__setattr__(graph_tensor_hook_attr_name, node)

        for graph_operation_hook_attr_name in self.graph_operation_hook_attr_names:
            graph_operation_hook_node_name = self.graph_operation_hook_node_names[graph_operation_hook_attr_name]
            node = session.graph.get_operation_by_name(name=graph_operation_hook_node_name)
            self.__setattr__(graph_operation_hook_attr_name, node)

        for graph_iterator_hook_attr_name in self.graph_iterator_hook_attr_names:
            iterator_resource_name, output_types, output_shapes, output_classes = \
                self.graph_iterator_hook_node_names[graph_iterator_hook_attr_name]
            iterator_resource = session.graph.get_tensor_by_name(name=iterator_resource_name)
            iterator = tf.data.Iterator(iterator_resource, None, output_types, output_shapes, output_classes)
            self.__setattr__(graph_iterator_hook_attr_name, iterator)

    def _record_graph_hook_names(self):

        # Record serializable node names/info for each graph hook
        for graph_tensor_hook_attr_name in self.graph_tensor_hook_attr_names:
            hook = self.__getattribute__(graph_tensor_hook_attr_name)
            self.graph_tensor_hook_node_names[graph_tensor_hook_attr_name] = hook.name

        for graph_operation_hook_attr_name in self.graph_operation_hook_attr_names:
            hook = self.__getattribute__(graph_operation_hook_attr_name)
            self.graph_operation_hook_node_names[graph_operation_hook_attr_name] = hook.name

        for graph_iterator_hook_attr_name in self.graph_iterator_hook_attr_names:
            hook = self.__getattribute__(graph_iterator_hook_attr_name)
            iterator_resource_name = hook._iterator_resource.name
            output_types = hook.output_types
            output_shapes = hook.output_shapes
            output_classes = hook.output_classes
            self.graph_iterator_hook_node_names[graph_iterator_hook_attr_name] = (
                iterator_resource_name, output_types, output_shapes, output_classes
            )

    def _create_batched_dataset_initializers(self, interactions, user_features, item_features, user_batch_size=None):

        if user_batch_size is not None:

            # Raise exception if interactions and user_features aren't sparse matrices
            if (not sp.issparse(interactions)) or (not sp.issparse(user_features)):
                raise BatchNonSparseInputException()

            # Coerce to CSR for fast batching
            if not isinstance(interactions, sp.csr_matrix):
                interactions = sp.csr_matrix(interactions)
            if not isinstance(user_features, sp.csr_matrix):
                user_features = sp.csr_matrix(user_features)

            n_users = user_features.shape[0]

            interactions_batched = []
            user_features_batched = []

            start_batch = 0
            while start_batch < n_users:

                # min() ensures that the batch bounds doesn't go past the end of the index
                end_batch = min(start_batch + user_batch_size, n_users)

                interactions_batched.append(interactions[start_batch:end_batch])
                user_features_batched.append(user_features[start_batch:end_batch])

                start_batch = end_batch

            # Overwrite the input with the new, batched input
            interactions = interactions_batched
            user_features = user_features_batched

        # TODO this is hand-wavy and begging for a cleaner refactor
        (int_ds, uf_ds, if_ds), (int_init, uf_init, if_init) = self._create_datasets_and_initializers(
            interactions=interactions, user_features=user_features, item_features=item_features
        )

        # Ensure that lengths make sense
        if len(int_init) != len(uf_init):
            raise ValueError('Number of batches in user_features and interactions must be equal.')
        if (len(if_init) > 1) and (len(if_init) != len(uf_init)):
            raise ValueError('Number of batches in item_features must be 1 or equal to the number of batches in '
                             'user_features.')

        # Cycle item features when zipping because there should only be one
        datasets = [ds_set for ds_set in zip(int_ds, uf_ds, cycle(if_ds))]
        initializers = [init_set for init_set in zip(int_init, uf_init, cycle(if_init))]

        return datasets, initializers

    def _create_datasets_and_initializers(self, interactions=None, user_features=None, item_features=None):

        datasets = []
        initializers = []

        if interactions is not None:
            interactions_datasets = datasets_from_raw_input(raw_input=interactions)
            interactions_initializers = [self.tf_interaction_iterator.make_initializer(dataset)
                                         for dataset in interactions_datasets]
            datasets.append(interactions_datasets)
            initializers.append(interactions_initializers)

        if user_features is not None:
            user_features_datasets = datasets_from_raw_input(raw_input=user_features)
            user_features_initializers = [self.tf_user_feature_iterator.make_initializer(dataset)
                                          for dataset in user_features_datasets]
            datasets.append(user_features_datasets)
            initializers.append(user_features_initializers)

        if item_features is not None:
            item_features_datasets = datasets_from_raw_input(raw_input=item_features)
            item_features_initializers = [self.tf_item_feature_iterator.make_initializer(dataset)
                                          for dataset in item_features_datasets]
            datasets.append(item_features_datasets)
            initializers.append(item_features_initializers)

        return datasets, initializers

    def _build_input_iterators(self):
        self.tf_user_feature_iterator = create_tensorrec_iterator(name='tf_user_feature_iterator')
        self.tf_item_feature_iterator = create_tensorrec_iterator(name='tf_item_feature_iterator')
        self.tf_interaction_iterator = create_tensorrec_iterator(name='tf_interaction_iterator')

    def _build_tf_graph(self, n_user_features, n_item_features):

        # Build placeholders
        self.tf_n_sampled_items = tf.placeholder('int64')
        self.tf_similar_items_ids = tf.placeholder('int64', [None])
        self.tf_learning_rate = tf.placeholder('float', None)
        self.tf_alpha = tf.placeholder('float', None)

        tf_user_feature_rows, tf_user_feature_cols, tf_user_feature_values, tf_n_users, _ = \
            self.tf_user_feature_iterator.get_next()
        tf_item_feature_rows, tf_item_feature_cols, tf_item_feature_values, tf_n_items, _ = \
            self.tf_item_feature_iterator.get_next()
        tf_interaction_rows, tf_interaction_cols, tf_interaction_values, _, _ = \
            self.tf_interaction_iterator.get_next()

        tf_user_feature_indices = tf.stack([tf_user_feature_rows, tf_user_feature_cols], axis=1)
        tf_item_feature_indices = tf.stack([tf_item_feature_rows, tf_item_feature_cols], axis=1)
        tf_interaction_indices = tf.stack([tf_interaction_rows, tf_interaction_cols], axis=1)

        # Construct the features and interactions as sparse matrices
        tf_user_features = tf.SparseTensor(tf_user_feature_indices, tf_user_feature_values,
                                           [tf_n_users, n_user_features])
        tf_item_features = tf.SparseTensor(tf_item_feature_indices, tf_item_feature_values,
                                           [tf_n_items, n_item_features])
        tf_interactions = tf.SparseTensor(tf_interaction_indices, tf_interaction_values,
                                          [tf_n_users, tf_n_items])

        # Construct the sampling py_func
        sample_items_partial = partial(sample_items, replace=self.loss_graph_factory.is_sampled_with_replacement)
        self.tf_sample_indices = tf.py_func(func=sample_items_partial,
                                            inp=[tf_n_items, tf_n_users, self.tf_n_sampled_items],
                                            Tout=tf.int64)
        self.tf_sample_indices.set_shape([None, None])

        # Collect the weights for regularization
        tf_weights = []

        # Build the item representations
        self.tf_item_representation, item_weights = \
            self.item_repr_graph_factory.connect_representation_graph(tf_features=tf_item_features,
                                                                      n_components=self.n_components,
                                                                      n_features=n_item_features,
                                                                      node_name_ending='item')
        tf_weights.extend(item_weights)

        tf_x_user, tf_x_item = split_sparse_tensor_indices(tf_sparse_tensor=tf_interactions, n_dimensions=2)
        tf_transposed_sample_indices = tf.transpose(self.tf_sample_indices)
        tf_x_user_sample = tf_transposed_sample_indices[0]
        tf_x_item_sample = tf_transposed_sample_indices[1]

        # These lists will hold the reprs and predictions for each taste
        tastes_tf_user_representations = []
        tastes_tf_predictions = []
        tastes_tf_prediction_serials = []
        tastes_tf_sample_prediction_serials = []

        # If this model does not use attention, Nones are used as sentinels in place of the attentions
        if self.attention_graph_factory is not None:
            tastes_tf_attentions = []
            tastes_tf_attention_serials = []
            tastes_tf_sample_attention_serials = []
            tastes_tf_attention_representations = []
        else:
            tastes_tf_attentions = None
            tastes_tf_attention_serials = None
            tastes_tf_sample_attention_serials = None
            tastes_tf_attention_representations = None

        # Build n_tastes user representations and predictions
        for taste in range(self.n_tastes):
            tf_user_representation, user_weights = \
                self.user_repr_graph_factory.connect_representation_graph(tf_features=tf_user_features,
                                                                          n_components=self.n_components,
                                                                          n_features=n_user_features,
                                                                          node_name_ending='user_{}'.format(taste))
            tastes_tf_user_representations.append(tf_user_representation)
            tf_weights.extend(user_weights)

            # Connect attention, if applicable
            if self.attention_graph_factory is not None:
                tf_attention_representation, attention_weights = \
                    self.attention_graph_factory.connect_representation_graph(tf_features=tf_user_features,
                                                                              n_components=self.n_components,
                                                                              n_features=n_user_features,
                                                                              node_name_ending='attn_{}'.format(taste))
                tf_weights.extend(attention_weights)

                tf_attention = self.prediction_graph_factory.connect_dense_prediction_graph(
                    tf_user_representation=tf_attention_representation,
                    tf_item_representation=self.tf_item_representation
                )
                tf_attention_serial = self.prediction_graph_factory.connect_serial_prediction_graph(
                    tf_user_representation=tf_attention_representation,
                    tf_item_representation=self.tf_item_representation,
                    tf_x_user=tf_x_user,
                    tf_x_item=tf_x_item,
                )
                tf_sample_attention_serial = self.prediction_graph_factory.connect_serial_prediction_graph(
                    tf_user_representation=tf_user_representation,
                    tf_item_representation=self.tf_item_representation,
                    tf_x_user=tf_x_user_sample,
                    tf_x_item=tf_x_item_sample,
                )

                tastes_tf_attentions.append(tf_attention)
                tastes_tf_attention_serials.append(tf_attention_serial)
                tastes_tf_sample_attention_serials.append(tf_sample_attention_serial)
                tastes_tf_attention_representations.append(tf_attention_representation)

            # Connect the configurable prediction graphs for each taste
            tf_prediction = self.prediction_graph_factory.connect_dense_prediction_graph(
                tf_user_representation=tf_user_representation,
                tf_item_representation=self.tf_item_representation
            )
            tf_prediction_serial = self.prediction_graph_factory.connect_serial_prediction_graph(
                tf_user_representation=tf_user_representation,
                tf_item_representation=self.tf_item_representation,
                tf_x_user=tf_x_user,
                tf_x_item=tf_x_item,
            )
            tf_sample_predictions_serial = self.prediction_graph_factory.connect_serial_prediction_graph(
                tf_user_representation=tf_user_representation,
                tf_item_representation=self.tf_item_representation,
                tf_x_user=tf_x_user_sample,
                tf_x_item=tf_x_item_sample,
            )

            # Append to tastes
            tastes_tf_predictions.append(tf_prediction)
            tastes_tf_prediction_serials.append(tf_prediction_serial)
            tastes_tf_sample_prediction_serials.append(tf_sample_predictions_serial)

        # If attention is in the graph, build the API node
        if self.attention_graph_factory is not None:
            self.tf_user_attention_representation = tf.stack(tastes_tf_attention_representations)

        self.tf_user_representation = tf.stack(tastes_tf_user_representations)
        self.tf_prediction = collapse_mixture_of_tastes(
            tastes_predictions=tastes_tf_predictions,
            tastes_attentions=tastes_tf_attentions
        )
        self.tf_prediction_serial = collapse_mixture_of_tastes(
            tastes_predictions=tastes_tf_prediction_serials,
            tastes_attentions=tastes_tf_attention_serials
        )
        tf_sample_predictions_serial = collapse_mixture_of_tastes(
            tastes_predictions=tastes_tf_sample_prediction_serials,
            tastes_attentions=tastes_tf_sample_attention_serials
        )

        # Add biases, if this is a biased estimator
        if self.biased:
            tf_user_feature_biases, self.tf_projected_user_biases = project_biases(
                tf_features=tf_user_features, n_features=n_user_features
            )
            tf_item_feature_biases, self.tf_projected_item_biases = project_biases(
                tf_features=tf_item_features, n_features=n_item_features
            )

            tf_weights.append(tf_user_feature_biases)
            tf_weights.append(tf_item_feature_biases)

            self.tf_prediction = bias_prediction_dense(
                tf_prediction=self.tf_prediction,
                tf_projected_user_biases=self.tf_projected_user_biases,
                tf_projected_item_biases=self.tf_projected_item_biases)

            self.tf_prediction_serial = bias_prediction_serial(
                tf_prediction_serial=self.tf_prediction_serial,
                tf_projected_user_biases=self.tf_projected_user_biases,
                tf_projected_item_biases=self.tf_projected_item_biases,
                tf_x_user=tf_x_user,
                tf_x_item=tf_x_item)

            tf_sample_predictions_serial = bias_prediction_serial(
                tf_prediction_serial=tf_sample_predictions_serial,
                tf_projected_user_biases=self.tf_projected_user_biases,
                tf_projected_item_biases=self.tf_projected_item_biases,
                tf_x_user=tf_x_user_sample,
                tf_x_item=tf_x_item_sample)

        tf_interactions_serial = tf_interactions.values

        # Construct API nodes
        self.tf_rankings = rank_predictions(tf_prediction=self.tf_prediction)
        self.tf_predict_similar_items = predict_similar_items(prediction_graph_factory=self.prediction_graph_factory,
                                                              tf_item_representation=self.tf_item_representation,
                                                              tf_similar_items_ids=self.tf_similar_items_ids)
        self.tf_rank_similar_items = rank_predictions(tf_prediction=self.tf_predict_similar_items)

        # Compose loss function args
        # This composition is for execution safety: it prevents loss functions that are incorrectly configured from
        # having visibility of certain nodes.
        loss_graph_kwargs = {
            'tf_prediction_serial': self.tf_prediction_serial,
            'tf_interactions_serial': tf_interactions_serial,
            'tf_interactions': tf_interactions,
            'tf_n_users': tf_n_users,
            'tf_n_items': tf_n_items,
        }
        if self.loss_graph_factory.is_dense:
            loss_graph_kwargs.update({
                'tf_prediction': self.tf_prediction,
                'tf_rankings': self.tf_rankings,
            })
        if self.loss_graph_factory.is_sample_based:
            tf_sample_predictions = densify_sampled_item_predictions(
                tf_sample_predictions_serial=tf_sample_predictions_serial,
                tf_n_sampled_items=self.tf_n_sampled_items,
                tf_n_users=tf_n_users,
            )
            loss_graph_kwargs.update({'tf_sample_predictions': tf_sample_predictions,
                                      'tf_n_sampled_items': self.tf_n_sampled_items})

        # Build loss graph
        self.tf_basic_loss = self.loss_graph_factory.connect_loss_graph(**loss_graph_kwargs)

        self.tf_weight_reg_loss = sum(tf.nn.l2_loss(weights) for weights in tf_weights)
        self.tf_loss = self.tf_basic_loss + (self.tf_alpha * self.tf_weight_reg_loss)
        self.tf_optimizer = tf.train.AdamOptimizer(learning_rate=self.tf_learning_rate).minimize(self.tf_loss)

        # Record the new node names
        self._record_graph_hook_names()

    def fit(self, interactions, user_features, item_features, epochs=100, learning_rate=0.1, alpha=0.00001,
            verbose=False, user_batch_size=None, n_sampled_items=None):
        """
        Constructs the TensorRec graph and fits the model.
        :param interactions: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of interactions of shape [n_users, n_items].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param epochs: Integer
        The number of epochs to fit the model.
        :param learning_rate: Float
        The learning rate of the model.
        :param alpha:
        The weight regularization loss coefficient.
        :param verbose: boolean
        If true, the model will print a number of status statements during fitting.
        :param user_batch_size: int or None
        The maximum number of users per batch, or None for all users.
        :param n_sampled_items: int or None
        The number of items to sample per user for use in loss functions. Must be non-None if
        self.loss_graph_factory.is_sample_based is True.
        """

        # Pass-through to fit_partial
        self.fit_partial(interactions=interactions,
                         user_features=user_features,
                         item_features=item_features,
                         epochs=epochs,
                         learning_rate=learning_rate,
                         alpha=alpha,
                         verbose=verbose,
                         user_batch_size=user_batch_size,
                         n_sampled_items=n_sampled_items)

    def fit_partial(self, interactions, user_features, item_features, epochs=1, learning_rate=0.1,
                    alpha=0.00001, verbose=False, user_batch_size=None, n_sampled_items=None):
        """
        Constructs the TensorRec graph and fits the model.
        :param interactions: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of interactions of shape [n_users, n_items].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param epochs: Integer
        The number of epochs to fit the model.
        :param learning_rate: Float
        The learning rate of the model.
        :param alpha:
        The weight regularization loss coefficient.
        :param verbose: boolean
        If true, the model will print a number of status statements during fitting.
        :param user_batch_size: int or None
        The maximum number of users per batch, or None for all users.
        :param n_sampled_items: int or None
        The number of items to sample per user for use in loss functions. Must be non-None if
        self.loss_graph_factory.is_sample_based is True.
        """

        session = get_session()

        # Arg checking
        if self.loss_graph_factory.is_sample_based:
            if (n_sampled_items is None) or (n_sampled_items <= 0):
                raise ValueError("n_sampled_items must be an integer >0")
        if (n_sampled_items is not None) and (not self.loss_graph_factory.is_sample_based):
            logging.warning('n_sampled_items was specified, but the loss graph is not sample-based')

        # Check if the iterators have been constructed. If not, build them.
        if self.tf_interaction_iterator is None:
            self._build_input_iterators()

        if verbose:
            logging.info('Processing interaction and feature data')

        dataset_sets, initializer_sets = self._create_batched_dataset_initializers(interactions=interactions,
                                                                                user_features=user_features,
                                                                                item_features=item_features,
                                                                                user_batch_size=user_batch_size)

        # Check if the graph has been constructed by checking the dense prediction node
        # If it hasn't been constructed, initialize it
        if self.tf_prediction is None:

            # Check input dimensions
            first_batch = dataset_sets[0]
            _, n_user_features = get_dimensions_from_tensorrec_dataset(first_batch[1])
            _, n_item_features = get_dimensions_from_tensorrec_dataset(first_batch[2])

            # Numbers of features are either learned at fit time from the shape of these two matrices or specified at
            # TensorRec construction and cannot be changed.
            self._build_tf_graph(n_user_features=n_user_features, n_item_features=n_item_features)
            session.run(tf.global_variables_initializer())

        # Build the shared feed dict
        feed_dict = {self.tf_learning_rate: learning_rate,
                     self.tf_alpha: calculate_batched_alpha(num_batches=len(initializer_sets), alpha=alpha)}
        if self.loss_graph_factory.is_sample_based:
            feed_dict[self.tf_n_sampled_items] = n_sampled_items

        if verbose:
            logging.info('Beginning fitting')

        for epoch in range(epochs):
            for batch, initializers in enumerate(initializer_sets):

                session.run(initializers)
                if not verbose:
                    session.run(self.tf_optimizer, feed_dict=feed_dict)

                else:
                    _, loss, serial_predictions, wr_loss = session.run(
                        [self.tf_optimizer, self.tf_basic_loss, self.tf_prediction_serial, self.tf_weight_reg_loss],
                        feed_dict=feed_dict
                    )
                    mean_loss = np.mean(loss)
                    mean_pred = np.mean(serial_predictions)
                    weight_reg_l2_loss = alpha * wr_loss
                    logging.info('EPOCH {} BATCH {} loss = {}, weight_reg_l2_loss = {}, mean_pred = {}'.format(
                        epoch, batch, mean_loss, weight_reg_l2_loss, mean_pred
                    ))

    def predict(self, user_features, item_features):
        """
        Predict recommendation scores for the given users and items.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The predictions in an ndarray of shape [n_users, n_items]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=user_features,
                                                                 item_features=item_features)
        get_session().run(initializers)

        predictions = self.tf_prediction.eval(session=get_session())

        return predictions

    def predict_similar_items(self, item_features, item_ids, n_similar):
        """
        Predicts the most similar items to the given item_ids.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param item_ids: list or np.array
        The ids of the items of interest.
        E.g. [4, 8, 12] to get sims for items 4, 8, and 12.
        :param n_similar: int
        The number of similar items to get per item of interest.
        :return: list of lists of tuples
        The first level list corresponds to input arg item_ids.
        The second level list is of length n_similar and contains tuples of (item_id, score) for each similar item.
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_similar_items')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=None,
                                                                 item_features=item_features)
        get_session().run(initializers)

        feed_dict = {self.tf_similar_items_ids: np.array(item_ids)}
        sims = self.tf_predict_similar_items.eval(session=get_session(), feed_dict=feed_dict)

        results = []
        for i in range(len(item_ids)):
            item_sims = sims[i]
            best = np.argpartition(item_sims, -n_similar)[-n_similar:]
            item_results = sorted(zip(best, item_sims[best]), key=lambda x: -x[1])
            results.append(item_results)

        return results

    def predict_rank(self, user_features, item_features):
        """
        Predict recommendation ranks for the given users and items.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The ranks in an ndarray of shape [n_users, n_items]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_rank')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=user_features,
                                                                 item_features=item_features)
        get_session().run(initializers)

        rankings = self.tf_rankings.eval(session=get_session())

        return rankings

    def predict_user_representation(self, user_features):
        """
        Predict latent representation vectors for the given users.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The latent user representations in an ndarray of shape [n_users, n_components]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_user_representation')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=user_features,
                                                                 item_features=None)
        get_session().run(initializers)

        user_repr = self.tf_user_representation.eval(session=get_session())

        # If there is only one user repr per user, collapse from rank 3 to rank 2
        if self.n_tastes == 1:
            user_repr = np.sum(user_repr, axis=0)

        return user_repr

    def predict_user_attention_representation(self, user_features):
        """
        Predict latent attention representation vectors for the given users.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The latent user attention representations in an ndarray of shape [n_users, n_components]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_user_attention_representation')

        if self.attention_graph_factory is None:
            raise ModelWithoutAttentionException()

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=user_features,
                                                                 item_features=None)
        get_session().run(initializers)
        user_attn_repr = self.tf_user_attention_representation.eval(session=get_session())

        # If there is only one user attn repr per user, collapse from rank 3 to rank 2
        if self.n_tastes == 1:
            user_attn_repr = np.sum(user_attn_repr, axis=0)

        return user_attn_repr

    def predict_item_representation(self, item_features):
        """
        Predict representation vectors for the given items.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The latent item representations in an ndarray of shape [n_items, n_components]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_item_representation')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=None,
                                                                 item_features=item_features)
        get_session().run(initializers)
        item_repr = self.tf_item_representation.eval(session=get_session())
        return item_repr

    def predict_user_bias(self, user_features):
        """
        Predict bias values for the given users.
        :param user_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of user features of shape [n_users, n_user_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The user biases in an ndarray of shape [n_users]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_user_bias')

        if not self.biased:
            raise ModelNotBiasedException(actor='user')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=user_features,
                                                                 item_features=None)
        get_session().run(initializers)
        predictions = self.tf_projected_user_biases.eval(session=get_session())
        return predictions

    def predict_item_bias(self, item_features):
        """
        Predict bias values for the given items.
        :param item_features: scipy.sparse matrix, tensorflow.data.Dataset, str, or list
        A matrix of item features of shape [n_items, n_item_features].
        If a Dataset, the Dataset must follow the format used in tensorrec.input_utils.
        If a str, the string must be the path to a TFRecord file.
        If a list, the list must contain scipy.sparse matrices, tensorflow.data.Datasets, or strs.
        :return: np.ndarray
        The item biases in an ndarray of shape [n_items]
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='predict_item_bias')

        if not self.biased:
            raise ModelNotBiasedException(actor='item')

        _, initializers = self._create_datasets_and_initializers(interactions=None,
                                                                 user_features=None,
                                                                 item_features=item_features)
        get_session().run(initializers)
        predictions = self.tf_projected_item_biases.eval(session=get_session())
        return predictions

    def save_model(self, directory_path):
        """
        Saves the model to files in the given directory.
        :param directory_path: str
        The path to the directory in which to save the model.
        :return:
        """

        # Ensure that the model has been fit
        if self.tf_prediction is None:
            raise ModelNotFitException(method='save_model')

        if not os.path.exists(directory_path):
            os.makedirs(directory_path)

        saver = tf.train.Saver()
        session_path = os.path.join(directory_path, 'tensorrec_session.cpkt')
        saver.save(sess=get_session(), save_path=session_path)

        # Break connections to the graph before saving the python object
        self._break_graph_hooks()
        tensorrec_path = os.path.join(directory_path, 'tensorrec.pkl')
        with open(tensorrec_path, 'wb') as file:
            pickle.dump(file=file, obj=self)

        # Reconnect to the graph after saving
        self._attach_graph_hooks()

    @classmethod
    def load_model(cls, directory_path):
        """
        Loads the TensorRec model and TensorFlow session saved in the given directory.
        :param directory_path: str
        The path to the directory containing the saved model.
        :return:
        """

        graph_path = os.path.join(directory_path, 'tensorrec_session.cpkt.meta')
        saver = tf.train.import_meta_graph(graph_path)

        session_path = os.path.join(directory_path, 'tensorrec_session.cpkt')
        saver.restore(sess=get_session(), save_path=session_path)

        tensorrec_path = os.path.join(directory_path, 'tensorrec.pkl')
        with open(tensorrec_path, 'rb') as file:
            model = pickle.load(file=file)
        model._attach_graph_hooks()
        return model


text:
package org.shipkit.gradle.exec;

import org.gradle.api.Action;
import org.gradle.process.ExecResult;
import org.gradle.process.ExecSpec;

import java.util.Collection;

/**
 * Object that contains information about the executable command line.
 * It has: the command line arguments, action that configures the execution,
 * action that is triggered when the execution is complete.
 * <p>
 * To minimize public API and improve maintenance, this class should remain a value object, without any behavior.
 */
public class ExecCommand {

    private final String description;
    private final Collection<String> commandLine;
    private final Action<ExecSpec> setupAction;
    private final Action<ExecResult> resultAction;
    private final String loggingPrefix;

    /**
     * Generic command line to be executed
     *
     * @param loggingPrefix see {@link #getLoggingPrefix()}
     * @param description human readable description of the command
     * @param commandLine command line to be executed
     * @param setupAction action that configures the command line execution
     * @param resultAction action that is triggered after the command line was executed
     */
    public ExecCommand(String loggingPrefix, String description, Collection<String> commandLine, Action<ExecSpec> setupAction, Action<ExecResult> resultAction) {
        this.loggingPrefix = loggingPrefix;
        this.description = description;
        this.commandLine = commandLine;
        this.setupAction = setupAction;
        this.resultAction = resultAction;
    }

    /**
     * Command line to be executed.
     */
    public Collection<String> getCommandLine() {
        return commandLine;
    }

    /**
     * The action that configures the execution of command line
     */
    public Action<ExecSpec> getSetupAction() {
        return setupAction;
    }

    /**
     * The action that takes place after the command line is executed
     */
    public Action<ExecResult> getResultAction() {
        return resultAction;
    }

    /**
     * Description of the command, for example: "Checking out git revision"
     */
    public String getDescription() {
        return description;
    }

    /**
     * Logging prefix to be used to prefix every line of output captured from running the command.
     */
    public String getLoggingPrefix() {
        return loggingPrefix;
    }
}