text:
var AWS = require('aws-sdk'),
    s3 = new AWS.S3(),
    _ = require('underscore')._;

module.exports = function(settings) {

  return {
    log:log,
    get_changes:get_changes
  };

  function log(id, timestamp, callback) {
    s3.putObject({
      Bucket: settings.bucket,
      Key: timestamp+'-'+id,
      Body: ''
    }, function(error, data) {
      if(error) {
        console.log(error);
        callback({code:500,msgs:["S3 Logging Error"]});
      } else {
        callback(null);
      }
    });
  }

  function get_changes(from, to, callback) {

    var options = {
      Bucket: settings.bucket,
      MaxKeys: 100
    }
    if(settings.prefix) options.Prefix = settings.prefix;
    if(from) options.Marker = from+'';

    getList(to, options, function(error, data) {
      callback(error,data);
    });

  }

  function getList(to, options, callback) {
    var data = [];

    s3.listObjects(options, function(error, response) {
      if(error) {
        console.log(error);
        callback({code:500,msgs:["S3 List Error"]});
      } else {

        var lastKey = null;

        for(var x in response.Contents) {
          var key = response.Contents[x].Key;
          lastKey = key;
          var timestamp = key.substr(0,key.indexOf('-'));
          var id = key.substr(key.indexOf('-')+1);

          // Skip rows outside of our bounds
          console.log(to);
          console.log(timestamp);
          if(to && timestamp > to) return callback(null, data);

          data.push({
            timestamp: parseInt(timestamp),
            id: id
          });
        }

        if(lastKey && response.IsTruncated) {
          var newOptions = _.clone(options);
          newOptions.Marker = lastKey;

          getList(to, newOptions, function(error, moreData) {
            if(error) {
              callback(error);
            } else {
              callback(null,data.concat(moreData));
            }
          });

        } else {
          callback(null, data);
        }
      }

    });

  }

}


text:
layout: page
title: Orb Tone Entertainment Award Ceremony
date: 2016-05-24
author: William Fuentes
tags: weekly links, java
status: published
summary: Pellentesque quis lorem ac ante rhoncus ultrices eu.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 01/13/2019
  endDate: 01/16/2019
  ctyhocn: WASSSHX
  groupCode: OTEAC
published: true
---
Pellentesque scelerisque neque libero, vel mattis enim blandit et. Praesent facilisis blandit neque vel rutrum. Curabitur posuere tellus vel justo condimentum, in fermentum mi vulputate. Sed in tincidunt risus, ut blandit ligula. Nulla eget convallis augue, ut condimentum mi. Maecenas odio erat, luctus in purus eu, sagittis interdum elit. Sed ultricies convallis nisi eget imperdiet. Donec fermentum ultrices facilisis. Maecenas ultrices fringilla orci a maximus. Proin augue odio, aliquam id convallis fermentum, interdum vel justo.
Nullam lobortis suscipit dignissim. Maecenas blandit sapien tortor, at congue nunc condimentum et. Morbi sed ex eget turpis porttitor efficitur sed a turpis. Phasellus feugiat ultrices risus ac rhoncus. Suspendisse sit amet sapien tristique, ultrices sapien a, laoreet risus. Etiam pellentesque nibh sit amet nulla volutpat auctor. Mauris sodales arcu sit amet est varius tincidunt.

* Proin malesuada metus a fermentum ornare
* Duis euismod dui a tempor condimentum
* Curabitur viverra massa semper pellentesque imperdiet
* Cras tincidunt orci at dolor bibendum placerat.

In hac habitasse platea dictumst. Aliquam nec erat dui. Aenean scelerisque, felis in maximus ultricies, felis dolor consequat lacus, in ullamcorper elit diam et dui. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Suspendisse non ante urna. Vivamus imperdiet ultrices varius. Morbi non magna id sapien feugiat ornare.

redpajama_set_name: RedPajamaGithub


text:
namespace v8 {
namespace internal {
namespace compiler {

enum ImmediateMode {
  kArithmeticImm,  // 12 bit unsigned immediate shifted left 0 or 12 bits
  kShift32Imm,     // 0 - 31
  kShift64Imm,     // 0 - 63
  kLogical32Imm,
  kLogical64Imm,
  kLoadStoreImm8,   // signed 8 bit or 12 bit unsigned scaled by access size
  kLoadStoreImm16,
  kLoadStoreImm32,
  kLoadStoreImm64,
  kNoImmediate
};

// Adds Arm64-specific methods for generating operands.
class Arm64OperandGenerator FINAL : public OperandGenerator {
 public:
  explicit Arm64OperandGenerator(InstructionSelector* selector)
      : OperandGenerator(selector) {}

  InstructionOperand UseOperand(Node* node, ImmediateMode mode) {
    if (CanBeImmediate(node, mode)) {
      return UseImmediate(node);
    }
    return UseRegister(node);
  }

  bool CanBeImmediate(Node* node, ImmediateMode mode) {
    int64_t value;
    if (node->opcode() == IrOpcode::kInt32Constant)
      value = OpParameter<int32_t>(node);
    else if (node->opcode() == IrOpcode::kInt64Constant)
      value = OpParameter<int64_t>(node);
    else
      return false;
    return CanBeImmediate(value, mode);
  }

  bool CanBeImmediate(int64_t value, ImmediateMode mode) {
    unsigned ignored;
    switch (mode) {
      case kLogical32Imm:
        // TODO(dcarney): some unencodable values can be handled by
        // switching instructions.
        return Assembler::IsImmLogical(static_cast<uint64_t>(value), 32,
                                       &ignored, &ignored, &ignored);
      case kLogical64Imm:
        return Assembler::IsImmLogical(static_cast<uint64_t>(value), 64,
                                       &ignored, &ignored, &ignored);
      case kArithmeticImm:
        return Assembler::IsImmAddSub(value);
      case kShift32Imm:
        return 0 <= value && value < 32;
      case kShift64Imm:
        return 0 <= value && value < 64;
      case kLoadStoreImm8:
        return IsLoadStoreImmediate(value, LSByte);
      case kLoadStoreImm16:
        return IsLoadStoreImmediate(value, LSHalfword);
      case kLoadStoreImm32:
        return IsLoadStoreImmediate(value, LSWord);
      case kLoadStoreImm64:
        return IsLoadStoreImmediate(value, LSDoubleWord);
      case kNoImmediate:
        return false;
    }
    return false;
  }

 private:
  bool IsLoadStoreImmediate(int64_t value, LSDataSize size) {
    return Assembler::IsImmLSScaled(value, size) ||
           Assembler::IsImmLSUnscaled(value);
  }
};

static void VisitRRFloat64(InstructionSelector* selector, ArchOpcode opcode,
                           Node* node) {
  Arm64OperandGenerator g(selector);
  selector->Emit(opcode, g.DefineAsRegister(node),
                 g.UseRegister(node->InputAt(0)));
}

static void VisitRRR(InstructionSelector* selector, ArchOpcode opcode,
                     Node* node) {
  Arm64OperandGenerator g(selector);
  selector->Emit(opcode, g.DefineAsRegister(node),
                 g.UseRegister(node->InputAt(0)),
                 g.UseRegister(node->InputAt(1)));
}

static void VisitRRRFloat64(InstructionSelector* selector, ArchOpcode opcode,
                            Node* node) {
  Arm64OperandGenerator g(selector);
  selector->Emit(opcode, g.DefineAsRegister(node),
                 g.UseRegister(node->InputAt(0)),
                 g.UseRegister(node->InputAt(1)));
}

static void VisitRRO(InstructionSelector* selector, ArchOpcode opcode,
                     Node* node, ImmediateMode operand_mode) {
  Arm64OperandGenerator g(selector);
  selector->Emit(opcode, g.DefineAsRegister(node),
                 g.UseRegister(node->InputAt(0)),
                 g.UseOperand(node->InputAt(1), operand_mode));
}

template <typename Matcher>
static bool TryMatchShift(InstructionSelector* selector, Node* node,
                          InstructionCode* opcode, IrOpcode::Value shift_opcode,
                          ImmediateMode imm_mode,
                          AddressingMode addressing_mode) {
  if (node->opcode() != shift_opcode) return false;
  Arm64OperandGenerator g(selector);
  Matcher m(node);
  if (g.CanBeImmediate(m.right().node(), imm_mode)) {
    *opcode |= AddressingModeField::encode(addressing_mode);
    return true;
  }
  return false;
}

static bool TryMatchAnyShift(InstructionSelector* selector, Node* node,
                             InstructionCode* opcode, bool try_ror) {
  return TryMatchShift<Int32BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord32Shl, kShift32Imm,
                                          kMode_Operand2_R_LSL_I) ||
         TryMatchShift<Int32BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord32Shr, kShift32Imm,
                                          kMode_Operand2_R_LSR_I) ||
         TryMatchShift<Int32BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord32Sar, kShift32Imm,
                                          kMode_Operand2_R_ASR_I) ||
         (try_ror && TryMatchShift<Int32BinopMatcher>(
                         selector, node, opcode, IrOpcode::kWord32Ror,
                         kShift32Imm, kMode_Operand2_R_ROR_I)) ||
         TryMatchShift<Int64BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord64Shl, kShift64Imm,
                                          kMode_Operand2_R_LSL_I) ||
         TryMatchShift<Int64BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord64Shr, kShift64Imm,
                                          kMode_Operand2_R_LSR_I) ||
         TryMatchShift<Int64BinopMatcher>(selector, node, opcode,
                                          IrOpcode::kWord64Sar, kShift64Imm,
                                          kMode_Operand2_R_ASR_I) ||
         (try_ror && TryMatchShift<Int64BinopMatcher>(
                         selector, node, opcode, IrOpcode::kWord64Ror,
                         kShift64Imm, kMode_Operand2_R_ROR_I));
}

// Shared routine for multiple binary operations.
template <typename Matcher>
static void VisitBinop(InstructionSelector* selector, Node* node,
                       InstructionCode opcode, ImmediateMode operand_mode,
                       FlagsContinuation* cont) {
  Arm64OperandGenerator g(selector);
  Matcher m(node);
  InstructionOperand inputs[4];
  size_t input_count = 0;
  InstructionOperand outputs[2];
  size_t output_count = 0;
  bool try_ror_operand = true;

  if (m.IsInt32Add() || m.IsInt64Add() || m.IsInt32Sub() || m.IsInt64Sub()) {
    try_ror_operand = false;
  }

  if (g.CanBeImmediate(m.right().node(), operand_mode)) {
    inputs[input_count++] = g.UseRegister(m.left().node());
    inputs[input_count++] = g.UseImmediate(m.right().node());
  } else if (TryMatchAnyShift(selector, m.right().node(), &opcode,
                              try_ror_operand)) {
    Matcher m_shift(m.right().node());
    inputs[input_count++] = g.UseRegister(m.left().node());
    inputs[input_count++] = g.UseRegister(m_shift.left().node());
    inputs[input_count++] = g.UseImmediate(m_shift.right().node());
  } else if (m.HasProperty(Operator::kCommutative) &&
             TryMatchAnyShift(selector, m.left().node(), &opcode,
                              try_ror_operand)) {
    Matcher m_shift(m.left().node());
    inputs[input_count++] = g.UseRegister(m.right().node());
    inputs[input_count++] = g.UseRegister(m_shift.left().node());
    inputs[input_count++] = g.UseImmediate(m_shift.right().node());
  } else {
    inputs[input_count++] = g.UseRegister(m.left().node());
    inputs[input_count++] = g.UseRegister(m.right().node());
  }

  if (cont->IsBranch()) {
    inputs[input_count++] = g.Label(cont->true_block());
    inputs[input_count++] = g.Label(cont->false_block());
  }

  outputs[output_count++] = g.DefineAsRegister(node);
  if (cont->IsSet()) {
    outputs[output_count++] = g.DefineAsRegister(cont->result());
  }

  DCHECK_NE(0u, input_count);
  DCHECK_NE(0u, output_count);
  DCHECK_GE(arraysize(inputs), input_count);
  DCHECK_GE(arraysize(outputs), output_count);

  Instruction* instr = selector->Emit(cont->Encode(opcode), output_count,
                                      outputs, input_count, inputs);
  if (cont->IsBranch()) instr->MarkAsControl();
}

// Shared routine for multiple binary operations.
template <typename Matcher>
static void VisitBinop(InstructionSelector* selector, Node* node,
                       ArchOpcode opcode, ImmediateMode operand_mode) {
  FlagsContinuation cont;
  VisitBinop<Matcher>(selector, node, opcode, operand_mode, &cont);
}

template <typename Matcher>
static void VisitAddSub(InstructionSelector* selector, Node* node,
                        ArchOpcode opcode, ArchOpcode negate_opcode) {
  Arm64OperandGenerator g(selector);
  Matcher m(node);
  if (m.right().HasValue() && (m.right().Value() < 0) &&
      g.CanBeImmediate(-m.right().Value(), kArithmeticImm)) {
    selector->Emit(negate_opcode, g.DefineAsRegister(node),
                   g.UseRegister(m.left().node()),
                   g.TempImmediate(-m.right().Value()));
  } else {
    VisitBinop<Matcher>(selector, node, opcode, kArithmeticImm);
  }
}

void InstructionSelector::VisitLoad(Node* node) {
  MachineType rep = RepresentationOf(OpParameter<LoadRepresentation>(node));
  MachineType typ = TypeOf(OpParameter<LoadRepresentation>(node));
  Arm64OperandGenerator g(this);
  Node* base = node->InputAt(0);
  Node* index = node->InputAt(1);
  ArchOpcode opcode;
  ImmediateMode immediate_mode = kNoImmediate;
  switch (rep) {
    case kRepFloat32:
      opcode = kArm64LdrS;
      immediate_mode = kLoadStoreImm32;
      break;
    case kRepFloat64:
      opcode = kArm64LdrD;
      immediate_mode = kLoadStoreImm64;
      break;
    case kRepBit:  // Fall through.
    case kRepWord8:
      opcode = typ == kTypeInt32 ? kArm64Ldrsb : kArm64Ldrb;
      immediate_mode = kLoadStoreImm8;
      break;
    case kRepWord16:
      opcode = typ == kTypeInt32 ? kArm64Ldrsh : kArm64Ldrh;
      immediate_mode = kLoadStoreImm16;
      break;
    case kRepWord32:
      opcode = kArm64LdrW;
      immediate_mode = kLoadStoreImm32;
      break;
    case kRepTagged:  // Fall through.
    case kRepWord64:
      opcode = kArm64Ldr;
      immediate_mode = kLoadStoreImm64;
      break;
    default:
      UNREACHABLE();
      return;
  }
  if (g.CanBeImmediate(index, immediate_mode)) {
    Emit(opcode | AddressingModeField::encode(kMode_MRI),
         g.DefineAsRegister(node), g.UseRegister(base), g.UseImmediate(index));
  } else {
    Emit(opcode | AddressingModeField::encode(kMode_MRR),
         g.DefineAsRegister(node), g.UseRegister(base), g.UseRegister(index));
  }
}

void InstructionSelector::VisitStore(Node* node) {
  Arm64OperandGenerator g(this);
  Node* base = node->InputAt(0);
  Node* index = node->InputAt(1);
  Node* value = node->InputAt(2);

  StoreRepresentation store_rep = OpParameter<StoreRepresentation>(node);
  MachineType rep = RepresentationOf(store_rep.machine_type());
  if (store_rep.write_barrier_kind() == kFullWriteBarrier) {
    DCHECK(rep == kRepTagged);
    // TODO(dcarney): refactor RecordWrite function to take temp registers
    //                and pass them here instead of using fixed regs
    // TODO(dcarney): handle immediate indices.
    InstructionOperand temps[] = {g.TempRegister(x11), g.TempRegister(x12)};
    Emit(kArm64StoreWriteBarrier, g.NoOutput(), g.UseFixed(base, x10),
         g.UseFixed(index, x11), g.UseFixed(value, x12), arraysize(temps),
         temps);
    return;
  }
  DCHECK_EQ(kNoWriteBarrier, store_rep.write_barrier_kind());
  ArchOpcode opcode;
  ImmediateMode immediate_mode = kNoImmediate;
  switch (rep) {
    case kRepFloat32:
      opcode = kArm64StrS;
      immediate_mode = kLoadStoreImm32;
      break;
    case kRepFloat64:
      opcode = kArm64StrD;
      immediate_mode = kLoadStoreImm64;
      break;
    case kRepBit:  // Fall through.
    case kRepWord8:
      opcode = kArm64Strb;
      immediate_mode = kLoadStoreImm8;
      break;
    case kRepWord16:
      opcode = kArm64Strh;
      immediate_mode = kLoadStoreImm16;
      break;
    case kRepWord32:
      opcode = kArm64StrW;
      immediate_mode = kLoadStoreImm32;
      break;
    case kRepTagged:  // Fall through.
    case kRepWord64:
      opcode = kArm64Str;
      immediate_mode = kLoadStoreImm64;
      break;
    default:
      UNREACHABLE();
      return;
  }
  if (g.CanBeImmediate(index, immediate_mode)) {
    Emit(opcode | AddressingModeField::encode(kMode_MRI), g.NoOutput(),
         g.UseRegister(base), g.UseImmediate(index), g.UseRegister(value));
  } else {
    Emit(opcode | AddressingModeField::encode(kMode_MRR), g.NoOutput(),
         g.UseRegister(base), g.UseRegister(index), g.UseRegister(value));
  }
}

void InstructionSelector::VisitCheckedLoad(Node* node) {
  MachineType rep = RepresentationOf(OpParameter<MachineType>(node));
  MachineType typ = TypeOf(OpParameter<MachineType>(node));
  Arm64OperandGenerator g(this);
  Node* const buffer = node->InputAt(0);
  Node* const offset = node->InputAt(1);
  Node* const length = node->InputAt(2);
  ArchOpcode opcode;
  switch (rep) {
    case kRepWord8:
      opcode = typ == kTypeInt32 ? kCheckedLoadInt8 : kCheckedLoadUint8;
      break;
    case kRepWord16:
      opcode = typ == kTypeInt32 ? kCheckedLoadInt16 : kCheckedLoadUint16;
      break;
    case kRepWord32:
      opcode = kCheckedLoadWord32;
      break;
    case kRepFloat32:
      opcode = kCheckedLoadFloat32;
      break;
    case kRepFloat64:
      opcode = kCheckedLoadFloat64;
      break;
    default:
      UNREACHABLE();
      return;
  }
  Emit(opcode, g.DefineAsRegister(node), g.UseRegister(buffer),
       g.UseRegister(offset), g.UseOperand(length, kArithmeticImm));
}

void InstructionSelector::VisitCheckedStore(Node* node) {
  MachineType rep = RepresentationOf(OpParameter<MachineType>(node));
  Arm64OperandGenerator g(this);
  Node* const buffer = node->InputAt(0);
  Node* const offset = node->InputAt(1);
  Node* const length = node->InputAt(2);
  Node* const value = node->InputAt(3);
  ArchOpcode opcode;
  switch (rep) {
    case kRepWord8:
      opcode = kCheckedStoreWord8;
      break;
    case kRepWord16:
      opcode = kCheckedStoreWord16;
      break;
    case kRepWord32:
      opcode = kCheckedStoreWord32;
      break;
    case kRepFloat32:
      opcode = kCheckedStoreFloat32;
      break;
    case kRepFloat64:
      opcode = kCheckedStoreFloat64;
      break;
    default:
      UNREACHABLE();
      return;
  }
  Emit(opcode, g.NoOutput(), g.UseRegister(buffer), g.UseRegister(offset),
       g.UseOperand(length, kArithmeticImm), g.UseRegister(value));
}

template <typename Matcher>
static void VisitLogical(InstructionSelector* selector, Node* node, Matcher* m,
                         ArchOpcode opcode, bool left_can_cover,
                         bool right_can_cover, ImmediateMode imm_mode) {
  Arm64OperandGenerator g(selector);

  // Map instruction to equivalent operation with inverted right input.
  ArchOpcode inv_opcode = opcode;
  switch (opcode) {
    case kArm64And32:
      inv_opcode = kArm64Bic32;
      break;
    case kArm64And:
      inv_opcode = kArm64Bic;
      break;
    case kArm64Or32:
      inv_opcode = kArm64Orn32;
      break;
    case kArm64Or:
      inv_opcode = kArm64Orn;
      break;
    case kArm64Eor32:
      inv_opcode = kArm64Eon32;
      break;
    case kArm64Eor:
      inv_opcode = kArm64Eon;
      break;
    default:
      UNREACHABLE();
  }

  // Select Logical(y, ~x) for Logical(Xor(x, -1), y).
  if ((m->left().IsWord32Xor() || m->left().IsWord64Xor()) && left_can_cover) {
    Matcher mleft(m->left().node());
    if (mleft.right().Is(-1)) {
      // TODO(all): support shifted operand on right.
      selector->Emit(inv_opcode, g.DefineAsRegister(node),
                     g.UseRegister(m->right().node()),
                     g.UseRegister(mleft.left().node()));
      return;
    }
  }

  // Select Logical(x, ~y) for Logical(x, Xor(y, -1)).
  if ((m->right().IsWord32Xor() || m->right().IsWord64Xor()) &&
      right_can_cover) {
    Matcher mright(m->right().node());
    if (mright.right().Is(-1)) {
      // TODO(all): support shifted operand on right.
      selector->Emit(inv_opcode, g.DefineAsRegister(node),
                     g.UseRegister(m->left().node()),
                     g.UseRegister(mright.left().node()));
      return;
    }
  }

  if (m->IsWord32Xor() && m->right().Is(-1)) {
    selector->Emit(kArm64Not32, g.DefineAsRegister(node),
                   g.UseRegister(m->left().node()));
  } else if (m->IsWord64Xor() && m->right().Is(-1)) {
    selector->Emit(kArm64Not, g.DefineAsRegister(node),
                   g.UseRegister(m->left().node()));
  } else {
    VisitBinop<Matcher>(selector, node, opcode, imm_mode);
  }
}

void InstructionSelector::VisitWord32And(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);
  if (m.left().IsWord32Shr() && CanCover(node, m.left().node()) &&
      m.right().HasValue()) {
    uint32_t mask = m.right().Value();
    uint32_t mask_width = base::bits::CountPopulation32(mask);
    uint32_t mask_msb = base::bits::CountLeadingZeros32(mask);
    if ((mask_width != 0) && (mask_msb + mask_width == 32)) {
      // The mask must be contiguous, and occupy the least-significant bits.
      DCHECK_EQ(0u, base::bits::CountTrailingZeros32(mask));

      // Select Ubfx for And(Shr(x, imm), mask) where the mask is in the least
      // significant bits.
      Int32BinopMatcher mleft(m.left().node());
      if (mleft.right().IsInRange(0, 31)) {
        // Ubfx cannot extract bits past the register size, however since
        // shifting the original value would have introduced some zeros we can
        // still use ubfx with a smaller mask and the remaining bits will be
        // zeros.
        uint32_t lsb = mleft.right().Value();
        if (lsb + mask_width > 32) mask_width = 32 - lsb;

        Emit(kArm64Ubfx32, g.DefineAsRegister(node),
             g.UseRegister(mleft.left().node()),
             g.UseImmediate(mleft.right().node()), g.TempImmediate(mask_width));
        return;
      }
      // Other cases fall through to the normal And operation.
    }
  }
  VisitLogical<Int32BinopMatcher>(
      this, node, &m, kArm64And32, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical32Imm);
}

void InstructionSelector::VisitWord64And(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);
  if (m.left().IsWord64Shr() && CanCover(node, m.left().node()) &&
      m.right().HasValue()) {
    uint64_t mask = m.right().Value();
    uint64_t mask_width = base::bits::CountPopulation64(mask);
    uint64_t mask_msb = base::bits::CountLeadingZeros64(mask);
    if ((mask_width != 0) && (mask_msb + mask_width == 64)) {
      // The mask must be contiguous, and occupy the least-significant bits.
      DCHECK_EQ(0u, base::bits::CountTrailingZeros64(mask));

      // Select Ubfx for And(Shr(x, imm), mask) where the mask is in the least
      // significant bits.
      Int64BinopMatcher mleft(m.left().node());
      if (mleft.right().IsInRange(0, 63)) {
        // Ubfx cannot extract bits past the register size, however since
        // shifting the original value would have introduced some zeros we can
        // still use ubfx with a smaller mask and the remaining bits will be
        // zeros.
        uint64_t lsb = mleft.right().Value();
        if (lsb + mask_width > 64) mask_width = 64 - lsb;

        Emit(kArm64Ubfx, g.DefineAsRegister(node),
             g.UseRegister(mleft.left().node()),
             g.UseImmediate(mleft.right().node()), g.TempImmediate(mask_width));
        return;
      }
      // Other cases fall through to the normal And operation.
    }
  }
  VisitLogical<Int64BinopMatcher>(
      this, node, &m, kArm64And, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical64Imm);
}

void InstructionSelector::VisitWord32Or(Node* node) {
  Int32BinopMatcher m(node);
  VisitLogical<Int32BinopMatcher>(
      this, node, &m, kArm64Or32, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical32Imm);
}

void InstructionSelector::VisitWord64Or(Node* node) {
  Int64BinopMatcher m(node);
  VisitLogical<Int64BinopMatcher>(
      this, node, &m, kArm64Or, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical64Imm);
}

void InstructionSelector::VisitWord32Xor(Node* node) {
  Int32BinopMatcher m(node);
  VisitLogical<Int32BinopMatcher>(
      this, node, &m, kArm64Eor32, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical32Imm);
}

void InstructionSelector::VisitWord64Xor(Node* node) {
  Int64BinopMatcher m(node);
  VisitLogical<Int64BinopMatcher>(
      this, node, &m, kArm64Eor, CanCover(node, m.left().node()),
      CanCover(node, m.right().node()), kLogical64Imm);
}

void InstructionSelector::VisitWord32Shl(Node* node) {
  VisitRRO(this, kArm64Lsl32, node, kShift32Imm);
}

void InstructionSelector::VisitWord64Shl(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);
  if ((m.left().IsChangeInt32ToInt64() || m.left().IsChangeUint32ToUint64()) &&
      m.right().IsInRange(32, 63)) {
    // There's no need to sign/zero-extend to 64-bit if we shift out the upper
    // 32 bits anyway.
    Emit(kArm64Lsl, g.DefineAsRegister(node),
         g.UseRegister(m.left().node()->InputAt(0)),
         g.UseImmediate(m.right().node()));
    return;
  }
  VisitRRO(this, kArm64Lsl, node, kShift64Imm);
}

void InstructionSelector::VisitWord32Shr(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);
  if (m.left().IsWord32And() && m.right().IsInRange(0, 31)) {
    uint32_t lsb = m.right().Value();
    Int32BinopMatcher mleft(m.left().node());
    if (mleft.right().HasValue()) {
      uint32_t mask = (mleft.right().Value() >> lsb) << lsb;
      uint32_t mask_width = base::bits::CountPopulation32(mask);
      uint32_t mask_msb = base::bits::CountLeadingZeros32(mask);
      // Select Ubfx for Shr(And(x, mask), imm) where the result of the mask is
      // shifted into the least-significant bits.
      if ((mask_msb + mask_width + lsb) == 32) {
        DCHECK_EQ(lsb, base::bits::CountTrailingZeros32(mask));
        Emit(kArm64Ubfx32, g.DefineAsRegister(node),
             g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
             g.TempImmediate(mask_width));
        return;
      }
    }
  }
  VisitRRO(this, kArm64Lsr32, node, kShift32Imm);
}

void InstructionSelector::VisitWord64Shr(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);
  if (m.left().IsWord64And() && m.right().IsInRange(0, 63)) {
    uint64_t lsb = m.right().Value();
    Int64BinopMatcher mleft(m.left().node());
    if (mleft.right().HasValue()) {
      // Select Ubfx for Shr(And(x, mask), imm) where the result of the mask is
      // shifted into the least-significant bits.
      uint64_t mask = (mleft.right().Value() >> lsb) << lsb;
      uint64_t mask_width = base::bits::CountPopulation64(mask);
      uint64_t mask_msb = base::bits::CountLeadingZeros64(mask);
      if ((mask_msb + mask_width + lsb) == 64) {
        DCHECK_EQ(lsb, base::bits::CountTrailingZeros64(mask));
        Emit(kArm64Ubfx, g.DefineAsRegister(node),
             g.UseRegister(mleft.left().node()), g.TempImmediate(lsb),
             g.TempImmediate(mask_width));
        return;
      }
    }
  }
  VisitRRO(this, kArm64Lsr, node, kShift64Imm);
}

void InstructionSelector::VisitWord32Sar(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);
  // Select Sxth/Sxtb for (x << K) >> K where K is 16 or 24.
  if (CanCover(node, m.left().node()) && m.left().IsWord32Shl()) {
    Int32BinopMatcher mleft(m.left().node());
    if (mleft.right().Is(16) && m.right().Is(16)) {
      Emit(kArm64Sxth32, g.DefineAsRegister(node),
           g.UseRegister(mleft.left().node()));
      return;
    } else if (mleft.right().Is(24) && m.right().Is(24)) {
      Emit(kArm64Sxtb32, g.DefineAsRegister(node),
           g.UseRegister(mleft.left().node()));
      return;
    }
  }
  VisitRRO(this, kArm64Asr32, node, kShift32Imm);
}

void InstructionSelector::VisitWord64Sar(Node* node) {
  VisitRRO(this, kArm64Asr, node, kShift64Imm);
}

void InstructionSelector::VisitWord32Ror(Node* node) {
  VisitRRO(this, kArm64Ror32, node, kShift32Imm);
}

void InstructionSelector::VisitWord64Ror(Node* node) {
  VisitRRO(this, kArm64Ror, node, kShift64Imm);
}

void InstructionSelector::VisitInt32Add(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);
  // Select Madd(x, y, z) for Add(Mul(x, y), z).
  if (m.left().IsInt32Mul() && CanCover(node, m.left().node())) {
    Int32BinopMatcher mleft(m.left().node());
    Emit(kArm64Madd32, g.DefineAsRegister(node),
         g.UseRegister(mleft.left().node()),
         g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node()));
    return;
  }
  // Select Madd(x, y, z) for Add(x, Mul(x, y)).
  if (m.right().IsInt32Mul() && CanCover(node, m.right().node())) {
    Int32BinopMatcher mright(m.right().node());
    Emit(kArm64Madd32, g.DefineAsRegister(node),
         g.UseRegister(mright.left().node()),
         g.UseRegister(mright.right().node()), g.UseRegister(m.left().node()));
    return;
  }
  VisitAddSub<Int32BinopMatcher>(this, node, kArm64Add32, kArm64Sub32);
}

void InstructionSelector::VisitInt64Add(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);
  // Select Madd(x, y, z) for Add(Mul(x, y), z).
  if (m.left().IsInt64Mul() && CanCover(node, m.left().node())) {
    Int64BinopMatcher mleft(m.left().node());
    Emit(kArm64Madd, g.DefineAsRegister(node),
         g.UseRegister(mleft.left().node()),
         g.UseRegister(mleft.right().node()), g.UseRegister(m.right().node()));
    return;
  }
  // Select Madd(x, y, z) for Add(x, Mul(x, y)).
  if (m.right().IsInt64Mul() && CanCover(node, m.right().node())) {
    Int64BinopMatcher mright(m.right().node());
    Emit(kArm64Madd, g.DefineAsRegister(node),
         g.UseRegister(mright.left().node()),
         g.UseRegister(mright.right().node()), g.UseRegister(m.left().node()));
    return;
  }
  VisitAddSub<Int64BinopMatcher>(this, node, kArm64Add, kArm64Sub);
}

void InstructionSelector::VisitInt32Sub(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);

  // Select Msub(a, x, y) for Sub(a, Mul(x, y)).
  if (m.right().IsInt32Mul() && CanCover(node, m.right().node())) {
    Int32BinopMatcher mright(m.right().node());
    Emit(kArm64Msub32, g.DefineAsRegister(node),
         g.UseRegister(mright.left().node()),
         g.UseRegister(mright.right().node()), g.UseRegister(m.left().node()));
    return;
  }

  if (m.left().Is(0)) {
    Emit(kArm64Neg32, g.DefineAsRegister(node),
         g.UseRegister(m.right().node()));
  } else {
    VisitAddSub<Int32BinopMatcher>(this, node, kArm64Sub32, kArm64Add32);
  }
}

void InstructionSelector::VisitInt64Sub(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);

  // Select Msub(a, x, y) for Sub(a, Mul(x, y)).
  if (m.right().IsInt64Mul() && CanCover(node, m.right().node())) {
    Int64BinopMatcher mright(m.right().node());
    Emit(kArm64Msub, g.DefineAsRegister(node),
         g.UseRegister(mright.left().node()),
         g.UseRegister(mright.right().node()), g.UseRegister(m.left().node()));
    return;
  }

  if (m.left().Is(0)) {
    Emit(kArm64Neg, g.DefineAsRegister(node), g.UseRegister(m.right().node()));
  } else {
    VisitAddSub<Int64BinopMatcher>(this, node, kArm64Sub, kArm64Add);
  }
}

void InstructionSelector::VisitInt32Mul(Node* node) {
  Arm64OperandGenerator g(this);
  Int32BinopMatcher m(node);

  if (m.left().IsInt32Sub() && CanCover(node, m.left().node())) {
    Int32BinopMatcher mleft(m.left().node());

    // Select Mneg(x, y) for Mul(Sub(0, x), y).
    if (mleft.left().Is(0)) {
      Emit(kArm64Mneg32, g.DefineAsRegister(node),
           g.UseRegister(mleft.right().node()),
           g.UseRegister(m.right().node()));
      return;
    }
  }

  if (m.right().IsInt32Sub() && CanCover(node, m.right().node())) {
    Int32BinopMatcher mright(m.right().node());

    // Select Mneg(x, y) for Mul(x, Sub(0, y)).
    if (mright.left().Is(0)) {
      Emit(kArm64Mneg32, g.DefineAsRegister(node),
           g.UseRegister(m.left().node()),
           g.UseRegister(mright.right().node()));
      return;
    }
  }

  VisitRRR(this, kArm64Mul32, node);
}

void InstructionSelector::VisitInt64Mul(Node* node) {
  Arm64OperandGenerator g(this);
  Int64BinopMatcher m(node);

  if (m.left().IsInt64Sub() && CanCover(node, m.left().node())) {
    Int64BinopMatcher mleft(m.left().node());

    // Select Mneg(x, y) for Mul(Sub(0, x), y).
    if (mleft.left().Is(0)) {
      Emit(kArm64Mneg, g.DefineAsRegister(node),
           g.UseRegister(mleft.right().node()),
           g.UseRegister(m.right().node()));
      return;
    }
  }

  if (m.right().IsInt64Sub() && CanCover(node, m.right().node())) {
    Int64BinopMatcher mright(m.right().node());

    // Select Mneg(x, y) for Mul(x, Sub(0, y)).
    if (mright.left().Is(0)) {
      Emit(kArm64Mneg, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
           g.UseRegister(mright.right().node()));
      return;
    }
  }

  VisitRRR(this, kArm64Mul, node);
}

void InstructionSelector::VisitInt32MulHigh(Node* node) {
  // TODO(arm64): Can we do better here?
  Arm64OperandGenerator g(this);
  InstructionOperand const smull_operand = g.TempRegister();
  Emit(kArm64Smull, smull_operand, g.UseRegister(node->InputAt(0)),
       g.UseRegister(node->InputAt(1)));
  Emit(kArm64Asr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32));
}

void InstructionSelector::VisitUint32MulHigh(Node* node) {
  // TODO(arm64): Can we do better here?
  Arm64OperandGenerator g(this);
  InstructionOperand const smull_operand = g.TempRegister();
  Emit(kArm64Umull, smull_operand, g.UseRegister(node->InputAt(0)),
       g.UseRegister(node->InputAt(1)));
  Emit(kArm64Lsr, g.DefineAsRegister(node), smull_operand, g.TempImmediate(32));
}

void InstructionSelector::VisitInt32Div(Node* node) {
  VisitRRR(this, kArm64Idiv32, node);
}

void InstructionSelector::VisitInt64Div(Node* node) {
  VisitRRR(this, kArm64Idiv, node);
}

void InstructionSelector::VisitUint32Div(Node* node) {
  VisitRRR(this, kArm64Udiv32, node);
}

void InstructionSelector::VisitUint64Div(Node* node) {
  VisitRRR(this, kArm64Udiv, node);
}

void InstructionSelector::VisitInt32Mod(Node* node) {
  VisitRRR(this, kArm64Imod32, node);
}

void InstructionSelector::VisitInt64Mod(Node* node) {
  VisitRRR(this, kArm64Imod, node);
}

void InstructionSelector::VisitUint32Mod(Node* node) {
  VisitRRR(this, kArm64Umod32, node);
}

void InstructionSelector::VisitUint64Mod(Node* node) {
  VisitRRR(this, kArm64Umod, node);
}

void InstructionSelector::VisitChangeFloat32ToFloat64(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float32ToFloat64, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeInt32ToFloat64(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Int32ToFloat64, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeUint32ToFloat64(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Uint32ToFloat64, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeFloat64ToInt32(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64ToInt32, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeFloat64ToUint32(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64ToUint32, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeInt32ToInt64(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Sxtw, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitChangeUint32ToUint64(Node* node) {
  Arm64OperandGenerator g(this);
  Node* value = node->InputAt(0);
  switch (value->opcode()) {
    case IrOpcode::kWord32And:
    case IrOpcode::kWord32Or:
    case IrOpcode::kWord32Xor:
    case IrOpcode::kWord32Shl:
    case IrOpcode::kWord32Shr:
    case IrOpcode::kWord32Sar:
    case IrOpcode::kWord32Ror:
    case IrOpcode::kWord32Equal:
    case IrOpcode::kInt32Add:
    case IrOpcode::kInt32AddWithOverflow:
    case IrOpcode::kInt32Sub:
    case IrOpcode::kInt32SubWithOverflow:
    case IrOpcode::kInt32Mul:
    case IrOpcode::kInt32MulHigh:
    case IrOpcode::kInt32Div:
    case IrOpcode::kInt32Mod:
    case IrOpcode::kInt32LessThan:
    case IrOpcode::kInt32LessThanOrEqual:
    case IrOpcode::kUint32Div:
    case IrOpcode::kUint32LessThan:
    case IrOpcode::kUint32LessThanOrEqual:
    case IrOpcode::kUint32Mod:
    case IrOpcode::kUint32MulHigh: {
      // 32-bit operations will write their result in a W register (implicitly
      // clearing the top 32-bit of the corresponding X register) so the
      // zero-extension is a no-op.
      Emit(kArchNop, g.DefineSameAsFirst(node), g.Use(value));
      return;
    }
    default:
      break;
  }
  Emit(kArm64Mov32, g.DefineAsRegister(node), g.UseRegister(value));
}

void InstructionSelector::VisitTruncateFloat64ToFloat32(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64ToFloat32, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitTruncateInt64ToInt32(Node* node) {
  Arm64OperandGenerator g(this);
  Node* value = node->InputAt(0);
  if (CanCover(node, value)) {
    Int64BinopMatcher m(value);
    if ((m.IsWord64Sar() && m.right().HasValue() &&
         (m.right().Value() == 32)) ||
        (m.IsWord64Shr() && m.right().IsInRange(32, 63))) {
      Emit(kArm64Lsr, g.DefineAsRegister(node), g.UseRegister(m.left().node()),
           g.UseImmediate(m.right().node()));
      return;
    }
  }

  Emit(kArm64Mov32, g.DefineAsRegister(node), g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitFloat64Add(Node* node) {
  VisitRRRFloat64(this, kArm64Float64Add, node);
}

void InstructionSelector::VisitFloat64Sub(Node* node) {
  Arm64OperandGenerator g(this);
  Float64BinopMatcher m(node);
  if (m.left().IsMinusZero() && m.right().IsFloat64RoundDown() &&
      CanCover(m.node(), m.right().node())) {
    if (m.right().InputAt(0)->opcode() == IrOpcode::kFloat64Sub &&
        CanCover(m.right().node(), m.right().InputAt(0))) {
      Float64BinopMatcher mright0(m.right().InputAt(0));
      if (mright0.left().IsMinusZero()) {
        Emit(kArm64Float64RoundUp, g.DefineAsRegister(node),
             g.UseRegister(mright0.right().node()));
        return;
      }
    }
  }
  VisitRRRFloat64(this, kArm64Float64Sub, node);
}

void InstructionSelector::VisitFloat64Mul(Node* node) {
  VisitRRRFloat64(this, kArm64Float64Mul, node);
}

void InstructionSelector::VisitFloat64Div(Node* node) {
  VisitRRRFloat64(this, kArm64Float64Div, node);
}

void InstructionSelector::VisitFloat64Mod(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64Mod, g.DefineAsFixed(node, d0),
       g.UseFixed(node->InputAt(0), d0),
       g.UseFixed(node->InputAt(1), d1))->MarkAsCall();
}

void InstructionSelector::VisitFloat64Max(Node* node) { UNREACHABLE(); }

void InstructionSelector::VisitFloat64Min(Node* node) { UNREACHABLE(); }

void InstructionSelector::VisitFloat64Sqrt(Node* node) {
  VisitRRFloat64(this, kArm64Float64Sqrt, node);
}

void InstructionSelector::VisitFloat64RoundDown(Node* node) {
  VisitRRFloat64(this, kArm64Float64RoundDown, node);
}

void InstructionSelector::VisitFloat64RoundTruncate(Node* node) {
  VisitRRFloat64(this, kArm64Float64RoundTruncate, node);
}

void InstructionSelector::VisitFloat64RoundTiesAway(Node* node) {
  VisitRRFloat64(this, kArm64Float64RoundTiesAway, node);
}

void InstructionSelector::VisitCall(Node* node, BasicBlock* handler) {
  Arm64OperandGenerator g(this);
  const CallDescriptor* descriptor = OpParameter<const CallDescriptor*>(node);

  FrameStateDescriptor* frame_state_descriptor = NULL;
  if (descriptor->NeedsFrameState()) {
    frame_state_descriptor =
        GetFrameStateDescriptor(node->InputAt(descriptor->InputCount()));
  }

  CallBuffer buffer(zone(), descriptor, frame_state_descriptor);

  // Compute InstructionOperands for inputs and outputs.
  // TODO(turbofan): on ARM64 it's probably better to use the code object in a
  // register if there are multiple uses of it. Improve constant pool and the
  // heuristics in the register allocator for where to emit constants.
  InitializeCallBuffer(node, &buffer, true, false);

  // Push the arguments to the stack.
  bool pushed_count_uneven = buffer.pushed_nodes.size() & 1;
  int aligned_push_count = buffer.pushed_nodes.size();
  // TODO(dcarney): claim and poke probably take small immediates,
  //                loop here or whatever.
  // Bump the stack pointer(s).
  if (aligned_push_count > 0) {
    // TODO(dcarney): it would be better to bump the csp here only
    //                and emit paired stores with increment for non c frames.
    Emit(kArm64Claim | MiscField::encode(aligned_push_count), g.NoOutput());
  }
  // Move arguments to the stack.
  {
    int slot = buffer.pushed_nodes.size() - 1;
    // Emit the uneven pushes.
    if (pushed_count_uneven) {
      Node* input = buffer.pushed_nodes[slot];
      Emit(kArm64Poke | MiscField::encode(slot), g.NoOutput(),
           g.UseRegister(input));
      slot--;
    }
    // Now all pushes can be done in pairs.
    for (; slot >= 0; slot -= 2) {
      Emit(kArm64PokePair | MiscField::encode(slot), g.NoOutput(),
           g.UseRegister(buffer.pushed_nodes[slot]),
           g.UseRegister(buffer.pushed_nodes[slot - 1]));
    }
  }

  // Pass label of exception handler block.
  CallDescriptor::Flags flags = descriptor->flags();
  if (handler != nullptr) {
    flags |= CallDescriptor::kHasExceptionHandler;
    buffer.instruction_args.push_back(g.Label(handler));
  }

  // Select the appropriate opcode based on the call type.
  InstructionCode opcode;
  switch (descriptor->kind()) {
    case CallDescriptor::kCallCodeObject: {
      opcode = kArchCallCodeObject;
      break;
    }
    case CallDescriptor::kCallJSFunction:
      opcode = kArchCallJSFunction;
      break;
    default:
      UNREACHABLE();
      return;
  }
  opcode |= MiscField::encode(flags);

  // Emit the call instruction.
  InstructionOperand* first_output =
      buffer.outputs.size() > 0 ? &buffer.outputs.front() : NULL;
  Instruction* call_instr =
      Emit(opcode, buffer.outputs.size(), first_output,
           buffer.instruction_args.size(), &buffer.instruction_args.front());
  call_instr->MarkAsCall();
}

// Shared routine for multiple compare operations.
static void VisitCompare(InstructionSelector* selector, InstructionCode opcode,
                         InstructionOperand left, InstructionOperand right,
                         FlagsContinuation* cont) {
  Arm64OperandGenerator g(selector);
  opcode = cont->Encode(opcode);
  if (cont->IsBranch()) {
    selector->Emit(opcode, g.NoOutput(), left, right,
                   g.Label(cont->true_block()),
                   g.Label(cont->false_block()))->MarkAsControl();
  } else {
    DCHECK(cont->IsSet());
    selector->Emit(opcode, g.DefineAsRegister(cont->result()), left, right);
  }
}

// Shared routine for multiple word compare operations.
static void VisitWordCompare(InstructionSelector* selector, Node* node,
                             InstructionCode opcode, FlagsContinuation* cont,
                             bool commutative, ImmediateMode immediate_mode) {
  Arm64OperandGenerator g(selector);
  Node* left = node->InputAt(0);
  Node* right = node->InputAt(1);

  // Match immediates on left or right side of comparison.
  if (g.CanBeImmediate(right, immediate_mode)) {
    VisitCompare(selector, opcode, g.UseRegister(left), g.UseImmediate(right),
                 cont);
  } else if (g.CanBeImmediate(left, immediate_mode)) {
    if (!commutative) cont->Commute();
    VisitCompare(selector, opcode, g.UseRegister(right), g.UseImmediate(left),
                 cont);
  } else {
    VisitCompare(selector, opcode, g.UseRegister(left), g.UseRegister(right),
                 cont);
  }
}

static void VisitWord32Compare(InstructionSelector* selector, Node* node,
                               FlagsContinuation* cont) {
  VisitWordCompare(selector, node, kArm64Cmp32, cont, false, kArithmeticImm);
}

static void VisitWordTest(InstructionSelector* selector, Node* node,
                          InstructionCode opcode, FlagsContinuation* cont) {
  Arm64OperandGenerator g(selector);
  VisitCompare(selector, opcode, g.UseRegister(node), g.UseRegister(node),
               cont);
}

static void VisitWord32Test(InstructionSelector* selector, Node* node,
                            FlagsContinuation* cont) {
  VisitWordTest(selector, node, kArm64Tst32, cont);
}

static void VisitWord64Test(InstructionSelector* selector, Node* node,
                            FlagsContinuation* cont) {
  VisitWordTest(selector, node, kArm64Tst, cont);
}

// Shared routine for multiple float compare operations.
static void VisitFloat64Compare(InstructionSelector* selector, Node* node,
                                FlagsContinuation* cont) {
  Arm64OperandGenerator g(selector);
  Float64BinopMatcher m(node);
  if (m.right().Is(0.0)) {
    VisitCompare(selector, kArm64Float64Cmp, g.UseRegister(m.left().node()),
                 g.UseImmediate(m.right().node()), cont);
  } else {
    VisitCompare(selector, kArm64Float64Cmp, g.UseRegister(m.left().node()),
                 g.UseRegister(m.right().node()), cont);
  }
}

void InstructionSelector::VisitBranch(Node* branch, BasicBlock* tbranch,
                                      BasicBlock* fbranch) {
  OperandGenerator g(this);
  Node* user = branch;
  Node* value = branch->InputAt(0);

  FlagsContinuation cont(kNotEqual, tbranch, fbranch);

  // Try to combine with comparisons against 0 by simply inverting the branch.
  while (CanCover(user, value) && value->opcode() == IrOpcode::kWord32Equal) {
    Int32BinopMatcher m(value);
    if (m.right().Is(0)) {
      user = value;
      value = m.left().node();
      cont.Negate();
    } else {
      break;
    }
  }

  // Try to combine the branch with a comparison.
  if (CanCover(user, value)) {
    switch (value->opcode()) {
      case IrOpcode::kWord32Equal:
        cont.OverwriteAndNegateIfEqual(kEqual);
        return VisitWord32Compare(this, value, &cont);
      case IrOpcode::kInt32LessThan:
        cont.OverwriteAndNegateIfEqual(kSignedLessThan);
        return VisitWord32Compare(this, value, &cont);
      case IrOpcode::kInt32LessThanOrEqual:
        cont.OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
        return VisitWord32Compare(this, value, &cont);
      case IrOpcode::kUint32LessThan:
        cont.OverwriteAndNegateIfEqual(kUnsignedLessThan);
        return VisitWord32Compare(this, value, &cont);
      case IrOpcode::kUint32LessThanOrEqual:
        cont.OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
        return VisitWord32Compare(this, value, &cont);
      case IrOpcode::kWord64Equal:
        cont.OverwriteAndNegateIfEqual(kEqual);
        return VisitWordCompare(this, value, kArm64Cmp, &cont, false,
                                kArithmeticImm);
      case IrOpcode::kInt64LessThan:
        cont.OverwriteAndNegateIfEqual(kSignedLessThan);
        return VisitWordCompare(this, value, kArm64Cmp, &cont, false,
                                kArithmeticImm);
      case IrOpcode::kInt64LessThanOrEqual:
        cont.OverwriteAndNegateIfEqual(kSignedLessThanOrEqual);
        return VisitWordCompare(this, value, kArm64Cmp, &cont, false,
                                kArithmeticImm);
      case IrOpcode::kUint64LessThan:
        cont.OverwriteAndNegateIfEqual(kUnsignedLessThan);
        return VisitWordCompare(this, value, kArm64Cmp, &cont, false,
                                kArithmeticImm);
      case IrOpcode::kFloat64Equal:
        cont.OverwriteAndNegateIfEqual(kEqual);
        return VisitFloat64Compare(this, value, &cont);
      case IrOpcode::kFloat64LessThan:
        cont.OverwriteAndNegateIfEqual(kUnsignedLessThan);
        return VisitFloat64Compare(this, value, &cont);
      case IrOpcode::kFloat64LessThanOrEqual:
        cont.OverwriteAndNegateIfEqual(kUnsignedLessThanOrEqual);
        return VisitFloat64Compare(this, value, &cont);
      case IrOpcode::kProjection:
        // Check if this is the overflow output projection of an
        // <Operation>WithOverflow node.
        if (ProjectionIndexOf(value->op()) == 1u) {
          // We cannot combine the <Operation>WithOverflow with this branch
          // unless the 0th projection (the use of the actual value of the
          // <Operation> is either NULL, which means there's no use of the
          // actual value, or was already defined, which means it is scheduled
          // *AFTER* this branch).
          Node* const node = value->InputAt(0);
          Node* const result = NodeProperties::FindProjection(node, 0);
          if (result == NULL || IsDefined(result)) {
            switch (node->opcode()) {
              case IrOpcode::kInt32AddWithOverflow:
                cont.OverwriteAndNegateIfEqual(kOverflow);
                return VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32,
                                                     kArithmeticImm, &cont);
              case IrOpcode::kInt32SubWithOverflow:
                cont.OverwriteAndNegateIfEqual(kOverflow);
                return VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32,
                                                     kArithmeticImm, &cont);
              default:
                break;
            }
          }
        }
        break;
      case IrOpcode::kInt32Add:
        return VisitWordCompare(this, value, kArm64Cmn32, &cont, true,
                                kArithmeticImm);
      case IrOpcode::kInt32Sub:
        return VisitWordCompare(this, value, kArm64Cmp32, &cont, false,
                                kArithmeticImm);
      case IrOpcode::kWord32And: {
        Int32BinopMatcher m(value);
        if (m.right().HasValue() &&
            (base::bits::CountPopulation32(m.right().Value()) == 1)) {
          // If the mask has only one bit set, we can use tbz/tbnz.
          DCHECK((cont.condition() == kEqual) ||
                 (cont.condition() == kNotEqual));
          Emit(cont.Encode(kArm64TestAndBranch32), g.NoOutput(),
               g.UseRegister(m.left().node()),
               g.TempImmediate(
                   base::bits::CountTrailingZeros32(m.right().Value())),
               g.Label(cont.true_block()),
               g.Label(cont.false_block()))->MarkAsControl();
          return;
        }
        return VisitWordCompare(this, value, kArm64Tst32, &cont, true,
                                kLogical32Imm);
      }
      case IrOpcode::kWord64And: {
        Int64BinopMatcher m(value);
        if (m.right().HasValue() &&
            (base::bits::CountPopulation64(m.right().Value()) == 1)) {
          // If the mask has only one bit set, we can use tbz/tbnz.
          DCHECK((cont.condition() == kEqual) ||
                 (cont.condition() == kNotEqual));
          Emit(cont.Encode(kArm64TestAndBranch), g.NoOutput(),
               g.UseRegister(m.left().node()),
               g.TempImmediate(
                   base::bits::CountTrailingZeros64(m.right().Value())),
               g.Label(cont.true_block()),
               g.Label(cont.false_block()))->MarkAsControl();
          return;
        }
        return VisitWordCompare(this, value, kArm64Tst, &cont, true,
                                kLogical64Imm);
      }
      default:
        break;
    }
  }

  // Branch could not be combined with a compare, compare against 0 and branch.
  Emit(cont.Encode(kArm64CompareAndBranch32), g.NoOutput(),
       g.UseRegister(value), g.Label(cont.true_block()),
       g.Label(cont.false_block()))->MarkAsControl();
}

void InstructionSelector::VisitSwitch(Node* node, BasicBlock* default_branch,
                                      BasicBlock** case_branches,
                                      int32_t* case_values, size_t case_count,
                                      int32_t min_value, int32_t max_value) {
  Arm64OperandGenerator g(this);
  InstructionOperand value_operand = g.UseRegister(node->InputAt(0));
  InstructionOperand default_operand = g.Label(default_branch);

  // Note that {value_range} can be 0 if {min_value} is -2^31 and {max_value}
  // is 2^31-1, so don't assume that it's non-zero below.
  size_t value_range =
      1u + bit_cast<uint32_t>(max_value) - bit_cast<uint32_t>(min_value);

  // Determine whether to issue an ArchTableSwitch or an ArchLookupSwitch
  // instruction.
  size_t table_space_cost = 4 + value_range;
  size_t table_time_cost = 3;
  size_t lookup_space_cost = 3 + 2 * case_count;
  size_t lookup_time_cost = case_count;
  if (case_count > 0 &&
      table_space_cost + 3 * table_time_cost <=
          lookup_space_cost + 3 * lookup_time_cost &&
      min_value > std::numeric_limits<int32_t>::min()) {
    InstructionOperand index_operand = value_operand;
    if (min_value) {
      index_operand = g.TempRegister();
      Emit(kArm64Sub32, index_operand, value_operand,
           g.TempImmediate(min_value));
    }
    size_t input_count = 2 + value_range;
    auto* inputs = zone()->NewArray<InstructionOperand>(input_count);
    inputs[0] = index_operand;
    std::fill(&inputs[1], &inputs[input_count], default_operand);
    for (size_t index = 0; index < case_count; ++index) {
      size_t value = case_values[index] - min_value;
      BasicBlock* branch = case_branches[index];
      DCHECK_LE(0u, value);
      DCHECK_LT(value + 2, input_count);
      inputs[value + 2] = g.Label(branch);
    }
    Emit(kArchTableSwitch, 0, nullptr, input_count, inputs, 0, nullptr)
        ->MarkAsControl();
    return;
  }

  // Generate a sequence of conditional jumps.
  size_t input_count = 2 + case_count * 2;
  auto* inputs = zone()->NewArray<InstructionOperand>(input_count);
  inputs[0] = value_operand;
  inputs[1] = default_operand;
  for (size_t index = 0; index < case_count; ++index) {
    int32_t value = case_values[index];
    BasicBlock* branch = case_branches[index];
    inputs[index * 2 + 2 + 0] = g.TempImmediate(value);
    inputs[index * 2 + 2 + 1] = g.Label(branch);
  }
  Emit(kArchLookupSwitch, 0, nullptr, input_count, inputs, 0, nullptr)
      ->MarkAsControl();
}

void InstructionSelector::VisitWord32Equal(Node* const node) {
  Node* const user = node;
  FlagsContinuation cont(kEqual, node);
  Int32BinopMatcher m(user);
  if (m.right().Is(0)) {
    Node* const value = m.left().node();
    if (CanCover(user, value)) {
      switch (value->opcode()) {
        case IrOpcode::kInt32Add:
          return VisitWordCompare(this, value, kArm64Cmn32, &cont, true,
                                  kArithmeticImm);
        case IrOpcode::kInt32Sub:
          return VisitWordCompare(this, value, kArm64Cmp32, &cont, false,
                                  kArithmeticImm);
        case IrOpcode::kWord32And:
          return VisitWordCompare(this, value, kArm64Tst32, &cont, true,
                                  kLogical32Imm);
        default:
          break;
      }
      return VisitWord32Test(this, value, &cont);
    }
  }
  VisitWord32Compare(this, node, &cont);
}

void InstructionSelector::VisitInt32LessThan(Node* node) {
  FlagsContinuation cont(kSignedLessThan, node);
  VisitWord32Compare(this, node, &cont);
}

void InstructionSelector::VisitInt32LessThanOrEqual(Node* node) {
  FlagsContinuation cont(kSignedLessThanOrEqual, node);
  VisitWord32Compare(this, node, &cont);
}

void InstructionSelector::VisitUint32LessThan(Node* node) {
  FlagsContinuation cont(kUnsignedLessThan, node);
  VisitWord32Compare(this, node, &cont);
}

void InstructionSelector::VisitUint32LessThanOrEqual(Node* node) {
  FlagsContinuation cont(kUnsignedLessThanOrEqual, node);
  VisitWord32Compare(this, node, &cont);
}

void InstructionSelector::VisitWord64Equal(Node* const node) {
  Node* const user = node;
  FlagsContinuation cont(kEqual, node);
  Int64BinopMatcher m(user);
  if (m.right().Is(0)) {
    Node* const value = m.left().node();
    if (CanCover(user, value)) {
      switch (value->opcode()) {
        case IrOpcode::kWord64And:
          return VisitWordCompare(this, value, kArm64Tst, &cont, true,
                                  kLogical64Imm);
        default:
          break;
      }
      return VisitWord64Test(this, value, &cont);
    }
  }
  VisitWordCompare(this, node, kArm64Cmp, &cont, false, kArithmeticImm);
}

void InstructionSelector::VisitInt32AddWithOverflow(Node* node) {
  if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
    FlagsContinuation cont(kOverflow, ovf);
    return VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32,
                                         kArithmeticImm, &cont);
  }
  FlagsContinuation cont;
  VisitBinop<Int32BinopMatcher>(this, node, kArm64Add32, kArithmeticImm, &cont);
}

void InstructionSelector::VisitInt32SubWithOverflow(Node* node) {
  if (Node* ovf = NodeProperties::FindProjection(node, 1)) {
    FlagsContinuation cont(kOverflow, ovf);
    return VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32,
                                         kArithmeticImm, &cont);
  }
  FlagsContinuation cont;
  VisitBinop<Int32BinopMatcher>(this, node, kArm64Sub32, kArithmeticImm, &cont);
}

void InstructionSelector::VisitInt64LessThan(Node* node) {
  FlagsContinuation cont(kSignedLessThan, node);
  VisitWordCompare(this, node, kArm64Cmp, &cont, false, kArithmeticImm);
}

void InstructionSelector::VisitInt64LessThanOrEqual(Node* node) {
  FlagsContinuation cont(kSignedLessThanOrEqual, node);
  VisitWordCompare(this, node, kArm64Cmp, &cont, false, kArithmeticImm);
}

void InstructionSelector::VisitUint64LessThan(Node* node) {
  FlagsContinuation cont(kUnsignedLessThan, node);
  VisitWordCompare(this, node, kArm64Cmp, &cont, false, kArithmeticImm);
}

void InstructionSelector::VisitFloat64Equal(Node* node) {
  FlagsContinuation cont(kEqual, node);
  VisitFloat64Compare(this, node, &cont);
}

void InstructionSelector::VisitFloat64LessThan(Node* node) {
  FlagsContinuation cont(kUnsignedLessThan, node);
  VisitFloat64Compare(this, node, &cont);
}

void InstructionSelector::VisitFloat64LessThanOrEqual(Node* node) {
  FlagsContinuation cont(kUnsignedLessThanOrEqual, node);
  VisitFloat64Compare(this, node, &cont);
}

void InstructionSelector::VisitFloat64ExtractLowWord32(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64ExtractLowWord32, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitFloat64ExtractHighWord32(Node* node) {
  Arm64OperandGenerator g(this);
  Emit(kArm64Float64ExtractHighWord32, g.DefineAsRegister(node),
       g.UseRegister(node->InputAt(0)));
}

void InstructionSelector::VisitFloat64InsertLowWord32(Node* node) {
  // TODO(arm64): Some AArch64 specialist should be able to improve this.
  Arm64OperandGenerator g(this);
  Node* left = node->InputAt(0);
  Node* right = node->InputAt(1);
  Emit(kArm64Float64InsertLowWord32, g.DefineAsRegister(node),
       g.UseRegister(left), g.UseRegister(right));
}

void InstructionSelector::VisitFloat64InsertHighWord32(Node* node) {
  // TODO(arm64): Some AArch64 specialist should be able to improve this.
  Arm64OperandGenerator g(this);
  Node* left = node->InputAt(0);
  Node* right = node->InputAt(1);
  Emit(kArm64Float64InsertHighWord32, g.DefineAsRegister(node),
       g.UseRegister(left), g.UseRegister(right));
}

// static
MachineOperatorBuilder::Flags
InstructionSelector::SupportedMachineOperatorFlags() {
  return MachineOperatorBuilder::kFloat64RoundDown |
         MachineOperatorBuilder::kFloat64RoundTruncate |
         MachineOperatorBuilder::kFloat64RoundTiesAway |
         MachineOperatorBuilder::kWord32ShiftIsSafe |
         MachineOperatorBuilder::kInt32DivIsSafe |
         MachineOperatorBuilder::kUint32DivIsSafe;
}

}  // namespace compiler
}  // namespace internal
}  // namespace v8


text:
/**
 * Wrap PSM2 API under the original PSM API.
 * This file allows na_psm.c to be compiled to use the PSM2 API,
 * thus allowing the same na_psm.c source file to support both
 * PSM and PSM2.
 */

/* define PSM-style aliases for PSM2 data types */
typedef psm2_error_t psm_error_t;
typedef psm2_ep_t psm_ep_t;
typedef psm2_epaddr_t psm_epaddr_t;
typedef psm2_epid_t psm_epid_t;
typedef psm2_uuid_t psm_uuid_t;
typedef psm2_mq_t psm_mq_t;
typedef psm2_mq_req_t psm_mq_req_t;
typedef psm2_mq_status_t psm_mq_status_t;

/* locally defined struct aliases */
typedef struct psm2_optkey psm_optkey_t;
typedef struct psm2_ep_open_opts psm_ep_open_opts_t;

/* defines/errors used by na_psm.c */
#define PSM_VERNO_MAJOR       PSM2_VERNO_MAJOR
#define PSM_VERNO_MINOR       PSM2_VERNO_MINOR
#define PSM_EP_CLOSE_GRACEFUL PSM2_EP_CLOSE_GRACEFUL
#define PSM_EP_CLOSE_FORCE    PSM2_EP_CLOSE_FORCE
#define PSM_EP_CLOSE_TIMEOUT  PSM2_EP_CLOSE_TIMEOUT
#define PSM_MQ_ORDERMASK_ALL  PSM2_MQ_ORDERMASK_ALL

#define PSM_OK PSM2_OK

/* inline wrapper functions */

static NA_INLINE psm_error_t
psm_init(int *major, int *minor)
{
    return psm2_init(major, minor);
}

static NA_INLINE psm_error_t
psm_finalize(void)
{
    return psm2_finalize();
}

static NA_INLINE void
psm_epaddr_setctxt(psm_epaddr_t epaddr, void *ctxt)
{
    psm2_epaddr_setctxt(epaddr, ctxt);
}

#if 0 /* currently not used */
static NA_INLINE void *
psm_epaddr_getctxt(psm_epaddr_t epaddr) {
  return psm2_epaddr_getctxt(epaddr);
}
#endif

static NA_INLINE const char *
psm_error_get_string(psm_error_t error)
{
    return psm2_error_get_string(error);
}

static NA_INLINE psm_error_t
psm_mq_cancel(psm_mq_req_t *ireq)
{
    return psm2_mq_cancel(ireq);
}

static NA_INLINE psm_error_t
psm_mq_test(psm_mq_req_t *ireq, psm_mq_status_t *status)
{
    return psm2_mq_test(ireq, status);
}

static NA_INLINE psm_error_t
psm_mq_isend(psm_mq_t mq, psm_epaddr_t dest, uint32_t flags, uint64_t stag,
    const void *buf, uint32_t len, void *context, psm_mq_req_t *req)
{
    return psm2_mq_isend(mq, dest, flags, stag, buf, len, context, req);
}

static NA_INLINE psm_error_t
psm_mq_irecv(psm_mq_t mq, uint64_t tag, uint64_t tagsel, uint32_t flags,
    void *buf, uint32_t len, void *context, psm_mq_req_t *reqo)
{
    return psm2_mq_irecv(mq, tag, tagsel, flags, buf, len, context, reqo);
}

static NA_INLINE psm_error_t
psm_mq_ipeek(psm_mq_t mq, psm_mq_req_t *oreq, psm_mq_status_t *status)
{
    return psm2_mq_ipeek(mq, oreq, status);
}

static NA_INLINE psm_error_t
psm_mq_init(psm_ep_t ep, uint64_t ignored, const psm_optkey_t *opts,
    int numopts, psm_mq_t *mqo)
{
    return psm2_mq_init(ep, ignored, opts, numopts, mqo);
}

static NA_INLINE psm_error_t
psm_mq_finalize(psm_mq_t mq)
{
    return psm2_mq_finalize(mq);
}

static NA_INLINE psm_error_t
psm_ep_open_opts_get_defaults(psm_ep_open_opts_t *opts)
{
    return psm2_ep_open_opts_get_defaults(opts);
}

static NA_INLINE psm2_error_t
psm_ep_open(psm_uuid_t const unique_job_key, const psm_ep_open_opts_t *opts_i,
    psm_ep_t *epo, psm_epid_t *epido)
{
    return psm2_ep_open(unique_job_key, opts_i, epo, epido);
}

static NA_INLINE psm_error_t
psm_ep_close(psm_ep_t ep, int mode, int64_t timeout_in)
{
    return psm2_ep_close(ep, mode, timeout_in);
}

static NA_INLINE psm_error_t
psm_ep_connect(psm_ep_t ep, int num_of_epid, psm_epid_t const *array_of_epid,
    int const *array_of_epid_mask, psm_error_t *array_of_errors,
    psm_epaddr_t *array_of_epaddr, int64_t timeout)
{
    return psm2_ep_connect(ep, num_of_epid, array_of_epid, array_of_epid_mask,
        array_of_errors, array_of_epaddr, timeout);
}


text:
"""Main Controller"""
import logging

from tg import expose, request, config, session
from tg.decorators import with_trailing_slash
from tg.flash import TGFlash
from pylons import tmpl_context as c
from pylons import response
from paste.deploy.converters import asbool

from allura.app import SitemapEntry
from allura.lib.base import WsgiDispatchController
from allura.lib import plugin
from allura.controllers.error import ErrorController
from allura import model as M
from allura.lib.widgets import project_list as plw
from .auth import AuthController
from .trovecategories import TroveCategoryController
from .search import SearchController, ProjectBrowseController
from .static import NewForgeController
from .site_admin import SiteAdminController
from .rest import RestController

__all__ = ['RootController']

log = logging.getLogger(__name__)

TGFlash.static_template = '''$('#messages').notify('%(message)s', {status: '%(status)s'});'''

class W:
    project_summary = plw.ProjectSummary()

class RootController(WsgiDispatchController):

    """
    The root controller for the allura application.

    All the other controllers and WSGI applications should be mounted on this
    controller. For example::

        panel = ControlPanelController()
        another_app = AnotherWSGIApplication()

    Keep in mind that WSGI applications shouldn't be mounted directly: They
    must be wrapped around with :class:`tg.controllers.WSGIAppController`.

    """

    auth = AuthController()
    error = ErrorController()
    nf = NewForgeController()
    search = SearchController()
    rest = RestController()
    categories = TroveCategoryController()

    def __init__(self):
        n_url_prefix = '/%s/' % request.path.split('/')[1]
        n = self._lookup_neighborhood(n_url_prefix)
        if n and not n.url_prefix.startswith('//'):
            n.bind_controller(self)
        self.browse = ProjectBrowseController()
        self.nf.admin = SiteAdminController()

        super(RootController, self).__init__()

    def _lookup_neighborhood(self, url_prefix):
        n = M.Neighborhood.query.get(url_prefix=url_prefix)
        return n

    def _setup_request(self):
        c.project = c.app = None
        c.user = plugin.AuthenticationProvider.get(request).authenticate_request()
        assert c.user is not None, ('c.user should always be at least User.anonymous(). '
                                    'Did you run `paster setup-app` to create the database?')
        if not c.user.is_anonymous():
            c.user.track_active(request)
            if asbool(config.get('force_ssl.logged_in')):
                session.secure = True

            # Make sure the page really isn't cached (not accessible by back button, etc)
            # pylons.configuration defaults to "no-cache" only.
            # See also http://blog.55minutes.com/2011/10/how-to-defeat-the-browser-back-button-cache/ and
            # https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/http-caching?hl=en#defining_optimal_cache-control_policy
            response.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'

    def _cleanup_request(self):
        pass

    @expose('jinja:allura:templates/neighborhood_list.html')
    @with_trailing_slash
    def index(self, **kw):
        """Handle the front-page."""
        neighborhoods = M.Neighborhood.query.find().sort('name')
        categories = M.ProjectCategory.query.find(
            {'parent_id': None}).sort('name').all()
        c.custom_sidebar_menu = [
            SitemapEntry(cat.label, '/browse/' + cat.name) for cat in categories
        ]
        return dict(neighborhoods=neighborhoods, title="All Neighborhoods")


text:
.class Landroid/content/ISyncServiceAdapter$Stub$Proxy;
.super Ljava/lang/Object;
.source "ISyncServiceAdapter.java"

# interfaces
.implements Landroid/content/ISyncServiceAdapter;

# annotations
.annotation system Ldalvik/annotation/EnclosingClass;
    value = Landroid/content/ISyncServiceAdapter$Stub;
.end annotation

.annotation system Ldalvik/annotation/InnerClass;
    accessFlags = 0xa
    name = "Proxy"
.end annotation

# instance fields
.field private mRemote:Landroid/os/IBinder;

# direct methods
.method constructor <init>(Landroid/os/IBinder;)V
    .registers 2
    .param p1, "remote"    # Landroid/os/IBinder;

    .prologue
    .line 80
    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    .line 82
    iput-object p1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    .line 80
    return-void
.end method

# virtual methods
.method public asBinder()Landroid/os/IBinder;
    .registers 2

    .prologue
    .line 86
    iget-object v0, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    return-object v0
.end method

.method public cancelSync(Landroid/content/ISyncContext;)V
    .registers 7
    .param p1, "syncContext"    # Landroid/content/ISyncContext;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v1, 0x0

    .line 125
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 127
    .local v0, "_data":Landroid/os/Parcel;
    :try_start_5
    const-string/jumbo v2, "android.content.ISyncServiceAdapter"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 128
    if-eqz p1, :cond_11

    invoke-interface {p1}, Landroid/content/ISyncContext;->asBinder()Landroid/os/IBinder;

    move-result-object v1

    :cond_11
    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 129
    iget-object v1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v2, 0x2

    const/4 v3, 0x0

    const/4 v4, 0x1

    invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    :try_end_1c
    .catchall {:try_start_5 .. :try_end_1c} :catchall_20

    .line 132
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 123
    return-void

    .line 131
    :catchall_20
    move-exception v1

    .line 132
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 131
    throw v1
.end method

.method public getInterfaceDescriptor()Ljava/lang/String;
    .registers 2

    .prologue
    .line 90
    const-string/jumbo v0, "android.content.ISyncServiceAdapter"

    return-object v0
.end method

.method public startSync(Landroid/content/ISyncContext;Landroid/os/Bundle;)V
    .registers 8
    .param p1, "syncContext"    # Landroid/content/ISyncContext;
    .param p2, "extras"    # Landroid/os/Bundle;
    .annotation system Ldalvik/annotation/Throws;
        value = {
            Landroid/os/RemoteException;
        }
    .end annotation

    .prologue
    const/4 v1, 0x0

    .line 103
    invoke-static {}, Landroid/os/Parcel;->obtain()Landroid/os/Parcel;

    move-result-object v0

    .line 105
    .local v0, "_data":Landroid/os/Parcel;
    :try_start_5
    const-string/jumbo v2, "android.content.ISyncServiceAdapter"

    invoke-virtual {v0, v2}, Landroid/os/Parcel;->writeInterfaceToken(Ljava/lang/String;)V

    .line 106
    if-eqz p1, :cond_11

    invoke-interface {p1}, Landroid/content/ISyncContext;->asBinder()Landroid/os/IBinder;

    move-result-object v1

    :cond_11
    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeStrongBinder(Landroid/os/IBinder;)V

    .line 107
    if-eqz p2, :cond_2a

    .line 108
    const/4 v1, 0x1

    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V

    .line 109
    const/4 v1, 0x0

    invoke-virtual {p2, v0, v1}, Landroid/os/Bundle;->writeToParcel(Landroid/os/Parcel;I)V

    .line 114
    :goto_1e
    iget-object v1, p0, Landroid/content/ISyncServiceAdapter$Stub$Proxy;->mRemote:Landroid/os/IBinder;

    const/4 v2, 0x1

    const/4 v3, 0x0

    const/4 v4, 0x1

    invoke-interface {v1, v2, v0, v3, v4}, Landroid/os/IBinder;->transact(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z
    :try_end_26
    .catchall {:try_start_5 .. :try_end_26} :catchall_2f

    .line 117
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 101
    return-void

    .line 112
    :cond_2a
    const/4 v1, 0x0

    :try_start_2b
    invoke-virtual {v0, v1}, Landroid/os/Parcel;->writeInt(I)V
    :try_end_2e
    .catchall {:try_start_2b .. :try_end_2e} :catchall_2f

    goto :goto_1e

    .line 116
    :catchall_2f
    move-exception v1

    .line 117
    invoke-virtual {v0}, Landroid/os/Parcel;->recycle()V

    .line 116
    throw v1
.end method


text:
namespace FKIdentifiers{
    const qint32 initObject=-1;
    const qint32 deinitObject=-2;
    const qint32 createServant=-3;
    const qint32 deleteServant=-4;
    const qint32 resetServant=-5;
    const qint32 actorId=-6;
}

#endif


text:
import fs from 'fs';
import http from 'http';
import path from 'path';
import { findAPortNotInUse } from 'portscanner';
import url from 'url';
import { log } from '../src/logger';

const mimeTypes: { [extension: string]: string } = {
  html: 'text/html',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  png: 'image/png',
  js: 'text/javascript',
  css: 'text/css'
};

const server = http.createServer((req, res) => {
  let uri = <string>url.parse(<string>req.url).pathname;

  if (uri === '/') uri = '/testApp.html';

  const filename = path.join(__dirname, uri);
  fs.exists(filename, exists => {
    if (!exists) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.write('404 Not Found\n');
      res.end();

      return;
    }
    const mimeType = mimeTypes[path.extname(filename).split('.')[1]];
    res.writeHead(200, { 'Content-Type': mimeType });

    const fileStream = fs.createReadStream(filename);
    fileStream.pipe(res);
  });
});

export async function startTestApp() {
  const port = await findAPortNotInUse(3000, 3050, '127.0.0.1');
  process.env.TEST_APP_PORT = port.toString();
  await new Promise(resolve => {
    server.listen(port, resolve);
  });
  log(`Test app started on port ${port}`)
}

export async function stopTestApp() {
  await new Promise(resolve => {
    server.close(resolve);
  });
}

if (require.main === module) {
  startTestApp().catch(err => {
    log(err);
  });
}


text:
package de.fhg.iais.commons;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.base.Charsets;

import de.fhg.iais.commons.annotation.OnlyCalledFromTests;
import de.fhg.iais.commons.dbc.Check;
import de.fhg.iais.commons.dbc.DbcException;

public final class Files {
    private static final Logger LOG = LoggerFactory.getLogger(Files.class);
    private static final Charset DEFAULT_CHARSET = Charsets.UTF_8;
    private static final boolean NOT_UNIX_LIKE = !File.separator.equals("/");

    private Files() {
        // helper class with only static methods
    }

    //    public static boolean delete(File file) {
    //        try {
    //            if ( file.exists() ) {
    //                return file.delete();
    //            } else {
    //                return true;
    //            }
    //        } catch ( Exception e ) {
    //            return false;
    //        }
    //    }

    /**
     * Copy file.
     *
     * @param sourceFile
     * @param destFile
     * @return -1 in case of failure.
     */
    //    public static int copy(final File sourceFile, final File destFile) {
    //        // this is a new implementation using NIO which is about 20% faster since it does
    //        // not need a java-based byte[] to copy data chunks; the data is transfered using
    //        // device built-in buffers which does not even go over the computers RAM data bus
    //        if ( !destFile.exists() ) {
    //            try {
    //                destFile.createNewFile(); //NOSONAR
    //            } catch ( IOException e ) {
    //                LOG.error("", e);
    //                return -1;
    //            }
    //        }
    //
    //        FileChannel source = null;
    //        FileChannel destination = null;
    //
    //        int sum = -1;
    //        try {
    //            source = new FileInputStream(sourceFile).getChannel();
    //            destination = new FileOutputStream(destFile).getChannel();
    //            sum = (int) destination.transferFrom(source, 0, source.size());
    //        } catch ( IOException e ) {
    //            LOG.error("", e);
    //        } finally {
    //            IOUtils.closeQuietly(source);
    //            IOUtils.closeQuietly(destination);
    //        }
    //        return sum;
    //    }

    /**
     * Create an FileInputStream.
     *
     * @param f
     * @return null in case of error.
     */
    //    public static FileInputStream fileInputStream(File f) {
    //        try {
    //            return new FileInputStream(f);
    //        } catch ( Exception e ) {
    //            return null;
    //        }
    //    }

    /**
     * Creates a FileReader. Throw DbcException case of error (charset, io).
     *
     * @param file
     * @param buffered
     * @return Reader.
     */
    private static Reader fileReader(File file, boolean buffered) {
        return fileReader(file, buffered, DEFAULT_CHARSET);
    }

    private static Reader fileReader(File file, boolean buffered, Charset charset) {
        try {
            return buffered ? new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)) : new InputStreamReader(
                new FileInputStream(file),
                charset);
        } catch ( FileNotFoundException e ) {
            throw new DbcException("File not found: " + file.getAbsolutePath(), e);
        }
    }

    /**
     * writes a binary file to disk and closes the stream.
     *
     * @param file File to write content to.
     * @param input Content to write
     * @throws FileNotFoundException
     * @throws IOException
     */
    //    public static void writeBinary(File file, InputStream input) {
    //        if ( file == null ) {
    //            throw new DbcException("File must not be null.");
    //        }
    //        if ( file.exists() ) {
    //            throw new DbcException("File " + file.getAbsoluteFile() + " exists.");
    //        }
    //
    //        byte[] buffer = new byte[4096];
    //        int len = 0;
    //        FileOutputStream fos = null;
    //        try {
    //            fos = new FileOutputStream(file);
    //
    //            while ( (len = input.read(buffer)) != -1 ) {
    //                fos.write(buffer, 0, len);
    //            }
    //            fos.flush();
    //        } catch ( IOException e ) {
    //            throw new DbcException(e);
    //        } finally {
    //            try {
    //                fos.close();
    //            } catch ( IOException ioe ) {
    //                throw new DbcException(ioe);
    //            }
    //        }
    //    }

    //    private static void writeBinary(File file, byte[] bytes, boolean append) {
    //        RandomAccessFile raf = null;
    //        Exception storedExep = null;
    //        if ( file == null ) {
    //            throw new DbcException("File must not be null.");
    //        }
    //        if ( !append ) {
    //            delete(file);
    //        }
    //        try {
    //            raf = new RandomAccessFile(file, "rw");
    //            if ( append ) {
    //                raf.seek(raf.length());
    //            }
    //            raf.write(bytes);
    //            raf.close();
    //        } catch ( Exception e ) {
    //            storedExep = e;
    //        } finally {
    //            try {
    //                raf.close();
    //            } catch ( Exception ee ) { // NOSONAR
    //                // silent catch
    //            }
    //        }
    //        if ( storedExep != null ) {
    //            throw new DbcException("Failed while " + (append ? "appending " : "writing ") + (bytes == null ? "Null" : bytes.length), storedExep);
    //        }
    //    }

    /**
     * Write a text file to disk and closes the stream. Charset Encoding default is utf8.
     *
     * @param target
     * @param content
     */
    //    public static boolean writeText(File target, String content) {
    //        return writeText(target, content, DEFAULT_CHARSET);
    //    }

    /**
     * Write a text file to disk and closes the stream. Charset Encoding default is utf8.
     *
     * @param target
     * @param content
     * @param charset
     */
    //    private static boolean writeText(File target, String content, Charset charset) {
    //        boolean success = false;
    //        Writer out = fileWriter(target, true, charset);
    //        try {
    //            out.write(content);
    //            success = true;
    //        } catch ( Exception e ) {
    //            throw new DbcException("Writing " + target + " failed: " + e.getMessage(), e);
    //        } finally {
    //            try {
    //                out.flush();
    //                out.close();
    //            } catch ( IOException e ) {
    //                throw new DbcException(e);
    //            }
    //        }
    //        return success;
    //    }

    //    private static Writer fileWriter(File file, boolean buffered, Charset charset) {
    //        try {
    //            return buffered ? new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)) : new OutputStreamWriter(new FileOutputStream(
    //                file), charset);
    //        } catch ( FileNotFoundException e ) {
    //            throw new DbcException("Error writing: " + file.getAbsolutePath(), e);
    //        }
    //    }

    //    public static void appendText(File target, String content, Object... vars) {
    //        appendText(target, Strings.sprint(content, vars), DEFAULT_CHARSET);
    //    }

    //    private static void appendText(File target, String content, Charset charset) {
    //        if ( charset == null ) {
    //            writeBinary(target, content.getBytes(), true);
    //        } else {
    //            writeBinary(target, content.getBytes(charset), true);
    //        }
    //    }

    //    public static boolean exists(File f) {
    //        try {
    //            return f.exists();
    //        } catch ( Exception e ) {
    //            return false;
    //        }
    //    }

    //    public static boolean ensureParentFolderExists(File f) {
    //        try {
    //            File parent = new File(cutBehindLast(f.getAbsolutePath(), File.separator));
    //            if ( !exists(parent) ) {
    //                return mkdir(parent);
    //            } else {
    //                return true;
    //            }
    //        } catch ( Exception e ) {
    //            return false;
    //        }
    //    }

    /**
     * @return input with cut off anything behind last occurrence of a given token.
     */
    //    private static String cutBehindLast(final String input, final String token) {
    //        if ( input != null ) {
    //            int pos = input.lastIndexOf(token);
    //            if ( pos > -1 ) {
    //                return input.substring(0, pos + token.length());
    //            }
    //        }
    //        return input;
    //    }

    //    public static boolean mkdir(File f) {
    //        try {
    //            return f.exists() || f.mkdirs();
    //        } catch ( Exception e ) {
    //            LOG.error("", e);
    //            return false;
    //        }
    //    }

    //    public static boolean mkdir(String f) {
    //        return mkdir(new File(f));
    //    }

    public static boolean deleteFolderRecursive(String path) throws IOException {
        File file = new File(path);
        return deleteFolderRecursive(file, file.getCanonicalPath(), false);
    }

    /**
     * delete recursively all directories of a folder, then all files, the the folder itself.

     * Tries to avoid following symbolic links, which is not easy to do platform independant. A safe robust solution would be nice.
     *
     * @param path the folder to delete
     * @param canonicalPrefixOfFile the prefix of the canonical name of all Files for which erasing is legal (sym link ...)
     * @param forceWritePermission if true, try to get write permission for then directory/file
     * @return true, if successful
     */
    public static boolean deleteFolderRecursive(File path, String canonicalPrefixOfFile, boolean forceWritePermission) {
        if ( path.exists() ) {
            try {
                String canonicalPath = path.getCanonicalPath();
                if ( !canonicalPath.startsWith(canonicalPrefixOfFile) ) {
                    LOG.error("deleteFolderRecursive aborted. Canonical path '" + canonicalPath + "' doesn't fit to '" + canonicalPrefixOfFile + "'");
                    return false;
                }
            } catch ( IOException e ) {
                LOG.error("deleteFolderRecursive aborted. Could not access the canonical path: " + canonicalPrefixOfFile, e);
                return false;
            }
            if ( forceWritePermission ) {
                path.setWritable(true); // hopefully was the write permission changed, if not: an error will occur later ...
            }
            File[] files = path.listFiles();
            for ( File file : files ) {
                if ( file.isDirectory() ) {
                    boolean isDeleted = deleteFolderRecursive(file, canonicalPrefixOfFile, forceWritePermission);
                    if ( !isDeleted ) {
                        LOG.error("deleteFolderRecursive aborted. Could not delete directory: " + file.getAbsolutePath());
                        return false;
                    }
                } else {
                    boolean isDeleted = file.setWritable(true) && file.delete();
                    if ( !isDeleted ) {
                        LOG.error("deleteFolderRecursive aborted. Could not delete file: " + file.getAbsolutePath());
                        return false;
                    }
                }
            }
            return path.delete();
        } else {
            LOG.error("deleteFolderRecursive aborted. Path does not exist: " + path.getAbsolutePath());
            return false;
        }
    }

    /**
     * Delete a directory and test if successful, throws exception if failed.
     *
     * @param dir
     */
    //    public static void deleteDirectory(final File dir) {
    //        if ( dir.exists() ) {
    //            try {
    //                FileUtils.deleteDirectory(dir);
    //            } catch ( IOException e ) {
    //                Check.isFalse(dir.exists(), dir.getAbsolutePath() + " could not be deleted.");
    //            }
    //        }
    //    }

    /**
     * deletes a directory subtree
     *
     * @param path
     * @throws IOException
     */
    //    public static void deleteTree(File path) throws IOException {
    //        if ( path.exists() ) {
    //            File[] files = path.listFiles();
    //            for ( int i = 0; i < files.length; i++ ) {
    //                File file = files[i];
    //                if ( file.isDirectory() ) {
    //                    deleteFolderRecursive(file, file.getCanonicalPath(), false);
    //                } else {
    //                    if ( !file.delete() ) {
    //                        throw new DbcException("Unable to delete File " + file.getAbsolutePath());
    //                    }
    //                }
    //            }
    //            if ( !path.delete() ) {
    //                throw new DbcException("Unable to delete Folder " + path.getAbsolutePath());
    //            }
    //        }
    //    }

    /**
     * extrahiert den namen ohne pfad und extension. a) bei foldern: verzeichnisnamen ohne pfad b) bei
     * dateien: den namen der datei ohne pfad
     */
    //    public static String getNameOnly(final String input) {
    //        if ( input == null ) {
    //            return "";
    //        }
    //
    //        String result = input;
    //        int x = result.lastIndexOf('.');
    //        result = (x == -1) ? result : result.substring(0, x);
    //        x = input.lastIndexOf(File.separator);
    //        if ( NOT_UNIX_LIKE ) {
    //            int y = result.lastIndexOf('/');
    //            x = x < y ? y : x;
    //        }
    //        return (x == -1) ? result : result.substring(x + 1);
    //    }

    /**
     * extrahiert den namen ohne pfad und extension. a) bei foldern: verzeichnisnamen ohne pfad b) bei
     * dateien: den namen der datei ohne pfad
     */
    //    public static String getNameOnly(File input) {
    //        if ( input == null ) {
    //            return "";
    //        } else {
    //            return getNameOnly(input.getAbsolutePath());
    //        }
    //    }

    @OnlyCalledFromTests
    //    public static String readText(String file) {
    //        return readText(new File(file));
    //    }
    //    public static String readText(File file) {
    //        return readText(file, DEFAULT_CHARSET);
    //    }
    private static boolean close(InputStream s) {
        try {
            s.close();
            return true;
        } catch ( IOException e ) { // NOSONAR
            // silent catch
        }
        return false;
    }

    private static boolean close(Reader s) {
        try {
            s.close();
            return true;
        } catch ( IOException e ) { // NOSONAR
            // silent catch
        }
        return false;
    }

    //    private static String readText(File file, Charset charset) {
    //        StringBuilder buffer = new StringBuilder(Math.max(16, (int) file.length())); // using the correct size reduces re-allocation of char[] space
    //        Reader reader = fileReader(file, true, charset);
    //        int ch;
    //        try {
    //            while ( (ch = reader.read()) > -1 ) {
    //                buffer.append((char) ch);
    //            }
    //        } catch ( Exception e ) {
    //            throw new DbcException("Error reading " + file.getAbsolutePath() + ", charset (" + charset + "): " + e.getMessage(), e);
    //        }
    //        close(reader);
    //        return buffer.toString();
    //    }

    /**
     * Read a text file, but ignores given comment line prefix and empty lines.
     *
     * @param file
     * @param charset
     * @param commentPrefix
     * @return the text file without comment lines and empty lines
     */
    @OnlyCalledFromTests
    //        public static String[] readText(final File file, final Charset charset, final String commentPrefix) {
    //            StringBuilder result = new StringBuilder(Math.max(16, (int) file.length())); // preset
    //            LineReader lineReader = new LineReader(file);
    //            while ( lineReader.hasLine() ) {
    //                final String line = lineReader.nextLineTrimNotNull();
    //                if ( !Strings.isEmpty(line) && !line.startsWith(commentPrefix) ) {
    //                    result.append(line).append(Strings.NEWLINE);
    //                }
    //            }
    //            lineReader.close();
    //
    //            return result.toString().split(Strings.NEWLINE);
    //        }
    //    public static File[] eachFile(File folder, final String... includedPattern) {
    //        final Pattern[] pattern;
    //        if ( includedPattern == null || includedPattern.length == 0 ) {
    //            pattern = null;
    //        } else {
    //            pattern = new Pattern[includedPattern.length];
    //            for ( int i = 0; i < includedPattern.length; i++ ) {
    //                pattern[i] = compileFilePattern(includedPattern[i].toLowerCase(Strings.LOCALE_GERMAN));
    //            }
    //        }
    //        final File[] name = folder.listFiles(new FilenameFilter() {
    //            @Override
    //            public boolean accept(File dir, String name) {
    //                if ( pattern == null ) {
    //                    return new File(dir, name).isFile();
    //                } else {
    //                    if ( !new File(dir, name).isFile() ) {
    //                        return false;
    //                    }
    //                    for ( Pattern p : pattern ) {
    //                        if ( p.matcher(name.toLowerCase(Strings.LOCALE_GERMAN)).matches() ) {
    //                            return true;
    //                        }
    //                    }
    //                }
    //                return false;
    //            }
    //        });
    //        return name == null ? new File[] {} : name;
    //    }
    //    private static Pattern compileFilePattern(final String pattern) {
    //        String preparedPattern = Strings.replaceAll(pattern, ".", "\\.");
    //        preparedPattern = Strings.replaceAll(preparedPattern, "?", ".?");
    //        preparedPattern = Strings.replaceAll(preparedPattern, "*", ".*");
    //
    //        return Pattern.compile(preparedPattern);
    //    }
    public static Properties readProperties(File f) {
        Properties p = new Properties();
        Reader r = Files.fileReader(f, false);
        try {
            p.load(r);
        } catch ( IOException e ) {
            throw new DbcException("Error reading property file: " + f.getAbsolutePath(), e);
        } finally {
            close(r);
        }
        return p;
    }

    //    public static String canonize(File f) {
    //        try {
    //            return f.getCanonicalPath();
    //        } catch ( IOException e ) {
    //            return f.getAbsolutePath();
    //        }
    //    }

    //    public static String createNameFromCurrentTime() {
    //        return new SimpleDateFormat("yyDDDHHmmssSSS").format(new Date());
    //    }

    //    public static String createNameFromCurrentTimeWithDailyFolders() {
    //        return new SimpleDateFormat("DDD/HHmmssSSS").format(new Date());
    //    }

    public static void createFileIfDoesNotExist(File file) throws IOException {
        if ( file.exists() ) {
            //            Check.isTrue(file.createNewFile());
            setWritable(file, true);
        }
    }

    public static void createDirectoryIfDoesNotExist(File dir) {
        if ( !dir.exists() ) {
            Check.isTrue(dir.mkdirs());
            setWritable(dir, true);
        }
    }

    private static boolean setWritable(File f, boolean writable) {
        return f.setWritable(writable, false);
    }

}


text:
#ifndef MODULES_ROUTING_COMMON_ROUTING_GFLAGS_H_
#define MODULES_ROUTING_COMMON_ROUTING_GFLAGS_H_

#include "gflags/gflags.h"

DECLARE_string(routing_conf_file);
DECLARE_string(routing_node_name);

DECLARE_string(routing_adapter_config_filename);

DECLARE_double(min_length_for_lane_change);
DECLARE_bool(enable_change_lane_in_result);

#endif  // MODULES_ROUTING_COMMON_ROUTING_GFLAGS_H_


text:
You may find yourself in a situation where you have to request multiple
resources from multiple API endpoints and then combine that data in some
way.

One way to achieve this would be with nested promises.

```javascript
fetch('/blogs').then((response) => {
  let blogs = response.body;

  fetch('/tags').then((response) => {
    let tags = response.body;

    // combine blogs and tags ...
  })
})
```

This nesting isn't ideal and it can get hard to read as the full
implementation is put into place.

The `Promise` API provides an alternative.

```javascript
let blogsPromise = fetch('/blogs')
let tagsPromise = fetch('/tags')

Promise.all([blogsPromise, tagsPromise]).then(([blogsResp, tagsResp]) => {
  // combine blogs and tags ...
})
```

With
[`Promise.all()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all)
we are able to wrap any number of promises and wait for all of them to
resolve until we do something with the results. This allows us to create a
context in which we have all the data we need without a bunch of nesting.


text:
package com.ctrip.framework.apollo.biz.repository;

import com.ctrip.framework.apollo.biz.entity.GrayReleaseRule;

import org.springframework.data.repository.PagingAndSortingRepository;

import java.util.List;

public interface GrayReleaseRuleRepository extends PagingAndSortingRepository<GrayReleaseRule, Long> {

  GrayReleaseRule findTopByAppIdAndClusterNameAndNamespaceNameAndBranchNameOrderByIdDesc(String appId, String clusterName,
                                                                                String namespaceName, String branchName);

  List<GrayReleaseRule> findByAppIdAndClusterNameAndNamespaceName(String appId,
                                                               String clusterName, String namespaceName);

  List<GrayReleaseRule> findFirst500ByIdGreaterThanOrderByIdAsc(Long id);

}