text:
namespace v8 {
namespace internal {

#define __ ACCESS_MASM(masm)

static void ProbeTable(Isolate* isolate,
                       MacroAssembler* masm,
                       Code::Flags flags,
                       StubCache::Table table,
                       Register name,
                       Register receiver,
                       // Number of the cache entry pointer-size scaled.
                       Register offset,
                       Register extra) {
  ExternalReference key_offset(isolate->stub_cache()->key_reference(table));
  ExternalReference value_offset(isolate->stub_cache()->value_reference(table));
  ExternalReference map_offset(isolate->stub_cache()->map_reference(table));

  Label miss;

  // Multiply by 3 because there are 3 fields per entry (name, code, map).
  __ lea(offset, Operand(offset, offset, times_2, 0));

  if (extra.is_valid()) {
    // Get the code entry from the cache.
    __ mov(extra, Operand::StaticArray(offset, times_1, value_offset));

    // Check that the key in the entry matches the name.
    __ cmp(name, Operand::StaticArray(offset, times_1, key_offset));
    __ j(not_equal, &miss);

    // Check the map matches.
    __ mov(offset, Operand::StaticArray(offset, times_1, map_offset));
    __ cmp(offset, FieldOperand(receiver, HeapObject::kMapOffset));
    __ j(not_equal, &miss);

    // Check that the flags match what we're looking for.
    __ mov(offset, FieldOperand(extra, Code::kFlagsOffset));
    __ and_(offset, ~Code::kFlagsNotUsedInLookup);
    __ cmp(offset, flags);
    __ j(not_equal, &miss);

#ifdef DEBUG
    if (FLAG_test_secondary_stub_cache && table == StubCache::kPrimary) {
      __ jmp(&miss);
    } else if (FLAG_test_primary_stub_cache && table == StubCache::kSecondary) {
      __ jmp(&miss);
    }
#endif

    // Jump to the first instruction in the code stub.
    __ add(extra, Immediate(Code::kHeaderSize - kHeapObjectTag));
    __ jmp(extra);

    __ bind(&miss);
  } else {
    // Save the offset on the stack.
    __ push(offset);

    // Check that the key in the entry matches the name.
    __ cmp(name, Operand::StaticArray(offset, times_1, key_offset));
    __ j(not_equal, &miss);

    // Check the map matches.
    __ mov(offset, Operand::StaticArray(offset, times_1, map_offset));
    __ cmp(offset, FieldOperand(receiver, HeapObject::kMapOffset));
    __ j(not_equal, &miss);

    // Restore offset register.
    __ mov(offset, Operand(esp, 0));

    // Get the code entry from the cache.
    __ mov(offset, Operand::StaticArray(offset, times_1, value_offset));

    // Check that the flags match what we're looking for.
    __ mov(offset, FieldOperand(offset, Code::kFlagsOffset));
    __ and_(offset, ~Code::kFlagsNotUsedInLookup);
    __ cmp(offset, flags);
    __ j(not_equal, &miss);

#ifdef DEBUG
    if (FLAG_test_secondary_stub_cache && table == StubCache::kPrimary) {
      __ jmp(&miss);
    } else if (FLAG_test_primary_stub_cache && table == StubCache::kSecondary) {
      __ jmp(&miss);
    }
#endif

    // Restore offset and re-load code entry from cache.
    __ pop(offset);
    __ mov(offset, Operand::StaticArray(offset, times_1, value_offset));

    // Jump to the first instruction in the code stub.
    __ add(offset, Immediate(Code::kHeaderSize - kHeapObjectTag));
    __ jmp(offset);

    // Pop at miss.
    __ bind(&miss);
    __ pop(offset);
  }
}

void StubCompiler::GenerateDictionaryNegativeLookup(MacroAssembler* masm,
                                                    Label* miss_label,
                                                    Register receiver,
                                                    Handle<Name> name,
                                                    Register scratch0,
                                                    Register scratch1) {
  ASSERT(name->IsUniqueName());
  ASSERT(!receiver.is(scratch0));
  Counters* counters = masm->isolate()->counters();
  __ IncrementCounter(counters->negative_lookups(), 1);
  __ IncrementCounter(counters->negative_lookups_miss(), 1);

  __ mov(scratch0, FieldOperand(receiver, HeapObject::kMapOffset));

  const int kInterceptorOrAccessCheckNeededMask =
      (1 << Map::kHasNamedInterceptor) | (1 << Map::kIsAccessCheckNeeded);

  // Bail out if the receiver has a named interceptor or requires access checks.
  __ test_b(FieldOperand(scratch0, Map::kBitFieldOffset),
            kInterceptorOrAccessCheckNeededMask);
  __ j(not_zero, miss_label);

  // Check that receiver is a JSObject.
  __ CmpInstanceType(scratch0, FIRST_SPEC_OBJECT_TYPE);
  __ j(below, miss_label);

  // Load properties array.
  Register properties = scratch0;
  __ mov(properties, FieldOperand(receiver, JSObject::kPropertiesOffset));

  // Check that the properties array is a dictionary.
  __ cmp(FieldOperand(properties, HeapObject::kMapOffset),
         Immediate(masm->isolate()->factory()->hash_table_map()));
  __ j(not_equal, miss_label);

  Label done;
  NameDictionaryLookupStub::GenerateNegativeLookup(masm,
                                                   miss_label,
                                                   &done,
                                                   properties,
                                                   name,
                                                   scratch1);
  __ bind(&done);
  __ DecrementCounter(counters->negative_lookups_miss(), 1);
}

void StubCache::GenerateProbe(MacroAssembler* masm,
                              Code::Flags flags,
                              Register receiver,
                              Register name,
                              Register scratch,
                              Register extra,
                              Register extra2,
                              Register extra3) {
  Label miss;

  // Assert that code is valid.  The multiplying code relies on the entry size
  // being 12.
  ASSERT(sizeof(Entry) == 12);

  // Assert the flags do not name a specific type.
  ASSERT(Code::ExtractTypeFromFlags(flags) == 0);

  // Assert that there are no register conflicts.
  ASSERT(!scratch.is(receiver));
  ASSERT(!scratch.is(name));
  ASSERT(!extra.is(receiver));
  ASSERT(!extra.is(name));
  ASSERT(!extra.is(scratch));

  // Assert scratch and extra registers are valid, and extra2/3 are unused.
  ASSERT(!scratch.is(no_reg));
  ASSERT(extra2.is(no_reg));
  ASSERT(extra3.is(no_reg));

  Register offset = scratch;
  scratch = no_reg;

  Counters* counters = masm->isolate()->counters();
  __ IncrementCounter(counters->megamorphic_stub_cache_probes(), 1);

  // Check that the receiver isn't a smi.
  __ JumpIfSmi(receiver, &miss);

  // Get the map of the receiver and compute the hash.
  __ mov(offset, FieldOperand(name, Name::kHashFieldOffset));
  __ add(offset, FieldOperand(receiver, HeapObject::kMapOffset));
  __ xor_(offset, flags);
  // We mask out the last two bits because they are not part of the hash and
  // they are always 01 for maps.  Also in the two 'and' instructions below.
  __ and_(offset, (kPrimaryTableSize - 1) << kHeapObjectTagSize);
  // ProbeTable expects the offset to be pointer scaled, which it is, because
  // the heap object tag size is 2 and the pointer size log 2 is also 2.
  ASSERT(kHeapObjectTagSize == kPointerSizeLog2);

  // Probe the primary table.
  ProbeTable(isolate(), masm, flags, kPrimary, name, receiver, offset, extra);

  // Primary miss: Compute hash for secondary probe.
  __ mov(offset, FieldOperand(name, Name::kHashFieldOffset));
  __ add(offset, FieldOperand(receiver, HeapObject::kMapOffset));
  __ xor_(offset, flags);
  __ and_(offset, (kPrimaryTableSize - 1) << kHeapObjectTagSize);
  __ sub(offset, name);
  __ add(offset, Immediate(flags));
  __ and_(offset, (kSecondaryTableSize - 1) << kHeapObjectTagSize);

  // Probe the secondary table.
  ProbeTable(
      isolate(), masm, flags, kSecondary, name, receiver, offset, extra);

  // Cache miss: Fall-through and let caller handle the miss by
  // entering the runtime system.
  __ bind(&miss);
  __ IncrementCounter(counters->megamorphic_stub_cache_misses(), 1);
}

void StubCompiler::GenerateLoadGlobalFunctionPrototype(MacroAssembler* masm,
                                                       int index,
                                                       Register prototype) {
  __ LoadGlobalFunction(index, prototype);
  __ LoadGlobalFunctionInitialMap(prototype, prototype);
  // Load the prototype from the initial map.
  __ mov(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}

void StubCompiler::GenerateDirectLoadGlobalFunctionPrototype(
    MacroAssembler* masm,
    int index,
    Register prototype,
    Label* miss) {
  // Get the global function with the given index.
  Handle<JSFunction> function(
      JSFunction::cast(masm->isolate()->native_context()->get(index)));
  // Check we're still in the same context.
  Register scratch = prototype;
  const int offset = Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX);
  __ mov(scratch, Operand(esi, offset));
  __ mov(scratch, FieldOperand(scratch, GlobalObject::kNativeContextOffset));
  __ cmp(Operand(scratch, Context::SlotOffset(index)), function);
  __ j(not_equal, miss);

  // Load its initial map. The global functions all have initial maps.
  __ Move(prototype, Immediate(Handle<Map>(function->initial_map())));
  // Load the prototype from the initial map.
  __ mov(prototype, FieldOperand(prototype, Map::kPrototypeOffset));
}

void StubCompiler::GenerateLoadArrayLength(MacroAssembler* masm,
                                           Register receiver,
                                           Register scratch,
                                           Label* miss_label) {
  // Check that the receiver isn't a smi.
  __ JumpIfSmi(receiver, miss_label);

  // Check that the object is a JS array.
  __ CmpObjectType(receiver, JS_ARRAY_TYPE, scratch);
  __ j(not_equal, miss_label);

  // Load length directly from the JS array.
  __ mov(eax, FieldOperand(receiver, JSArray::kLengthOffset));
  __ ret(0);
}

void StubCompiler::GenerateLoadFunctionPrototype(MacroAssembler* masm,
                                                 Register receiver,
                                                 Register scratch1,
                                                 Register scratch2,
                                                 Label* miss_label) {
  __ TryGetFunctionPrototype(receiver, scratch1, scratch2, miss_label);
  __ mov(eax, scratch1);
  __ ret(0);
}

void StubCompiler::GenerateFastPropertyLoad(MacroAssembler* masm,
                                            Register dst,
                                            Register src,
                                            bool inobject,
                                            int index,
                                            Representation representation) {
  ASSERT(!representation.IsDouble());
  int offset = index * kPointerSize;
  if (!inobject) {
    // Calculate the offset into the properties array.
    offset = offset + FixedArray::kHeaderSize;
    __ mov(dst, FieldOperand(src, JSObject::kPropertiesOffset));
    src = dst;
  }
  __ mov(dst, FieldOperand(src, offset));
}

static void PushInterceptorArguments(MacroAssembler* masm,
                                     Register receiver,
                                     Register holder,
                                     Register name,
                                     Handle<JSObject> holder_obj) {
  STATIC_ASSERT(StubCache::kInterceptorArgsNameIndex == 0);
  STATIC_ASSERT(StubCache::kInterceptorArgsInfoIndex == 1);
  STATIC_ASSERT(StubCache::kInterceptorArgsThisIndex == 2);
  STATIC_ASSERT(StubCache::kInterceptorArgsHolderIndex == 3);
  STATIC_ASSERT(StubCache::kInterceptorArgsLength == 4);
  __ push(name);
  Handle<InterceptorInfo> interceptor(holder_obj->GetNamedInterceptor());
  ASSERT(!masm->isolate()->heap()->InNewSpace(*interceptor));
  Register scratch = name;
  __ mov(scratch, Immediate(interceptor));
  __ push(scratch);
  __ push(receiver);
  __ push(holder);
}

static void CompileCallLoadPropertyWithInterceptor(
    MacroAssembler* masm,
    Register receiver,
    Register holder,
    Register name,
    Handle<JSObject> holder_obj,
    IC::UtilityId id) {
  PushInterceptorArguments(masm, receiver, holder, name, holder_obj);
  __ CallExternalReference(
      ExternalReference(IC_Utility(id), masm->isolate()),
      StubCache::kInterceptorArgsLength);
}

// Generate call to api function.
// This function uses push() to generate smaller, faster code than
// the version above. It is an optimization that should will be removed
// when api call ICs are generated in hydrogen.
void StubCompiler::GenerateFastApiCall(MacroAssembler* masm,
                                       const CallOptimization& optimization,
                                       Handle<Map> receiver_map,
                                       Register receiver,
                                       Register scratch_in,
                                       bool is_store,
                                       int argc,
                                       Register* values) {
  // Copy return value.
  __ pop(scratch_in);
  // receiver
  __ push(receiver);
  // Write the arguments to stack frame.
  for (int i = 0; i < argc; i++) {
    Register arg = values[argc-1-i];
    ASSERT(!receiver.is(arg));
    ASSERT(!scratch_in.is(arg));
    __ push(arg);
  }
  __ push(scratch_in);
  // Stack now matches JSFunction abi.
  ASSERT(optimization.is_simple_api_call());

  // Abi for CallApiFunctionStub.
  Register callee = eax;
  Register call_data = ebx;
  Register holder = ecx;
  Register api_function_address = edx;
  Register scratch = edi;  // scratch_in is no longer valid.

  // Put holder in place.
  CallOptimization::HolderLookup holder_lookup;
  Handle<JSObject> api_holder = optimization.LookupHolderOfExpectedType(
      receiver_map,
      &holder_lookup);
  switch (holder_lookup) {
    case CallOptimization::kHolderIsReceiver:
      __ Move(holder, receiver);
      break;
    case CallOptimization::kHolderFound:
      __ LoadHeapObject(holder, api_holder);
     break;
    case CallOptimization::kHolderNotFound:
      UNREACHABLE();
      break;
  }

  Isolate* isolate = masm->isolate();
  Handle<JSFunction> function = optimization.constant_function();
  Handle<CallHandlerInfo> api_call_info = optimization.api_call_info();
  Handle<Object> call_data_obj(api_call_info->data(), isolate);

  // Put callee in place.
  __ LoadHeapObject(callee, function);

  bool call_data_undefined = false;
  // Put call_data in place.
  if (isolate->heap()->InNewSpace(*call_data_obj)) {
    __ mov(scratch, api_call_info);
    __ mov(call_data, FieldOperand(scratch, CallHandlerInfo::kDataOffset));
  } else if (call_data_obj->IsUndefined()) {
    call_data_undefined = true;
    __ mov(call_data, Immediate(isolate->factory()->undefined_value()));
  } else {
    __ mov(call_data, call_data_obj);
  }

  // Put api_function_address in place.
  Address function_address = v8::ToCData<Address>(api_call_info->callback());
  __ mov(api_function_address, Immediate(function_address));

  // Jump to stub.
  CallApiFunctionStub stub(isolate, is_store, call_data_undefined, argc);
  __ TailCallStub(&stub);
}

void StoreStubCompiler::GenerateRestoreName(MacroAssembler* masm,
                                            Label* label,
                                            Handle<Name> name) {
  if (!label->is_unused()) {
    __ bind(label);
    __ mov(this->name(), Immediate(name));
  }
}

// Generate code to check that a global property cell is empty. Create
// the property cell at compilation time if no cell exists for the
// property.
void StubCompiler::GenerateCheckPropertyCell(MacroAssembler* masm,
                                             Handle<JSGlobalObject> global,
                                             Handle<Name> name,
                                             Register scratch,
                                             Label* miss) {
  Handle<PropertyCell> cell =
      JSGlobalObject::EnsurePropertyCell(global, name);
  ASSERT(cell->value()->IsTheHole());
  Handle<Oddball> the_hole = masm->isolate()->factory()->the_hole_value();
  if (masm->serializer_enabled()) {
    __ mov(scratch, Immediate(cell));
    __ cmp(FieldOperand(scratch, PropertyCell::kValueOffset),
           Immediate(the_hole));
  } else {
    __ cmp(Operand::ForCell(cell), Immediate(the_hole));
  }
  __ j(not_equal, miss);
}

void StoreStubCompiler::GenerateNegativeHolderLookup(
    MacroAssembler* masm,
    Handle<JSObject> holder,
    Register holder_reg,
    Handle<Name> name,
    Label* miss) {
  if (holder->IsJSGlobalObject()) {
    GenerateCheckPropertyCell(
        masm, Handle<JSGlobalObject>::cast(holder), name, scratch1(), miss);
  } else if (!holder->HasFastProperties() && !holder->IsJSGlobalProxy()) {
    GenerateDictionaryNegativeLookup(
        masm, miss, holder_reg, name, scratch1(), scratch2());
  }
}

// Receiver_reg is preserved on jumps to miss_label, but may be destroyed if
// store is successful.
void StoreStubCompiler::GenerateStoreTransition(MacroAssembler* masm,
                                                Handle<JSObject> object,
                                                LookupResult* lookup,
                                                Handle<Map> transition,
                                                Handle<Name> name,
                                                Register receiver_reg,
                                                Register storage_reg,
                                                Register value_reg,
                                                Register scratch1,
                                                Register scratch2,
                                                Register unused,
                                                Label* miss_label,
                                                Label* slow) {
  int descriptor = transition->LastAdded();
  DescriptorArray* descriptors = transition->instance_descriptors();
  PropertyDetails details = descriptors->GetDetails(descriptor);
  Representation representation = details.representation();
  ASSERT(!representation.IsNone());

  if (details.type() == CONSTANT) {
    Handle<Object> constant(descriptors->GetValue(descriptor), masm->isolate());
    __ CmpObject(value_reg, constant);
    __ j(not_equal, miss_label);
  } else if (representation.IsSmi()) {
      __ JumpIfNotSmi(value_reg, miss_label);
  } else if (representation.IsHeapObject()) {
    __ JumpIfSmi(value_reg, miss_label);
    HeapType* field_type = descriptors->GetFieldType(descriptor);
    HeapType::Iterator<Map> it = field_type->Classes();
    if (!it.Done()) {
      Label do_store;
      while (true) {
        __ CompareMap(value_reg, it.Current());
        it.Advance();
        if (it.Done()) {
          __ j(not_equal, miss_label);
          break;
        }
        __ j(equal, &do_store, Label::kNear);
      }
      __ bind(&do_store);
    }
  } else if (representation.IsDouble()) {
    Label do_store, heap_number;
    __ AllocateHeapNumber(storage_reg, scratch1, scratch2, slow);

    __ JumpIfNotSmi(value_reg, &heap_number);
    __ SmiUntag(value_reg);
    __ push(value_reg);
    __ fild_s(Operand(esp, 0));
    __ pop(value_reg);
    __ SmiTag(value_reg);
    __ jmp(&do_store);

    __ bind(&heap_number);
    __ CheckMap(value_reg, masm->isolate()->factory()->heap_number_map(),
                miss_label, DONT_DO_SMI_CHECK);
    __ fld_d(FieldOperand(value_reg, HeapNumber::kValueOffset));

    __ bind(&do_store);
    __ fstp_d(FieldOperand(storage_reg, HeapNumber::kValueOffset));
  }

  // Stub never generated for non-global objects that require access
  // checks.
  ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());

  // Perform map transition for the receiver if necessary.
  if (details.type() == FIELD &&
      object->map()->unused_property_fields() == 0) {
    // The properties must be extended before we can store the value.
    // We jump to a runtime call that extends the properties array.
    __ pop(scratch1);  // Return address.
    __ push(receiver_reg);
    __ push(Immediate(transition));
    __ push(value_reg);
    __ push(scratch1);
    __ TailCallExternalReference(
        ExternalReference(IC_Utility(IC::kSharedStoreIC_ExtendStorage),
                          masm->isolate()),
        3,
        1);
    return;
  }

  // Update the map of the object.
  __ mov(scratch1, Immediate(transition));
  __ mov(FieldOperand(receiver_reg, HeapObject::kMapOffset), scratch1);

  // Update the write barrier for the map field.
  __ RecordWriteField(receiver_reg,
                      HeapObject::kMapOffset,
                      scratch1,
                      scratch2,
                      OMIT_REMEMBERED_SET,
                      OMIT_SMI_CHECK);

  if (details.type() == CONSTANT) {
    ASSERT(value_reg.is(eax));
    __ ret(0);
    return;
  }

  int index = transition->instance_descriptors()->GetFieldIndex(
      transition->LastAdded());

  // Adjust for the number of properties stored in the object. Even in the
  // face of a transition we can use the old map here because the size of the
  // object and the number of in-object properties is not going to change.
  index -= object->map()->inobject_properties();

  SmiCheck smi_check = representation.IsTagged()
      ? INLINE_SMI_CHECK : OMIT_SMI_CHECK;
  // TODO(verwaest): Share this code as a code stub.
  if (index < 0) {
    // Set the property straight into the object.
    int offset = object->map()->instance_size() + (index * kPointerSize);
    if (representation.IsDouble()) {
      __ mov(FieldOperand(receiver_reg, offset), storage_reg);
    } else {
      __ mov(FieldOperand(receiver_reg, offset), value_reg);
    }

    if (!representation.IsSmi()) {
      // Update the write barrier for the array address.
      if (!representation.IsDouble()) {
        __ mov(storage_reg, value_reg);
      }
      __ RecordWriteField(receiver_reg,
                          offset,
                          storage_reg,
                          scratch1,
                          EMIT_REMEMBERED_SET,
                          smi_check);
    }
  } else {
    // Write to the properties array.
    int offset = index * kPointerSize + FixedArray::kHeaderSize;
    // Get the properties array (optimistically).
    __ mov(scratch1, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));
    if (representation.IsDouble()) {
      __ mov(FieldOperand(scratch1, offset), storage_reg);
    } else {
      __ mov(FieldOperand(scratch1, offset), value_reg);
    }

    if (!representation.IsSmi()) {
      // Update the write barrier for the array address.
      if (!representation.IsDouble()) {
        __ mov(storage_reg, value_reg);
      }
      __ RecordWriteField(scratch1,
                          offset,
                          storage_reg,
                          receiver_reg,
                          EMIT_REMEMBERED_SET,
                          smi_check);
    }
  }

  // Return the value (register eax).
  ASSERT(value_reg.is(eax));
  __ ret(0);
}

// Both name_reg and receiver_reg are preserved on jumps to miss_label,
// but may be destroyed if store is successful.
void StoreStubCompiler::GenerateStoreField(MacroAssembler* masm,
                                           Handle<JSObject> object,
                                           LookupResult* lookup,
                                           Register receiver_reg,
                                           Register name_reg,
                                           Register value_reg,
                                           Register scratch1,
                                           Register scratch2,
                                           Label* miss_label) {
  // Stub never generated for non-global objects that require access
  // checks.
  ASSERT(object->IsJSGlobalProxy() || !object->IsAccessCheckNeeded());

  FieldIndex index = lookup->GetFieldIndex();

  Representation representation = lookup->representation();
  ASSERT(!representation.IsNone());
  if (representation.IsSmi()) {
    __ JumpIfNotSmi(value_reg, miss_label);
  } else if (representation.IsHeapObject()) {
    __ JumpIfSmi(value_reg, miss_label);
    HeapType* field_type = lookup->GetFieldType();
    HeapType::Iterator<Map> it = field_type->Classes();
    if (!it.Done()) {
      Label do_store;
      while (true) {
        __ CompareMap(value_reg, it.Current());
        it.Advance();
        if (it.Done()) {
          __ j(not_equal, miss_label);
          break;
        }
        __ j(equal, &do_store, Label::kNear);
      }
      __ bind(&do_store);
    }
  } else if (representation.IsDouble()) {
    // Load the double storage.
    if (index.is_inobject()) {
      __ mov(scratch1, FieldOperand(receiver_reg, index.offset()));
    } else {
      __ mov(scratch1, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));
      __ mov(scratch1, FieldOperand(scratch1, index.offset()));
    }

    // Store the value into the storage.
    Label do_store, heap_number;
    __ JumpIfNotSmi(value_reg, &heap_number);
    __ SmiUntag(value_reg);
    __ push(value_reg);
    __ fild_s(Operand(esp, 0));
    __ pop(value_reg);
    __ SmiTag(value_reg);
    __ jmp(&do_store);
    __ bind(&heap_number);
    __ CheckMap(value_reg, masm->isolate()->factory()->heap_number_map(),
                miss_label, DONT_DO_SMI_CHECK);
    __ fld_d(FieldOperand(value_reg, HeapNumber::kValueOffset));
    __ bind(&do_store);
    __ fstp_d(FieldOperand(scratch1, HeapNumber::kValueOffset));
    // Return the value (register eax).
    ASSERT(value_reg.is(eax));
    __ ret(0);
    return;
  }

  ASSERT(!representation.IsDouble());
  // TODO(verwaest): Share this code as a code stub.
  SmiCheck smi_check = representation.IsTagged()
      ? INLINE_SMI_CHECK : OMIT_SMI_CHECK;
  if (index.is_inobject()) {
    // Set the property straight into the object.
    __ mov(FieldOperand(receiver_reg, index.offset()), value_reg);

    if (!representation.IsSmi()) {
      // Update the write barrier for the array address.
      // Pass the value being stored in the now unused name_reg.
      __ mov(name_reg, value_reg);
      __ RecordWriteField(receiver_reg,
                          index.offset(),
                          name_reg,
                          scratch1,
                          EMIT_REMEMBERED_SET,
                          smi_check);
    }
  } else {
    // Write to the properties array.
    // Get the properties array (optimistically).
    __ mov(scratch1, FieldOperand(receiver_reg, JSObject::kPropertiesOffset));
    __ mov(FieldOperand(scratch1, index.offset()), value_reg);

    if (!representation.IsSmi()) {
      // Update the write barrier for the array address.
      // Pass the value being stored in the now unused name_reg.
      __ mov(name_reg, value_reg);
      __ RecordWriteField(scratch1,
                          index.offset(),
                          name_reg,
                          receiver_reg,
                          EMIT_REMEMBERED_SET,
                          smi_check);
    }
  }

  // Return the value (register eax).
  ASSERT(value_reg.is(eax));
  __ ret(0);
}

void StubCompiler::GenerateTailCall(MacroAssembler* masm, Handle<Code> code) {
  __ jmp(code, RelocInfo::CODE_TARGET);
}

#undef __
#define __ ACCESS_MASM(masm())

Register StubCompiler::CheckPrototypes(Handle<HeapType> type,
                                       Register object_reg,
                                       Handle<JSObject> holder,
                                       Register holder_reg,
                                       Register scratch1,
                                       Register scratch2,
                                       Handle<Name> name,
                                       Label* miss,
                                       PrototypeCheckType check) {
  Handle<Map> receiver_map(IC::TypeToMap(*type, isolate()));

  // Make sure there's no overlap between holder and object registers.
  ASSERT(!scratch1.is(object_reg) && !scratch1.is(holder_reg));
  ASSERT(!scratch2.is(object_reg) && !scratch2.is(holder_reg)
         && !scratch2.is(scratch1));

  // Keep track of the current object in register reg.
  Register reg = object_reg;
  int depth = 0;

  Handle<JSObject> current = Handle<JSObject>::null();
  if (type->IsConstant()) current =
      Handle<JSObject>::cast(type->AsConstant()->Value());
  Handle<JSObject> prototype = Handle<JSObject>::null();
  Handle<Map> current_map = receiver_map;
  Handle<Map> holder_map(holder->map());
  // Traverse the prototype chain and check the maps in the prototype chain for
  // fast and global objects or do negative lookup for normal objects.
  while (!current_map.is_identical_to(holder_map)) {
    ++depth;

    // Only global objects and objects that do not require access
    // checks are allowed in stubs.
    ASSERT(current_map->IsJSGlobalProxyMap() ||
           !current_map->is_access_check_needed());

    prototype = handle(JSObject::cast(current_map->prototype()));
    if (current_map->is_dictionary_map() &&
        !current_map->IsJSGlobalObjectMap() &&
        !current_map->IsJSGlobalProxyMap()) {
      if (!name->IsUniqueName()) {
        ASSERT(name->IsString());
        name = factory()->InternalizeString(Handle<String>::cast(name));
      }
      ASSERT(current.is_null() ||
             current->property_dictionary()->FindEntry(name) ==
             NameDictionary::kNotFound);

      GenerateDictionaryNegativeLookup(masm(), miss, reg, name,
                                       scratch1, scratch2);

      __ mov(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
      reg = holder_reg;  // From now on the object will be in holder_reg.
      __ mov(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
    } else {
      bool in_new_space = heap()->InNewSpace(*prototype);
      if (depth != 1 || check == CHECK_ALL_MAPS) {
        __ CheckMap(reg, current_map, miss, DONT_DO_SMI_CHECK);
      }

      // Check access rights to the global object.  This has to happen after
      // the map check so that we know that the object is actually a global
      // object.
      if (current_map->IsJSGlobalProxyMap()) {
        __ CheckAccessGlobalProxy(reg, scratch1, scratch2, miss);
      } else if (current_map->IsJSGlobalObjectMap()) {
        GenerateCheckPropertyCell(
            masm(), Handle<JSGlobalObject>::cast(current), name,
            scratch2, miss);
      }

      if (in_new_space) {
        // Save the map in scratch1 for later.
        __ mov(scratch1, FieldOperand(reg, HeapObject::kMapOffset));
      }

      reg = holder_reg;  // From now on the object will be in holder_reg.

      if (in_new_space) {
        // The prototype is in new space; we cannot store a reference to it
        // in the code.  Load it from the map.
        __ mov(reg, FieldOperand(scratch1, Map::kPrototypeOffset));
      } else {
        // The prototype is in old space; load it directly.
        __ mov(reg, prototype);
      }
    }

    // Go to the next object in the prototype chain.
    current = prototype;
    current_map = handle(current->map());
  }

  // Log the check depth.
  LOG(isolate(), IntEvent("check-maps-depth", depth + 1));

  if (depth != 0 || check == CHECK_ALL_MAPS) {
    // Check the holder map.
    __ CheckMap(reg, current_map, miss, DONT_DO_SMI_CHECK);
  }

  // Perform security check for access to the global object.
  ASSERT(current_map->IsJSGlobalProxyMap() ||
         !current_map->is_access_check_needed());
  if (current_map->IsJSGlobalProxyMap()) {
    __ CheckAccessGlobalProxy(reg, scratch1, scratch2, miss);
  }

  // Return the register containing the holder.
  return reg;
}

void LoadStubCompiler::HandlerFrontendFooter(Handle<Name> name, Label* miss) {
  if (!miss->is_unused()) {
    Label success;
    __ jmp(&success);
    __ bind(miss);
    TailCallBuiltin(masm(), MissBuiltin(kind()));
    __ bind(&success);
  }
}

void StoreStubCompiler::HandlerFrontendFooter(Handle<Name> name, Label* miss) {
  if (!miss->is_unused()) {
    Label success;
    __ jmp(&success);
    GenerateRestoreName(masm(), miss, name);
    TailCallBuiltin(masm(), MissBuiltin(kind()));
    __ bind(&success);
  }
}

Register LoadStubCompiler::CallbackHandlerFrontend(
    Handle<HeapType> type,
    Register object_reg,
    Handle<JSObject> holder,
    Handle<Name> name,
    Handle<Object> callback) {
  Label miss;

  Register reg = HandlerFrontendHeader(type, object_reg, holder, name, &miss);

  if (!holder->HasFastProperties() && !holder->IsJSGlobalObject()) {
    ASSERT(!reg.is(scratch2()));
    ASSERT(!reg.is(scratch3()));
    Register dictionary = scratch1();
    bool must_preserve_dictionary_reg = reg.is(dictionary);

    // Load the properties dictionary.
    if (must_preserve_dictionary_reg) {
      __ push(dictionary);
    }
    __ mov(dictionary, FieldOperand(reg, JSObject::kPropertiesOffset));

    // Probe the dictionary.
    Label probe_done, pop_and_miss;
    NameDictionaryLookupStub::GeneratePositiveLookup(masm(),
                                                     &pop_and_miss,
                                                     &probe_done,
                                                     dictionary,
                                                     this->name(),
                                                     scratch2(),
                                                     scratch3());
    __ bind(&pop_and_miss);
    if (must_preserve_dictionary_reg) {
      __ pop(dictionary);
    }
    __ jmp(&miss);
    __ bind(&probe_done);

    // If probing finds an entry in the dictionary, scratch2 contains the
    // index into the dictionary. Check that the value is the callback.
    Register index = scratch2();
    const int kElementsStartOffset =
        NameDictionary::kHeaderSize +
        NameDictionary::kElementsStartIndex * kPointerSize;
    const int kValueOffset = kElementsStartOffset + kPointerSize;
    __ mov(scratch3(),
           Operand(dictionary, index, times_4, kValueOffset - kHeapObjectTag));
    if (must_preserve_dictionary_reg) {
      __ pop(dictionary);
    }
    __ cmp(scratch3(), callback);
    __ j(not_equal, &miss);
  }

  HandlerFrontendFooter(name, &miss);
  return reg;
}

void LoadStubCompiler::GenerateLoadField(Register reg,
                                         Handle<JSObject> holder,
                                         FieldIndex field,
                                         Representation representation) {
  if (!reg.is(receiver())) __ mov(receiver(), reg);
  if (kind() == Code::LOAD_IC) {
    LoadFieldStub stub(isolate(), field);
    GenerateTailCall(masm(), stub.GetCode());
  } else {
    KeyedLoadFieldStub stub(isolate(), field);
    GenerateTailCall(masm(), stub.GetCode());
  }
}

void LoadStubCompiler::GenerateLoadCallback(
    Register reg,
    Handle<ExecutableAccessorInfo> callback) {
  // Insert additional parameters into the stack frame above return address.
  ASSERT(!scratch3().is(reg));
  __ pop(scratch3());  // Get return address to place it below.

  STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 0);
  STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 1);
  STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 2);
  STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 3);
  STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 4);
  STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 5);
  __ push(receiver());  // receiver
  // Push data from ExecutableAccessorInfo.
  if (isolate()->heap()->InNewSpace(callback->data())) {
    ASSERT(!scratch2().is(reg));
    __ mov(scratch2(), Immediate(callback));
    __ push(FieldOperand(scratch2(), ExecutableAccessorInfo::kDataOffset));
  } else {
    __ push(Immediate(Handle<Object>(callback->data(), isolate())));
  }
  __ push(Immediate(isolate()->factory()->undefined_value()));  // ReturnValue
  // ReturnValue default value
  __ push(Immediate(isolate()->factory()->undefined_value()));
  __ push(Immediate(reinterpret_cast<int>(isolate())));
  __ push(reg);  // holder

  // Save a pointer to where we pushed the arguments. This will be
  // passed as the const PropertyAccessorInfo& to the C++ callback.
  __ push(esp);

  __ push(name());  // name

  __ push(scratch3());  // Restore return address.

  // Abi for CallApiGetter
  Register getter_address = edx;
  Address function_address = v8::ToCData<Address>(callback->getter());
  __ mov(getter_address, Immediate(function_address));

  CallApiGetterStub stub(isolate());
  __ TailCallStub(&stub);
}

void LoadStubCompiler::GenerateLoadConstant(Handle<Object> value) {
  // Return the constant value.
  __ LoadObject(eax, value);
  __ ret(0);
}

void LoadStubCompiler::GenerateLoadInterceptor(
    Register holder_reg,
    Handle<Object> object,
    Handle<JSObject> interceptor_holder,
    LookupResult* lookup,
    Handle<Name> name) {
  ASSERT(interceptor_holder->HasNamedInterceptor());
  ASSERT(!interceptor_holder->GetNamedInterceptor()->getter()->IsUndefined());

  // So far the most popular follow ups for interceptor loads are FIELD
  // and CALLBACKS, so inline only them, other cases may be added
  // later.
  bool compile_followup_inline = false;
  if (lookup->IsFound() && lookup->IsCacheable()) {
    if (lookup->IsField()) {
      compile_followup_inline = true;
    } else if (lookup->type() == CALLBACKS &&
               lookup->GetCallbackObject()->IsExecutableAccessorInfo()) {
      ExecutableAccessorInfo* callback =
          ExecutableAccessorInfo::cast(lookup->GetCallbackObject());
      compile_followup_inline = callback->getter() != NULL &&
          callback->IsCompatibleReceiver(*object);
    }
  }

  if (compile_followup_inline) {
    // Compile the interceptor call, followed by inline code to load the
    // property from further up the prototype chain if the call fails.
    // Check that the maps haven't changed.
    ASSERT(holder_reg.is(receiver()) || holder_reg.is(scratch1()));

    // Preserve the receiver register explicitly whenever it is different from
    // the holder and it is needed should the interceptor return without any
    // result. The CALLBACKS case needs the receiver to be passed into C++ code,
    // the FIELD case might cause a miss during the prototype check.
    bool must_perfrom_prototype_check = *interceptor_holder != lookup->holder();
    bool must_preserve_receiver_reg = !receiver().is(holder_reg) &&
        (lookup->type() == CALLBACKS || must_perfrom_prototype_check);

    // Save necessary data before invoking an interceptor.
    // Requires a frame to make GC aware of pushed pointers.
    {
      FrameScope frame_scope(masm(), StackFrame::INTERNAL);

      if (must_preserve_receiver_reg) {
        __ push(receiver());
      }
      __ push(holder_reg);
      __ push(this->name());

      // Invoke an interceptor.  Note: map checks from receiver to
      // interceptor's holder has been compiled before (see a caller
      // of this method.)
      CompileCallLoadPropertyWithInterceptor(
          masm(), receiver(), holder_reg, this->name(), interceptor_holder,
          IC::kLoadPropertyWithInterceptorOnly);

      // Check if interceptor provided a value for property.  If it's
      // the case, return immediately.
      Label interceptor_failed;
      __ cmp(eax, factory()->no_interceptor_result_sentinel());
      __ j(equal, &interceptor_failed);
      frame_scope.GenerateLeaveFrame();
      __ ret(0);

      // Clobber registers when generating debug-code to provoke errors.
      __ bind(&interceptor_failed);
      if (FLAG_debug_code) {
        __ mov(receiver(), Immediate(BitCast<int32_t>(kZapValue)));
        __ mov(holder_reg, Immediate(BitCast<int32_t>(kZapValue)));
        __ mov(this->name(), Immediate(BitCast<int32_t>(kZapValue)));
      }

      __ pop(this->name());
      __ pop(holder_reg);
      if (must_preserve_receiver_reg) {
        __ pop(receiver());
      }

      // Leave the internal frame.
    }

    GenerateLoadPostInterceptor(holder_reg, interceptor_holder, name, lookup);
  } else {  // !compile_followup_inline
    // Call the runtime system to load the interceptor.
    // Check that the maps haven't changed.
    __ pop(scratch2());  // save old return address
    PushInterceptorArguments(masm(), receiver(), holder_reg,
                             this->name(), interceptor_holder);
    __ push(scratch2());  // restore old return address

    ExternalReference ref =
        ExternalReference(IC_Utility(IC::kLoadPropertyWithInterceptor),
                          isolate());
    __ TailCallExternalReference(ref, StubCache::kInterceptorArgsLength, 1);
  }
}

Handle<Code> StoreStubCompiler::CompileStoreCallback(
    Handle<JSObject> object,
    Handle<JSObject> holder,
    Handle<Name> name,
    Handle<ExecutableAccessorInfo> callback) {
  Register holder_reg = HandlerFrontend(
      IC::CurrentTypeOf(object, isolate()), receiver(), holder, name);

  __ pop(scratch1());  // remove the return address
  __ push(receiver());
  __ push(holder_reg);
  __ Push(callback);
  __ Push(name);
  __ push(value());
  __ push(scratch1());  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference store_callback_property =
      ExternalReference(IC_Utility(IC::kStoreCallbackProperty), isolate());
  __ TailCallExternalReference(store_callback_property, 5, 1);

  // Return the generated code.
  return GetCode(kind(), Code::FAST, name);
}

#undef __
#define __ ACCESS_MASM(masm)

void StoreStubCompiler::GenerateStoreViaSetter(
    MacroAssembler* masm,
    Handle<HeapType> type,
    Register receiver,
    Handle<JSFunction> setter) {
  // ----------- S t a t e -------------
  //  -- esp[0] : return address
  // -----------------------------------
  {
    FrameScope scope(masm, StackFrame::INTERNAL);

    // Save value register, so we can restore it later.
    __ push(value());

    if (!setter.is_null()) {
      // Call the JavaScript setter with receiver and value on the stack.
      if (IC::TypeToMap(*type, masm->isolate())->IsJSGlobalObjectMap()) {
        // Swap in the global receiver.
        __ mov(receiver,
               FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset));
      }
      __ push(receiver);
      __ push(value());
      ParameterCount actual(1);
      ParameterCount expected(setter);
      __ InvokeFunction(setter, expected, actual,
                        CALL_FUNCTION, NullCallWrapper());
    } else {
      // If we generate a global code snippet for deoptimization only, remember
      // the place to continue after deoptimization.
      masm->isolate()->heap()->SetSetterStubDeoptPCOffset(masm->pc_offset());
    }

    // We have to return the passed value, not the return value of the setter.
    __ pop(eax);

    // Restore context register.
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
  }
  __ ret(0);
}

#undef __
#define __ ACCESS_MASM(masm())

Handle<Code> StoreStubCompiler::CompileStoreInterceptor(
    Handle<JSObject> object,
    Handle<Name> name) {
  __ pop(scratch1());  // remove the return address
  __ push(receiver());
  __ push(this->name());
  __ push(value());
  __ push(scratch1());  // restore return address

  // Do tail-call to the runtime system.
  ExternalReference store_ic_property =
      ExternalReference(IC_Utility(IC::kStoreInterceptorProperty), isolate());
  __ TailCallExternalReference(store_ic_property, 3, 1);

  // Return the generated code.
  return GetCode(kind(), Code::FAST, name);
}

void StoreStubCompiler::GenerateStoreArrayLength() {
  // Prepare tail call to StoreIC_ArrayLength.
  __ pop(scratch1());  // remove the return address
  __ push(receiver());
  __ push(value());
  __ push(scratch1());  // restore return address

  ExternalReference ref =
      ExternalReference(IC_Utility(IC::kStoreIC_ArrayLength),
                        masm()->isolate());
  __ TailCallExternalReference(ref, 2, 1);
}

Handle<Code> KeyedStoreStubCompiler::CompileStorePolymorphic(
    MapHandleList* receiver_maps,
    CodeHandleList* handler_stubs,
    MapHandleList* transitioned_maps) {
  Label miss;
  __ JumpIfSmi(receiver(), &miss, Label::kNear);
  __ mov(scratch1(), FieldOperand(receiver(), HeapObject::kMapOffset));
  for (int i = 0; i < receiver_maps->length(); ++i) {
    __ cmp(scratch1(), receiver_maps->at(i));
    if (transitioned_maps->at(i).is_null()) {
      __ j(equal, handler_stubs->at(i));
    } else {
      Label next_map;
      __ j(not_equal, &next_map, Label::kNear);
      __ mov(transition_map(), Immediate(transitioned_maps->at(i)));
      __ jmp(handler_stubs->at(i), RelocInfo::CODE_TARGET);
      __ bind(&next_map);
    }
  }
  __ bind(&miss);
  TailCallBuiltin(masm(), MissBuiltin(kind()));

  // Return the generated code.
  return GetICCode(
      kind(), Code::NORMAL, factory()->empty_string(), POLYMORPHIC);
}

Handle<Code> LoadStubCompiler::CompileLoadNonexistent(Handle<HeapType> type,
                                                      Handle<JSObject> last,
                                                      Handle<Name> name) {
  NonexistentHandlerFrontend(type, last, name);

  // Return undefined if maps of the full prototype chain are still the
  // same and no global property with this name contains a value.
  __ mov(eax, isolate()->factory()->undefined_value());
  __ ret(0);

  // Return the generated code.
  return GetCode(kind(), Code::FAST, name);
}

Register* LoadStubCompiler::registers() {
  // receiver, name, scratch1, scratch2, scratch3, scratch4.
  Register receiver = LoadIC::ReceiverRegister();
  Register name = LoadIC::NameRegister();
  static Register registers[] = { receiver, name, ebx, eax, edi, no_reg };
  return registers;
}

Register* KeyedLoadStubCompiler::registers() {
  // receiver, name, scratch1, scratch2, scratch3, scratch4.
  Register receiver = KeyedLoadIC::ReceiverRegister();
  Register name = KeyedLoadIC::NameRegister();
  static Register registers[] = { receiver, name, ebx, eax, edi, no_reg };
  return registers;
}

Register StoreStubCompiler::value() {
  return eax;
}

Register* StoreStubCompiler::registers() {
  // receiver, name, scratch1, scratch2, scratch3.
  static Register registers[] = { edx, ecx, ebx, edi, no_reg };
  return registers;
}

Register* KeyedStoreStubCompiler::registers() {
  // receiver, name, scratch1, scratch2, scratch3.
  static Register registers[] = { edx, ecx, ebx, edi, no_reg };
  return registers;
}

#undef __
#define __ ACCESS_MASM(masm)

void LoadStubCompiler::GenerateLoadViaGetter(MacroAssembler* masm,
                                             Handle<HeapType> type,
                                             Register receiver,
                                             Handle<JSFunction> getter) {
  {
    FrameScope scope(masm, StackFrame::INTERNAL);

    if (!getter.is_null()) {
      // Call the JavaScript getter with the receiver on the stack.
      if (IC::TypeToMap(*type, masm->isolate())->IsJSGlobalObjectMap()) {
        // Swap in the global receiver.
        __ mov(receiver,
                FieldOperand(receiver, JSGlobalObject::kGlobalReceiverOffset));
      }
      __ push(receiver);
      ParameterCount actual(0);
      ParameterCount expected(getter);
      __ InvokeFunction(getter, expected, actual,
                        CALL_FUNCTION, NullCallWrapper());
    } else {
      // If we generate a global code snippet for deoptimization only, remember
      // the place to continue after deoptimization.
      masm->isolate()->heap()->SetGetterStubDeoptPCOffset(masm->pc_offset());
    }

    // Restore context register.
    __ mov(esi, Operand(ebp, StandardFrameConstants::kContextOffset));
  }
  __ ret(0);
}

#undef __
#define __ ACCESS_MASM(masm())

Handle<Code> LoadStubCompiler::CompileLoadGlobal(
    Handle<HeapType> type,
    Handle<GlobalObject> global,
    Handle<PropertyCell> cell,
    Handle<Name> name,
    bool is_dont_delete) {
  Label miss;

  HandlerFrontendHeader(type, receiver(), global, name, &miss);
  // Get the value from the cell.
  if (masm()->serializer_enabled()) {
    __ mov(eax, Immediate(cell));
    __ mov(eax, FieldOperand(eax, PropertyCell::kValueOffset));
  } else {
    __ mov(eax, Operand::ForCell(cell));
  }

  // Check for deleted property if property can actually be deleted.
  if (!is_dont_delete) {
    __ cmp(eax, factory()->the_hole_value());
    __ j(equal, &miss);
  } else if (FLAG_debug_code) {
    __ cmp(eax, factory()->the_hole_value());
    __ Check(not_equal, kDontDeleteCellsCannotContainTheHole);
  }

  Counters* counters = isolate()->counters();
  __ IncrementCounter(counters->named_load_global_stub(), 1);
  // The code above already loads the result into the return register.
  __ ret(0);

  HandlerFrontendFooter(name, &miss);

  // Return the generated code.
  return GetCode(kind(), Code::NORMAL, name);
}

Handle<Code> BaseLoadStoreStubCompiler::CompilePolymorphicIC(
    TypeHandleList* types,
    CodeHandleList* handlers,
    Handle<Name> name,
    Code::StubType type,
    IcCheckType check) {
  Label miss;

  if (check == PROPERTY &&
      (kind() == Code::KEYED_LOAD_IC || kind() == Code::KEYED_STORE_IC)) {
    __ cmp(this->name(), Immediate(name));
    __ j(not_equal, &miss);
  }

  Label number_case;
  Label* smi_target = IncludesNumberType(types) ? &number_case : &miss;
  __ JumpIfSmi(receiver(), smi_target);

  Register map_reg = scratch1();
  __ mov(map_reg, FieldOperand(receiver(), HeapObject::kMapOffset));
  int receiver_count = types->length();
  int number_of_handled_maps = 0;
  for (int current = 0; current < receiver_count; ++current) {
    Handle<HeapType> type = types->at(current);
    Handle<Map> map = IC::TypeToMap(*type, isolate());
    if (!map->is_deprecated()) {
      number_of_handled_maps++;
      __ cmp(map_reg, map);
      if (type->Is(HeapType::Number())) {
        ASSERT(!number_case.is_unused());
        __ bind(&number_case);
      }
      __ j(equal, handlers->at(current));
    }
  }
  ASSERT(number_of_handled_maps != 0);

  __ bind(&miss);
  TailCallBuiltin(masm(), MissBuiltin(kind()));

  // Return the generated code.
  InlineCacheState state =
      number_of_handled_maps > 1 ? POLYMORPHIC : MONOMORPHIC;
  return GetICCode(kind(), type, name, state);
}

#undef __
#define __ ACCESS_MASM(masm)

void KeyedLoadStubCompiler::GenerateLoadDictionaryElement(
    MacroAssembler* masm) {
  // ----------- S t a t e -------------
  //  -- ecx    : key
  //  -- edx    : receiver
  //  -- esp[0] : return address
  // -----------------------------------
  Label slow, miss;

  // This stub is meant to be tail-jumped to, the receiver must already
  // have been verified by the caller to not be a smi.
  __ JumpIfNotSmi(ecx, &miss);
  __ mov(ebx, ecx);
  __ SmiUntag(ebx);
  __ mov(eax, FieldOperand(edx, JSObject::kElementsOffset));

  // Push receiver on the stack to free up a register for the dictionary
  // probing.
  __ push(edx);
  __ LoadFromNumberDictionary(&slow, eax, ecx, ebx, edx, edi, eax);
  // Pop receiver before returning.
  __ pop(edx);
  __ ret(0);

  __ bind(&slow);
  __ pop(edx);

  // ----------- S t a t e -------------
  //  -- ecx    : key
  //  -- edx    : receiver
  //  -- esp[0] : return address
  // -----------------------------------
  TailCallBuiltin(masm, Builtins::kKeyedLoadIC_Slow);

  __ bind(&miss);
  // ----------- S t a t e -------------
  //  -- ecx    : key
  //  -- edx    : receiver
  //  -- esp[0] : return address
  // -----------------------------------
  TailCallBuiltin(masm, Builtins::kKeyedLoadIC_Miss);
}

#undef __

} }  // namespace v8::internal

#endif  // V8_TARGET_ARCH_X87


text:
<!DOCTYPE html>

  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta charset="utf-8"/>
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

  <title>

      Thank You · prepsourced.com

  </title>

  <link rel="stylesheet" href="/public/css/style.css" type="text/css" media="all"/>
  <link rel="stylesheet" href="/public/css/poole.css">
  <link rel="stylesheet" href="/public/css/syntax.css">
  <link rel="stylesheet" href="/public/css/lanyon.css">
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700|Open+Sans+Condensed:300,700' rel='stylesheet' type='text/css'>

  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="/public/apple-touch-icon-precomposed.png">
  <link rel="shortcut icon" href="/public/favicon.ico">

  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">

<input type="checkbox" class="sidebar-checkbox" id="sidebar-checkbox">

Prepsourced.com - your weekly prepping digest.

    Home

    Currently v1.0.0

      © 2015. All rights reserved.

            prepsourced.com
            Your weekly prepping digest

Thank You

Thanks for signing up for prepsourced.com!

Check your email now for your first edition.
(each new edition will arrive in your inbox on Sunday night)

Not seeing the first edition in you inbox?

Be sure to check your spam folder and whitelist craig.bensemann@gmail.com

If you still can't find it email craig.bensemann@gmail.com and we'll get you taken care of.

Copyright 2015 © prepsourced.com / All Rights Reserved

redpajama_set_name: RedPajamaGithub


text:
#include <grpc/support/port_platform.h>

#ifdef GPR_WIN32

#include "src/core/support/env.h"
#include "src/core/support/string.h"

#include <stdlib.h>

#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/string_util.h>

char *gpr_getenv(const char *name) {
  size_t size;
  char *result = NULL;
  char *duplicated;
  errno_t err;

  err = _dupenv_s(&result, &size, name);
  if (err) return NULL;
  duplicated = gpr_strdup(result);
  free(result);
  return duplicated;
}

void gpr_setenv(const char *name, const char *value) {
  errno_t res = _putenv_s(name, value);
  GPR_ASSERT(res == 0);
}

#endif /* GPR_WIN32 */


text:
//= require "license"

/**
 *  == scripty2 ui ==
 *  * [[s2.css]]: functions for CSS parsing, color normalization and CSS value interpolation.
**/

/**
 *  == scripty2 core ==
 *
 *  Core contains various JavaScript and DOM extensions used by scripty2 fx and scripty2 ui,
 *  plus developer utility classes.
**/

/** section: scripty2 core
 * s2
 * The s2 namespace is the main container for the various scripty2 frameworks
 * and also provides the libraries' version number and information about extensions.
**/
var s2 = {
  /**
   * s2.Version = '<%= SCRIPTY2_VERSION %>'
   *
   * This constant lists the version of scripty2.
  **/
  Version: '<%= SCRIPTY2_VERSION %>',

  /**
   * s2.Extensions
   *
   * Holds information about extension modules plugged into scripty2. Currently unused.
  **/
  Extensions: {}
};

//= require "css"
//= require "effects"

//= require "extensions/misc"
//= require "extensions/element"

//= require "addons/helpers"


text:
<?xml version="1.0" encoding="UTF-8"?>
<sbml xmlns="http://www.sbml.org/sbml/level2/version2" level="2" version="2">
  <model id="case_01117" name="case_01117">
    <listOfCompartments>
      <compartment id="C" size="1" constant="false"/>
    </listOfCompartments>
    <listOfSpecies>
      <species id="S1" compartment="C" initialConcentration="1" constant="true"/>
    </listOfSpecies>
    <listOfRules>
      <rateRule variable="C">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
          <cn type="integer"> 1 </cn>
        </math>
      </rateRule>
    </listOfRules>
  </model>
</sbml>


text:
export interface QueryResponse{
  data
}


text:
/**
 * @name Mocker
 * @fileOverview Creates new context for requirejs to mock module's dependencies
 * @author sergey
 */
define(function () {
  'use strict';
  var cnt = 0;

  return function(stubs) {
    var map = {};
    cnt++;

    for (var key in stubs) {
      if (stubs.hasOwnProperty(key)) {
        var stubName = ['stub', key.replace(/\//g, '_'), cnt].join('_');
        map[key] = stubName;
        (function (name, value){
          return define(name, function () {
            return value;
          });
        })(stubName, stubs[key]);
      }
    }

    return require.config({
      context: "context_" + cnt,
      map: {
        "*": map
      },
      baseUrl: require.s.contexts._.config.baseUrl
    });
  };
});


text:
from openstack_dashboard.dashboards.project.images.images \
    import forms as images_forms

class AdminCreateImageForm(images_forms.CreateImageForm):
    pass

class AdminUpdateImageForm(images_forms.UpdateImageForm):
    pass


text:
require File.expand_path("../../../spec_helper", __FILE__)
require File.join(FIXTURE_PATH, 'more', 'card')
require File.join(FIXTURE_PATH, 'more', 'course')

# add a default value
Card.property :bg_color, :default => '#ccc'

class BusinessCard < Card
  property :extension_code
  property :job_title
end

class DesignBusinessCard < BusinessCard
  property :bg_color, :default => '#eee'
end

class OnlineCourse < Course
  property :url
  view_by :url
end

class Animal < CouchRest::ExtendedDocument
  use_database TEST_SERVER.default_database
  property :name
  view_by :name
end

class Dog < Animal; end

describe "Subclassing an ExtendedDocument" do

  before(:each) do
    @card = BusinessCard.new
  end

  it "shouldn't messup the parent's properties" do
    Card.properties.should_not == BusinessCard.properties
  end

  it "should share the same db default" do
    @card.database.uri.should == Card.database.uri
  end

  it "should share the same autovalidation details" do
    @card.auto_validation.should be_true
  end

  it "should have kept the validation details" do
    @card.should_not be_valid
  end

  it "should have added the new validation details" do
    validated_fields = @card.class.validators.contexts[:default].map{|v| v.field_name}
    validated_fields.should include(:extension_code)
    validated_fields.should include(:job_title)
  end

  it "should not add to the parent's validations" do
    validated_fields = Card.validators.contexts[:default].map{|v| v.field_name}
    validated_fields.should_not include(:extension_code)
    validated_fields.should_not include(:job_title)
  end

  it "should inherit default property values" do
    @card.bg_color.should == '#ccc'
  end

  it "should be able to overwrite a default property" do
    DesignBusinessCard.new.bg_color.should == '#eee'
  end

  it "should have a design doc slug based on the subclass name" do
    Course.refresh_design_doc
    OnlineCourse.design_doc_slug.should =~ /^OnlineCourse/
  end

  it "should have its own design_doc_fresh" do
    Animal.refresh_design_doc
    Dog.design_doc_fresh.should_not == true
    Dog.refresh_design_doc
    Dog.design_doc_fresh.should == true
  end

  it "should not add views to the parent's design_doc" do
    Course.design_doc['views'].keys.should_not include('by_url')
  end

  it "should not add the parent's views to its design doc" do
    Course.refresh_design_doc
    OnlineCourse.refresh_design_doc
    OnlineCourse.design_doc['views'].keys.should_not include('by_title')
  end

  it "should have an all view with a guard clause for couchrest-type == subclass name in the map function" do
    OnlineCourse.design_doc['views']['all']['map'].should =~ /if \(doc\['couchrest-type'\] == 'OnlineCourse'\)/
  end
end


text:
package com.intellij.compiler.chainsSearch;

import com.intellij.codeInsight.NullableNotNullManager;
import com.intellij.codeInsight.completion.*;
import com.intellij.codeInsight.lookup.ExpressionLookupItem;
import com.intellij.codeInsight.lookup.LookupElement;
import com.intellij.codeInsight.lookup.LookupElementDecorator;
import com.intellij.codeInsight.lookup.VariableLookupItem;
import com.intellij.compiler.chainsSearch.completion.lookup.ChainCompletionNewVariableLookupElement;
import com.intellij.compiler.chainsSearch.completion.lookup.JavaRelevantChainLookupElement;
import com.intellij.compiler.chainsSearch.context.ChainCompletionContext;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.util.Couple;
import com.intellij.psi.*;
import com.intellij.psi.util.InheritanceUtil;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.ObjectUtils;
import com.intellij.util.containers.ContainerUtil;
import org.jetbrains.annotations.NotNull;

import java.util.Collection;
import java.util.stream.Collectors;

public class MethodChainLookupRangingHelper {
  @NotNull
  public static LookupElement toLookupElement(OperationChain chain,
                                              ChainCompletionContext context) {
    int unreachableParametersCount = 0;
    int matchedParametersInContext = 0;
    LookupElement chainLookupElement = null;

    for (ChainOperation op : chain.getPath()) {
      if (op instanceof ChainOperation.MethodCall) {
        PsiMethod method = ObjectUtils.notNull(MethodChainsSearchUtil.getMethodWithMinNotPrimitiveParameters(((ChainOperation.MethodCall)op).getCandidates(),
                                                                                context.getTarget().getTargetClass()));
        Couple<Integer> info = calculateParameterInfo(method, context);
        unreachableParametersCount += info.getFirst();
        matchedParametersInContext += info.getSecond();

        if (chainLookupElement == null) {
          LookupElement qualifierLookupElement = method.hasModifierProperty(PsiModifier.STATIC) ? null : createQualifierLookupElement(chain.getQualifierClass(), context);
          LookupElement headLookupElement = createMethodLookupElement(method);
          chainLookupElement = qualifierLookupElement == null ? headLookupElement : new JavaChainLookupElement(qualifierLookupElement, headLookupElement);
        } else {
          chainLookupElement = new JavaChainLookupElement(chainLookupElement, new JavaMethodCallElement(method));
        }
      } else {
        if (chainLookupElement == null) {
          chainLookupElement = createQualifierLookupElement(chain.getQualifierClass(), context);
        }
        PsiClass castClass = ((ChainOperation.TypeCast)op).getCastClass();
        PsiClassType type = JavaPsiFacade.getElementFactory(castClass.getProject()).createType(castClass);
        chainLookupElement = PrioritizedLookupElement.withPriority(CastingLookupElementDecorator.createCastingElement(chainLookupElement, type), -1);
      }
    }

    if (context.getTarget().isIteratorAccess()) {
      chainLookupElement = decorateWithIteratorAccess(chain.getFirst()[0], chainLookupElement);
    }

    return new JavaRelevantChainLookupElement(ObjectUtils.notNull(chainLookupElement),
                                              new ChainRelevance(chain.length(), unreachableParametersCount, matchedParametersInContext));
  }

  @NotNull
  private static LookupElementDecorator<LookupElement> decorateWithIteratorAccess(PsiMethod method, LookupElement chainLookupElement) {
    return new LookupElementDecorator<LookupElement>(chainLookupElement) {
      @Override
      public void handleInsert(InsertionContext context) {
        super.handleInsert(context);
        Document document = context.getDocument();
        int tail = context.getTailOffset();
        PsiType tailReturnType = method.getReturnType();
        if (tailReturnType instanceof PsiArrayType) {
          document.insertString(tail, "[0]");
          context.getEditor().getCaretModel().moveToOffset(tail + 1);
        } else {
          PsiClass returnClass = ObjectUtils.notNull(PsiUtil.resolveClassInClassTypeOnly(tailReturnType));
          PsiDocumentManager.getInstance(context.getProject()).doPostponedOperationsAndUnblockDocument(document);
          if (InheritanceUtil.isInheritor(returnClass, CommonClassNames.JAVA_UTIL_LIST)) {
            document.insertString(tail, ".get(0)");
            context.getEditor().getCaretModel().moveToOffset(tail + 5);
          } else if (InheritanceUtil.isInheritor(returnClass, CommonClassNames.JAVA_UTIL_COLLECTION)) {
            document.insertString(tail, ".iterator().next()");
          } else if (InheritanceUtil.isInheritor(returnClass, CommonClassNames.JAVA_UTIL_ITERATOR)) {
            document.insertString(tail, ".next()");
          } else if (InheritanceUtil.isInheritor(returnClass, CommonClassNames.JAVA_UTIL_STREAM_STREAM)) {
            document.insertString(tail, ".findFirst().get()");
          }
        }
      }
    };
  }

  @NotNull
  private static LookupElement createQualifierLookupElement(@NotNull PsiClass qualifierClass,
                                                            @NotNull ChainCompletionContext context) {
    PsiNamedElement element = context.getQualifiers(qualifierClass).findFirst().orElse(null);
    if (element == null) {
      return new ChainCompletionNewVariableLookupElement(qualifierClass, context);
    } else {
      if (element instanceof PsiVariable) {
        return new VariableLookupItem((PsiVariable)element);
      }
      else if (element instanceof PsiMethod) {
        return createMethodLookupElement((PsiMethod)element);
      }
      throw new AssertionError("unexpected element: " + element);
    }
  }

  @NotNull
  private static Couple<Integer> calculateParameterInfo(@NotNull PsiMethod method,
                                                        @NotNull ChainCompletionContext context) {
    int unreachableParametersCount = 0;
    int matchedParametersInContext = 0;
    for (PsiParameter parameter : method.getParameterList().getParameters()) {
      PsiType type = parameter.getType();
      if (!ChainCompletionContext.isWidelyUsed(type)) {
        Collection<PsiElement> contextVariables = context.getQualifiers(type).collect(Collectors.toList());
        PsiElement contextVariable = ContainerUtil.getFirstItem(contextVariables, null);
        if (contextVariable != null) {
          matchedParametersInContext++;
          continue;
        }
        if (!NullableNotNullManager.isNullable(parameter)) {
          unreachableParametersCount++;
        }
      }
    }

    return Couple.of(unreachableParametersCount, matchedParametersInContext);
  }

  @NotNull
  private static LookupElement createMethodLookupElement(@NotNull PsiMethod method) {
    LookupElement result;
    if (method.isConstructor()) {
      PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(method.getProject());
      result = new ExpressionLookupItem(elementFactory.createExpressionFromText("new " + method.getContainingClass().getQualifiedName() + "()", null));
    } else if (method.hasModifierProperty(PsiModifier.STATIC)) {
      result = new JavaMethodCallElement(method, false, true);
    } else {
      result = new JavaMethodCallElement(method);
    }
    return result;
  }
}


text:
<form id="{$form.name}" name="{$form.name}">
<link rel="stylesheet" href="{$js_url}/jquery-ui/ui-openbiz/jquery.css" type="text/css" />
{literal}

{/literal}

{$form.currentRecordId}{$form.title}

		{if $dataPanel.fld_icon.element !='' }

		{/if}

			{$dataPanel.fld_name.element}

{$dataPanel.fld_author.element}

			 {if $dataPanel.fld_latest_release.element.create_time}
			 {$dataPanel.fld_latest_release.element.create_date}
			 {else}
			 {$dataPanel.fld_release_time.element}
			 {/if}

				{$dataPanel.fld_package_id.label}
				{$dataPanel.fld_package_id.element}

				{$dataPanel.fld_category.label}
				{$dataPanel.fld_category.element}

				{$dataPanel.fld_type.label}
				{$dataPanel.fld_type.element}

			{if $dataPanel.fld_latest_release.element}

{$actionPanel.btn_install.element}

				{t}Version{/t} {$dataPanel.fld_latest_release.element.version}
				{$dataPanel.fld_latest_release.element.filesize}

			{else}

				{t}No Release Available{/t}

			{/if}

				{assign var=item value=$dataPanel.fld_description}

				{if $item.label}

					{$item.label}

					{if $errors.$itemName}
					{$errors.$itemName}
					{elseif $item.description}
					{$item.description}
					{/if}

				{/if}

					{$item.element}

	{assign var=es_counter value=0}
	{foreach item=setname name=elemsets  from=$form.elementSets}
		{if $es_counter != 0 }

{$setname}

		{/if}
		{assign var=es_counter value=$es_counter+1}
	{/foreach}

	{assign var=es_counter value=0}
	{foreach item=setname name=elemsets  from=$form.elementSets}

		{if $es_counter eq 0 }

		{else}

		{assign var=es_elem_counter value=0}
		{foreach item=item key=itemName from=$dataPanel}
			{if $item.elementset eq $setname}
			{if $item.type eq 'CKEditor' or $item.type eq 'RichText'
				or $item.type eq 'Textarea' or $item.type eq 'LabelTextarea'
				or $item.type eq 'HTMLPreview'
				or $item.type eq 'LabelTextarea' or $item.type eq 'LabelImage'
				 or $item.type eq 'RawData'
				 or $item.type eq 'IDCardReader'
				 or $item.type eq 'FormElement'
			}

				{if $item.label}

					{$item.label}

					{if $errors.$itemName}
					{$errors.$itemName}
					{elseif $item.description}
					{$item.description}
					{/if}

				{/if}

					{$item.element}

			{else}
				{if $item.type eq 'Hidden' }

				{else}
					{if $es_elem_counter is odd}

					{else}

					{/if}
				{/if}

				{if $item.label}

					{$item.label}

				{/if}

				{if $item.type eq 'Checkbox' }
					{$item.element} {$item.description}
				{else}
					{$item.element}
					{if $errors.$itemName}
					{$errors.$itemName}
					{elseif $item.description}
					{$item.description}
					{/if}
				{/if}

			{/if}
			{assign var=es_elem_counter value=$es_elem_counter+1}
			{/if}
		{/foreach}

		{/if}

	{assign var=es_counter value=$es_counter+1}
	{/foreach}

	 	{if $actionPanel|@count > 0}
	 		{if $form.ActionElementSets|@count > 0}

	 			{assign var=es_counter value=0}
			 	{foreach item=setname name=elemsets  from=$form.ActionElementSets}
					 	{if $es_counter is odd}

						{else}

						{/if}
						{foreach item=elem from=$actionPanel}
							{if $elem.elementset eq $setname}
								{$elem.element}
							{/if}
						{/foreach}

						{assign var=es_counter value=$es_counter+1}
			 	{/foreach}

		 	{else}

				{$actionPanel.btn_cancel.element}

			{/if}
		{/if}

	{if $errors}

	    {foreach item=errMsg from=$errors}

{$errMsg}

	    {/foreach}
	    {literal}{/literal}

	{/if}

	{if $notices}

	    {foreach item=noticeMsg from=$notices}

{$noticeMsg}

	    {/foreach}

	    {literal}{/literal}
	{/if}

</form>


text:
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;

public class GameManager : NetworkLobbyManager
{
    public RoomBroadcaster broadcaster;

    public GamePlay[] gamePlayPrefabs;
    public TowerManager[] towerManagerPrefabs;
    public string[] gameLevels;

    public int SelectedGamePlay { get; set; }

    public int SelectedTowerManager { get; set; }

    private int selectedLevel = 0;
    public int SelectedLevel
    {
        get
        {
            return selectedLevel;
        }
        set
        {
            selectedLevel = value;
            playScene = gameLevels[value];
        }
    }

    private GamePlay gamePlay = null;
    private TowerManager towerManager = null;

    public int LocalPlayerSlotId { get; set; }

    public override void OnLobbyServerSceneChanged(string sceneName)
    {
        base.OnLobbyServerSceneChanged(sceneName);
        if (sceneName != "Main")
        {
            if (null == gamePlay)
            {
                gamePlay = Instantiate(gamePlayPrefabs[SelectedGamePlay]);
                gamePlay.manager = this;
                gamePlay.InitPlayerList();
            }
            if (null == towerManager)
            {
                towerManager = Instantiate(towerManagerPrefabs[SelectedTowerManager]);
                NetworkServer.Spawn(towerManager.gameObject);
            }
        }
        else
        {
            gamePlay = null;
            towerManager = null;
        }
    }

    void Start()
    {
        try
        {
            broadcaster.Initialize();
            broadcaster.StartAsClient();
        }
        catch
        {
            Debug.LogWarning("Broadcaster Failed.");
        }
    }

    public override void OnStopClient()
    {
        base.OnStopClient();

        var objs = GameObject.FindGameObjectsWithTag("DestroyOnRestart");
        for (int i = 0; i < objs.Length; i++)
        {
            Destroy(objs[i]);
        }
    }

    public override void OnStartHost()
    {
        base.OnStartHost();

        try
        {
            broadcaster.Initialize();

            broadcaster.broadcastData = string.Concat(new object[]
            {
            "NetworkManager:",
            Network.player.ipAddress,
            ':',
            networkPort
            });

            broadcaster.StartAsServer();
        }
        catch
        {
            Debug.LogWarning("Broadcaster Failed.");
        }
    }

    void OnGUI()
    {
        if (!showLobbyGUI)
        {
            return;
        }

        GUI.depth = 1;

        string name = SceneManager.GetSceneAt(0).name;
        if (name != lobbyScene)
        {
            return;
        }

        int num = 10;
        int num2 = 40;
        bool flag = client == null || client.connection == null || client.connection.connectionId == -1;
        if (!IsClientConnected() && !NetworkServer.active)
        {
            if (flag)
            {
                if (Application.platform != RuntimePlatform.WebGLPlayer)
                {
                    if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Host"))
                    {
                        try
                        {
                            if (broadcaster.running)
                                broadcaster.StopBroadcast();
                        }
                        catch
                        {
                            Debug.LogWarning("Broadcaster Failed.");
                        }
                        StartHost();
                    }
                    num2 += 24;
                }
                if (GUI.Button(new Rect((float)num, (float)num2, 105f, 20f), "Join"))
                {
                    StartClient();
                }
                networkAddress = GUI.TextField(new Rect((float)(num + 100), (float)num2, 95f, 20f), networkAddress);
                num2 += 24;
            }
            else
            {
                GUI.Label(new Rect((float)num, (float)num2, 200f, 20f), string.Concat(new object[]
                {
                        "Connecting to ",
                        networkAddress,
                        ":",
                        networkPort,
                        ".."
                }));
                num2 += 24;
                if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Cancel Connection Attempt"))
                {
                    StopClient();
                }
            }
        }
        else
        {
            if (NetworkServer.active)
            {
                string text = "Server: port=" + networkPort;
                if (useWebSockets)
                {
                    text += " (Using WebSockets)";
                }
                GUI.Label(new Rect((float)num, (float)num2, 300f, 20f), text);
                num2 += 24;
            }
            if (IsClientConnected())
            {
                GUI.Label(new Rect((float)num, (float)num2, 300f, 20f), string.Concat(new object[]
                {
                        "Client: address=",
                        (Network.player.ipAddress == networkAddress) ? networkAddress : networkAddress + '(' + Network.player.ipAddress + ')',
                        " port=",
                        networkPort
                }));
                num2 += 24;
            }
        }

        if (NetworkServer.active || IsClientConnected())
        {
            if (GUI.Button(new Rect((float)num, (float)num2, 200f, 20f), "Disconnect"))
            {
                try
                {
                    broadcaster.StopBroadcast();
                    broadcaster.Initialize();
                    broadcaster.StartAsClient();
                }
                catch
                {
                    Debug.LogWarning("Broadcaster Failed.");
                }
                StopHost();
            }
            num2 += 24;

            Rect position = new Rect(90f, 180f, 500f, 150f);
            GUI.Box(position, "Players:");
            broadcaster.showGUI = false;
        }
        else
        {
            if (null != broadcaster)
                broadcaster.showGUI = true;
        }

    }
}


text:
using System;
using MatterHackers.Agg;
using MatterHackers.MatterControl.DesignTools.EditableTypes;
using MatterHackers.RenderOpenGl;
using MatterHackers.RenderOpenGl.OpenGl;
using MatterHackers.VectorMath;

namespace MatterHackers.MeshVisualizer
{
	public static class WorldViewExtensions
	{
		public static void RenderDirectionAxis(this WorldView world, DirectionAxis axis, Matrix4X4 matrix, double size)
		{
			GLHelper.PrepareFor3DLineRender(true);

			Frustum frustum = world.GetClippingFrustum();
			Vector3 length = axis.Normal * size;
			var color = Agg.Color.Red;

			// draw center line
			{
				var min = axis.Origin - length;
				Vector3 start = Vector3Ex.Transform(min, matrix);

				var max = axis.Origin + length;
				Vector3 end = Vector3Ex.Transform(max, matrix);

				world.Render3DLineNoPrep(frustum, start, end, color, 1);
			}

			var perpendicular = Vector3.GetPerpendicular(axis.Normal, Vector3.Zero).GetNormal();
			// draw some lines to mark the rotation plane
			int count = 20;
			bool first = true;
			var firstEnd = Vector3.Zero;
			var lastEnd = Vector3.Zero;
			var center = Vector3Ex.Transform(axis.Origin, matrix);
			for (int i = 0; i < count; i++)
			{
				var rotation = size / 4 * Vector3Ex.Transform(perpendicular, Matrix4X4.CreateRotation(axis.Normal, MathHelper.Tau * i / count));
				// draw center line
				var max = axis.Origin + rotation;
				Vector3 end = Vector3Ex.Transform(max, matrix);

				world.Render3DLineNoPrep(frustum, center, end, color, 1);
				if (!first)
				{
					world.Render3DLineNoPrep(frustum, end, lastEnd, color, 1);
				}
				else
				{
					firstEnd = end;
				}

				lastEnd = end;
				first = false;
			}

			world.Render3DLineNoPrep(frustum, firstEnd, lastEnd, color, 1);

			GL.Enable(EnableCap.Lighting);
		}
	}
}


text:
#ifndef VERBATIM_VERTEX_BUFFER
#define VERBATIM_VERTEX_BUFFER

#include "verbatim_array.hpp"
#include "verbatim_vertex.hpp"

// Forward declaration.
class Program;

/** Vertex buffer.
 */
class VertexBuffer
{
  private:
    /** Current vertex buffer. */
    static const VertexBuffer* g_bound_vertex_buffer;

    /** Currently programmed vertex buffer. */
    static const VertexBuffer* g_programmed_vertex_buffer;

  private:
    /** OpenGL id. */
    GLuint m_id_data[2];

    /** Vertex array. */
    Array<Vertex> m_vertices;

    /** Index array. */
    Array<uint16_t> m_indices;

  private:
    /** \brief Accessor.
     *
     * \return Vertex buffer OpenGL id.
     */
    GLuint getVertexId() const
    {
      return m_id_data[0];
    }

    /** \brief Accessor.
     *
     * \return Index buffer OpenGL id.
     */
    GLuint getIndexId() const
    {
      return m_id_data[1];
    }

  public:
    /** \brief Accessor.
     *
     * \param idx Index of vertex to access.
     * \return Vertex at given index.
     */
    const Vertex& getVertex(size_t idx) const
    {
      return m_vertices[idx];
    }

  public:
    /** \brief Constructor.
     */
    VertexBuffer();

  public:
    /** \brief Add face to this vertex buffer.
     *
     * \param op Index to add.
     */
    void addIndex(uint16_t op)
    {
#if defined(USE_LD)
      if(g_debug)
      {
        std::cout << op << std::endl;
      }
#endif
      m_indices.add(op);
    }

    /** \brief Add vertex to this vertex buffer.
     *
     * \param op Vertex to add.
     */
    void addVertex(const Vertex &op)
    {
#if defined(USE_LD)
      if(g_debug)
      {
        std::cout << op << std::endl;
      }
#endif
      m_vertices.add(op);
    }

    /** \brief Tell if amount of vertices fits in this vertex buffer.
     *
     * \param op Number of offered vertices.
     * \return True if fits, false if not.
     */
    bool fitsVertices(size_t op)
    {
      return (65536 >= (m_vertices.getSize() + op));
    }

    /** \brief Accessor.
     *
     * \return Index count.
     */
    size_t getIndexCount() const
    {
      return m_indices.getSize();
    }

    /** \brief Accessor.
     *
     * \return Vertex count.
     */
    size_t getVertexCount() const
    {
      return m_vertices.getSize();
    }

  private:
    /** \brief Bind this vertex buffer for rendering and/or modification.
     */
    void bind() const;

  public:
    /** \brief Update this vertex buffer into the GPU.
     *
     * \param indicesEnabled Set to true (default) if index buffer is relevant and should be uploaded.
     */
    void update(bool indicesEnabled = true);

    /** \brief Use this vertex buffer for rendering.
     *
     * \param op Program to use.
     */
    void use(const Program *op) const;

  public:
    /** \brief Reset programmed vertex buffer.
     *
     * Must be done when changing a program.
     */
    static void reset_programmed_vertex_buffer()
    {
      g_programmed_vertex_buffer = NULL;
    }

    /** \brief Unbind vertex buffer.
     */
    static void unbind()
    {
      dnload_glBindBuffer(GL_ARRAY_BUFFER, 0);
      dnload_glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);

      g_bound_vertex_buffer = NULL;
      reset_programmed_vertex_buffer();
    }

#if defined(USE_LD)
  public:
    /** \brief Print operator.
     *
     * \param lhs Left-hand-side operand.
     * \param rhs Right-hand-side operand.
     */
    friend std::ostream& operator<<(std::ostream &lhs, const VertexBuffer &rhs)
    {
      return lhs << "VertexBuffer(" << &rhs << ')';
    }
#endif
};

#endif


text:
#import <IDEKit/IDEEditorStepperView.h>

@class IDEActionButton, NSImage;

@interface IDEEditorMenuStepperView : IDEEditorStepperView
{
    IDEActionButton *_actionButton;
    id <IDEEditorMenuStepperViewDelegate> _delegate;
}

+ (id)keyPathsForValuesAffectingCanMove;
- (BOOL)canMove;
- (struct CGSize)centerViewSizeInHeight:(double)arg1;
@property id <IDEEditorMenuStepperViewDelegate> delegate; // @synthesize delegate=_delegate;
@property NSImage *image;
- (id)menuForActionButton;
- (id)newCenterView;
- (void)selectNext:(id)arg1;
- (void)selectPrevious:(id)arg1;
- (void)setGradientStyle:(int)arg1;

@end


text:
"""Data loader which loads spoof data."""

import functools

import numpy as np
import tensorflow as tf

# pylint:disable=unused-import
from smurf.data.data_utils import evaluate
from smurf.data.data_utils import list_eval_keys

def _shift_images(image, include_flow, max_shift):
  """Create an artificial flow from a static image."""
  crop_to_height = image.shape[0] - max_shift * 2
  crop_to_width = image.shape[1] - max_shift * 2
  global_flow = tf.random.uniform([2], minval=-max_shift, maxval=max_shift)
  height_shift = global_flow[0]
  width_shift = global_flow[1]
  height_shift = tf.cast(height_shift, tf.int32)
  width_shift = tf.cast(width_shift, tf.int32)
  frame1 = tf.image.crop_to_bounding_box(
      tf.expand_dims(image, axis=0),
      offset_height=max_shift,
      offset_width=max_shift,
      target_height=crop_to_height,
      target_width=crop_to_width)[0]
  frame2 = tf.image.crop_to_bounding_box(
      tf.expand_dims(image, axis=0),
      offset_height=max_shift + height_shift,
      offset_width=max_shift + width_shift,
      target_height=crop_to_height, target_width=crop_to_width
  )[0]
  flow = tf.ones_like(frame1, tf.int32)
  flow = flow[:, :, 1:] * tf.reshape(
      tf.stack([height_shift, width_shift]), (1, 1, 2))
  images = tf.stack([frame1, frame2], axis=0)
  images = tf.cast(images, tf.float32)
  output = {'images': images}
  if include_flow:
    output['flow'] = tf.cast(flow, tf.float32)
    output['flow_valid'] = tf.ones_like(output['flow'][Ellipsis, 1:])
    occlusions = tf.ones((crop_to_height - tf.abs(height_shift),
                          crop_to_width - tf.abs(width_shift)))
    occlusions = tf.cond(
        height_shift > 0,
        lambda: tf.pad(occlusions, [[height_shift, 0], [0, 0]]),
        lambda: tf.pad(occlusions, [[0, -height_shift], [0, 0]]))
    occlusions = tf.cond(
        width_shift > 0,
        lambda: tf.pad(occlusions, [[0, 0], [width_shift, 0]]),
        lambda: tf.pad(occlusions, [[0, 0], [0, -width_shift]]))
    output['occlusions'] = tf.expand_dims(occlusions, axis=-1)
  return output

def make_dataset(path,
                 mode,
                 seq_len=2,
                 shuffle_buffer_size=0,
                 height=None,
                 width=None,
                 resize_gt_flow=True,
                 gt_flow_shape=None,
                 seed=41):
  """Creates a spoof dataset for testing purposes."""
  del path
  del shuffle_buffer_size
  del resize_gt_flow
  del gt_flow_shape
  del seed

  if seq_len != 2:
    raise ValueError('Only compatible with seq_len == 2.')
  max_shift = 12
  height = height or 256
  width = width or 512
  background = np.random.randn(height + max_shift * 2, width + max_shift * 2, 3)
  ds = tf.data.Dataset.from_tensor_slices([background])
  if 'train' in mode:
    ds = ds.repeat()
  else:
    ds = ds.repeat(10)

  include_flow = 'eval' in mode or 'sup' in mode
  ds = ds.map(functools.partial(_shift_images, include_flow=include_flow,
                                max_shift=max_shift))
  ds = ds.prefetch(10)

  return ds


text:
<?php
/**
 * DO NOT EDIT THIS FILE!
 *
 * This file was automatically generated from external sources.
 *
 * Any manual change here will be lost the next time the SDK
 * is updated. You've been warned!
 */

namespace DTS\eBaySDK\Trading\Enums;

class ProPackCodeType
{
    const C_CUSTOM_CODE = 'CustomCode';
    const C_DISABLED = 'Disabled';
    const C_ENABLED = 'Enabled';
    const C_POWER_SELLER_ONLY = 'PowerSellerOnly';
    const C_TOP_RATED_SELLER_ONLY = 'TopRatedSellerOnly';
}


text:
use crate::schema::connection;
use diesel::*;

include!("pg_custom_schema.rs");
use self::custom_schema::users;

#[derive(Insertable)]
#[diesel(table_name = users)]
struct NewUser {
    id: i32,
}

#[test]
fn custom_schemas_are_loaded_by_infer_schema() {
    let conn = &mut connection();
    insert_into(users::table)
        .values(&NewUser { id: 1 })
        .execute(conn)
        .unwrap();
    let users = users::table.select(users::id).load(conn);

    assert_eq!(Ok(vec![1]), users);
}


text:
package persistence

import (
	"crypto/rand"
	"encoding/hex"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"sort"
	"strings"
	"time"

	"github.com/andres-erbsen/chatterbox/client/encoding"
	"github.com/andres-erbsen/chatterbox/proto"
	"github.com/andres-erbsen/chatterbox/shred"
)

type Paths struct {
	RootDir     string
	Application string
}

const (
	MetadataFileName = "metadata.pb"
	AccountFileName  = "account.pb"
)

func (p *Paths) ConversationDir() string { return filepath.Join(p.RootDir, "conversations") }

func (p *Paths) AccountPath() string {
	return filepath.Join(p.RootDir, "account.pb")
}

func (p *Paths) OutboxDir() string { return filepath.Join(p.RootDir, "outbox") }

func (p *Paths) TempDir() string {
	return filepath.Join(p.RootDir, ".tmp", p.Application)
}

func ConversationName(metadata *proto.ConversationMetadata) string {
	names := make([]string, 0, len(metadata.Participants))
	already := make(map[string]struct{})
	for _, s := range metadata.Participants {
		if _, ok := already[s]; !ok {
			names = append(names, encoding.EscapeFilename(s))
			already[s] = struct{}{}
		}
	}
	sort.Strings(names)
	return encoding.EscapeFilename(metadata.Subject) + " %between " + strings.Join(names, " %and ")
}

func MessageName(date time.Time, sender string) string {
	//messageName := "date-sender"
	dateStr := date.UTC().Format(time.RFC3339Nano)
	return fmt.Sprintf("%s-%s", dateStr, sender)
}

func (p *Paths) MkdirInTemp() (string, error) {
	if err := os.Mkdir(p.TempDir(), 0700); err != nil && !os.IsExist(err) {
		return "", err
	}
	return ioutil.TempDir(p.TempDir(), "")
}

func (p *Paths) TempFile() (string, error) {
	if err := os.Mkdir(p.TempDir(), 0700); err != nil && !os.IsExist(err) {
		return "", err
	}
	f, err := ioutil.TempFile(p.TempDir(), "")
	if err != nil {
		return "", err
	}
	ret := f.Name()
	f.Close()
	return ret, nil
}

// Unmarshal reads an Unmarshal()-able from a file
func UnmarshalFromFile(path string, out interface {
	Unmarshal([]byte) error
}) error {
	fileContents, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	return out.Unmarshal(fileContents)
}

// MarshalToFile atomically writes a Marshal()-able object to a file by first
// writing to a new file in tmpDir and then atomically renaming it to the
// destination file.
func (p *Paths) MarshalToFile(path string, in interface {
	Marshal() ([]byte, error)
}) error {
	inBytes, err := in.Marshal()
	if err != nil {
		return err
	}
	tmpFile, err := p.TempFile()
	if err != nil {
		return err
	}
	err = ioutil.WriteFile(tmpFile, inBytes, 0600)
	if err != nil {
		return err
	}
	err = os.Rename(tmpFile, path)
	if err != nil {
		return err
	}
	return nil
}

func (p *Paths) ConversationToOutbox(metadata *proto.ConversationMetadata, msgs ...string) error {
	path := filepath.Join(p.OutboxDir(), ConversationName(metadata))
	tmpDir, err := p.MkdirInTemp()
	if err != nil {
		return err
	}
	defer shred.RemoveAll(tmpDir)
	if err := p.MarshalToFile(filepath.Join(tmpDir, MetadataFileName), metadata); err != nil {
		return err
	}
	return os.Rename(filepath.Join(tmpDir), path)
}

func (p *Paths) MessageToOutbox(conversationName, message string) error {
	tempfile, err := p.TempFile()
	defer shred.Remove(tempfile)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(tempfile, []byte(message), 0600); err != nil {
		return err
	}

	conv_outbox := filepath.Join(p.OutboxDir(), conversationName)

	base := filepath.Base(tempfile)
	return os.Rename(filepath.Join(p.TempDir(), base), filepath.Join(conv_outbox, base))
}

func (p *Paths) AtomicWriteFile(path string, bs []byte, perm os.FileMode) error {
	tempfile, err := p.TempFile()
	defer shred.Remove(tempfile)
	if err != nil {
		return err
	}
	if err = ioutil.WriteFile(tempfile, []byte(bs), perm); err != nil {
		return err
	}
	return os.Rename(filepath.Join(tempfile), path)
}

func ReadConversationMetadata(dir string) (*proto.ConversationMetadata, error) {
	c := new(proto.ConversationMetadata)
	return c, UnmarshalFromFile(filepath.Join(dir, MetadataFileName), c)
}

func (p *Paths) ListConversations() ([]*proto.ConversationMetadata, error) {
	fis, err := ioutil.ReadDir(p.ConversationDir())
	if err != nil {
		return nil, err
	}
	ret := make([]*proto.ConversationMetadata, 0, len(fis))
	for _, fi := range fis {
		c, err := ReadConversationMetadata(filepath.Join(p.ConversationDir(), fi.Name()))
		if err != nil {
			return nil, err
		}
		ret = append(ret, c)
	}
	return ret, nil
}

type Message struct {
	Path, Sender, Content string
}

func ReadMessageFromFile(path string) (*Message, error) {
	base := filepath.Base(path)
	if len(base) < len("2015-02-16T07:09:55Z-") {
		return nil, fmt.Errorf("badly formatted message filename : " + path)
	}
	sender := base[len("2015-02-16T07:09:55Z-"):]
	contents, err := ioutil.ReadFile(path)
	if err != nil {
		return nil, fmt.Errorf("badly formatted message filename : " + path)
	}
	return &Message{Path: path, Sender: sender, Content: string(contents)}, nil
}

func (p *Paths) LoadMessages(conv *proto.ConversationMetadata) ([]*Message, error) {
	convpath := filepath.Join(p.ConversationDir(), ConversationName(conv))
	fis, err := ioutil.ReadDir(convpath)
	if err != nil {
		return nil, err
	}
	ret := make([]*Message, 0, len(fis))
	for _, fi := range fis {
		if fi.Name() == MetadataFileName {
			continue
		}
		msg, err := ReadMessageFromFile(filepath.Join(p.ConversationDir(), ConversationName(conv), fi.Name()))
		if err != nil {
			return nil, err
		}
		ret = append(ret, msg)
	}
	return ret, nil
}

func randHex(l int) string {
	s := make([]byte, (l+1)/2)
	if _, err := rand.Read(s); err != nil {
		panic(err)
	}
	return hex.EncodeToString(s)[:l]
}