'use strict'

const fs = require('fs')
const path = require('path')
const chalk = require('chalk')
const DocTree = require('doc-tree')

const postcss = require('postcss')
const atImport = require('postcss-import')
const cssnext = require('postcss-cssnext')
const cssnano = require('cssnano')
const mustache = require('mustache')
const marked = require('marked')
const mkdirp = require('mkdirp')
const hjs = require('highlight.js')
const inflection = require('inflection')
const minifier = require('html-minifier')
const minify = minifier.minify

// Declarations
// ============

const pkg = require('../package.json')
const start = Date.now()
const year = new Date().getFullYear()
const CNAME = 'fortune.js.org'

const outputPath = path.join(__dirname, '../dist')
const assetPath = path.join(__dirname, 'assets')
const apiPath = path.join(__dirname, '../lib')
const templatePath = path.join(__dirname, 'templates')
const docPath = path.join(__dirname, '../doc')
const stylesheetPath = path.join(__dirname, 'stylesheets')

const templates = {}
const docs = {}
const api = [
  {
    module: 'Fortune',
    path: 'index.js'
  },
  {
    module: 'Adapter',
    path: 'adapter/index.js'
  },
  {
    module: 'FortuneHTTP',
    label: 'HTTP Server',
    pkg: 'fortune-http',
    path: '../node_modules/fortune-http/lib/index.js'
  },
  {
    module: 'HttpSerializer',
    label: 'HTTP Serializer',
    pkg: 'fortune-http',
    path: '../node_modules/fortune-http/lib/serializer.js'
  },
  {
    module: 'FortuneWS',
    label: 'WebSocket',
    pkg: 'fortune-ws',
    path: [
      '../node_modules/fortune-ws/lib/index.js',
      '../node_modules/fortune-ws/lib/request.js',
      '../node_modules/fortune-ws/lib/sync.js'
    ]
  }
]

const renderer = new marked.Renderer()

renderer.heading = (text, level) => {
  const escapedText = text.toLowerCase().replace(/[^\w]+/g, '-')

  return level !== 1 ?
    `<h${level} id="${escapedText}">${text}<a class="anchor" ` +
    `href="#${escapedText}" title="Link to this section “${text}”">#</a>` +
    `</h${level}>` :
    `<h1>${text}</h1>`
}

const markedOptions = {
  renderer, highlight: (code, lang) => hjs.highlight(lang, code).value
}

const minifyOptions = { collapseWhitespace: true }

// Initialization
// ==============

function processAPI (ns, obj) {
  const context = obj.context
  const type = context.type
  const name = context.name

  if (ns === name) {
    obj.context.anchor = ns.toLowerCase()
    obj.context.path = ns
  }
  else {
    obj.context.anchor = (`${ns}-${name}`).toLowerCase()
    obj.context.path = (type === 'class' ?
      (ns.split('.').slice(0, -1).join('.') + '.') : (ns + '.')) +
      `<span class="key">${name}</span>`
  }

  if (type === 'class')
    obj.context.isClass = true

  if (type === 'property')
    obj.context.isProperty = true

  if (type === 'method' || type === 'function' || type === 'constructor')
    obj.context.isFunction = true

  if (type === 'constructor' ||
    (name === 'constructor' && obj.context.isFunction))
    obj.context.isConstructor = true

  const getName = element => {
    if (element.type === 'AllLiteral') return 'any type'
    if (element.name) return element.name
    if (element.applications) return 'an array of ' +
      element.applications.map(getName)
      .map(s => inflection.pluralize(s)).join(' or ')
    return ''
  }
  const setArray = str => `${str} (array)`
  const params = []

  for (let tag of obj.comment.tags) {
    if (tag.title === 'return') {
      obj.comment.returnType = tag.type.name
      if (tag.type.elements) obj.comment.returnType =
        tag.type.elements.map(getName).join(' | ')
      if (tag.type.applications) obj.comment.returnType =
        tag.type.applications.map(getName).map(setArray).join(' | ')
      continue
    }
    if (tag.title === 'param') {
      let name = tag.name
      let type = tag.type.name
      const description = tag.description
      const isOptional = tag.type.type === 'OptionalType'
      const isArray = tag.type.expression &&
        (tag.type.expression.expression || tag.type.expression)
        .name === 'Array'
      const isUnion = tag.type.type === 'UnionType' ||
        (tag.type.expression && tag.type.expression.type === 'UnionType')
      const isRest = tag.type.expression &&
        tag.type.expression.type === 'RestType'

      if (isOptional)
        type = tag.type.expression.name

      if (isArray) {
        type = 'Array of ' + inflection.pluralize(
          (tag.type.expression.applications || tag.type.applications ||
            [ { type: 'AllLiteral' } ])
          .map(getName).map(inflection.pluralize.bind(inflection)).join(', '))
      }

      if (isUnion)
        type = 'Either ' + (tag.type.elements || tag.type.expression.elements)
          .map(getName).join(', or ')

      if (isRest) {
        type = `Arbitrary number of ` + getName(
          tag.type.expression.expression || tag.type.expression)
        name = `…${name}`
      }

      params.push(`<span class="parameter" title="${type}` + (description ?
        `. ${description}` : '') + `">` +
        (isOptional ? `[${name}]` : name) + '</span>')
    }
  }

  if (params.length) obj.comment.params = params.join(', ')

  return obj
}

const render = description => marked(description, markedOptions)
const outputDoc = doc => {
  const buffer = fs.readFileSync(path.join(apiPath, doc))
  const output = DocTree.parse(buffer).output({ render })
  return output
}

for (let container of api) {
  let docs = container.path
  if (!Array.isArray(docs)) docs = [ docs ]

  container.docs = Array.prototype
    .concat.apply([], docs.map(outputDoc))
    .map(processAPI.bind(null, container.module))
}

for (let file of fs.readdirSync(templatePath))
  templates[path.basename(file, '.mustache')] =
    fs.readFileSync(path.join(templatePath, file)).toString()

for (let file of fs.readdirSync(docPath)) {
  const basename = path.basename(file, '.md')

  docs[inflection.dasherize(basename.toLowerCase())] = {
    root: '../',
    title: inflection.titleize(basename),
    year, api,
    version: pkg.version,
    content: marked(
      fs.readFileSync(path.join(docPath, file)).toString(), markedOptions)
  }
}

const readme = fs.readFileSync(
  path.join(__dirname, '..', 'README.md')).toString()

const example = (/(##([\s\S]+)(?=\n## License))/g).exec(readme)[1]
  .replace('##', '####')

docs.readme = {
  root: './',
  title: 'Fortune.js',
  year, api,
  version: pkg.version,
  description: pkg.description,
  keywords: pkg.keywords.join(','),
  content: mustache.render(templates.home) +
    marked(example, markedOptions)
}

// Copy assets
// ===========

mkdirp.sync(path.join(outputPath, 'assets'))
for (let file of fs.readdirSync(assetPath))
  fs.createReadStream(path.join(assetPath, file))
  .pipe(fs.createWriteStream(path.join(
    outputPath, 'assets', path.basename(file))))

// Build stylesheets
// =================

const cssEntryPoint = path.join(stylesheetPath, 'index.css')

postcss([ atImport, cssnext, cssnano() ])
  .process(fs.readFileSync(cssEntryPoint).toString(), {
    from: cssEntryPoint
  })
  .then(result =>
    fs.writeFileSync(path.join(outputPath, 'assets/index.css'), result.css))

// Build the pages
// ===============

fs.writeFileSync(path.join(outputPath, 'index.html'), minify(
  mustache.render(templates.page, docs.readme, templates), minifyOptions))

mkdirp.sync(path.join(outputPath, 'api'))
fs.writeFileSync(path.join(outputPath, 'api/index.html'), minify(
  mustache.render(templates.page, {
    root: '../',
    title: 'API Reference',
    year, api,
    version: pkg.version,
    content: mustache.render(templates.api, api)
  }, templates), minifyOptions))

for (let doc in docs) {
  mkdirp.sync(path.join(outputPath, doc))
  fs.writeFileSync(path.join(outputPath, doc, 'index.html'), minify(
    mustache.render(templates.page, docs[doc], templates), minifyOptions))
}

// Write CNAME file
// ================

fs.writeFileSync(path.join(outputPath, 'CNAME'), CNAME)

// End
// ===

process.stderr.write(chalk.green(`Done! Build finished in ` +
  `${chalk.bold(((Date.now() - start) / 1000) + ' s')}.\n`))


Q:

How to Mock a list transformation using AutoMapper

I am using AutoMapper and have a definition of mapping engine as
private readonly IMappingEngine _mappingEngine;

I initialize it via constructor injection and use in the code as below
var product=//Get a single product
var productModel = _mappingEngine.Map<ProductModel>(product);

The above works perfectly. I now need to map a list of Product to list of ProductModel The following works in the controller action
var entities =//Get list of products
var model = entities.Select(e => _mappingEngine.Map<ProductModel>(e));

The above LINQ code uses foreach and converts each Product to a ProductModel Now I need to unit test the above code but unable to use Moq to mock the LINQ  statement above
I've tried the following
var mapper = new Mock<IMappingEngine>();
mapper.Setup(m => m.Map<ProductModel>(product)).Returns(ProductModel);

The above mapper setup works for single object mapping. How can we setup the above using a list of products
So, I want to be able to setup a list of Product like this:
var productList=new List<Product>{new Product{Id=1,name="product 1"},
                                  new Product{Id=2,name="product 2"}};

and define a mocking that will return a list of ProductModel like this:
var productModelList=new List<ProductModel>{new ProductModel{Id=1,name="product 1"},
                                            new ProductModel{Id=2,name="product 2"}};

when my test calls the controller (which uses the mock IMappingEngine to transform the list)
var model = entities.Select(e => _mappingEngine.Map<ProductModel>(e));

So, when writing Moq unit tests how can we setup the above so that _mappingEngine.Map that takes productList as input and returns productModelList?

A:

First up, do you really need to mock the mapping from Product to ProductModel, or would it be just as valid to create an instance of IMappingEngine and supply it to your controller, rather than a Mock.Object.
Something as simple adding the mapping in your test setup:
Mapper.CreateMap<Product, ProductModel>();

and clearing the mapping in your test teardown:
Mapper.Reset();

Would allow you to just supply Mapper.Engine to controllers constructor in your test.  Obviously it depends on your approach to testing, but for something like AutoMapper which is well used and reliable, with little time overhead, this may well be a valid approach.
Assuming you do want to mock the mapping, you can use a callback to return a different item for each call, doing something like this:
// Create a list of the mapped values you're expecting
var productModels = new List<ProductModel> {
    new ProductModel { Id=11,name="eleven"},
    new ProductModel { Id=12,name="twelve"},
    new ProductModel { Id=13,name="thirteen"}
};

// Mock the IMappingEngine
var engine = new Mock<IMappingEngine>();

// Create a variable to count the calls
var calls=0;

// Mock ALL calls to map, where the destination is ProductModel
// and source is Product
engine.Setup(m => m.Map<ProductModel>(It.IsAny<Product>()))
      .Returns(()=>productModels[calls]) // Return next productModel
      .Callback(()=>calls++)   // Increment counter to point to next model

You should notice, that the mock Setup is mocking individual mappings, not mapping a list of Product to a list of ProductModel.  That's because your call to entities.Select(e => _mappingEngine.Map<ProductModel>(e)) is looping through your list an item at a time, not asking the mapping engine (or your mock) to map the list in one go...
If you need to be more precise in your mocking, then it's also possible to extend the Callback to verify that the expected Product is being mapped.  You probably won't want to do this every time, but it can be useful in some circumstances.  So, you could do something like:
// Declare a list of expected products to map from
var products = new List<Product> {
    new Product {Id=1, name="One"},
    new Product {Id=2, name="Two"},
    new Product {Id=3, name="Three"}
};

engine.Setup(m => m.Map<ProductModel>(It.IsAny<Product>()))
      .Returns(() => productModels[calls])
      .Callback<Product>(x => {Assert.AreEqual(x.Id, products[calls].Id); calls++;});


(*
 * BatPervasives - Additional functions
 * Copyright (C) 1996 Xavier Leroy
 *               2003 Nicolas Cannasse
 *               2007 Zheng Li
 *               2008 David Teller
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version,
 * with the special exception on linking described in file LICENSE.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *)

(** {6 Additional functions.}

    @author Xavier Leroy (Base module)
    @author Nicolas Cannasse
    @author David Teller
    @author Zheng Li
*)

open BatIO

(** The initially opened module.

    This module provides the basic operations over the built-in types
    (numbers, booleans, strings, exceptions, references, lists, arrays,
    input-output channels, ...)

    This module is automatically opened at the beginning of each compilation.
    All components of this module can therefore be referred by their short
    name, without prefixing them by [BatPervasives].

    @author Xavier Leroy (Base module)
    @author Nicolas Cannasse
    @author David Teller
    @author Zheng Li
*)

val input_lines : Pervasives.in_channel -> string BatEnum.t
(** Returns an enumeration over lines of an input channel, as read by the
    [input_line] function. *)

val input_chars : Pervasives.in_channel -> char BatEnum.t
(** Returns an enumeration over characters of an input channel. *)

val input_list : Pervasives.in_channel -> string list
(** Returns the list of lines read from an input channel. *)

val input_all : Pervasives.in_channel -> string
(** Return the whole contents of an input channel as a single
    string. *)

val dump : 'a -> string
(** Attempt to convert a value to a string.

    Since types are lost at compile time, the representation might not
    match your type. For example, None will be printed 0 since they
    share the same runtime representation.

    [dump] may fail for ill-formed values, such as obtained from
    a faulty C binding or crazy uses of [Obj.set_tag].
*)

val print_any : 'b BatIO.output -> 'a -> unit
(** Attempt to print a value to an output.

    Uses [dump] to convert the value to a string and prints that
    string to the output.
*)

(** {6 List operations}

    More list operations are provided in module {!List}.
*)

val ( @ ) : 'a list -> 'a list -> 'a list
(** List concatenation. *)

(** {6 Input/output}

    This section only contains the most common input/output operations.
    More operations may be found in modules {!BatIO} and {!File}.
*)

val stdin : input
(** Standard input, as per Unix/Windows conventions (by default, keyboard).

    Use this input to read what the user is writing on the keyboard.*)

val stdout: unit output
(** Standard output, as per Unix/Windows conventions (by default, console).

    Use this output to display regular messages.*)

val stderr: unit output
(** Standard error output, as per Unix/Windows conventions.

    Use this output to display warnings and error messages.*)

val stdnull: unit output
(** An output which discards everything written to it.

    Use this output to ignore messages.*)

val flush_all : unit -> unit
(** Write all pending data to output channels, ignore all errors.

    It is normally not necessary to call this function, as all pending
    data is written when an output channel is closed or when the
    program itself terminates, either normally or because of an
    uncaught exception. However, this function is useful for
    debugging, as it forces pending data to be written immediately.
*)

(** {7 Output functions on standard output} *)

val print_bool : bool -> unit
(** Print a boolean on standard output. *)

val print_guess : 'a BatIO.output -> 'b -> unit
(** Attempt to print the representation of a runtime value on the
    standard output.  See remarks for {!dump}. This function is
    useful mostly for debugging. As a general rule, it should not be
    used in production code.*)

val print_all : input -> unit
(** Print the contents of an input to the standard output.*)

(** {7 Output functions on standard error} *)

val prerr_bool : bool -> unit
(** Print a boolean to stderr. *)

val prerr_guess : 'a -> unit
(** Attempt to print the representation of a runtime value on the
    error output.  See remarks for {!dump}. This function is
    useful mostly for debugging.*)

val prerr_all : input -> unit
(** Print the contents of an input to the error output.*)

(** {7 General output functions} *)

val output_file : filename:string -> text:string -> unit
(** creates a filename, write text into it and close it. *)

val open_out : ?mode:(BatFile.open_out_flag list) ->
  ?perm:BatFile.permission           ->
  string -> unit BatIO.output
(** Open the named file for writing, and return a new output channel
    on that file. You will need to close the file once you have
    finished using it.

    You may use optional argument [mode] to decide whether the
    output will overwrite the contents of the file (by default) or
    to add things at the end of the file, whether the file should be
    created if it does not exist yet (the default) or not, whether
    this operation should proceed if the file exists already (the
    default) or not, whether the file should be opened as text
    (the default) or as binary, and whether the file should be
    opened for non-blocking operations.

    You may use optional argument [perm] to specify the permissions
    of the file, as per Unix conventions. By default, files are created
    with default permissions (which depend on your setup).

    @raise Sys_error if the file could not be opened. *)

val open_out_bin : string -> unit BatIO.output
(** Same as {!open_out}, but the file is opened in binary mode, so
    that no translation takes place during writes. On operating
    systems that do not distinguish between text mode and binary
    mode, this function behaves like {!open_out} without any
    [mode] or [perm]. *)

val open_out_gen : open_flag list -> int -> string -> unit BatIO.output
(**
   [open_out_gen mode perm filename] opens the named file for writing,
   as described above. The extra argument [mode]
   specifies the opening mode. The extra argument [perm] specifies
   the file permissions, in case the file must be created.

   @deprecated Use {!open_out instead}*)

val flush : unit BatIO.output -> unit
(** Flush the buffer associated with the given output, performing
    all pending writes on that channel. Interactive programs must be
    careful about flushing standard output and standard error at the
    right time. *)

val output_char : unit BatIO.output -> char -> unit
(** Write the character on the given output channel. *)

val output_string : unit BatIO.output -> string -> unit
(** Write the string on the given output channel. *)

val output : unit BatIO.output -> string -> int -> int -> unit
(** [output oc buf pos len] writes [len] characters from string [buf],
    starting at offset [pos], to the given output channel [oc].
    @raise Invalid_argument if [pos] and [len] do not
    designate a valid substring of [buf]. *)

val output_byte : unit BatIO.output -> int -> unit
(** Write one 8-bit integer (as the single character with that code)
    on the given output channel. The given integer is taken modulo
    256. *)

val output_binary_int : unit BatIO.output -> int -> unit
(** Write one integer in binary format (4 bytes, big-endian)
    on the given output channel.
    The given integer is taken modulo 2{^32}.
    The only reliable way to read it back is through the
    {!Pervasives.input_binary_int} function. The format is compatible across
    all machines for a given version of OCaml. *)

val output_binary_float : unit BatIO.output -> float -> unit
(** Write one float in binary format (8 bytes, IEEE 754 double format)
    on the given output channel.
    The only reliable way to read it back is through the
    {!Pervasives.input_binary_float} function. The format is compatible across
    all machines for a given version of OCaml. *)

val output_value : unit BatIO.output -> 'a -> unit
(** Write the representation of a structured value of any type
    to a channel. Circularities and sharing inside the value
    are detected and preserved. The object can be read back,
    by the function {!input_value}. See the description of module
    {!Marshal} for more information. {!output_value} is equivalent
    to {!Marshal.output} with an empty list of flags. *)

val close_out : unit BatIO.output -> unit
(** Close the given channel, flushing all buffered write operations.
    Output functions raise a [Sys_error] exception when they are
    applied to a closed output channel, except [close_out] and [flush],
    which do nothing when applied to an already closed channel.
    @raise Sys_error if the operating
    system signals an error when flushing or closing. *)

val close_out_noerr : unit BatIO.output -> unit
(** Same as [close_out], but ignore all errors. *)

(** {7 General input functions} *)

val input_file : ?bin:bool -> string -> string
(** returns the data of a given filename. *)

val open_in : ?mode:(BatFile.open_in_flag list) ->
  ?perm:BatFile.permission ->
  string -> BatIO.input
(** Open the named file for reading. You will need to close the file once you have
    finished using it.

    You may use optional argument [mode] to decide whether the opening
    should fail if the file doesn't exist yet (by default) or whether
    the file should be created if it doesn't exist yet, whether the
    opening should fail if the file already exists or not (by
    default), whether the file should be read as binary (by default)
    or as text, and whether reading should be non-blocking.

    You may use optional argument [perm] to specify the permissions of
    the file, should it be created, as per Unix conventions. By
    default, files are created with default permissions (which depend
    on your setup).

    @raise Sys_error if the file could not be opened. *)

val open_in_bin : string -> BatIO.input
(** Same as {!Pervasives.open_in}, but the file is opened in binary mode,
    so that no translation takes place during reads. On operating
    systems that do not distinguish between text mode and binary
    mode, this function behaves like {!Pervasives.open_in}. *)

val open_in_gen : open_flag list -> int -> string -> BatIO.input
(** [open_in mode perm filename] opens the named file for reading,
    as described above. The extra arguments [mode] and [perm]
    specify the opening mode and file permissions.
    {!Pervasives.open_in} and {!Pervasives.open_in_bin} are special
    cases of this function.

    @deprecated Use {!open_in instead}*)

val input_char : BatIO.input -> char
(** Read one character from the given input channel.
    @raise End_of_file if there are no more characters to read. *)

val input_line : BatIO.input -> string
(** Read characters from the given input channel, until a
    newline character is encountered. Return the string of
    all characters read, without the newline character at the end.
    @raise End_of_file if the end of the file is reached
    at the beginning of line. *)

val input : BatIO.input -> string -> int -> int -> int
(** [input ic buf pos len] reads up to [len] characters from
    the given channel [ic], storing them in string [buf], starting at
    character number [pos].
    It returns the actual number of characters read, between 0 and
    [len] (inclusive).
    A return value of 0 means that the end of file was reached.
    A return value between 0 and [len] exclusive means that
    not all requested [len] characters were read, either because
    no more characters were available at that time, or because
    the implementation found it convenient to do a partial read;
    [input] must be called again to read the remaining characters,
    if desired.  (See also {!Pervasives.really_input} for reading
    exactly [len] characters.)
    @raise Invalid_argument if [pos] and [len]
    do not designate a valid substring of [buf]. *)

val really_input : BatIO.input -> string -> int -> int -> unit
(** [really_input ic buf pos len] reads [len] characters from channel [ic],
    storing them in string [buf], starting at character number [pos].
    @raise End_of_file if the end of file is reached before [len]
    characters have been read.
    @raise Invalid_argument if
    [pos] and [len] do not designate a valid substring of [buf]. *)

val input_byte : BatIO.input -> int
(** Same as {!Pervasives.input_char}, but return the 8-bit integer representing
    the character.
    @raise End_of_file if an end of file was reached. *)

val input_binary_int : BatIO.input -> int
(** Read an integer encoded in binary format (4 bytes, big-endian)
    from the given input channel. See {!Pervasives.output_binary_int}.
    @raise End_of_file if an end of file was reached while reading the
    integer. *)

val input_binary_float : BatIO.input -> float
(** Read a float encoded in binary format (8 bytes, IEEE 754 double format)
    from the given input channel. See {!Pervasives.output_binary_float}.
    @raise End_of_file if an end of file was reached while reading the
    float. *)

val input_value : BatIO.input -> 'a
(** Read the representation of a structured value, as produced
    by {!output_value}, and return the corresponding value.
    This function is identical to {!Marshal.input};
    see the description of module {!Marshal} for more information,
    in particular concerning the lack of type safety. *)

val close_in : BatIO.input -> unit
(** Close the given channel.  Input functions raise a [Sys_error]
    exception when they are applied to a closed input channel,
    except [close_in], which does nothing when applied to an already
    closed channel.
    @raise Sys_error if
    the operating system signals an error. *)

val close_in_noerr : BatIO.input -> unit
(** Same as [close_in], but ignore all errors. *)

(**
   {6 Fundamental functions and operators}
*)

external identity : 'a -> 'a = "%identity"
(** The identity function. *)

val undefined : ?message:string -> 'a -> 'b
  (** The undefined function.

      Evaluating [undefined x] always fails and raises an exception
      "Undefined". Optional argument [message] permits the
      customization of the error message.*)

##V3## val ( @@ ) : ('a -> 'b) -> 'a -> 'b
##V4## external ( @@ ) : ('a -> 'b) -> 'a -> 'b = "%apply"

(** Function application. [f @@ x] is equivalent to [f x].
    However, it binds less tightly (between [::] and [=],[<],[>],etc)
    and is right-associative, which makes it useful for composing sequences of
    function calls without too many parentheses. It is similar to Haskell's [$].
    Note that it replaces pre-2.0 [**>] and [<|]. *)

val ( % ) : ('a -> 'b) -> ('c -> 'a) -> 'c -> 'b
  (** Function composition: the mathematical [o] operator.
      [f % g] is [fun x -> f (g x)]. It is similar to Haskell's [.].

      Examples: the following are equivalent:
      [f (g (h x))], [f @@ g @@ h x], [f % g % h @@ x]. *)

##V3## val ( |> ) : 'a -> ('a -> 'b) -> 'b
##V4## external (|>) : 'a -> ('a -> 'b) -> 'b = "%revapply"
(** The "pipe": function application. [x |> f] is equivalent to [f x].

    This operator is commonly used to write a function composition by
    order of evaluation (the order used in object-oriented
    programming) rather than by inverse order (the order typically
    used in functional programming).

    For instance, [g (f x)] means "apply [f] to [x], then apply [g] to
    the result." The corresponding notation in most object-oriented
    programming languages would be somewhere along the lines of [x.f.g.h()],
    or "starting from [x], apply [f], then apply [g]." In OCaml,
    using the ( |> ) operator, this is written [x |> f |> g |> h].

    This operator may also be useful for composing sequences of
    function calls without too many parentheses. *)

val ( %> ) : ('a -> 'b) -> ('b -> 'c) -> 'a -> 'c
(** Piping function composition. [f %> g] is [fun x -> g (f x)].
    Whereas [f % g] applies [g] first and [f] second, [f @> g]
    applies [f], then [g].
    Note that it plays well with pipes, so for instance
    [x |> f %> g %> h |> i %> j] yields the expected result...
    but in such cases it's still recommended to use [|>] only.
    Note that it replaces pre-2.0 [|-], which {i didn't} integrate with
    pipes.
*)

val ( |? ) : 'a option -> 'a -> 'a
(** Like {!BatOption.default}, with the arguments reversed.
    [None |? 10] returns [10], while [Some "foo" |? "bar"] returns ["foo"].

    {b Note} This operator does not short circuit like [( || )] and [( && )].
    Both arguments will be evaluated.

    @since 2.0 *)

val flip : ( 'a -> 'b -> 'c ) -> 'b -> 'a -> 'c
(** Argument flipping.

    [flip f x y] is [f y x]. Don't abuse this function, it may shorten
    considerably your code but it also has the nasty habit of making
    it harder to read.*)

val curry : ('a * 'b -> 'c) -> 'a -> 'b -> 'c
(** Convert a function which accepts a pair of arguments into a
    function which accepts two arguments.

    [curry f] is [fun x y -> f (x,y)]*)

val uncurry : ('a -> 'b -> 'c) -> 'a * 'b -> 'c
(** Convert a function which accepts a two arguments into a function
    which accepts a pair of arguments.

    [uncurry f] is [fun (x, y) -> f x y]*)

val neg : ('a -> bool) -> 'a -> bool
(** [neg p] returns a new predicate that is the negation of the given
    predicate.  That is, the new predicate returns [false] when the
    input predicate returns [true] and vice versa.  This is for
    predicates with one argument.

    [neg p] is [fun x -> not (p x)]
*)

val neg2 : ('a -> 'b -> bool) -> 'a -> 'b -> bool
(** as [neg] but for predicates with two arguments *)

val const : 'a -> (_ -> 'a)
(** Ignore its second argument.

    [const x] is the function which always returns [x].*)

val unique : unit -> int
(** Returns an unique identifier every time it is called.

    {b Note} This is thread-safe.*)

val tap : ('a -> unit) -> 'a -> 'a
(** Allows application of a function in the middle of a pipe
    sequence without disturbing the sequence.  [x |> tap f]
    evaluates to [x], but has the side effect of [f x].  Useful for
    debugging. *)

val finally : (unit -> unit) -> ('a -> 'b) -> 'a -> 'b
(** [finally fend f x] calls [f x] and then [fend()] even if [f x] raised
    an exception. *)

val with_dispose : dispose:('a -> unit) -> ('a -> 'b) -> 'a -> 'b
(** [with_dispose dispose f x] invokes [f] on [x], calling [dispose x]
    when [f] terminates (either with a return value or an
    exception). *)

val forever : ('a -> 'b) -> 'a -> unit
(** [forever f x] invokes [f] on [x] repeatedly (until an exception occurs). *)

val ignore_exceptions : ('a -> 'b) -> 'a -> unit
(** [ignore_exceptions f x] invokes [f] on [x], ignoring both the returned value
    and the exceptions that may be raised. *)

val verify_arg : bool -> string -> unit
(** [verify_arg condition message] will raise [Invalid_argument message] if
    [condition] is false, otherwise it does nothing.

    @since 2.0 *)

val args : unit -> string BatEnum.t
(** An enumeration of the arguments passed to this program through the command line.

    [args ()] is given by the elements of [Sys.argv], minus the first element.*)

(**/**)
val invisible_args : int ref
(** The number of arguments which must never be returned by [args]

    Typically, [invisible_args] is [1], to drop the name of the executable. However,
    in some circumstances, it may be useful to pretend that some arguments need not
    be parsed.
*)
(**/**)

val exe  : string
(** The name of the current executable.

    [exe] is given by the first argument of [Sys.argv]*)

(**
   {6 Enumerations}

   In OCaml Batteries Included, all data structures are enumerable,
   which means that they support a number of standard operations,
   transformations, etc. The general manner of {i enumerating} the
   contents of a data structure is to invoke the [enum] function of
   your data structure.

   For instance, you may use the {!foreach} loop to apply a function
   [f] to all the consecutive elements of a string [s]. For this
   purpose, you may write either [foreach (String.enum s) f] or [open
   String in foreach (enum s) f]. Either possibility states that you
   are enumerating through a character string [s]. Should you prefer
   your enumeration to proceed from the end of the string to the
   beginning, you may replace {! String.enum} with {!
   String.backwards}. Therefore, either [foreach (String.backwards s)
   f] or [open String in foreach (backwards s) f] will apply [f]
   to all the consecutive elements of string [s], from the last to
   the first.

   Similarly, you may use {!List.enum} instead of {!String.enum} to
   visit the elements of a list in the usual order, or
   {!List.backwards} instead of {!String.backwards} to visit them
   in the opposite order, or {!Hashtbl.enum} for hash tables, etc.

   More operations on enumerations are defined in module {!BatEnum},
   including the necessary constructors to make your own structures
   enumerable.

   The various kinds of loops are detailed further in this documentation.
*)

val foreach: 'a BatEnum.t -> ('a -> unit) ->  unit
(** Imperative loop on an enumeration.

    [foreach e f] applies function [f] to each successive element of [e].
    For instance, [foreach (1 -- 10) print_int] invokes function [print_int]
    on [1], [2], ..., [10], printing [12345678910].

    {b Note} This function is one of the many loops available on
    enumerations.  Other commonly used loops are {!iter} (same usage
    scenario as [foreach], but with different notations), {!map}
    (convert an enumeration to another enumeration) or {!fold}
    (flatten an enumeration by applying an operation to each
    element).

*)

(**
   {7 General-purpose loops}

   {topic loops}

   The following functions are the three main general-purpose loops
   available in OCaml. By opposition to the loops available in
   imperative languages, OCaml loops are regular functions, which
   may be passed, composed, currified, etc. In particular, each
   of these loops may be considered either as a manner of applying
   a function to a data structure or as transforming a function
   into another function which will act on a whole data structure.

   For instance, if [f] is a function operating on one value, you may
   lift this function to operate on all values of an enumeration (and
   consequently on all values of any data structure of OCaml Batteries
   Included) by applying {!iter}, {!map} or {!fold} to this function.
*)

val iter : ('a -> unit) -> 'a BatEnum.t -> unit
(** Imperative loop on an enumeration. This loop is typically used
    to lift a function with an effect but no meaningful result and
    get it to work on enumerations.

    If [f] is a function [iter f] is a function which behaves as [f]
    but acts upon enumerations rather than individual elements. As
    indicated in the type of [iter], [f] must produce values of type
    [unit] (i.e. [f] has no meaningful result) the resulting function
    produces no meaningful result either.

    In other words, [iter f] is a function which, when applied upon
    an enumeration [e], calls [f] with each element of [e] in turn.

    For instance, [iter f (1 -- 10)] invokes function [f] on [1],
    [2], ..., [10] and produces value [()].
*)

val map : ('a -> 'b) -> 'a BatEnum.t -> 'b BatEnum.t
(** Transformation loop on an enumeration, used to build an enumeration
    from another enumeration. This loop is typically used to transform
    an enumeration into another enumeration with the same number of
    elements, in the same order.

    If [f] is a function, [map f e] is a function which behaves as
    [f] but acts upon enumerations rather than individual elements --
    and builds a new enumeration from the results of each application.

    In other words, [map f] is a function which, when applied
    upon an enumeration containing elements [e0], [e1], ...,
    produces enumeration [f e0], [f e1], ...

    For instance, if [odd] is the function which returns [true]
    when applied to an odd number or [false] when applied to
    an even number, [map odd (1 -- 10)] produces enumeration
    [true], [false], [true], ..., [false].

    Similarly, if [square] is the function [fun x -> x * x],
    [map square (1 -- 10)] produces the enumeration of the
    square numbers of all numbers between [1] and [10].
*)

val filter_map : ('a -> 'b option) -> 'a BatEnum.t -> 'b BatEnum.t
(** Similar to a map, except that you can skip over some items of the
    incoming enumeration by returning None instead of Some value.
    Think of it as a {!filter} combined with a {!map}.
*)

val reduce : ('a -> 'a -> 'a) -> 'a BatEnum.t -> 'a
(** Transformation loop on an enumeration, used to build a single value
    from an enumeration.

    If [f] is a function and [e] is an enumeration, [reduce f e] applies
    function [f] to the first two elements of [e], then to the result of this
    expression and to the third element of [e], then to the result of this
    new expression and to the fourth element of [e]...

    In other words, [reduce f e] returns [a0] if [e] contains only
    one element [a0], otherwise [f (... (f (f a0) a1) ...) aN] where
    [a0,a1..aN] are the elements of [e].

    @raise Not_found if [e] is empty.

    For instance, if [add] is the function [fun x y -> x + y],
    [reduce add] is the function which computes the sum of the
    elements of an enumeration -- and doesn't work on empty
    enumerations. Therefore, [reduce add (1 -- 10)]
    produces result [55].
*)

val fold : ('b -> 'a -> 'b) -> 'b -> 'a BatEnum.t -> 'b
(** Transformation loop on an enumeration, used to build a single value
    from an enumeration. This is the most powerful general-purpose
    loop and also the most complex.

    If [f] is a function, [fold f v e] applies [f v] to the first
    element of [e], then, calling [acc_1] the result of this
    operation, applies [f acc_1] to the second element of [e], then,
    calling [acc_2] the result of this operation, applies [f acc_2]
    to the third element of [e]...

    In other words, [fold f v e] returns [v] if [e] is empty,
    otherwise [f (... (f (f v a0) a1) ...) aN] where a0,a1..aN are
    the elements of [e].

    For instance, if [add] is the function [fun x y -> x + y],
    [fold add 0] is the function which computes the sum of the
    elements of an enumeration. Therefore, [fold add 0 (1 -- 10)]
    produces result [55].
*)

val scanl : ('b -> 'a -> 'b) -> 'b -> 'a BatEnum.t -> 'b BatEnum.t
(** Functional loop on an enumeration, used to build an enumeration
    from both an enumeration and an initial value. This function may
    be seen as a variant of {!fold} which returns not only the final
    result of {!fold} but the enumeration of all the intermediate
    results of {!fold}.

    If [f] is a function, [scanl f v e] is applies [f v] to the first
    element of [e], then, calling [acc_1] the result of this
    operation, applies [f acc_1] to the second element of [e], then,
    calling [acc_2] the result of this operation, applies [f acc_2]
    to the third element of [e]...

    For instance, if [add] is the function [fun x y -> x + y],
    [scanl add 0] is the function which computes the sum of the
    elements of an enumeration. Therefore, [scanl add 0 (1 -- 10)]
    produces result the enumeration with elements [0, 1, 3, 6, 10,
    15, 21, 28, 36, 45, 55].  *)

val ( /@ ) : 'a BatEnum.t -> ('a -> 'b) -> 'b BatEnum.t

val ( @/ ) : ('a -> 'b) -> 'a BatEnum.t -> 'b BatEnum.t
(**
   Mapping operators.

   These operators have the same meaning as function {!map} but are
   sometimes more readable than this function, when chaining
   several transformations in a row.
*)

val ( //@ ) : 'a BatEnum.t -> ('a -> 'b option) -> 'b BatEnum.t

val ( @// ) : ('a -> 'b option) -> 'a BatEnum.t -> 'b BatEnum.t
(**
   Map combined with filter. Same as {!filter_map}.
*)

(**
   {7 Other operations on enumerations}
*)

val exists: ('a -> bool) -> 'a BatEnum.t -> bool
(** [exists f e] returns [true] if there is some [x] in [e] such
    that [f x]*)

val for_all: ('a -> bool) -> 'a BatEnum.t -> bool
(** [exists f e] returns [true] if for every [x] in [e], [f x] is true*)

val find : ('a -> bool) -> 'a BatEnum.t -> 'a
(** [find f e] returns the first element [x] of [e] such that [f x] returns
    [true], consuming the enumeration up to and including the
    found element, or, raises [Not_found] if no such element exists
    in the enumeration, consuming the whole enumeration in the search.

    Since [find] consumes a prefix of the enumeration, it can be used several
    times on the same enumeration to find the next element.

    @raise Not_found if no element in the whole enumeration satisfies the predicate *)

val peek : 'a BatEnum.t -> 'a option
(** [peek e] returns [None] if [e] is empty or [Some x] where [x] is
    the next element of [e]. The element is not removed from the
    enumeration. *)

val get : 'a BatEnum.t -> 'a option
(** [get e] returns [None] if [e] is empty or [Some x] where [x] is
    the next element of [e], in which case the element is removed
    from the enumeration. *)

val push : 'a BatEnum.t -> 'a -> unit
(** [push e x] will add [x] at the beginning of [e]. *)

val junk : 'a BatEnum.t -> unit
(** [junk e] removes the first element from the enumeration, if any. *)

val filter : ('a -> bool) -> 'a BatEnum.t -> 'a BatEnum.t
(** [filter f e] returns an enumeration over all elements [x] of [e] such
    as [f x] returns [true]. *)

val ( // ) : 'a BatEnum.t -> ('a -> bool) -> 'a BatEnum.t
(** Filtering (pronounce this operator name "such that").

    For instance, [(1 -- 37) // odd] is the enumeration of all odd
    numbers between 1 and 37.*)

val concat : 'a BatEnum.t BatEnum.t -> 'a BatEnum.t
(** [concat e] returns an enumeration over all elements of all enumerations
    of [e]. *)

val ( -- ) : int -> int -> int BatEnum.t
(** Enumerate numbers.

    [5 -- 10] is the enumeration 5,6,7,8,9,10.
    [10 -- 5] is the empty enumeration*)

val ( --^ ) : int -> int -> int BatEnum.t
(** Enumerate numbers, without the right endpoint

    [5 -- 10] is the enumeration 5,6,7,8,9.
*)

val ( --. ) : (float * float) -> float -> float BatEnum.t
(** [(a, step) --. b)] creates a float enumeration from [a] to [b] with an
    increment of [step] between elements.

    [(5.0, 1.0) --. 10.0] is the enumeration 5.0,6.0,7.0,8.0,9.0,10.0.
    [(10.0, -1.0) --. 5.0] is the enumeration 10.0,9.0,8.0,7.0,6.0,5.0.
    [(10.0, 1.0) --. 1.0] is the empty enumeration. *)

val ( --- ) : int -> int -> int BatEnum.t
(** As [--], but accepts enumerations in reverse order.

    [5 --- 10] is the enumeration 5,6,7,8,9,10.
    [10 --- 5] is the enumeration 10,9,8,7,6,5.*)

val ( --~ ) : char -> char -> char BatEnum.t
(** As ( -- ), but for characters.*)

val print :  ?first:string -> ?last:string -> ?sep:string -> ('a BatInnerIO.output -> 'b -> unit) -> 'a BatInnerIO.output -> 'b BatEnum.t -> unit
(** Print and consume the contents of an enumeration.*)

(**
   {6 Results}
*)

(** This type represents the outcome of a function which has the
    possibility of failure.  Normal results of type ['a] are marked
    with [Ok], while failure values of type ['b] are marked with
    [Bad].

    This is intended to be a safer alternative to functions raising
    exceptions to signal failure.  It is safer in that the possibility
    of failure has to be handled before the result of that computation
    can be used.

    For more functions related to this type, see the {!BatResult} module.
*)
type ('a, 'b) result = ('a, 'b) BatInnerPervasives.result =
  | Ok  of 'a
  | Bad of 'b
  (** The result of a computation - either an [Ok] with the normal
      result or a [Bad] with some value (often an exception) containing
      failure information*)

val ignore_ok : ('a, exn) result -> unit
(** [ignore_ok (f x)] ignores the result of [f x] if it's ok, but
    throws the exception contained if [Bad] is returned. *)

val ok : ('a, exn) result -> 'a
(** [f x |> ok] unwraps the [Ok] result of [f x] and returns it, or
    throws the exception contained if [Bad] is returned. *)

val wrap : ('a -> 'b) -> 'a -> ('b, exn) result
(** [wrap f x] wraps a function that would normally throw an exception
    on failure such that it now returns a result with either the [Ok]
    return value or the [Bad] exception. *)

(**
   {6 Thread-safety internals}

   Unless you are attempting to adapt Batteries Included to a new model of
   concurrency, you probably won't need this.
*)

val lock: BatConcurrent.lock ref
  (**
     A lock used to synchronize internal operations.

     By default, this is {!BatConcurrent.nolock}. However, if you're
     using a version of Batteries compiled in threaded mode, this uses
     {!BatMutex}. If you're attempting to use Batteries with another
     concurrency model, set the lock appropriately.
  *)


using System;
using System.Runtime.InteropServices;
using System.Security;

namespace KeenSoftwareHouse.Library.Parallelization.Threading
{
    [SuppressUnmanagedCodeSecurity]
    internal class NativeMethods
    {
        public const int WaitObject0 = 0x0;
        public const int WaitAbandoned = 0x80;
        public const int WaitTimeout = 0x102;
        public const int WaitFailed = -1;

        public static readonly int SpinCount = Environment.ProcessorCount != 1 ? 4000 : 0;
        public static readonly bool SpinEnabled = Environment.ProcessorCount != 1;

        // We need to import some stuff. We can't use
        // ProcessHacker.Native because it depends on this library.

        [DllImport("kernel32.dll")]
        public static extern bool CloseHandle(
            [In] IntPtr Handle
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr CreateEvent(
            [In] [Optional] IntPtr EventAttributes,
            [In] bool ManualReset,
            [In] bool InitialState,
            [In] [Optional] string Name
            );

        [DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
        public static extern IntPtr CreateSemaphore(
            [In] [Optional] IntPtr SemaphoreAttributes,
            [In] int InitialCount,
            [In] int MaximumCount,
            [In] [Optional] string Name
            );

        [DllImport("kernel32.dll")]
        public static extern bool ReleaseSemaphore(
            [In] IntPtr SemaphoreHandle,
            [In] int ReleaseCount,
            [In] IntPtr PreviousCount // out int
            );

        [DllImport("kernel32.dll")]
        public static extern bool ResetEvent(
            [In] IntPtr EventHandle
            );

        [DllImport("kernel32.dll")]
        public static extern bool SetEvent(
            [In] IntPtr EventHandle
            );

        [DllImport("kernel32.dll")]
        public static extern int WaitForSingleObject(
            [In] IntPtr Handle,
            [In] int Milliseconds
            );

        [DllImport("ntdll.dll")]
        public static extern int NtCreateKeyedEvent(
            [Out] out IntPtr KeyedEventHandle,
            [In] int DesiredAccess,
            [In] [Optional] IntPtr ObjectAttributes,
            [In] int Flags
            );

        [DllImport("ntdll.dll")]
        public static extern int NtReleaseKeyedEvent(
            [In] IntPtr KeyedEventHandle,
            [In] IntPtr KeyValue,
            [In] bool Alertable,
            [In] [Optional] IntPtr Timeout
            );

        [DllImport("ntdll.dll")]
        public static extern int NtWaitForKeyedEvent(
            [In] IntPtr KeyedEventHandle,
            [In] IntPtr KeyValue,
            [In] bool Alertable,
            [In] [Optional] IntPtr Timeout
            );
    }
}


Many enterprises are changing their business processes using advanced information technology (IT) applications to achieve enhanced productivity and operational efficiencies. These advanced applications tend to place increasing importance on peer-to-peer data communications, as compared to traditional client-server data communications. As a result, the underlying network architecture to support these applications is evolving to better accommodate this new model.
The performance of many peer-to-peer applications benefit from being implemented over service provider networks that support multipoint network services. A multipoint network service is one that allows each customer edge (CE) end point or node to communicate directly and independently with all other CE nodes. Ethernet switched campus networks are an example of a multipoint service architecture. The multipoint network service contrasts with the hub-and-spoke network service, where the end customer designates one CE node to the hub that multiplexes multiple point-to-point services over a single User-Network Interface (UNI) to reach multiple “spoke” CE nodes. In a hub-and-spoke network architecture, each spoke can reach any other spoke only by communicating through the hub. Traditional network service offering to the end customers via wide area networks (WANs) such as Frame Relay (FR) and asynchronous transfer mode (ATM) networks are based on a hub-and-spoke service architecture.
Virtual Private Network (VPN) services provide secure network connections between different locations. A company, for example, can use a VPN to provide secure connections between geographically dispersed sites that need to access the corporate network. There are three types of VPN that are classified by the network layer used to establish the connection between the customer and provider network. Layer 1 VPNs are simple point-to-point connections such as leased lines, ISDN links, and dial-up connections. In a Layer 2 VPN (L2VPN) the provider delivers Layer 2 circuits to the customer (one for each site) and provides switching of the customer data. Customers map their Layer 3 routing to the circuit mesh, with customer routes being transparent to the provider. Many traditional L2VPNs are based on Frame Relay or ATM packet technologies. In a Layer 3 VPN (L3VPN) the provider router participates in the customer's Layer 3 routing. That is, the CE routers peer only with attached PEs, advertise their routes to the provider, and the provider router manages the VPN-specific routing tables, as well as distributing routes to remote sites. In a Layer 3 Internet Protocol (IP) VPN, customer sites are connected via IP routers that can communicate privately over a shared backbone as if they are using their own private network. Multi-protocol label switching (MPLS) Border Gateway Protocol (BGP) networks are one type of L3VPN solution. An example of an IP-based Virtual Private Network is disclosed in U.S. Pat. No. 6,693,878. U.S. Pat. No. 6,665,273 describes a MPLS system with a network device for traffic engineering.
Virtual Private LAN Service (VPLS) has recently generated interest with enterprises and service providers as it offers multipoint Ethernet LAN services, often referred to as Transparent LAN Service (TLS), over MPLS networks. VPLS is an architecture that delivers a Layer 2 multipoint VPN service that in all respects emulates an Ethernet LAN across a wide metropolitan geographic area. All services in a VPLS appear to be on the same LAN, regardless of location. In other words, with VPLS, customers can communicate as if they were connected via a private Ethernet segment, i.e., multipoint Ethernet LAN services. VPLS thus supports the connection of multiple sites in a single bridged domain over a managed IP/MPLS network.
FIG. 1 illustrates an example of a basic VPLS architecture with an IP or MPLS service provider network core. The customer sites (i.e., CE devices) are connected to the service provider network at a PE device. Each PE-CE pair is shown connected by an Attachment Circuit (AC). An AC is the customer connection to a service provider network; that is, the connection between a CE and its associated PE. An AC may be a physical port, or a virtual port, and may be any transport technology, i.e., Frame Relay, ATM, Ethernet VLAN, etc. In the context of a VPLS, an AC is typically an Ethernet port. In the example of FIG. 1, each PE includes a Virtual Switch Instance (VSI) that emulates an Ethernet bridge (i.e., switch) function in terms of MAC address learning and forwarding in order to facilitate the provision of a multi-point L2VPN. A pseudowire (PW) is shown connecting every two VSIs. A PW is a virtual connection that is bi-directional in nature and, in this example, consists of a pair of unidirectional MPLS Virtual Circuits (VCs).
Conceptually in context of the VPLS service, a PW can be thought of as point-to-point virtual link for each offered service between a pair of VSIs. Therefore, if each VSI can be thought of as a virtual Ethernet switch for a given customer service instance, then each PW can be thought of as a virtual link connecting these virtual switches to each other for that service instance.
Another type of provider provisioned VPN architecture that uses PWs is the Virtual Private Wire Service (VPWS). VPWS is a Layer 2 service that provides point-to-point connectivity (e.g., Frame Relay, ATM, point-to-point Ethernet) and can be used to create port-based or VLAN-based Ethernet private lines across a MPLS-enabled IP network. Conceptually, in the context of the VPWS service, a PW can be thought of as a point-to-point virtual link connecting two customer ACs. After a PW is setup between a pair of PEs, frames received by one PE from an AC are encapsulated and sent over the PW to the remote PE, where native frames are reconstructed and forwarded to the other CE. All PEs in the SP network are connected together with a set of tunnels, with each tunnel carrying multiple PWs. Depending on the number of customer sites and the topology for connecting these sites, the number of PWs setup for a given customer can range from two, for a customer with only two sites, to many PWs for a customer who has locations connected to every PE.
For an Ethernet network to function properly, only one active path can exist between any two nodes. To provide path redundancy and prevent undesirable loops in the network topology caused by multiple active paths, Ethernet networks typically employ Spanning Tree Protocol (STP), or some variant of STP, e.g., MSTP or RSTP. (For purposes of the present application, STP and its variants are generically denoted by the acronym “xSTP”.) Switches in a network running STP gather information about other switches in the network through an exchange of data messages called Bridge Protocol Data Units (BPDUs). BPDUs contain information about the transmitting switch and its ports, including its switch and port Media Access Control (MAC) addresses and priorities. The exchange of BPDU messages results in the election of a root bridge on the network, and computation of the best path from each switch to the root switch. To provide path redundancy, STP defines a tree from the root that spans all of the switches in the network, with certain redundant paths being forced into a standby (i.e., blocked) state. If a particular network segment becomes unreachable the STP algorithm reconfigures the tree topology and re-establishes the link by activating an appropriate standby path. Examples of networks that run STP are disclosed in U.S. Pat. Nos. 6,519,231, 6,188,694 and 6,304,575.
A redundancy mechanism for Virtual Private LAN Service with Ethernet access network is described in Section 11.2 of the Internet Engineering Task Force (IETF) document draft-ietf-l2vpn-vpls-ldp-01.txt. The redundancy mechanism described in that draft leverages the use of xSTP on the Ethernet bridges in the access network as well on the PEs to provide a failure recovery mechanism for link and node failures. According to this approach, each network-facing PE (n-PE) runs xSTP such that each BPDU packet is terminated by the receiving n-PE and the information in the BPDU packet is processed by the n-PE. The n-PE then originates a new BPDU packet using the newly processed information. The main drawback of this mechanism is that it requires every node in the Ethernet access network, including n-PE devices, to execute the spanning-tree protocol. However, certain platforms (e.g., with router-based platforms) utilize n-PE devices that are not equipped to run xSTP protocols. These platforms would require costly xSTP-related software development in order to run xSTP protocols.
Thus, there is a need for alternative methods and apparatus that achieve redundancy functionality for VPLS services with Ethernet access networks, while obviating the need to run xSTP protocols on the n-PEs.


Gastric metaplasia and small bowel ulcerogenesis in a case of ulcerative jejunitis not related to celiac disease.
The possible relationship between gastric metaplasia and ulcerative lesions in an unusual case of ulcerative jejunitis not related to celiac disease and with extensive gastric metaplasia is discussed. Previous studies have described gastric metaplasia in duodenal ulcers on the basis of endoscopic data, and some authors maintain that acid secretion in metaplastic mucosa could represent a pathogenetic factor of ulcerogenesis, with a self-amplifying mechanism. In the absence of functional evidence, we could provide data, in a case of ulcerative jejunitis, about morphologic signs of acid secretion in gastric metaplastic epithelium using an antibody against HMFG-1, a good marker of acid-secreting fundic cells. Metaplastic areas demonstrated a focal positivity for HMFG-1, and these finding are suggestive of local acid secretion.


Back here at home a wakeup call from triple a. We have been warned about texting while driving. Now there's a new study about hands free devices and something called a kind of blindness behind the wheel which is where we find david kerley tonight. Reporter: So how many electrodes are you putting on? I am getting wired for research. I'm going to go ahead and stretch this over your head. Reporter: Maybe not a great look. I'm going to go ahead and put the chin strap on. Reporter: But all these connections -- go ahead and scan your eyes to the left and right as far as you can. Reporter: Will measure how much my brain can handle behind the wheel. Reaction time. Where my eyes look. Nine million cars today -- 62 million in five years -- will have systems that let you talk to your car so you can keep your hands on the wheel, but is it safer? 62 million in five years. Is it safer? With a small button on my thumb, I click when a green light flashes, simulating something on the road that needs my attention. I drive listening to the radio. Then another trip, with speech to text, hearing and answering email. Hey, I haven't heard from you in a while. Reporter: Reply. Okay, what would you like to say? I'll talk to you soon. Send. I clicked the button, but -- how did I do, joel? Your response times were a bit delayed when you are engaged in that speech to text task. Reporter: Here's what researchers for aaa found -- the least amount of distraction was the radio going up the scale, talking on a hands-free phone, talking to a passenger, a handheld phone was next. But it's those speech to text programs causing the most distraction. A fraction of a second. It can be dangerous. They call it, "inattention blindess." Even if your hands are on the wheel and your eyes are on the road, you may not be safe. Reporter: Automakers say the study sends a misleading message, suggesting hands-free and handheld devices are equally risky. The risk, says aaa, is that these systems sold as safe may really lead us -- Reporter: -- To distraction. Your next message is loading. Next a moment of terror 46

This transcript has been automatically generated and may not be 100% accurate.

Hands-Free Technology May Be Biggest Driving Distraction

ABC News' David Kerley helps test voice-activated gadgets designed to keep drivers' eyes on the road

{"id":19386520,"title":"The Distracted Brain and Driving","duration":"1:51","description":"Texting, talking and even listening to the radio may be dangerously distracting while driving a car.","section":"WNT","mediaType":"Default"}


---
  name: "Peter Linss"
  link: "https://twitter.com/plinss"
  github: "plinss"
---


Batman and Robin were at hand to help police (Picture: BBC Archive)

A team of ‘superheroes’ were on hand to help police following reports of an assault at a Tesco supermarket.

Officers in East Lothian, Scotland, didn’t even need to send out a bat signal before two men in Batman and Robin fancy-dress jumped into action.

David Hasselhoff and a smurf were also on hand to help apprehend the attacker after the man dressed as Robin was assaulted in the toilet roll aisle in the Musselburgh store last week.

Robin assaulted, police called, collective assisted our foot chase, minor upset to shelving in tescos during arrest, you couldn't script it! — EastLothianPolice (@EastLothPolice) November 7, 2013

The incident came to light after East Lothian Police tweeted about it, thanking the fancy-dressed group for their help.

One tweet read: ‘Thank you to Batman, Robin, Robin’s Dad, a Smurf, and the Hoff for helping us on Friday night. #Tesco, sorry about the toilet roll aisle.’

Thank you to Batman, Robin, Robin's Dad, a Smurf, and the Hoff for helping us on Friday night. #Tesco, sorry about the toilet roll aisle. — EastLothianPolice (@EastLothPolice) November 6, 2013

Another tweet by police officers in East Lothian read: ‘Robin assaulted, police called, collective assisted our foot chase, minor upset to shelving in Tescos during arrest, you couldn’t script it!’

A Police Scotland spokesman said: ‘A 21-year-old man was arrested and charged in connection with an assault in Eskview Road, Musselburgh, on Friday 1 November.

A man dressed as David Hasselhoff was also at the scene (Picture: Daily Mail / Steve Poole)

‘He was remanded in custody until Monday 4th November, where he appeared in court and pled guilty to the offence.’


Still Alice

There is a moment in Still Alice where directors Richard Glatzer and Wash Westmoreland plant the camera over Alice’s (Julianne Moore) shoulder as she sits in a chair. In the background are blurred images of her husband and children in conversation at the dinner table. They talk frankly about Alice as if she is not even in the room. In some ways she is not. Her distressed eyes are focused, as if searching for something that is just out of reach, but clearly her mind is some place else. She has become a shell of the woman they have known and loved for years; replaced by a stranger whose void face now bears a harsh reminder of the cruel and inexplicable nature of life.

It is a scene that is all too familiar, uncomfortably so in fact, to those who have had Alzheimer’s stricken a family member. It is a simple, but powerful, moment that Moore plays perfectly. As she does with most of the film, Moore brings a subtle sadness to the scene. Though her family is discussing how Alice’s condition is impacting their lives, it is Alice herself who we feel most connected to. Alice brings a human face to the illness; showing what it is like for those suffering with the disease to watch their world quickly erode around them.

Based on Lisa Genova’s novel of the same name, Still Alice is a somber reminder that life can change on the dime for all of us. Dr. Alice Howland is a renowned linguistics professor at Columbia University who lives a rather comfortable life with her husband (Alec Baldwin). Amongst her many academic achievements, Alice takes great pride in the fact that her three grown children (Kristen Stewart, Kate Bosworth and Hunter Parrish) are rather well-adjusted. Alice’s serene life is abruptly rattled when she is diagnosed with early onset Alzheimer’s.

Arriving 15 years earlier than it does for most sufferers of the disease, Alice struggles to maintain a normal life. As the illness has a tendency to be accelerated in individuals who are of higher functioning intelligence, Alice and her family are not prepared for the swift decline of her mental state. Soon Alice begins forgetting simple things such as where the bathroom in her house is located and conversations she had moments earlier. Despite her determination to combat the disease, Alice knows that these are all signs of an uphill battle in which the odds are stacked against her.

Still Alice is one of those films that essentially sinks or swims on the strength of the performances. Julianne Moore is sensational as Alice, bringing a bittersweet honesty to the role. Although the disease impacts Alice’s life faster than expected, Moore ensures that we have time to process every subtle change the character goes through. Every missing word hangs ominously in the air like dense fog, and Alice’s longing glaze, often devoid of recognition, is like an emotional punch to the gut. It is tough not to watch Moore embody the character without reflecting on those in our own lives who have battled with Alzheimer’s and other debilitating illnesses.

The downside is that once you look past Moore’s riveting work, it becomes apparent that Still Alice is not as tightly woven as it should be. While there is a rich honesty to the film, it is hard to shake the feeling that we have seen this all before. Glatzer and Westmoreland clearly understand the hardships that come with illness, but the film lacks that extra dramatic punch to truly make it soar. Instead it hits the familiar beats that one would expect. This is especially evident in how underutilized the supporting cast is. It is understandable that Glatzer and Westmoreland would give Moore plenty of room to develop the nuances of her character, but it is a shame that the likes of Baldwin and Stewart were not given meatier roles to chew on. As a result, Still Alice has several moments where the film is simply spinning its wheels in hopes of gripping onto one of Moore’s heartbreaking moments.

Without Julianne Moore’s restrained and moving performance, Still Alice would not be nearly as effective as it is. Sure the earnestness of it should be commended, but that alone does not make an engaging film. Glatzer and Westmoreland’s familiar rhythm needed a few more dramatic moments to give the film a much needed jolt of energy and pathos. Fortunately, Moore is at the top of her craft and is convincing enough to makes us forget the film’s shortcomings. She reminds us that, at the end of the day, it is the people who are afflicted with Alzheimer’s whose plight we should be trying our best to understand.

Like this:

LikeLoading...

Related

Published by Courtney Small

The founder of Cinema Axis, Courtney is a Rotten Tomatoes approved critic who can frequently be heard discussing film as co-host of Frameline on Radio Regent. Courtney has contributed to several publications including Leonard Maltin, In the Seats, That Shelf, Black Girl Nerds, and Comix Asylum. He also celebrates diversity in cinema as co-host of the Changing Reels podcast and is a member of the Online Film Critics Society.
View all posts by Courtney Small

Post navigation

6 Comments

Nice review. Perhaps, finally, a statue for Ms. Moore? I remember the film
‘Away from Her’ starring Julie Christie who battles with Alzheimer and gave a fine performance, as well. The whole film was solid, albeit depressing. How do you compare the two films?

It is stunning that Moore has not won an Oscar yet, especially considering her outstanding body of work. Only time will tell if this is the role that finally does it for her. In regards to how the film stacks up against ‘Away from Her’, Sarah Polley’s film tackled the subject matter in a more interesting and engaging way.

Moore is great in this and it’s a true testament to the kind of actress she is that she doesn’t make Alice out to be some kind of angel. She’s just a normal, everyday woman who, sadly, has this life-altering disease and knows that it’s going to ruin her life, slowly, but surely. Good review.

In a role such as the one Moore plays in the film it is easy to forget the importance of subtly on screen. She tackles each moment with grace. Other actresses would have tried to play several of those scenes far bigger than they needed to be.

Excellent review, I’ll definitely get around to checking out Still Alice and Moore’ stand out performance, she’s consistently great in everything I’ve seen her in. I used to volunteer at an old age home and it’s really quite disheartening seeing first hand how fast and dramatic Alzheimer’s can progress.


Welcome to õ.com!

The name of this domain is õ.com; it is an
Internationalized Domain Name
(IDN). According to the
Unicode
standard, the name for the õ character is "Latin small letter o with tilde".
One way to reach this domain is to type the
punycode
representation xn--mda.com in your
browser bar. The Unicode code point for this
character is U+00F5.

The character õ (capital form: Õ) is used in a number of
languages, including Estonian,
Vietnamese, and Portuguese. For more information,
see the article on this character in
Wikipedia.


North Carolina Gives Illegals the Right to Drive

August 7, 2001

Hundreds of thousands of illegal immigrants have taken advantage of North Carolina's liberal rules for obtaining a driver's license, allowing them at least partial entry into the mainstream of the United States and raising their earning power. Officials believe it is in the state's interest if all drivers have insurance and learn the laws of the road.

Officials of the Immigration and Naturalization Service aren't happy with licensing procedures like North Carolina's, but they say there is nothing they can do about it.

Tennessee granted licenses to illegals in May, and the legislatures of California and Texas have also voted to grant the same privileges -- though the governors of the latter two states vetoed the measures.

And some states, including Georgia, Minnesota and South Carolina, have made licenses far more difficult to obtain for those who can't document their legal status.

South Carolina's motor vehicle division, for example, requires applicants to produce either a Social Security card or a letter from the Social Security Administration stating the applicant is in the country legally.

Meanwhile, North Carolina accepts Mexican military I.D. cards or voter registration cards from other countries.

Since 1997, North Carolina has issued 400,000 licenses and I.D. cards to people lacking Social Security numbers, about 260,000 of them Hispanic. The state acknowledges some were not North Carolina residents.

Source: David Firestone, "In U.S. Illegally, Immigrants Get License to Drive," New York Times, August 4, 2001.


Steroid receptors in human renal carcinoma.
Glucocorticoid- and androgen-binding receptors were demonstrated in cytosol of human renal cell carcinomas by the dextran-coated charcoal technique. Sedimentation studies using preparative ultracentrifugation indicated a 7 to 8 S binding component. None of the renal carcinoma cells tested contained detectable estrogen receptors and a few samples had a very low but demonstrable progestin receptor level. In the normal kidneys tested, cytoplasmic components that bound only androgen could be detected. Competition studies showed that progestin competed for the glucocorticoid receptor sites in all the renal tumors tested, whereas diethylstilbestrol and testosterone were weak or not competitive. It is suggested that the response of some patients with renal carcinoma to high doses of progesterone or androgens could be explained by the ability of these hormones to block the activity of glucocorticoid receptors, which might be involved in tumor growth.


# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

static_library("renderer") {
  sources = [
    "web_cache_impl.cc",
    "web_cache_impl.h",
  ]

  deps = [
    "//base",
    "//components/web_cache/public/interfaces",
    "//content/public/common",
    "//content/public/renderer",
    "//services/service_manager/public/cpp",
    "//third_party/WebKit/public:blink",
  ]
}


General Keith Alexander stresses common ground between US officials and hackers at Def Con gathering in Las Vegas

This article is more than 8 years old

This article is more than 8 years old

The head of the American government's secretive National Security Agency has taken the unprecedented step of asking a convention of computer hackers to join him in an effort to make the internet more secure.

In a speech to the 20th annual Def Con gathering in Las Vegas, the four-star general Keith Alexander stressed common ground between US officials and hackers, telling them privacy must be preserved and that they could help by developing new tools.

"You're going to have to come in and help us," Alexander told thousands of attendees.

The conference founder, Jeff Moss, known in hacking circles as the Dark Tangent, told the conference he had invited Alexander, who rarely gives speeches, because he wanted them to learn about one of the world's "spookiest, least known" organisations.

Attendees were respectful and gave modest applause, though several said they were concerned about secret government snooping and the failure of authorities thus far to stop foreign-backed attacks.

"Americans pay taxes so that federal agencies can defend them," said a researcher who asked not to be named. "I see it as a hard sell asking a business entity to spend money for the common good."

Alexander won points by wearing the hacker "uniform" of jeans and a tee shirt, wandering the halls and praising specific hacking efforts, including intrusion detection tools and advances in cryptology.

He also confronted civil liberties concerns that are a major issue for many researchers devoted to the internet.

Taking questions screened by Moss, Alexander denied that the NSA had dossiers on millions of Americans, as some former employees have suggested.

"The people who would say we are doing that should know better," he said. "That is absolute nonsense."

Alexander used the speech to lobby for a cyber security bill moving through the Senate that would make it easier for companies under attack to share information with the government and each other as well as give critical infrastructure owners some reward for adhering to future security standards.

"Both parties see this as a significant problem," he said, adding that the experts like those at Def Con should help in the process. "What are the standards that we should jointly set that critical networks should have?"

In addition to conducting electronic intelligence gathering, primarily overseas, the defence-department-controlled NSA is charged with protecting the American army from cyber-attacks.

Increasingly, it has been sharing its findings with the FBI to aid in criminal cases and with the department of homeland security, which warns specific industries of new threats.

Displaying a slide with the logos of several dozen of companies breached by criminals or spies in the past two years, Alexander said only the most competent even knew they had been hacked.

"There are 10 times, almost 100 times more companies that don't know they have been hacked," he said.


---
abstract: 'We have studied a three-unit-cell-thick YBa$_2$Cu$_3$O$_{7-\delta}$ (YBCO) superconducting film grown on a slightly vicinal SrTiO$_3$ substrate that was polished from the (001) plane by a small miscut angle (less than 0.5$^\circ$). This produced, on its surface, a linear array of single-unit-cell-height steps with a period larger than 40 nm. A characteristic fault, with a displacement corresponding to one-third of the [*c*]{}-axis length of YBCO, is generated in the film on each substrate step, as observed by atomic force microscopy. Transport measurements with current flows parallel and perpendicular to the fault show that the fault serves as a superconducting weak link, as well as a unique one-dimensional flux-pinning center in an applied magnetic field. In addition, a characteristic fine structure is found in the flux-flow resistivity as a function of magnetic field, the origin of which may be ascribed to a matching effect between the periodically aligned faults and the flux lattice.'
author:
- 'A. Tsurumaki'
- 'Z. Hiroi'
title: 'Superconducting weak link generated on a linear array of substrate steps in ultrathin films of YBa$_2$Cu$_3$O$_{7-\delta}$'
---

Extensive studies of various transition metal oxides have been carried out over the last decade using high-quality epitaxial thin films. Many interesting phenomena have been found, which only manifest themselves in thin films [@1]. In order to obtain a high-quality thin film, the surface of the substrate materials is absolutely important. For the (001) surface of SrTiO$_3$ (STO), which is the most typical substrate material, a method to obtain a nearly ideal surface with atomically flat terraces and steps has been established utilizing NH$_4$F-HF (BHF) etching [@2] and high-temperature annealing [@3]. However, there still remain single-unit-cell-height steps on the surface, which must be taken into account when one studies the property of an ultrathin film.

In this work we focus on a cupric oxide superconductor YBa$_2$Cu$_3$O$_{7-\delta}$ (YBCO) having essentially a two-dimensional electronic state. Thus far, a number of studies on YBCO in the form of ultrathin films have been performed [@4; @5; @6; @7]. For example, Matsuda [*et al*]{}. reported that the zero-resistivity temperature [*T*]{}$_{c0}$ of ultrathin YBCO films at the superconducting transition decreased with a decrease of the numbers of unit cell [*n*]{}; thus, [*T*]{}$_{c0}$ = 80, 63 and 30 K for [*n*]{} = 10, 3 and 1, respectively [@6]. This reduction of [*T*]{}$_{c0}$ has been explained by assuming the presence of a Kosterlitz-Thouless (KT) transition [@5; @6], or otherwise a depletion of carrier density by interfacial charge transfer [@7], neither of which consider possible influences from the substrate step. Since the [*c*]{}-axis length of YBCO (1.17 nm) is approximately triple that of STO (0.39 nm), the substrate step must generate a “fault" in a [*c*]{}-axis oriented YBCO film. As schematically depicted in Fig. \[fig1\](a), only one of the pair of CuO$_2$ planes in the unit cell can be connected with another plane terminating at the fault, and, thus, its influence on the superconducting properties must be serious for an ultrathin YBCO film.

On the other hand, several recent studies on the flux pinning in YBCO films have focused on the influence of the substrate step [@8; @9; @10; @11; @12]. They used vicinal STO substrates having large miscut angles of $\theta$ = 1 $\sim$ 8$^\circ$ off the (001) plane or the (106) surface ($\theta$ = 9.5$^\circ$). On the surface of these substrates, there are linear arrays of closely-spaced steps at intervals of 3 $\sim$ 18 nm. In thick YBCO films grown on them, structural faults generated by the substrate steps have been actually observed by means of cross-sectional transmission electron microscopy; these are called antiphase boundaries (APBs) [@8; @9; @10]. Interestingly, anisotropy in the critical current density, which depends on whether it is measured parallel or perpendicular to the step line, has been observed and ascribed to the anisotropic flux pinning caused by the APBs, as evidenced mostly by magneto-optical measurements [@8; @9; @10; @11; @12]. However, because the high-density steps often cause deterioration of the grown films [@8; @12], the true effect of the substrate steps may be obscured for such vicinal substrates. Moreover, macrosteps that have heights corresponding to multiple unit cells of STO [@10] exist on the surface of highly vicinal substrates. Thus, in order to investigate the influence of single-unit-cell-height substrate steps, it is necessary to use a substrate with a smaller miscut angle, which gives less step lines separated by a wider terrace on the surface. On the one hand, it has been reported that faults generated by the substrate steps tend to disappear as the film thickness increases above a few nanometers [@8; @9]. Therefore, the preparation of an ultrathin YBCO film is another key issue.

In this report, we have studied high-quality, ultrathin YBCO films grown on slightly vicinal STO (001) substrates, with miscut angles less than 0.5$^\circ$, to search for step-induced phenomena. A characteristic one-third structural fault is generated on each substrate step in the YBCO film, which gives rise to a superconducting weak link. In addition, a matching effect between the periodically aligned one-dimensional faults and the flux lattice is observed for flux-flow resistivity in applied magnetic fields.

Samples were prepared on miscut STO (001) substrates by the pulsed laser deposition method at a substrate temperature of 670$^\circ$C and in an oxygen pressure of 1.5 $\times$ 10$^{-2}$ torr including 9$\%$ of ozone. They consisted of three layers, Pr$_{1.1}$Ba$_{1.9}$Cu$_3$O$_{7-\delta}$ (PBCO) / YBCO / PBCO, with each having a thickness corresponding to three unit cells, as depicted schematically in Fig. \[fig1\](a). PBCO is a non-superconductor having the same crystal structure as YBCO and was used to provide buffer and cap layers, to reduce the strain in the YBCO layer from the substrate and to protect the surface of the YBCO layer. We used several STO substrates polished off the (001) plane approximately toward the \[100\] direction with miscut angles $\theta$ of 0.1 $\sim$ 0.5$^\circ$ (Shinkosha Co., Ltd.). Before the film growth, they were etched in a BHF solution and annealed at 820 $\sim$ 900$^\circ$C in 10$^{-6}$ torr O$_2$. The thickness of films grown was controlled by observing an oscillation in the reflection intensity from high-energy electron diffraction. The epitaxial [*c*]{}-axis oriented growth was confirmed by x-ray diffraction measurements.

\[t\] ![\[fig1\](a) Schematic drawing of a sample consisting of a three-unit-cell-thick YBCO layer sandwiched between two three-unit-cell-thick PBCO layers grown on a STO substrate with a periodic array of one-unit-cell-height steps. AFM images of the surfaces of a 0.1$^\circ$ miscut STO substrate and the first three-unit-cell PBCO layer are shown in (b) and (c), respectively. Directions parallel and perpendicular to the step line are denoted by [*L*]{} and [*T*]{}, respectively. A surface profile along the [*T*]{} direction is shown below each image.](fig1.eps "fig:"){width="7.9cm"}

Atomic force microscopy (AFM) has observed a quasi-periodic linear array of single-unit-cell-height steps on the surface of a clean STO substrate, typically as shown in Fig. \[fig1\](b). The average spacing of steps [*l*]{} is approximately 200 nm, which is close to the value 220 nm expected from $\theta$ = 0.1$^\circ$. In the case of a substrate with $\theta$ = 0.5$^\circ$, [*l*]{} was found to be 48 nm close to the expected value of 45 nm. All the steps have a height corresponding to a single unit cell, 0.39 nm, with no macrosteps observed. Even after the deposition of a three-unit-cell thick PBCO film on the STO substrate, a similar array of steps with nearly equal periodicity is observed, as shown in the AFM image of Fig. \[fig1\](c). Since the step height is the same as the pre-existing one on the STO substrate and is obviously smaller than the unit cell of PBCO, a one-third fault must have been generated within the PBCO layer on each substrate step, as schematically depicted in Fig. \[fig1\](a). Such 0.4 nm-height steps are also observed on the top surface of a tri-layered sample containing a total of nine unit cells of YBCO and PBCO, though the appearance in the AFM image becomes less clear. When the total film thickness is larger than $\sim$10 unit cells, other types of steps appear with a height corresponding to the unit cell of YBCO or PBCO. This means that, as the film thickness increases, the memory of the substrate step tends to be lost by the introduction of the extra atomic planes. Thus, the one-third fault can exist only in an ultrathin YBCO film.

Electrical resistivity measurements were carried out by the standard four-probe method in two directions, a longitudinal ([*L*]{}) direction along the step line and a transverse ([*T*]{}) direction perpendicular to the step line \[Fig. \[fig1\](b)\]. A sample was cut into a bar, approximately 0.7 mm $\times$ 3.3 mm, with the longer axis along either the [*L*]{} or [*T*]{} direction. Resistivity values were calculated by assuming a current flow only within the middle YBCO layer. This may be reasonable at low temperatures (below 100 K), because the resistivity of metallic YBCO is much lower than semiconducting PBCO. At high temperatures, however, this underestimates the resistivity of YBCO.

\[t\] ![\[fig2\]Temperature dependence of the resistivity of two samples, A and B, prepared using the same conditions, on 0.5$^\circ$ miscut substrates measured along the [*L*]{} and [*T*]{} directions. The lower temperature part of transition around [*T*]{}$_{c0}$ is enlarged in (b). An excitation current of 5 $\mu$A was used.](fig2.eps "fig:"){width="7.8cm"}

Figure \[fig2\] shows the temperature dependence of the resistivity of two samples A and B grown under the same conditions on STO substrates with $\theta$ = 0.5$^\circ$ ([*l*]{} = 48 nm) in the [*L*]{} and [*T*]{} directions. The two samples exhibit similar behavior, illustrating good reproducibility of the data. The onset of the superconducting transition is approximately 93 K for each sample and in each direction; the midpoint is 85.2 K (83.4 K) in the [*L*]{} direction and 84.8 K (81.9 K) in the [*T*]{} direction for sample A (B). Thus, there is almost no difference in [*T*]{}$_c$ between the two directions in each sample. The transition widths defined by 10 - 90$\%$ of the resistivity drop are also similar, about 6.0 K.

In sharp contrast, there is a marked difference near the [*T*]{}$_{c0}$ between the two directions, as shown in Fig. \[fig2\](b). In sample A, the resistivity reaches zero at 81 K for [*L*]{}, while, for [*T*]{}, a long tail appears down to [*T*]{}$_{c0}$ = 66 K, 15 K lower than for [*L*]{}. This is obviously due to the effects of the substrate step. Faults generated on the step probably act as superconducting weak links only for a current running perpendicular to the step line. In sample B, zero resistivity is attained at 80.5 K for [*L*]{} and 71.6 K for [*T*]{}. Thus, a resistivity tail is also present, but the shape of the tail is slightly different from that of sample A. We have observed similar tails for five samples grown on substrates with $\theta$ = 0.5$^\circ$, but only in the [*T*]{} direction.

In a previous study performed without taking care of the existence of substrate steps [@5; @6] the [*T*]{}$_{c0}$ of a three-unit-cell-thick YBCO film was reported to be 63 K, and the transition width was about 15 K. The [*T*]{}$_c$ onset ($\sim$80 K) and [*T*]{}$_{c0}$ (63 K) in their sample coincide with our [*T*]{}$_{c0}$ values for the [*L*]{} and [*T*]{} directions, respectively. This suggests that the low [*T*]{}$_{c0}$ value is due to the influence of the substrate step. Since there will have existed randomly oriented steps on the polished surface of STO in the absence of an intentional miscut, the current always passed through step-induced faults in any in-plane direction. Therefore, the previously reported large decrease in [*T*]{}$_{c0}$ with decreasing film thickness may not be intrinsic, and its interpretation based on the KT transition should be reconsidered. As we have shown above, the intrinsic [*T*]{}$_{c0}$ value of the three-unit-cell-thick YBCO film is as high as 80 K, as obtained for the [*L*]{} direction free from disturbance by the substrate step.

It is to be noted in Fig. \[fig2\](a) that there is anisotropy in the normal-state resistivity between the [*L*]{} and [*T*]{} directions. The anisotropy $\rho_T$ / $\rho_L$ is approximately 2 for both samples A and B at 100 K. We found nearly equal ratios for 12 samples grown on various substrates with [*l*]{} = 42 $\sim$ 277 nm ($\theta$ = 0.1 $\sim$ 0.5$^\circ$), implying that the ratio is independent of [*l*]{}. Thus, this anisotropy must come from the bulk properties. Similar anisotropy of 1.5-5.5 was reported in previous studies for thicker films on substrates with large $\theta$, which was partly attributed to the contribution from the [*c*]{}-axis conduction to the resistivity only in the [*T*]{} direction [@8; @12]. However, this contribution is negligibly small in the present samples: given the ratio 100 between the resistivities along the [*c*]{}-axis and the [*ab*]{} plane in bulk YBCO, $\rho_T$ / $\rho_L$ is calculated to be 1.008 for $\theta$ = 0.5$^\circ$, using the equation given by Haage [*et al*]{}. [@8]. Alternatively, the origin of this resistivity anisotropy may be explained by assuming the preferred orientation of CuO chains along the substrate step. It is known that the [*b*]{}-axis resistivity in YBCO is about half that of the [*a*]{}-axis resistivity because of the contribution of the CuO chains [@13]. Moreover, such a preferred orientation has been actually reported in YBCO thick films grown on vicinal substrates with large miscut angles [@14; @15].

\[t\] ![\[fig3\]Magnetic-field dependence of resistivity for sample B measured at 70 K. The low-resistivity part is enlarged in (b). Experimental geometries for the [*L*]{} and [*T*]{} measurements are depicted in the inset of (a), where [*I*]{}, [*B*]{} and [*F*]{} denote current, magnetic field and the resulting Lorentz force. Two datasets measured with increasing and decreasing field are shown; they overlap completely. Several dips observed only for [*T*]{} are indicated by arrows in (b).](fig3.eps "fig:"){width="7.5cm"}

We have noticed further interesting differences in the resistivity between the two directions measured in applied magnetic fields. Figure \[fig3\] shows the magnetic field dependence of the resistivity in the [*L*]{} and [*T*]{} directions for sample B measured at 70 K, just below [*T*]{}$_{c0}$ = 72 K for the [*T*]{} direction. Magnetic fields are applied perpendicular to the film surface. Zero resistivity is retained for the [*L*]{} direction up to a large magnetic field of 2 T within the experimental resolution, while, for the [*T*]{} direction, finite resistivity is induced by a small field of about 0.1 T. This finite resistivity must be due to a flux-flow resistivity, because the applied fields are small and the measured temperature is close to [*T*]{}$_{c0}$ for the [*T*]{} direction. The observed difference implies that the step-induced fault serves as a one-dimensional flux pinning center; the Lorentz force is perpendicular to the step line for [*L*]{}, but parallel for [*T*]{}, as depicted in the insets of Fig. \[fig3\](a). This implication from the transport measurements for an ultrathin YBCO film is consistent with previous results obtained by magneto-optical measurements on thick films grown on substrates with larger miscut angles [@8; @10; @11].

Remarkably, an additional feature is observed in the flux-flow resistivity measured in the [*T*]{} direction. There are many tiny dips at certain magnetic fields. The noise level in our measurements (5 $\times$ 10$^{-10}$ $\Omega$ cm) is much smaller than these structures. In addition, two datasets measured with increasing and decreasing fields overlap completely with a perfectly symmetric profile for the sign reversal of the magnetic field. The dips remain at the same fields at temperatures between 67 and 73 K, while they become less apparent at increasing temperature and finally disappear above 78 K. Increasing the excitation current also causes no change in the dip positions.

Since the dips are observed only in the flux-flow resistivity regime, the origin must be attributed to an enhancement of flux pinning at certain magnetic fields. The most probable explanation is a matching effect between the flux lattice and pinning centers. In previous experiments, the matching effect has been clearly observed both for conventional superconductors [@16] and high temperature superconductors [@17] by introducing artificial pinning centers arranged in forms such as a triangular lattice. In the present case, the nature of the pinning centers must be quite different from those studied previously since this is an array of one-dimensional structural faults generated by the substrate step. Thus, such a simple matching effect as in triangular defects should not occur.

A matching effect for a two-dimensional superconductor with one-dimensional pinning centers has been considered theoretically [@18]. Given the spacing of the step lines for sample B (48 nm) in the equation given by Martinoli [@18], we estimate possible matching fields for the triangular flux lattice as 111, 194, 259, 345, 444, 777 and 1036 mT. The observed magnetic fields for major dips are 100, 200, 240, 320, 380, 480, 580, 760, 870, 1075 and 1265 mT. Thus, many of them are successfully reproduced. Small differences between the observed and calculated fields may be understood by assuming a spontaneous small deformation of the flux lattice [@18]. However, the dips observed at 580, 870 and 1265 mT cannot be explained by this matching effect.

The occurrence of such unaccountable resistivity dips has been also reported for artificial triangular pinning centers. The origin is not clear, but may be ascribed to an enhanced matching related to interstitial flux [@16] or fractional matching effects [@19]. More complicated matching may be expected in the present case for an array of one-dimensional pinning centers. Alternatively, we have to take into account the fact that our natural system is not as structurally perfect as the artificial systems. The periodicity of steps may have a distribution and meandering of step lines can occur, as actually observed in Fig. \[fig1\](b). These inevitable imperfections would make the pinning properties complicated. Therefore, it is necessary to measure transport properties on smaller areas created using a micro fabrication technique, which will be the subject of future work.

In summary, we have introduced a one-dimensional array of one-third faults in three-unit-cell-thick YBCO films by utilizing one-unit-cell-height steps on slightly vicinal STO substrates. It is shown that this fault serves as a superconducting weak link for a current perpendicular to the fault, giving rise to a tail in the resistive transition. Furthermore, we find many dips in the flux-flow resistivity at specific magnetic fields, suggesting a unique matching effect between the linear array of faults and the flux lattice.

We thank Y. Murakoa for his contributions at the initial stage of this work. We also thank K. Hirata for helpful discussion. This work was supported by the Global COE Program “Physical Sciences Frontier", given by MEXT.

[19]{} natexlab\#1[\#1]{}bibnamefont \#1[\#1]{}bibfnamefont \#1[\#1]{}citenamefont \#1[\#1]{}url \#1[`#1`]{}urlprefix\[2\][\#2]{} \[2\]\[\][[\#2](#2)]{}

, ****, ().

, , , , , , , , , ****, ().

, , , , , , , ****, ().

, , , , , , ****, ().

, , , , , ****, ().

, , , , , , ****, ().

, , , , , ****, ().

, , , , , , , , , ****, ().

, , , , , ****, ().

, , , ****, ().

, , , , ****, ().

, , , ****, ().

, , , , ****, ().

, , , , ****, ().

, ****, ().

, , , , ****, ().

, , , , , ****, ().

, ****, ().

, , , ****, ().


Functional cerebral activity during regeneration from entorhinal lesions in the rat.
The consequences of an unilateral electrolytic entorhinal lesion on the functional activity in all major anatomically defined brain regions were evaluated in the rat. The 14C-2 deoxyglucose method served as a tool to quantify alterations of local cerebral glucose utilization (LCGU) ipsilateral and contralateral to the lesion at 4 days, 2 weeks, or 3 months after stereotaxic surgery. Apart from a few minor increases in the contralateral hemisphere, the predominant pattern consisted of reductions in the range of 10-40% in the ipsilateral hemisphere. Ipsilaterally, in extrahippocampal areas, LCGU had regained control levels at 2 weeks postlesion in contrast to hippocampal regions, where reductions were more pronounced than in other brain areas and partially persisted for up to 3 months. Interestingly, the termination zones of entorhinal fibers in the dentate gyrus did not regain control levels within 3 months. We conclude from the data that functional recovery of denervated primary target areas does not occur within 3 months after entorhinal lesions and that altered functional activity may be found beyond the primary target areas predominantly during the acute recovery period after the lesion. The data suggest that sprouting fibers do not reestablish a fully functional neuronal network during the recovery period.