text:
/**
 * Functions that print to the output pane.
 */

/**
 * ID attribute of output pane XUL element.  Used by default in the
 * functions below; but additional output-like panes (like the Action history)
 * can be controlled by specifying the ID of the other pane instead.
 * @const
 */
var CF_DEBUG_ID = 'CF_DEBUG';

/**
 * Print object to output panes on all open sidebars AND to the
 * Javascript console.
 * Used for internal Chickenfoot debugging or trigger debugging.
 */
function debug(/*anything*/ obj) {
  try {
    var windowMediator =
      Components.classes["@mozilla.org/appshell/window-mediator;1"]
        .getService(Components.interfaces.nsIWindowMediator);
    var e = windowMediator.getEnumerator("navigator:browser");
    while (e.hasMoreElements()) {
      var chromeWindow = e.getNext();
      printDebug(chromeWindow, obj);
    }
  } catch (e) {
  }

  debugToErrorConsole(obj)
}

/**
 * Print object only to Javascript error console.
 * Use for debugging messages that shouldn't be allowed to clutter the output pane.
 */
function debugToErrorConsole(/*anything*/ obj) {
  var consoleService = Components.classes["@mozilla.org/consoleservice;1"]
                                 .getService(Components.interfaces.nsIConsoleService);
  consoleService.logStringMessage(toDebugString(obj));
}

// Objects that want to print themselves in a special way in the
// Chickenfoot output pane can define this method:
//    /*anything*/ toChickenfootDebugOutput(/*Node*/ debugEntry);
//        debugEntry    is the element of the Chickenfoot output pane to which this output will be appended.
//
//    toChickenfootDebugOutput can either:
//       - return an arbitrary string or object that should be displayed in the debug pane.
//         The caller will pass this object to toDebugString() to convert it into a string for display.
//    or:
//       - directly append child nodes to debugEntry, and return undefined to signal
//         to the caller that it handled the output itself.
//

/**
 * Print object to output pane in given chrome window.
 * Used by Chickenfoot output() command and by evaluate().
 */
function printDebug(/*ChromeWindow*/ chromeWindow,
                    /*anything*/ obj,
                    /*optional boolean*/ dontBringToFront,
                    /*optional boolean*/ isHTML,
                    /*optional String*/ id) {
  if (!id) id = CF_DEBUG_ID;

  // find sidebar
  var sidebarWindow = getSidebarWindow(chromeWindow);
  if (!sidebarWindow) return;
  var sidebar = sidebarWindow.document;

  // make sure Output tab is visible
  if (!dontBringToFront) autoswitchToOutputPane(sidebar)

  var debug = sidebar.getElementById(id);
  var node = getLatestDebugEntry(sidebar, id);
  addDebugOutput(node, obj, isHTML, chromeWindow);

  var win = debug.contentWindow;
  win.scrollTo(node.offsetLeft, node.offsetTop + node.offsetHeight);
}

/**
 * autoswitchTimeout controls the way Chickenfoot automatically switches to
 * the Output pane when a message is printed.  When the mouse is active anywhere
 * in the tab box, autoswitching is disabled until no more such mouse events
 * have happened for the duration of this timeout.  The timeout is in milliseconds.
 * @const
 */
var autoswitchTimeout = 5000; // milliseconds

function startOutputPaneAutoswitching(/*SidebarDocument*/ sidebar) {
  if (autoswitchTimeout) {
    var tab = sidebar.getElementById("CF_DEBUG_TAB");
    var tabbox = tab.parentNode.parentNode;
    tabbox.addEventListener("mousedown", mouseActivityInTabs, true)
    tabbox.addEventListener("mousemove", mouseActivityInTabs, true)
  }

  function mouseActivityInTabs(event) {
    // clock time when autoswitching will resume
    sidebar.autoswitchResume = new Date().getTime() + autoswitchTimeout
  }
}

function autoswitchToOutputPane(/*SidebarDocument*/ sidebar) {
  var now = new Date().getTime()
  if (now <= sidebar.autoswitchResume) {
    // don't autoswitch, because it's less than autoswitchTimeout msec since
    // user touched the tabs
    return;
  }

  var tab = sidebar.getElementById("CF_DEBUG_TAB");
  var tabbox = tab.parentNode.parentNode;
  tabbox.selectedTab = tab;
}

//takes string as optional fifth argument, specifying how obj should be printed
// should be used only when differs from how toDebugString(obj) returns.
function addDebugOutput(/*Node*/ node, /*anything*/ obj, /*boolean*/ isHTML, /*chromeWindow*/ chromeWindow, /*optional string*/ title) {
  var sidebarWindow = getSidebarWindow(chromeWindow);
  var doc = node.ownerDocument;
  var objToPrint = obj;

  // First see if obj knows how to make itself into debug output.
  var hasChickenfootDebugOutput = false;
  try {
    // Catch errors if obj.toChickenfootDebugOutput does not exist.  Some objects throw
    // security exceptions if you even look twice at them!
    // Don't actually call toChickenfootDebugOutput() inside this try-catch, so we can
    // distinguish these access exceptions (which we want to mask) from exceptions thrown
    // by toChickenfootDebugOutput() (which we DON'T want to mask, but propagate upwards so
    // that the author of that function can debug them).

    if (obj && typeof obj == "object" && typeof obj.toChickenfootDebugOutput == "function") {
      hasChickenfootDebugOutput = true;
    }
  } catch (err) {
  }

  if (hasChickenfootDebugOutput) {
    var result = obj.toChickenfootDebugOutput(doc, node);
    if (result === undefined) {
      return;
    } else {
      objToPrint = result;
    }
  }

  if (isHTML) {
    var text = toDebugString(objToPrint);
    var range1 = doc.createRange();
    range1.setStart(node, 0);
    range1.setEnd(node, 0);
    node.appendChild(range1.createContextualFragment(text+"<br>"));
    return;
  }

  // otherwise just convert obj to text
  if (title) {var newNode = title;}
  else {
    var text = toDebugString(objToPrint);
    var newNode = doc.createTextNode(text + "\n");
  }
  var spaceNode = doc.createTextNode("");
  if (typeof obj == "object") {
    var header; var bodyRow; var icon;

    try {
      var oldSpaces = node.getAttribute("spaces");
      if (oldSpaces == null) {numSpaces = "";}
      else {var numSpaces = oldSpaces + "1";}
    }
    catch(err) {var numSpaces = "errSpaces";}
    var spaces = numSpaces.length; var spacesString = "";
    for (var h = 0; h < spaces; h++) {
      spacesString += "  ";
    }
    var tableNode = makeElement(doc, "div", {}, [
      header = makeElement(doc, "div", {"class":"collapsed", "id":"current"},
      [
        doc.createTextNode(spacesString),
        icon = makeElement(doc, "img", { "class":"expandCollapseIcon", "src":"chrome://chickenfoot/skin/expand.gif", "height":9, "width":9 }, []),
        newNode
      ]),
      bodyRow = makeElement(doc,
                            "div",
                            {"style": "visibility:hidden",
                             "class": "objectProperties",
                             "spaces": numSpaces},
                            [])
    ]);

    //event listener function to expand and collapse
    function expandOrCollapse(event) {
      var doExpand = header.getAttribute("class") == "collapsed";
      header.setAttribute("class", doExpand ? "expanded" : "collapsed");
      bodyRow.style.visibility = doExpand ? "visible" : "hidden";
      icon.src = doExpand ? "chrome://chickenfoot/skin/collapse.gif" : "chrome://chickenfoot/skin/expand.gif";
      if (doExpand) {
        sidebarWindow.setCursor('wait');
        //check if is a function that shouldn't expand any more
        if (obj.chickenfootFunctionToDisplay) {
          var funcNode =
            makeElement(doc, "div", {}, [
              colorText(doc, obj.chickenfootFunctionToDisplay, "navy")
            ]);
          bodyRow.appendChild(funcNode);
        }
        //otherwise list its items
        else {
          var listOutput = [];
          try { listOutput = listImpl(obj, ".*", "expandibleList"); }
          catch (err) {}

          if (instanceOf(obj, Match)) {listOutput = getMatchIteration(obj, listOutput);}

          var longestString = 0;
          for (var m=0; m<listOutput.length; m++) {
            if (listOutput[m][1] && (listOutput[m][1].length > longestString)) {longestString = listOutput[m][1].length;}
          }

          for (var i=0; i<listOutput.length; i++) {
            var current = listOutput[i];
            var property = current[1];
            var value = current[2];

            //add the right number of spaces between property and value for visual columns
            var numberOfSpaces = longestString + 5 -(property.length);
            for (var k=0; k<numberOfSpaces; k++) {
              property += " ";
            }

            //if item is an object, recursively send it back to addDebugOutput
            if (typeof value == "object" && value !== null) {
              if ((instanceOf(value, Match) && (property.toString().substring(0, 4) != "next"))
                  || instanceOf(obj, Array)) {
                var name = property + " = " + toDebugString(value);
              }
              else {var name = property + toDebugString(value);}
              addDebugOutput(bodyRow, value, isHTML, chromeWindow, colorText(doc, name, "green"));
            }
            //if item is a function, allow it to expand once more
            else if (typeof value == "function") {
                //remove the "\n" characters in the header text
                var name = property + value;
                name = name.replace(/\n/g, "");
                value = spacesString + "    " + value.toString().replace(/\n/g, "\n" + spacesString + "    ");

                functionObj = new Object();
                functionObj.chickenfootFunctionToDisplay = value;
                addDebugOutput(bodyRow, functionObj, isHTML, chromeWindow, colorText(doc, name, "navy"));
              }
            else if (instanceOf(obj, Array)) {
              var name = property + " = " + toDebugString(value);
              bodyRow.appendChild(colorText(doc, spacesString + "  " + name + "\n", "purple"));
            }
            //otherwise, don't expand anymore, just print the item and its value
            else {
              var name = property + "  " + value;
              bodyRow.appendChild(colorText(doc, spacesString + "  " + name + "\n", "purple"));
            }
          }
        }
        sidebarWindow.setCursor('auto');
      } else {
        removeAllChildren(bodyRow);
      }
    }

    //event listener function to highlight match objects in html pages
    function highlightMatch() {
      //if no matches, just clear the document
      if (!obj.hasMatch) {
        try {clearAll(chromeWindow, header); fireMouseEvent("click", chromeWindow.content.wrappedJSObject.document.body); return;}
        catch(err) {return;}
      }
      //if XUL searching, don't do anything because red highlighting throws an error
      if (instanceOf(obj.document, XULDocument)) {return;}
      //then highlight all or just one, depending on whether they clicked on an expanded match object or not
      var win = obj.document.defaultView;
      if (!obj._toExpand) {
        clearAll(chromeWindow, obj);
        try {selectAll(win, obj);} catch (err) {debug(err)}
        header.style.color = 'red';
        header.title = 'black';
      }
      else {
        clearAll(chromeWindow, obj);
        var matchToSelect = oneMatch(obj);
        try {selectAll(obj.document.defaultView, matchToSelect);} catch (err) {debug(err)}
        header.childNodes[2].style.color = 'red';
        header.title = 'green';
      }
    }

    //event listener function to throw away object reference, remove event listeners, and disable entry
    function disableEntry(event) {
      if (this.getAttribute("id") == "toRemove") {
        this.removeEventListener("click", expandOrCollapse, false);
        this.setAttribute("id", "");
        if (instanceOf(obj, Match)) {
          clearAll(chromeWindow, obj);
          this.removeEventListener("click", highlightMatch, false);
          chromeWindow.content.wrappedJSObject.removeEventListener("click", function(event) {clearAll(chromeWindow, obj);}, false);
          this.title = "";
        }
        this.removeEventListener("mouseup", disableEntry, false);
      }
      else { return; }
    }

    //add all appropriate event listeners
    header.addEventListener("click", expandOrCollapse, false);
    header.addEventListener("mouseup", disableEntry, false);
    if (instanceOf(obj, Match)) {
      header.addEventListener("click", highlightMatch, false);
      highlightMatch(); // highlight all the matches now
      chromeWindow.content.wrappedJSObject.addEventListener("click", function(event) {clearAll(chromeWindow, obj);}, false);
    }
    newNode = tableNode;
  }
  node.appendChild(newNode);
}

//clears all highlighted match entries (in debug pane and html document)
function clearAll(chromeWindow, obj) {
  try {clearSelection(obj.document.defaultView);}
  catch(err) {}
  var sidebarWindow = getSidebarWindow(chromeWindow);
  var sidebar = sidebarWindow.document;
  var recentEntry = getLatestDebugEntry(sidebar, CF_DEBUG_ID);
  var treewalker = createDeepTreeWalker(recentEntry, NodeFilter.SHOW_All);
  var current = treewalker.nextNode();
  while (current) {
    if (current.title == "black") {current.style.color = "black";}
    if (current.title == "green") {current.childNodes[2].style.color = "green";}
    current = treewalker.nextNode();
  }
}

/**
 *
 * @param {Document} doc
 * @param {string} name
 * @param {Object} attrs
 * @param {Array.<Node>} children
 * @return {Element}
 */
function makeElement(doc, name, attrs, children) {
  var node = doc.createElement(name);
  for (var attr in attrs) {
    node.setAttribute(attr, attrs[attr]);
  }
  for (var i = 0; i < children.length; ++i) {
    node.appendChild(children[i]);
  }
  return node;
}

function removeAllChildren(/*Node*/ node) {
  for (var i = node.childNodes.length-1; i >= 0; --i) {
    node.removeChild(node.childNodes[i]);
  }
}

/**
 * Gray out all previous output entries and prepare to receive fresh output.
 * If id is provided, changes the output pane with the given id attribute;
 * otherwise defaults to CF_DEBUG_ID.
 */
function startNewDebug(/*ChromeWindow*/ chromeWindow,
                       /*optional String*/ id) {
  if (!id) id = CF_DEBUG_ID;

  // find sidebar
  var sidebarWindow = getSidebarWindow(chromeWindow);
  if (!sidebarWindow) return;
  var sidebar = sidebarWindow.document;

  var debug = sidebar.getElementById(id);
  var doc = debug.contentDocument;
  var body = doc.getElementsByTagName('body')[0];

  var div = getLatestDebugEntry(sidebar, id);
  if (div.hasChildNodes()) {
    // need to create a new PRE
    div.setAttribute("class", "old");
    disablePrevious(div);

    var newDiv = doc.createElement('PRE');
    newDiv.setAttribute("class", "new");
    body.appendChild(newDiv);
    div = body.lastChild;
  }

  var win = debug.contentWindow;
  win.scrollTo(div.offsetLeft, div.offsetTop + div.offsetHeight);
}

function disablePrevious(/*node*/ node) {
  var pred =
    function (node) {
      try{return (node.id == "current");}
      catch(err) {return false;}
    };
  var treewalker = createDeepTreeWalker(node, NodeFilter.SHOW_ALL, pred);
  var current = treewalker.nextNode();
  while (current) {
    current.id = "toRemove";
    fireMouseEvent("mouseup", current);
    current = treewalker.nextNode()
  }
}

/**
 * Clears the output pane in sidebar.
 * If id is provided, clears the output pane with the given id attribute;
 * otherwise defaults to CF_DEBUG_ID.
 */
function clearDebugPane(/*ChromeWindow*/ chromeWindow, /*optional String*/ id) {
  // find sidebar
  var sidebarWindow = getSidebarWindow(chromeWindow);
  if (!sidebarWindow) return;
  var sidebar = sidebarWindow.document;

  if (!id) id = CF_DEBUG_ID;
  var debug = sidebar.getElementById(id);
  var doc = debug.contentDocument;
  var body = doc.getElementsByTagName('body')[0];
  var parent = body.parentNode;
  parent.removeChild(body);

  var newBody = doc.createElement('BODY');
  parent.appendChild(newBody);
  getLatestDebugEntry(sidebar, id);
}

/**
 * Render an object or exception as a string for display to
 * the output pane.  Returns the string.
 */
function toDebugString(/*any*/ obj) {
  if (obj === null) {
    return 'null';
  }

  if (obj === undefined) {
    return 'undefined';
  }

  if (Range && instanceOf(obj, Range)) {
    return '[object Range]';
  }

  if (((typeof obj) == "object") && (obj.toString().match(/^java\./)) && hasJava()) {
    try { // catch errors if java isn't initialized yet
      if (instanceOf(obj, java.security.PrivilegedActionException)) {
        return toDebugString(obj.getException());
      } else if (instanceOf(obj, java.lang.reflect.InvocationTargetException)) {
        return toDebugString(obj.getCause());
      } else if (instanceOf(obj, java.lang.Throwable)) {
        var text = obj.toString();
        var stack = obj.getStackTrace();
        if (stack.length >= 1) {
          text += "\n in " + stack[0];
          for (var i = 1; i < stack.length; ++i) {
            var frame = stack[i].toString();
            if (frame.match(/^sun.reflect|java.lang.reflect/)) {
              break;
            } else {
              text += "\n    " + frame;
            }
          }
        }
        return text;
      }
    } catch (e) {
    }
  }

  try {
    if (instanceOf(obj, Error)
          /* FIX: the catalog of errors below is required because our instanceOf() doesn't
             handle subtyping. If user creates their own subclass of Error, we won't detect it
             here, which is bad. */
        || instanceOf(obj, SyntaxError)
        || instanceOf(obj, ReferenceError)
        || instanceOf(obj, TypeError)
        || instanceOf(obj, EvalError)
        || instanceOf(obj, RangeError)
        || instanceOf(obj, URIError)
        ) {
      return obj.toString() + '\n' + translateJavascriptStackTrace(obj.stack);
    }

    return obj.toString();
  } catch (error) {
    // Firefox 1.0.3 workaround:
    //   if obj is an array containing objects from the browser document,
    //   it throws "Illegal operation on WrappedNative prototype object"  nsresult: "0x8057000c (NS_ERROR_XPC_BAD_OP_ON_WN_PROTO)"
    // Deal with it by displaying the array directly.
    if (instanceOf(obj, Array)) {
      if (obj.length == 0) return "";
      var s = obj[0].toString();
      for (var i = 1; i < obj.length; ++i) {
        s += "," + obj[i].toString();
      }
      return s;
    } else {
      // exception was caused by something else;
      // pass it on
      throw error;
    }
  }

  /**
   * Parse the stack trace and return something
   * more human-readable.
   */
  function translateJavascriptStackTrace(/*String*/ stack) {
    var re = /(\w*)(\(.*\))@(.*):(\d+)/g;
    re.lastIndex = 0;

    var sb = new StringBuffer();
    while (m = re.exec(stack)) {
      var functionName = m[1];
      var args = m[2];
      var file = m[3];
      var line = m[4];

      if (file == "chrome://chickenfoot/content/chickenscratch.xul") {
        line -= 16;
      }

      if (functionName == "Error" || functionName == "Exception") {
        continue;
      }

      if (!functionName) functionName = "anonymous";

      sb.append((sb.length == 0) ? " in " : "    ");

      // the first chickenscratchEvaluate should be the top of the stack
      if (functionName == "chickenscratchEvaluate") {
        sb.append("top level line " + line + "\n");
        break;
      } else {
        sb.append(functionName + "() line " + line + "\n");
      }
    }
    return sb.toString();
  }

} // end toDebugString()

/**
 * Get the node representing the latest output entry, to which new text nodes
 * can be added as children.
 * If id is provided, changes the output pane with the given id attribute;
 * otherwise defaults to CF_DEBUG_ID.
 */
function getLatestDebugEntry(/*XULDocument*/ sidebar, /*optional String*/ id) {
  if (!id) id = CF_DEBUG_ID;
  var debug = sidebar.getElementById(id);
  var doc = debug.contentDocument;
  var body = doc.getElementsByTagName('body')[0];
  var div = body.lastChild;

  if (div == null || div.tagName != 'PRE') {
    // need to create a PRE element
    var newDiv = doc.createElement('PRE');
    newDiv.setAttribute("class", "new");
    body.appendChild(newDiv);
    div = body.lastChild;
  }

  return div;
}

function colorText(/*HTMLDocument*/ doc, /*string*/ text, /*string*/ color) {
  var textnode = doc.createTextNode(text);
  var font = doc.createElement("font");
  font.style.color = color;
  font.appendChild(textnode);
  return font;
}

function getMatchIteration(/*Match object*/ matchObj, /*Array*/ listOutput) {
  if ((matchObj == EMPTY_MATCH) || (matchObj._next == EMPTY_MATCH) || (matchObj._toExpand)) {
    return listOutput;
  }
  else {
    var matchIteration = new Array();
    var firstMatchCopy = oneMatch(matchObj);
    matchIteration.push(firstMatchCopy);
    firstMatchCopy._toExpand = true;
    matchObj = matchObj.next;

    while (matchObj != EMPTY_MATCH) {
      matchIteration.push(matchObj);
      matchObj._toExpand = true;
      matchObj = matchObj.next;
    }
    return listImpl(matchIteration, ".*", "expandibleList");
  }
}


text:
require 'rmodel'

DB = Mongo::Client.new(['localhost'], database: 'test')
source = Rmodel::Mongo::Source.new(DB, :users)

User = Struct.new(:id, :name, :email)
mapper = Rmodel::Mongo::Mapper.new(User).define_attributes(:name, :email)

class UserRepository < Rmodel::Repository
  scope :have_email do
    where(email: { '$exists' => true })
  end

  scope :start_with do |letter|
    where(name: { '$regex' => "^#{letter}", '$options' => 'i' })
  end
end

repo = UserRepository.new(source, mapper)
repo.delete_all

repo.insert(User.new(nil, 'John', 'john@example.com'))
repo.insert(User.new(nil, 'Bill', 'bill@example.com'))
repo.insert(User.new(nil, 'Bob'))

p repo.fetch.start_with('b').to_a
p repo.fetch.start_with('b').have_email.to_a
p repo.fetch.count

redpajama_set_name: RedPajamaGithub


text:
require 'test_helper'

class BidResultTest < ActiveSupport::TestCase
  # test "the truth" do
  #   assert true
  # end
end


text:
	<title>Russell Foster's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Russell Foster's panel show appearances

Russell Foster (born 1959-08-19[ref]) has appeared in 2 episodes between 2015-2016.  Russell Foster on Wikipedia.

2015

2016

2016-07-18 / The Infinite Monkey Cage

2015-12-17 / In Our Time


text:
package net.bytebuddy.implementation.bytecode;

import net.bytebuddy.build.HashCodeAndEqualsPlugin;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.Implementation;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

/**
 * A stack manipulation for creating an <i>undefined</i> type on which a constructor is to be called.
 */
@HashCodeAndEqualsPlugin.Enhance
public class TypeCreation extends StackManipulation.AbstractBase {

    /**
     * The type that is being created.
     */
    private final TypeDescription typeDescription;

    /**
     * Constructs a new type creation.
     *
     * @param typeDescription The type to be created.
     */
    protected TypeCreation(TypeDescription typeDescription) {
        this.typeDescription = typeDescription;
    }

    /**
     * Creates a type creation for the given type.
     *
     * @param typeDescription The type to be created.
     * @return A stack manipulation that represents the creation of the given type.
     */
    public static StackManipulation of(TypeDescription typeDescription) {
        if (typeDescription.isArray() || typeDescription.isPrimitive() || typeDescription.isAbstract()) {
            throw new IllegalArgumentException(typeDescription + " is not instantiable");
        }
        return new TypeCreation(typeDescription);
    }

    /**
     * {@inheritDoc}
     */
    public Size apply(MethodVisitor methodVisitor, Implementation.Context implementationContext) {
        methodVisitor.visitTypeInsn(Opcodes.NEW, typeDescription.getInternalName());
        return new Size(1, 1);
    }
}


text:
module Api
  module V1
    class EventsController < Api::BaseController
      load_resource :conference, find_by: :short_title
      respond_to :json

      # Disable forgery protection for any json requests. This is required for jsonp support
      skip_before_action :verify_authenticity_token

      def index
        events = Event.includes(:track, :event_type, event_users: :user)

        if @conference
          events = events.where(program: @conference.program)
        end

        respond_with events.confirmed, callback: params[:callback]
      end
    end
  end
end


text:
<?php

require_once dirname(__FILE__) . "/../API/Utility.php";
require_once dirname(__FILE__) . "/../Query/Student.php";

function temp_add_student($username) {
    $query = "INSERT INTO student (student_username) VALUES ($1)";
    return pg_query_params($GLOBALS['CONNECTION'], $query, array($username));
}
function temp_add_avail($term_id, $student_id) {
    $query = "INSERT INTO hour_block (term_id, student_id, block_day, block_hour, block_preference) VALUES ($1, $2, $3, $4, $5)";
    return pg_query_params($GLOBALS['CONNECTION'], $query, array($term_id, $student_id, "Monday", "12", "Preferred"));
}
function temp_remove_avail($term_id, $student_id) {
    $query = "DELETE FROM hour_block WHERE term_id=$1 AND student_id=$2";
    return pg_query_params($GLOBALS['CONNECTION'], $query, array($term_id, $student_id));
}

//  Database connection
if (!($CONNECTION =cody_db_connect())) {
    echo "
Connection Failed
\n";
    exit();
} else {
    echo "Connection to Database Established\n";
}

$query = "SELECT student_id, student_username FROM student WHERE active=true ORDER BY student_id ASC LIMIT 3";
if (!($results = pg_query($query))) {
    echo "Failed to pull test students\n";
    exit();
}
$students_initial = pg_fetch_all($results);

$arr = array();
foreach ($students_initial as $student) {
    array_push($arr, $student['student_username']);
}
echo "Test 1, should a list of students INCLUDING AT LEAST " . implode(", ", $arr) . "\n";
if (!($results = retrieve_students_no_availability(1))) {
    echo "Failed to retrieve students\n";
    exit();
}
$students = pg_fetch_all($results);
echo "    Students That Have Not Submitted Availability:\n";
foreach ($students as $student) {
    echo "        " . $student['student_id'] . " -- " . $student['student_username'] . "\n";
}

echo "Adding Availability for " . $students_initial[0]['student_username'] . "\n";
if (!temp_add_avail(1, $students_initial[0]['student_id'])) {
    echo "Failed to add availability\n";
    exit();
}
echo "Test 2, should display all test students except " . $students_initial[0]['student_username'] . "\n";
if (!($results = retrieve_students_no_availability(1))) {
    echo "Failed to retrieve students\n";
    temp_remove_avail(1, $students_inital[0]['student_id']);
    exit();
}
$students = pg_fetch_all($results);
echo "    Students That Have Not Submitted Availability:\n";
foreach ($students as $student) {
    echo "        " . $student['student_id'] . " -- " . $student['student_username'] . "\n";
}

echo "Adding Availability for " . $students_initial[2]['student_username'] . "\n";
if (!temp_add_avail(1, $students_initial[2]['student_id'])) {
    echo "Failed to add availability\n";
    temp_remove_avail(1, $students_inital[0]['student_id']);
    exit();
}
// echo "Test 3, should only display student " . $students_initial[1]['student_username'] . "\n";
echo "Test 3, should display all test students except " . $students_initial[0]['student_username'] . " and " . $students_initial[2]['student_username'] . "\n";
if (!($results = retrieve_students_no_availability(1))) {
    echo "Failed to retrieve students\n";
    temp_remove_avail(1, $students_inital[0]['student_id']);
    temp_remove_avail(1, $students_inital[2]['student_id']);
    exit();
}
$students = pg_fetch_all($results);
echo "    Students That Have Not Submitted Availability:\n";
foreach ($students as $student) {
    echo "        " . $student['student_id'] . " -- " . $student['student_username'] . "\n";
}

echo "Cleaning up\n";
foreach ($students_initial as $student) {
    temp_remove_avail(1, $student['student_id']);
}
echo "Done\n";

?>


text:
<?php

namespace Cmf\Data\Validator;

/**
 * Exception for Cmf\Data\Validator
 *
 * @author Vital Leshchyk <vitalleshchyk@gmail.com>
 */
class Exception extends \Cmf\System\Exception
{
}


text:
import os
import pytest
from unittest import TestCase

import torch
import torchmetrics
from torch import nn

from bigdl.nano.pytorch.lightning import LightningModule
from bigdl.nano.pytorch import Trainer
from bigdl.nano.common import check_avx512
from bigdl.nano.pytorch.utils import TORCH_VERSION_LESS_1_10

from test.pytorch.utils._train_torch_lightning import create_data_loader, data_transform
from test.pytorch.utils._train_torch_lightning import create_test_data_loader
from test.pytorch.utils._train_ipex_callback import CheckIPEXCallback, CheckIPEXFusedStepCallback
from test.pytorch.tests.test_lightning import ResNet18

num_classes = 10
batch_size = 32
dataset_size = 256
num_workers = 0
data_dir = os.path.join(os.path.dirname(__file__), "../data")

class TestPlugin(TestCase):
    model = ResNet18(pretrained=False, include_top=False, freeze=True)
    loss = nn.CrossEntropyLoss()
    optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
    data_loader = create_data_loader(data_dir, batch_size, num_workers,
                                     data_transform, subset=dataset_size)
    test_data_loader = create_test_data_loader(data_dir, batch_size, num_workers,
                                               data_transform, subset=dataset_size)

    def setUp(self):
        test_dir = os.path.dirname(__file__)
        project_test_dir = os.path.abspath(
            os.path.join(os.path.join(os.path.join(test_dir, ".."), ".."), "..")
        )
        os.environ['PYTHONPATH'] = project_test_dir

    def test_trainer_subprocess_plugin(self):
        pl_model = LightningModule(
            self.model, self.loss, self.optimizer,
            metrics=[torchmetrics.F1(num_classes), torchmetrics.Accuracy(num_classes=10)]
        )
        trainer = Trainer(num_processes=2, distributed_backend="subprocess",
                          max_epochs=4, use_ipex=True,
                          callbacks=[CheckIPEXCallback()])
        trainer.fit(pl_model, self.data_loader, self.test_data_loader)
        trainer.test(pl_model, self.test_data_loader)

    def test_trainer_spawn_plugin_bf16(self):
        # IPEX BF16 weight prepack needs the cpu support avx512bw, avx512vl and avx512dq
        model = ResNet18(pretrained=False, include_top=False, freeze=True)
        loss = nn.CrossEntropyLoss()
        optimizer = torch.optim.Adam(model.parameters(), lr=0.01)
        pl_model = LightningModule(
            model, loss, optimizer,
            metrics=[torchmetrics.F1(num_classes), torchmetrics.Accuracy(num_classes=10)]
        )
        trainer = Trainer(num_processes=2, distributed_backend="spawn",
                          max_epochs=4, use_ipex=True, precision="bf16",
                          callbacks=[CheckIPEXCallback(), CheckIPEXFusedStepCallback()])
        trainer.fit(pl_model, self.data_loader, self.test_data_loader)
        trainer.test(pl_model, self.test_data_loader)
        if trainer.use_ipex and TORCH_VERSION_LESS_1_10:
            import intel_pytorch_extension as ipex
            # Diable IPEX AMP
            # Avoid affecting other tests
            ipex.enable_auto_mixed_precision(None)

if __name__ == '__main__':
    pytest.main([__file__])


text:
$DESCRIPTION$

Obsolete from version **$OBSOLETE_FROM_VERSION$**.

**Old API**

$OLD_API$

**New API**

$NEW_API$


text:
<?xml version="1.0" encoding="UTF-8"?>
<metadata>
  <groupId>com.cocosw</groupId>
  <artifactId>style</artifactId>
  <version>0.0.1</version>
  <versioning>
    <versions>
      <version>0.0.1</version>
    </versions>
    <lastUpdated>20141215035750</lastUpdated>
  </versioning>
</metadata>


text:
#region Apache License

//-----------------------------------------------------------------------
// <copyright file="Permission.cs" company="StrixIT">
// Copyright 2015 StrixIT. Author R.G. Schurgers MA MSc.
//
// 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.
// </copyright>
//-----------------------------------------------------------------------

#endregion Apache License

using StrixIT.Platform.Core;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;

namespace StrixIT.Platform.Modules.Membership
{
    /// <summary>
    /// The class for a role permission.
    /// </summary>
    public class Permission
    {
        #region Public Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="Permission"/> class.
        /// </summary>
        /// <param name="name">The permission name</param>
        public Permission(string name) : this(Guid.Empty, Guid.Empty, name)
        {
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="Permission"/> class.
        /// </summary>
        /// <param name="id">The permission id</param>
        /// <param name="applicationId">The id of the application the permission belongs to</param>
        /// <param name="name">The permission name</param>
        public Permission(Guid id, Guid applicationId, string name)
        {
            this.Id = id;
            this.ApplicationId = applicationId;
            this.Name = name;
        }

        #endregion Public Constructors

        #region Private Constructors

        /// <summary>
        /// Prevents a default instance of the <see cref="Permission"/> class from being created.
        /// </summary>
        private Permission()
        {
        }

        #endregion Private Constructors

        #region Public Properties

        /// <summary>
        /// Gets the application the permission is for.
        /// </summary>
        public Application Application { get; private set; }

        /// <summary>
        /// Gets the id of the application the permission is for.
        /// </summary>
        [StrixRequired]
        public Guid ApplicationId { get; private set; }

        /// <summary>
        /// Gets the id of the permission.
        /// </summary>
        public Guid Id { get; private set; }

        /// <summary>
        /// Gets the permission name.
        /// </summary>
        [StrixRequired]
        [StringLength(100)]
        public string Name { get; private set; }

        /// <summary>
        /// Gets or sets the roles that have this permission.
        /// </summary>
        public ICollection<Role> Roles { get; set; }

        #endregion Public Properties
    }
}


text:
.reveal section img {
  background:none;
  border:none;
  box-shadow:none;
}

.reveal pre {
  border: none;
  box-shadow: none;
  font-size: 0.7em;
  line-height: 1.2em;
}

.reveal pre code {
  background-color: transparent;
  max-height: initial;
}


text:
<!--

    cudos-pol-pane - CUDOS component

    Author: Tim McMaster

-->

<link href="../bower_components/polymer/polymer.html" rel="import">
<link href="../bower_components/paper-material/paper-material.html" rel="import">
<link href="../bower_components/paper-ripple/paper-ripple.html" rel="import">
<link href="../bower_components/paper-behaviors/paper-button-behavior.html" rel="import">
<link href="../bower_components/iron-flex-layout/iron-flex-layout.html" rel="import">

<dom-module id="cudos-details-pane" attributes="policy">

    <style is="custom-style">
        fieldset {
            /*clear:both;*/
            float:right;
            height:500px;
            width:200px;
        }
    </style>

    <template>
        <fieldset>
            <legend>cudos-details-pane</legend>
        </fieldset>
    </template>

    <script>
        Polymer({
            is: "cudos-details-pane",

            properties: {

            }
        })
    </script>
</dom-module>


text:
import pickle
import marshal

list = [1, 2]
list.append(list)

print list

#byte1 = marshal.dumps(list)
byte2 = pickle.dumps(list)
print byte2


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

    <meta name="generator" content=
    "HTML Tidy for Windows (vers 1st August 2002), see www.w3.org">
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <link rel="stylesheet" type="text/css" href="../../../../boost.css">

    <title>Boost.Python - CallPolicies Concept</title>

Boost.Python

CallPolicies Concept

Introduction

CallPolicies Composition

Concept Requirements

CallPolicies Concept

Introduction

Models of the CallPolicies concept are used to specialize the behavior
    of Python callable objects generated by Boost.Python to wrapped C++
    objects like function and member function pointers, providing three
    behaviors:

precall - Python argument tuple management before the
      wrapped object is invoked

result_converter - C++ return value handling

postcall - Python argument tuple and result management
      after the wrapped object is invoked

extract_return_type - metafunction for extracting the return type from a given signature type sequence

CallPolicies Composition

    In order to allow the use of multiple models of CallPolicies in the same
    callable object, Boost.Python's CallPolicies class templates provide a
    chaining interface which allows them to be recursively composed. This
    interface takes the form of an optional template parameter,
    Base which defaults to default_call_policies.
    By convention, the precall function of the Base
    is invoked after the precall function supplied by the
    outer template, and the postcall function of the
    Base is invoked before the postcall
    function of the outer template. If a result_converter is
    supplied by the outer template, it replaces any
    result_converter supplied by the Base. For an
    example, see return_internal_reference.

Concept Requirements

CallPolicies Concept

In the table below, x denotes an object whose type
    P is a model of CallPolicies, a
    denotes a PyObject* pointing to a Python argument tuple
    object, and r denotes a PyObject*
    referring to a "preliminary" result object.

        Expression

        Type

        Result/Semantics

        x.precall(a)

        convertible to bool

        returns false and PyErr_Occurred() != 0
        upon failure, true otherwise.

        P::result_converter

        A model of ResultConverterGenerator.

        An MPL unary Metafunction
        Class used produce the "preliminary" result object.

        x.postcall(a, r)

        convertible to PyObject*

        0 0 and PyErr_Occurred() != 0
        upon failure. Must "conserve references" even in the event of an
        exception. In other words, if r is not returned, its
        reference count must be decremented; if another existing object is
        returned, its reference count must be incremented.

        P::extract_return_type

        A model of Metafunction.

        An MPL unary Metafunction used extract the return type from a given signature. By default it is derived from mpl::front.

    Models of CallPolicies are required to be CopyConstructible.

Revised

  13 November, 2002

© Copyright Dave Abrahams 2002.

Permission to copy, use, modify, sell and distribute this software is
    granted provided this copyright notice appears in all copies. This
    software is provided "as is" without express or implied warranty, and
    with no claim as to its suitability for any purpose.


text:
import * as React from 'react';

type DividerAlignType = 'center' | 'left' | 'right' | 'bottom' | 'top';

type DividerLayoutType = 'vertical' | 'horizontal';

type DividerBorderType = 'solid' | 'dashed' | 'dotted';

export interface DividerProps {
    align?: DividerAlignType;
    layout?: DividerLayoutType;
    type?: DividerBorderType;
    style?: object;
    className?: string;
    children?: React.ReactNode;
}

export declare class Divider extends React.Component<DividerProps, any> { }


text:
from requests import get
from datetime import datetime, timedelta
from nba_py.constants import League
import os

HAS_PANDAS = True
try:
    from pandas import DataFrame
except ImportError:
    HAS_PANDAS = False

HAS_REQUESTS_CACHE = True
CACHE_EXPIRE_MINUTES = int(os.getenv('NBA_PY_CACHE_EXPIRE_MINUTES', 10))
try:
    from requests_cache import install_cache
    install_cache(cache_name='nba_cache',
                  expire_after=timedelta(minutes=CACHE_EXPIRE_MINUTES))
except ImportError:
    HAS_REQUESTS_CACHE = False

# Constants
TODAY = datetime.today()
BASE_URL = 'http://stats.nba.com/stats/{endpoint}'
HEADERS = {'user-agent': ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) '
                          'AppleWebKit/537.36 (KHTML, like Gecko) '
                          'Chrome/45.0.2454.101 Safari/537.36'),
          }

def _api_scrape(json_inp, ndx):
    """
    Internal method to streamline the getting of data from the json

    Args:
        json_inp (json): json input from our caller
        ndx (int): index where the data is located in the api

    Returns:
        If pandas is present:
            DataFrame (pandas.DataFrame): data set from ndx within the
            API's json
        else:
            A dictionary of both headers and values from the page
    """

    try:
        headers = json_inp['resultSets'][ndx]['headers']
        values = json_inp['resultSets'][ndx]['rowSet']
    except KeyError:
        # This is so ugly but this is what you get when your data comes out
        # in not a standard format
        try:
            headers = json_inp['resultSet'][ndx]['headers']
            values = json_inp['resultSet'][ndx]['rowSet']
        except KeyError:
            # Added for results that only include one set (ex. LeagueLeaders)
            headers = json_inp['resultSet']['headers']
            values = json_inp['resultSet']['rowSet']
    if HAS_PANDAS:
        return DataFrame(values, columns=headers)
    else:
        # Taken from www.github.com/bradleyfay/py-goldsberry
        return [dict(zip(headers, value)) for value in values]

def _get_json(endpoint, params, referer='scores'):
    """
    Internal method to streamline our requests / json getting

    Args:
        endpoint (str): endpoint to be called from the API
        params (dict): parameters to be passed to the API

    Raises:
        HTTPError: if requests hits a status code != 200

    Returns:
        json (json): json object for selected API call
    """
    h = dict(HEADERS)
    h['referer'] = 'http://stats.nba.com/{ref}/'.format(ref=referer)
    _get = get(BASE_URL.format(endpoint=endpoint), params=params,
               headers=h)
    # print _get.url
    _get.raise_for_status()
    return _get.json()

class Scoreboard:
    """ A scoreboard for all games for a given day
    Displays current games plus info for a given day

    Args:
        :month: Specified month (1-12)
        :day: Specified day (1-31)
        :year: Specified year (YYYY)
        :league_id: ID for the league to look in (Default is 00)
        :offset: Day offset from which to operate

    Attributes:
        :json: Contains the full json dump to play around with
    """
    _endpoint = 'scoreboard'

    def __init__(self,
                 month=TODAY.month,
                 day=TODAY.day,
                 year=TODAY.year,
                 league_id=League.NBA,
                 offset=0):
        self._game_date = '{month:02d}/{day:02d}/{year}'.format(month=month,
                                                                day=day,
                                                                year=year)
        self.json = _get_json(endpoint=self._endpoint,
                              params={'LeagueID': league_id,
                                      'GameDate': self._game_date,
                                      'DayOffset': offset})

    def game_header(self):
        return _api_scrape(self.json, 0)

    def line_score(self):
        return _api_scrape(self.json, 1)

    def series_standings(self):
        return _api_scrape(self.json, 2)

    def last_meeting(self):
        return _api_scrape(self.json, 3)

    def east_conf_standings_by_day(self):
        return _api_scrape(self.json, 4)

    def west_conf_standings_by_day(self):
        return _api_scrape(self.json, 5)

    def available(self):
        return _api_scrape(self.json, 6)


text:
hello_in() {
  case $1 in
  english) echo Hello;;
  italian) echo Ciao;;
  *) echo unsupported $1 >&2; return 1;;
  esac
  return 0
}

testcase_translate_to_english() {
  subject hello_in english
  assert_equal 0 $status
  assert_match 'Hello' "$stdout"
}

testcase_translate_to_unsupported_language() {
  subject hello_in bash
  assert_equal 1 $status
  assert_match 'bash' "$stderr"
}


text:
package org.cloudbyexample.dc.service.docker;

import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageFindRequest;
import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageFindResponse;
import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageRequest;
import org.cloudbyexample.dc.schema.beans.docker.image.DockerImageResponse;
import org.springbyexample.schema.beans.response.Message;
import org.springbyexample.schema.beans.response.MessageType;
import org.springbyexample.service.AbstractService;
import org.springbyexample.service.util.MessageHelper;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

/**
 * Image service implementation.
 *
 * @author David Winterfeldt
 */
@Service
public class DockerImageServiceImpl extends AbstractService
        implements DockerImageService {

    private static final String IMAGE_BUILD_MSG = "image.build.msg";

    private final AmqpTemplate template;
    private final String routingKey;

    @Autowired
    public DockerImageServiceImpl(AmqpTemplate template,
            @Value("${agent.queue.name}") String routingKey,
            MessageHelper messageHelper) {
        super(messageHelper);

        this.template = template;
        this.routingKey = routingKey;
    }

    @Override
    public DockerImageFindResponse find() {
        DockerImageFindRequest request = new DockerImageFindRequest();

        DockerImageFindResponse response = (DockerImageFindResponse) template.convertSendAndReceive(routingKey, request);

        return response;
    }

    @Override
    public DockerImageResponse build(DockerImageRequest request) {
        return processImageRequest(request);
    }

    /**
     * Send request to agent and get response.
     */
    private DockerImageResponse processImageRequest(DockerImageRequest request) {
        Assert.notNull(request);

        template.convertAndSend(routingKey, request);

        return new DockerImageResponse()
            .withMessageList(new Message().withMessageType(MessageType.INFO)
                                          .withMessage(getMessage(IMAGE_BUILD_MSG)))
            .withResults(request.getRequest());
    }

}


text:
from flask.ext.script import Manager, Server

from app import create_app
from app.mod_user import manager as user_manager
from app.mod_dan import manager as dan_manager
from app.mod_proposal import manager as proposal_manager
from app.mod_collection import manager as collection_manager
from app.mod_event import manager as event_manager
from app.mod_discussion import manager as discussion_manager
from app.mod_school import manager as school_manager

# create the manager so decorators work
manager = Manager(create_app())
manager.add_command("runserver", Server(host='0.0.0.0'))
manager.add_command("user", user_manager)
manager.add_command("dan", dan_manager)
manager.add_command("proposal", proposal_manager)
manager.add_command("collection", collection_manager)
manager.add_command("event", event_manager)
manager.add_command("discussion", discussion_manager)
manager.add_command("school", school_manager)

@manager.command
def fake_data():
	from app import db
	from app.mod_user import create_admin, fake_users
	from app.mod_proposal import fake_proposals
	from app.mod_school import create as create_school
	from app.mod_event import fake_places, fake_events
	from app.mod_discussion import fake_discussions

	print('Dropping all data in database')
	db.connection.drop_database(db.app.config['MONGODB_SETTINGS']['db'])

	print('\nCreating default admin user')
	create_admin()

	print('\nCreating locations')
	create_school()

	print('\nCreating users')
	fake_users(25)

	print('\nCreating proposals')
	fake_proposals(40)

	print('\nCreating places')
	fake_places()

	print('\nCreating events')
	fake_events()

	print('\nCreating discussions')
	fake_discussions(30)

if __name__ == "__main__":
	manager.run()


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<title>QUnit Test Suite</title>
	<link rel="stylesheet" href="../../qunit/qunit.css" type="text/css" media="screen">

QUnit Test Suite

test markup


text:
package org.bondlib;

import org.junit.Test;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import static org.junit.Assert.fail;

public class FastBinaryReaderTest {

    // See FastBinaryProtocolTest for more tests (on both reader and writer)

    @Test(expected = IllegalArgumentException.class)
    public void testConstructorWithZeroProtocolVersion() {
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
        new FastBinaryReader(bais, 0);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructorWithInvalidProtocolVersion() {
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
        new FastBinaryReader(bais, 2);
    }

    @Test(expected = IllegalArgumentException.class)
    public void testConstructorWithNullInputStream() {
        ByteArrayInputStream bais = null;
        new FastBinaryReader(bais, 1);
    }

    @Test
    public void testSkipWithInvalidDataType() {
        ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
        FastBinaryReader reader = new FastBinaryReader(bais, 1);
        BondDataType dataType = BondDataType.BT_UNAVAILABLE;
        try {
            reader.skip(dataType);
        } catch (InvalidBondDataException e) {
            // success
        } catch (IOException e) {
            fail("Other IOException can't be thrown here: " + e);
        }
    }
}


text:
 - Full support of 0.9.26 API
```lua
 -- Additional OO style for TCCState
 tcc.delete(state)
 -- or
 state:delete()
```
```lua
 -- Constants can be used in two ways
 state:set_output_type(tcc.const.output_dll)
 -- or
 state:set_output_type('output_dll')
```

# Example code
```lua
  local tcc = require 'tcc' ('libtcc')

  local state = tcc.new()

  state:set_output_type('output_memory')

  state:compile_string [[
    int summ(int a, int b)
    {
      return a + b;
    }
  ]]

  state:relocate('relocate_auto')

  local summ = state:get_symbol('summ', 'int(*)(int,int)')

  print('5 + 7 = ' .. summ(5,7))

  state:delete()

```

# Differences from the C API
Binding is so close to the original API as possible, but some things still differ.
 1. Names lost 'tcc_' prefix as not needed.
 2. 'tcc.add_symbol' and 'tcc.get_symbol' have optional argument for in-place cast.
 3. 'tcc.run' accept table instead of argc-argv pair.


text:
#include "tensorflow/compiler/xla/service/reduce_scatter_combiner.h"

#include <algorithm>
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/all_reduce_key.h"
#include "tensorflow/compiler/xla/service/collective_combiner_utils.h"
#include "tensorflow/compiler/xla/service/collective_ops_utils.h"
#include "tensorflow/compiler/xla/service/hlo_casting_utils.h"
#include "tensorflow/compiler/xla/service/hlo_domain_map.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/service/hlo_instructions.h"
#include "tensorflow/compiler/xla/service/hlo_opcode.h"
#include "tensorflow/compiler/xla/service/hlo_query.h"
#include "tensorflow/compiler/xla/service/hlo_reachability.h"
#include "tensorflow/compiler/xla/service/shape_inference.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/status_macros.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
#include "tensorflow/core/lib/core/errors.h"

namespace xla {
namespace {

using ReduceScatterKey =
    std::tuple<AllReduceKey, /*scatter_dimension*/ int64_t>;

// Combines the elements of to_combine into a single ReduceScatter op. All
// entries in to_combine must be ReduceScatter ops with exactly one operand
// and the same reduction operation.
Status CombineReduceScatters(absl::Span<HloInstruction* const> to_combine) {
  if (to_combine.size() < 2) {
    return Status::OK();
  }
  VLOG(1) << "Combined " << to_combine.size() << " reduce-scatter ops";

  HloComputation& computation = *to_combine.back()->parent();
  HloComputation* reduction = to_combine[0]->to_apply();
  absl::optional<ReductionKind> first_reduction_kind =
      MatchReductionComputation(reduction);
  TF_RET_CHECK(first_reduction_kind);

  // Create a single bigger ReduceScatter of the operands of the smaller
  // ReduceScatters.
  std::vector<HloInstruction*> operands;
  std::vector<const Shape*> output_shapes;
  VLOG(1) << "Combining set";
  for (HloInstruction* hlo : to_combine) {
    VLOG(1) << "Set element: " << hlo->ToString();
    TF_RET_CHECK(hlo->opcode() == HloOpcode::kReduceScatter);
    TF_RET_CHECK(hlo->operands().size() == 1);
    absl::optional<ReductionKind> reduction_kind =
        MatchReductionComputation(hlo->to_apply());
    TF_RET_CHECK(reduction_kind);
    TF_RET_CHECK(*reduction_kind == *first_reduction_kind);
    TF_RET_CHECK(hlo->shape().IsArray());
    operands.push_back(hlo->operands()[0]);
    output_shapes.push_back(&hlo->shape());
  }

  const auto* rs = Cast<HloReduceScatterInstruction>(to_combine.front());

  HloInstruction* combined;
  // AllReduce ops with more than one operand produce a tuple.
  TF_RET_CHECK(operands.size() >= 2);
  combined = computation.AddInstruction(HloInstruction::CreateReduceScatter(
      ShapeUtil::MakeTupleShapeWithPtrs(output_shapes), operands, reduction,
      to_combine.front()->replica_groups(),
      /*constrain_layout=*/false, to_combine.front()->channel_id(),
      rs->use_global_device_ids(), rs->scatter_dimension()));

  // We have to propagate the sharding manually because Domain instructions are
  // not guaranteed to preserve it for side effecting instructions.
  if (to_combine.front()->has_sharding()) {
    combined->set_sharding(to_combine.front()->sharding());
  }
  VLOG(1) << "Replacing with : " << combined->ToString();

  // Replace all the smaller ReduceScatters with elements of the tuple output
  // of the single bigger ReduceScatter.
  for (int64_t i = 0; i < to_combine.size(); ++i) {
    auto replace_with = HloInstruction::CreateGetTupleElement(
        to_combine[i]->shape(), combined, i);
    TF_RETURN_IF_ERROR(computation.ReplaceWithNewInstruction(
        to_combine[i], std::move(replace_with)));
  }
  return Status::OK();
}
}  // namespace

ReduceScatterCombiner::ReduceScatterCombiner(int64_t combine_threshold_in_bytes,
                                             int64_t combine_threshold_count)
    : combine_threshold_in_bytes_(combine_threshold_in_bytes),
      combine_threshold_count_(combine_threshold_count) {}

StatusOr<bool> ReduceScatterCombiner::Run(HloModule* module) {
  VLOG(1) << "Running ReduceScatterCombiner with threshold of "
          << combine_threshold_in_bytes_ << " bytes";

  if (combine_threshold_in_bytes_ <= 0 || combine_threshold_count_ <= 0) {
    VLOG(1) << "Skip ReduceScatterCombiner because the threshold is zero";
    return false;
  }

  if (hlo_query::ContainsLayoutConstrainedCollective(
          *module, HloOpcode::kReduceScatter)) {
    VLOG(1) << "Skip ReduceScatterCombiner because the module contains "
               "reduce-scatter "
               "with constrained layouts";
    return false;
  }

  bool changed = false;
  for (HloComputation* computation : module->MakeNonfusionComputations()) {
    TF_ASSIGN_OR_RETURN(auto domain_map, HloDomainMap::Create(computation, ""));

    auto key_fn = [&domain_map](const HloInstruction* instruction)
        -> absl::optional<ReduceScatterKey> {
      auto* rs = DynCast<HloReduceScatterInstruction>(instruction);
      absl::optional<AllReduceKey> key =
          GetAllReduceKey(instruction, domain_map.get());

      if (!rs || !key) {
        return absl::nullopt;
      }
      return ReduceScatterKey{std::move(*key), rs->scatter_dimension()};
    };

    TF_ASSIGN_OR_RETURN(
        bool computation_changed,
        CombineInstructionsByKey<ReduceScatterKey>(
            computation, key_fn, &CombineReduceScatters,
            combine_threshold_in_bytes_, combine_threshold_count_));
    changed |= computation_changed;
  }

  return changed;
}

}  // namespace xla


text:
require_relative "shared_examples/requires_cask_token"
require_relative "shared_examples/invalid_option"

describe Cask::Cmd::Cat, :cask do
  it_behaves_like "a command that requires a Cask token"
  it_behaves_like "a command that handles invalid options"

  describe "given a basic Cask" do
    let(:basic_cask_content) {
      <<~'RUBY'
        cask "basic-cask" do
          version "1.2.3"
          sha256 "8c62a2b791cf5f0da6066a0a4b6e85f62949cd60975da062df44adf887f4370b"

          url "https://brew.sh/TestCask-#{version}.dmg"
          name "Basic Cask"
          desc "Cask for testing basic functionality"
          homepage "https://brew.sh/"

          app "TestCask.app"
        end
      RUBY
    }
    let(:caffeine_content) {
      <<~'RUBY'
        cask "local-caffeine" do
          version "1.2.3"
          sha256 "67cdb8a02803ef37fdbf7e0be205863172e41a561ca446cd84f0d7ab35a99d94"

          url "file://#{TEST_FIXTURE_DIR}/cask/caffeine.zip"
          homepage "https://brew.sh/"

          app "Caffeine.app"
        end
      RUBY
    }

    it "displays the Cask file content about the specified Cask" do
      expect {
        described_class.run("basic-cask")
      }.to output(basic_cask_content).to_stdout
    end

    it "can display multiple Casks" do
      expect {
        described_class.run("basic-cask", "local-caffeine")
      }.to output(basic_cask_content + caffeine_content).to_stdout
    end
  end

  it "raises an exception when the Cask does not exist" do
    expect { described_class.run("notacask") }
      .to raise_error(Cask::CaskUnavailableError, /is unavailable/)
  end
end


text:
<?php

require_once(TOOLS."cbSQLRetrieveData.php");
require_once(TOOLS."cbSQLConnectVar.php");
require_once(TOOLS."cbSQLConnectConfig.php");

class User{

   protected static $table_name = "user";
   protected static $db_fields = array('id','username','email','password','first_name','last_name','rights','last_loggedin','status','valid', 'other_comments', 'gender', 'company_position');
   // Attributes in user table

   public $id;
   public $username;
   public $email;
   public $password;
   public $first_name;
   public $last_name;
   public $rights;
   public $last_loggedin;
   public $status;
   public $valid;
   public $other_comments;
   public $gender;
   public $company_position;

   // This funciton tests the connection to the database.
   public function test()
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
            // $data = $this->fetch_assoc->QuerySingle("SELECT * FROM `user`");
         $data = $database->QuerySingle("SELECT * FROM `user`");

            // $data = $this->fetch_lazy->QuerySingle("SELECT * FROM `user`");
         return $data;
      }
      else
         return "There wasn't a connection...";
   }

   public function full_name()
   {
      if(isset($this->first_name) && isset($this->last_name))
      {
         return $this->first_name . " " . $this->last_name;
      }
      else
      {
         return "";
      }
   }

   public function isAdmin() {
      if($this->rights === 'super' || $this->rights === 'admin') {
         return true;
      }
   }

   public function gender()
   {
      if (isset($this->gender))
      {
         return $this->gender;
      }
      else
      {
         $database = cbSQLConnect::connect('object');
         if (isset($database))
         {
            $name = self::$table_name;
            $tempId = $this->id;
            $data = $database->Query("SELECT `gender` FROM :table WHERE `username` = :value LIMIT 1;",
             array(array(':value' => $tempId, ':table' => $name)));
            echo($data);
            $this->gender = $data['gender'];
         }

         return $this->gender;
      }
   }

   public static function authenticate($username="",$password="")
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $sql = "SELECT *  ";
         $sql .= "FROM  `user`  ";
         $sql .= "WHERE (";
         $sql .= "`username` =  :username ";       //
         $sql .= "OR  `email` =  :username";       //
         $sql .= ") ";                             //
         $sql .= "AND  `password` =  :password ";  //
         $sql .= "AND  `valid` =  '1';";
         $params = array(':password' => $password, ':username' => $username);
         array_unshift($params, '');
         unset($params[0]);
         $results_array = $database->QueryForObject($sql, $params);
         $user = !empty($results_array) ? array_shift($results_array) : false;
         if ($user) {
            $user = recast('User', $user);
            $user->displayableName = $user->displayName();
         }
         return $user;
      }
   }

   public static function getByID($id = '') {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $name = self::$table_name;
         $user = $database->getObjectById($name, $id);
         if ($user) {
            $user = recast('User', $user);
            $user->displayableName = $user->displayName();
         }
         unset($user->password);
         return $user;
      }
   }

   public static function current_user()
   {
      $session = mySession::getInstance();
      $user_id = $session->getVar('user_id');

      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $name = self::$table_name;
         $user = $database->getObjectById($name, $user_id);
         if ($user) {
            $user = recast('User', $user);
            $user->displayableName = $user->displayName();
         }
         unset($user->password);
         return $user;
      }
   }

   public static function getAllUsers()
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $users = $database->QuerySingle("SELECT * FROM `user` ORDER BY `id`");
         if ($users)
         {
            $data = array();
            foreach ($users as $user)
            {
               $data[] = recast("User", $user);
            }
            return $data;
         }
         else
         {
            return false;
         }
      }
   }

   public static function getUserByCred($email = null, $username = null)
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $sql = "SELECT *  ";
         $sql .= "FROM  `user`  ";
         $sql .= "WHERE (";
         $sql .= "`username` =  :username ";       //
         $sql .= "OR  `email` =  :email";       //
         $sql .= ") ";                             //
         $sql .= "AND  `valid` =  '1';";
         $params = array(':username' => $username, ':email' => $email);
         array_unshift($params, '');
         unset($params[0]);
         $results_array = $database->QueryForObject($sql, $params);
         return !empty($results_array) ? array_shift($results_array) : false;
      }
   }
   public static function getByUsername($username = null)
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $sql = "SELECT *  ";
         $sql .= "FROM  `user`  ";
         $sql .= "WHERE ";
         $sql .= "`username` =  :username ";       //
         $sql .= "AND  `valid` =  '1';";
         $params = array(':username' => $username);
         array_unshift($params, '');
         unset($params[0]);
         $results_array = $database->QueryForObject($sql, $params);
         return !empty($results_array) ? recast('User', array_shift($results_array)) : false;
      }
   }

public static function getUserById($user_id = null)
{
   $database = cbSQLConnect::connect('object');
   if (isset($database) && $user_id)
   {
      $name = self::$table_name;
      return $database->getObjectById($name, $user_id);
   }
}

public static function get_all_something($thing)
{
   $database = cbSQLConnect::connect('object');
   if (isset($database))
   {
      $users = $database->QuerySingle("SELECT $thing FROM `user` WHERE `valid`='1' AND `status`='current' ORDER BY `id`");

      $data = array();
      foreach($users as $user)
      {
         $data[] = strtolower($user->{$thing});
      }
      return $data;
   }
}

public function displayName()
{
   $name = $this->first_name." ";
   $name .= $this->last_name;
   return $name;
}

public function save()
{
      // return $this->id;
   return isset($this->id) ? $this->update() : $this->create();
}

   // create the object if it doesn't already exits.
   // create the object if it doesn't already exits.
protected function create()
{
   $database = cbSQLConnect::connect('object');
   if (isset($database))
   {
      $fields = self::$db_fields;
      $data = array();
      foreach($fields as $key)
      {
         if ($this->{$key})
         {
            $data[$key] = $this->{$key};
         }
         else
            $data[$key] = NULL;

      }
         // array_unshift($params, '');
         // unset($params[0]);
         // return $data;
         $insert = $database->SQLInsert($data, "user"); // return true if sucess or false
         if ($insert)
         {
            return $insert;
         }
         else
         {
            return "Insert didn't compute";
         }
      }
   }

   // update the object if it does already exist.
   protected function update()
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         $fields = self::$db_fields;
         foreach($fields as $key)
         {
            $flag = $database->SQLUpdate("user", $key, $this->{$key}, "id", $this->id);
            if ($flag == "fail")
            {
               break;
            }
         }
         if ($flag == "fail")
         {
            return false;
         }
         else
            return true;
      }
   }

   // Delete the object from the table.
   public function delete()
   {
      $database = cbSQLConnect::connect('object');
      if (isset($database))
      {
         return ($database->SQLDelete(self::$table_name, 'id', $this->id));
      }
   }

   // reset password
   public function resetPassword()
   {
      $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+';
      $random_string_length = 10;
      $string = '';
      $max = strlen($characters) - 1;
      for ($i = 0; $i < $random_string_length; $i++) {
         $string .= $characters[mt_rand(0, $max)];
      }
      $from = "noreply@familyhistorydatabase.org";
      $headers  = 'MIME-Version: 1.0' . "\r\n";
      $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
      $headers .= "From: " . $from;
      $subject = 'FHD: Password Reset';
      $message = '

      The password has been reset for '.$this->displayName().' The new password is:

      <bold>'.$string.'</bold>

      Please log in using this password and go to your profile page to change it to your own password.
      ';
      $this->password = sha1($string);
      if ($this->save()) {
         return mail($this->email,$subject,$message,$headers);
      }
      return false;
   }
}

?>


text:
package nodes.cfg;

public class BreakStmtNode extends CFGNode {
    public BreakStmtNode(String name) {
        super(name);
    }

    @Override
    public String getNodeType() {
        return "BreakStmt";
    }
}


text:
<?php

namespace Illuminate\Routing;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Illuminate\Pipeline\Pipeline;
use Illuminate\Container\Container;

class ControllerDispatcher
{
    use RouteDependencyResolverTrait;

    /**
     * The router instance.
     *
     * @var \Illuminate\Routing\Router
     */
    protected $router;

    /**
     * The IoC container instance.
     *
     * @var \Illuminate\Container\Container
     */
    protected $container;

    /**
     * Create a new controller dispatcher instance.
     *
     * @param  \Illuminate\Routing\Router  $router
     * @param  \Illuminate\Container\Container  $container
     * @return void
     */
    public function __construct(Router $router,
                                Container $container = null)
    {
        $this->router = $router;
        $this->container = $container;
    }

    /**
     * Dispatch a request to a given controller and method.
     *
     * @param  \Illuminate\Routing\Route  $route
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $controller
     * @param  string  $method
     * @return mixed
     */
    public function dispatch(Route $route, Request $request, $controller, $method)
    {
        $instance = $this->makeController($controller);

        return $this->callWithinStack($instance, $route, $request, $method);
    }

    /**
     * Make a controller instance via the IoC container.
     *
     * @param  string  $controller
     * @return mixed
     */
    protected function makeController($controller)
    {
        Controller::setRouter($this->router);

        return $this->container->make($controller);
    }

    /**
     * Call the given controller instance method.
     *
     * @param  \Illuminate\Routing\Controller  $instance
     * @param  \Illuminate\Routing\Route  $route
     * @param  \Illuminate\Http\Request  $request
     * @param  string  $method
     * @return mixed
     */
    protected function callWithinStack($instance, $route, $request, $method)
    {
        $middleware = $this->getMiddleware($instance, $method);

        $shouldSkipMiddleware = $this->container->bound('middleware.disable') &&
                                $this->container->make('middleware.disable') === true;

        // Here we will make a stack onion instance to execute this request in, which gives
        // us the ability to define middlewares on controllers.
        return (new Pipeline($this->container))
                    ->send($request)
                    ->through($shouldSkipMiddleware ? [] : $middleware)
                    ->then(function ($request) use ($instance, $route, $method) {
                        return $this->router->prepareResponse(
                            $request, $this->call($instance, $route, $method)
                        );
                    });
    }

    /**
     * Get the middleware for the controller instance.
     *
     * @param  \Illuminate\Routing\Controller  $instance
     * @param  string  $method
     * @return array
     */
    protected function getMiddleware($instance, $method)
    {
        $results = [];

        foreach ($instance->getMiddleware() as $name => $options) {
            if (!$this->methodExcludedByOptions($method, $options)) {
                $results[] = $this->router->resolveMiddlewareClassName($name);
            }
        }

        return $results;
    }

    /**
     * Determine if the given options exclude a particular method.
     *
     * @param  string  $method
     * @param  array  $options
     * @return bool
     */
    public function methodExcludedByOptions($method, array $options)
    {
        return (!empty($options['only']) && !in_array($method, (array) $options['only'])) ||
            (!empty($options['except']) && in_array($method, (array) $options['except']));
    }

    /**
     * Call the given controller instance method.
     *
     * @param  \Illuminate\Routing\Controller  $instance
     * @param  \Illuminate\Routing\Route  $route
     * @param  string  $method
     * @return mixed
     */
    protected function call($instance, $route, $method)
    {
        $parameters = $this->resolveClassMethodDependencies(
            $route->parametersWithoutNulls(), $instance, $method
        );

        return $instance->callAction($method, $parameters);
    }
}


text:
require 'rubypress'
require 'mime/types'

module WordpressUtility
  class Post
    attr_reader :errors

    def initialize(params)
      @errors = []
      @uploaded_images = []
      @wordpress_client = Rubypress::Client.new( host: params[:host],
                                                username: params[:user],
                                                password: params[:password],
                                                path: params[:path] )
    end

    def publish(text, images)
      post_id = create_post({ title: get_title_from_content(text), content: text })

      upload_images(images)

      edit_post({ id: post_id.to_i,
                  content: text,
                  images: @uploaded_images.map { |image| "" }
                })

      draft_post_link(post_id.to_i)
    end

    def create_post(params)
      @wordpress_client.newPost( content: {
                                           post_status: 'draft',
                                           post_date: Time.now,
                                           post_content: params[:content].squish,
                                           post_title: params[:title]
                                          }
                               )
    end

    def edit_post(params)
      @wordpress_client.editPost( post_id: params[:id],
                                  content: {
                                            post_content: "#{params[:content]} #{params[:images].join("\n")}"
                                           }
                                )
    end

    def upload_image(filename)
      image = @wordpress_client.uploadFile(data: { name: File.basename(filename),
                                            type: MIME::Types.type_for(filename).first.to_s,
                                            bits: XMLRPC::Base64.new(File.open(filename).read)
                                          }
                                    )
      @uploaded_images << image['url']
    end

    def draft_post_link(id)
      "Click  here  to update the Post" if id.present?
    end

    private
      def upload_images(images)
        images.each do |image|
          begin
            upload_image(image)
          rescue => e
            @errors << 'Unable to upload few images' unless @errors.include?('Unable to upload few images')
          end
        end
      end

      def get_title_from_content(content)
        title = content.split(/\n/).reject{ |t| t == "" }.first
        title.length > 60 ? title.squish.split(' ')[0, 6].join(' ') : title
      end
  end
end


text:
layout: post
date: 2015-12-20
title: "Pronovias ALDABRA 2015 Sleeveless Cathedral Train Aline/Princess"
category: Pronovias
tags: [Pronovias,Aline/Princess ,Bateau,Cathedral Train,Sleeveless,2015,Satin]
---
### Pronovias ALDABRA
Just **$309.99**
### 2015  Sleeveless Cathedral Train Aline/Princess

BRANDS	Pronovias

Silhouette	Aline/Princess

Neckline	Bateau

Hemline/Train	Cathedral Train

Sleeve	Sleeveless

Years	2015

Fabric	Satin

Buy it: [https://www.readybrides.com/en/pronovias/4268-pronovias-aldabra.html](https://www.readybrides.com/en/pronovias/4268-pronovias-aldabra.html)


text: DELETE FROM `waffle_flag` where `name` = 'register_survey';


text:
/**
 * Local storage listener
 * - Add/remove listeners using exported methods rather than appending multiple listeners to window
 */

type Listener = (event: StorageEvent) => void;
const listeners: Listener[] = [];

window.addEventListener("storage", (event) => {
  if (event.storageArea != localStorage) return;
  for (let i = 0; i < listeners.length; i++) {
    listeners[i](event);
  }
});

export function add(listener: Listener) {
  listeners.push(listener);
  return () => {
    remove(listener);
  };
}

export function remove(listener: Listener) {
  listeners.splice(listeners.indexOf(listener), 1);
}


text:
var chai = require("chai"),
	expect = chai.expect;
	chai.should();

// In this instance, we're not testing the instrumentor, so we want the
// un-instrumented version.
var instrument = require("../lib/instrumentor");

path = global.__steamshovel ? "../lib-cov" : "../lib";

// A quick function to add some dummy results to the map.
function addSomeResults(map, instrumentcount, filterise, depth) {
	var iteration = 0;

	filterise = filterise || function() { return true; };
	depth = depth || 1;

	Object.keys(map).forEach(function(key) {
		Object.keys(map[key].instruments)
			.map(function(instrument) {
				return map[key].instruments[instrument];
			})
			.filter(filterise)
			.slice(0,instrumentcount).forEach(function(instrument) {
				iteration ++;
				instrument.results.push({
					"depth": depth,
					"time": Date.now(),
					"timeOffset": 1,
					"memoryUsage": process.memoryUsage(),
					"invocation": iteration,
					"milestone": "Hello!",
					"value": Math.random()
				});
			});
	});
}

function clearResults(map) {
	Object.keys(map).forEach(function(key) {
		Object.keys(map[key].instruments)
			.map(function(instrument) {
				return map[key].instruments[instrument];
			})
			.forEach(function(instrument) {
				instrument.results.length = 0;
			});
	});
}

describe("Statistics", function() {
	var stats	= require(path + "/stats"),
		util	= require(path + "/stats/utils");

	// Fixture for testing stats
	var fixtureSource = "if (1) { console.log(1 ? 'hello world!' : a); }\n";
		fixtureSource+= "console.log(a = b + 1);\n"
		fixtureSource+= "function console() { return function() {}; }";

	// Generating a very simple instrument map to test statistics against
	var testFixture = instrument(fixtureSource, "dummy.js");
		testFixture = testFixture.split(/\n+/)[4];
		testFixture = testFixture.substr(57).replace(/\;$/,"");
		testFixture = JSON.parse(testFixture);

	var instrumentMap = {};
		instrumentMap[testFixture.filetag] = testFixture;

	beforeEach(function() {
		clearResults(instrumentMap);
	});

	it("should export an object with methods", function() {
		stats.should.be.an("object");
		stats.basic.should.be.a("function");
	});

	it("should calculate all basic statistics when called generally",
		function() {

		var data = stats.basic(instrumentMap);

		data.lines.should.be.an("object");
		data.conditions.should.be.an("object");
		data.expressions.should.be.an("object");
		data.functions.should.be.an("object");
	});

	it("should be able to retrieve instruments from the map", function() {
		var instruments = util.getInstruments(instrumentMap);
		expect(instruments.length).to.equal(17);
	});

	it("should retrieve instruments from the map filtered by key", function() {
		var demoKey = "ic6c44d10e8569f579e7a40c3a91caad0";
		expect(util.getInstruments(instrumentMap, "abc").length).to.equal(0);
		expect(util.getInstruments(instrumentMap, demoKey).length).to.equal(17);
	});

	it("should be able to get the shallowest map call depth", function() {
		addSomeResults(instrumentMap, 5, util.withkey("line"), 10);

		expect(util.shallowestCall(instrumentMap)).to.equal(10);

		addSomeResults(instrumentMap, 10, null, 50);

		expect(util.shallowestCall(instrumentMap)).to.equal(10);

		addSomeResults(instrumentMap, 10, null, 3);

		expect(util.shallowestCall(instrumentMap)).to.equal(3);
	});

	it("should be able to get the computed value of an instrument", function() {
		addSomeResults(instrumentMap, 3, util.withkey("line"), 10);
		addSomeResults(instrumentMap, 10, null, 50);

		var instruments = util.getInstruments(instrumentMap);
		var getValue = util.calculateValue(instrumentMap);

		expect(getValue(instruments[0])).to.be.greaterThan(0);
		expect(getValue(instruments[0])).to.be.lessThan(0.01);
		expect(getValue(instruments[0])).to.be.greaterThan(0.000001);

		clearResults(instrumentMap);
		addSomeResults(instrumentMap, 10, null, 2);
		expect(getValue(instruments[0])).to.equal(1);
	});

	it("should calculate lines from an example map", function() {
		addSomeResults(instrumentMap, 3, util.withkey("line"));
		var data = stats.basic.lines(instrumentMap);

		// First with the very even data...
		expect(data.total).to.equal(5);
		expect(data.covered).to.equal(3);
		expect(data.percentage).to.equal(3/5 * 100);

		// Now with some messy data...
		addSomeResults(instrumentMap, 5, util.withkey("line"), 10);
		data = stats.basic.lines(instrumentMap);

		expect(data.total).to.equal(5);
		expect(data.covered).to.equal(3.8192000000000004);
		expect(Math.floor(data.percentage * 100)/100)
			.to.equal(Math.floor(3.8192000000000004/5 * 10000) / 100);
	});

	it("should calculate conditions from an example map", function() {
		addSomeResults(instrumentMap, 3, util.isOfType([
											"IfStatement",
											"LogicalExpression",
											"ConditionalExpression",
										]));

		var data = stats.basic.conditions(instrumentMap);

		expect(data.total).to.equal(2);
		expect(data.covered).to.equal(0.75);
		expect(Math.floor(data.percentage * 100)/100)
			.to.equal(Math.floor(3/8 * 10000) / 100);

		addSomeResults(instrumentMap, 8, util.isOfType([
											"IfStatement",
											"LogicalExpression",
											"ConditionalExpression",
										]),
										10);

		data = stats.basic.conditions(instrumentMap);

		expect(data.total).to.equal(2);
		expect(data.covered).to.equal(1.2620000000000002);
		expect(Math.floor(data.percentage * 100)/100)
			.to.equal(Math.floor(5.048000000000001/8 * 10000) / 100);
	});

	it("should calculate expressions from an example map", function() {
		var data = stats.basic.expressions(instrumentMap);

		expect(data.total).to.equal(12);
		expect(data.covered).to.equal(0);
		expect(data.percentage).to.equal(0);

		function expression(instrument) {
			return !instrument.line;
		}

		addSomeResults(instrumentMap, 3, expression, 1);
		addSomeResults(instrumentMap, 10, expression, 7);

		data = stats.basic.expressions(instrumentMap);

		expect(data.total).to.equal(12);
		expect(data.covered).to.equal(8.6);
		expect(Math.floor(data.percentage * 100)/100)
			.to.equal(Math.floor(8.6/12 * 10000) / 100);
	});

	it("should calculate functions from an example map", function() {

		addSomeResults(instrumentMap, 1, util.isOfType([
											"FunctionDeclaration",
											"FunctionExpression"
										]),
										1);
		addSomeResults(instrumentMap, 2, util.isOfType([
											"FunctionDeclaration",
											"FunctionExpression"
										]),
										10);

		var data = stats.basic.functions(instrumentMap);

		expect(data.total).to.equal(2);
		expect(data.covered).to.equal(0.9397333333333333);
		expect(Math.floor(data.percentage * 100)/100)
			.to.equal(Math.floor(1.4096/3 * 10000) / 100);
	});

});


text:
/* The external format of the fixed header.  */

typedef struct nlm32_sparc_external_fixed_header
{

  /* The signature field identifies the file as an NLM.  It must contain
     the signature string, which depends upon the NLM target. */

  unsigned char signature[24];

  /* The version of the header.  At this time, the highest version number
     is 4. */

  unsigned char version[4];

  /* The name of the module, which must be a DOS name (1-8 characters followed
     by a period and a 1-3 character extension).  The first byte is the byte
     length of the name and the last byte is a null terminator byte.  This
     field is fixed length, and any unused bytes should be null bytes.  The
     value is set by the OUTPUT keyword to NLMLINK. */

  unsigned char moduleName[14];

  /* Padding to make it come out correct. */

  unsigned char pad1[2];

  /* The byte offset of the code image from the start of the file. */

  unsigned char codeImageOffset[4];

  /* The size of the code image, in bytes. */

  unsigned char codeImageSize[4];

  /* The byte offset of the data image from the start of the file. */

  unsigned char dataImageOffset[4];

  /* The size of the data image, in bytes. */

  unsigned char dataImageSize[4];

  /* The size of the uninitialized data region that the loader is to be
     allocated at load time.  Uninitialized data follows the initialized
     data in the NLM address space. */

  unsigned char uninitializedDataSize[4];

  /* The byte offset of the custom data from the start of the file.  The
     custom data is set by the CUSTOM keyword to NLMLINK.  It is possible
     for this to be EOF if there is no custom data. */

  unsigned char customDataOffset[4];

  /* The size of the custom data, in bytes. */

  unsigned char customDataSize[4];

  /* The byte offset of the module dependencies from the start of the file.
     The module dependencies are determined by the MODULE keyword in
     NLMLINK. */

  unsigned char moduleDependencyOffset[4];

  /* The number of module dependencies at the moduleDependencyOffset. */

  unsigned char numberOfModuleDependencies[4];

  /* The byte offset of the relocation fixup data from the start of the file */

  unsigned char relocationFixupOffset[4];

  unsigned char numberOfRelocationFixups[4];

  unsigned char externalReferencesOffset[4];

  unsigned char numberOfExternalReferences[4];

  unsigned char publicsOffset[4];

  unsigned char numberOfPublics[4];

  /* The byte offset of the internal debug info from the start of the file.
     It is possible for this to be EOF if there is no debug info. */

  unsigned char debugInfoOffset[4];

  unsigned char numberOfDebugRecords[4];

  unsigned char codeStartOffset[4];

  unsigned char exitProcedureOffset[4];

  unsigned char checkUnloadProcedureOffset[4];

  unsigned char moduleType[4];

  unsigned char flags[4];

} Nlm32_sparc_External_Fixed_Header;


text:
This is just enough info to get you up and running.

Much more info available via `npm help` once it's installed.

## IMPORTANT

**You need node v0.4 or higher to run this program.**

To install on older versions of node, do the following:

    git clone git://github.com/isaacs/npm.git ./npm
    cd npm
    git checkout origin/0.2
    make dev

## Simple Install

To install npm with one command, do this:

    curl http://npmjs.org/install.sh | sh

If that fails, try this:

    git clone http://github.com/isaacs/npm.git
    cd npm
    sudo make install

If you're sitting in the code folder reading this document in your
terminal, then you've already got the code.  Just do:

    sudo make install

and npm will install itself.

If you don't have make, and don't have curl or git, and ALL you have is
this code and node, you can do:

    sudo node ./cli.js install npm

## Permissions

**tl;dr**

* Use `sudo` for greater safety.
* To enforce this added safety, do `npm config set unsafe-perm false`,
  or add `--no-unsafe` to the command line.
* npm will downgrade permissions if it's root before running any build
  scripts that package authors specified.
* If you were fine before, you can safely ignore this change.

### More details...

As of version 0.3, it is recommended to run some npm commands as root.
This allows npm to change the user identifier to the `nobody` user prior
to running any package build or test commands.

If this user id switch fails (generally because you are not the root
user) then the command will fail.

If you would prefer to run npm as your own user, giving package scripts
the same rights that your user account enjoys, then you may do so by
setting the `unsafe-perm` config value to `true`:

    npm config set unsafe-perm true

or simply by setting the `--unsafe` flag to any individual command:

    npm test express --unsafe

Note that root/sudo access is only required when npm is doing the
following actions:

1. Writing files and folders to the root.
2. Running package lifecycle scripts (generally to either build or
   test).

If you run npm without root privileges, and it doesn't have to do either
of these things, then no error will occur.

npm will automatically attempt to escalate permissions (generally by
prompting for your password) if it attempts to *remove* a file and fails
with an EPERM or EACCES error.  No other permission escalation is
attempted.

This is a departure from npm's history, and comes at long last.

## More Fancy Installing

First, get the code.  Maybe use git for this.  That'd be cool.  Very fancy.

The default make target is `install`, which downloads the current stable
version of npm, and installs that for you.

If you want to install the exact code that you're looking at, the bleeding-edge
master branch, do this:

    sudo make dev

If you'd prefer to just symlink in the current code so you can hack
on it, you can do this:

    sudo make link

If you check out the Makefile, you'll see that these are just running npm commands
at the cli.js script directly.  You can also use npm without ever installing
it by using `node cli.js` instead of "npm".  Set up an alias if you want, that's
fine.  (You'll still need read permission to the root/binroot/manroot folders,
but at this point, you probably grok all that anyway.)

## Uninstalling

So sad to see you go.

    sudo npm uninstall npm

Or, if that fails,

    sudo make uninstall

## Using npm Programmatically

If you would like to use npm programmatically, you can do that as of
version 0.2.6.  It's not very well documented, but it IS rather simple.

    var npm = require("npm")
    npm.load(myConfigObject, function (er) {
      if (er) return handlError(er)
      npm.commands.install(["some", "args"], function (er, data) {
        if (er) return commandFailed(er)
        // command succeeded, and data might have some info
      })
      npm.on("log", function (message) { .... })
    })

See `./cli.js` for an example of pulling config values off of the
command line arguments.  You may also want to check out `npm help
config` to learn about all the options you can set there.

As more features are added for programmatic access to the npm library,
this section will likely be split out into its own documentation page.

## More Docs

Check out the [docs](http://github.com/isaacs/npm/blob/master/doc/),
especially the
[faq](http://github.com/isaacs/npm/blob/master/doc/faq.md#readme).

You can use the `npm help` command to read any of them.

If you're a developer, and you want to use npm to publish your program,
you should
[read this](http://github.com/isaacs/npm/blob/master/doc/developers.md#readme)