text:
package com.fns.grivet.service;

import java.io.IOException;
import java.nio.charset.Charset;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.io.IOUtils;
import org.json.JSONObject;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit.jupiter.SpringExtension;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fns.grivet.QueryInit;
import com.fns.grivet.query.NamedQuery;

import io.restassured.path.json.JsonPath;

@ActiveProfiles(value = { "hsqldb", "insecure" })
@ExtendWith(SpringExtension.class)
@SpringBootTest(classes = QueryInit.class)
public class NamedQueryServiceSprocTest {

	@Autowired
	private ResourceLoader resolver;

	@Autowired
	private ClassRegistryService classRegistryService;

	@Autowired
	private NamedQueryService namedQueryService;

	@Autowired
	private ObjectMapper objectMapper;

	@BeforeEach
	public void setUp() throws IOException {
		Resource r = resolver.getResource("classpath:TestType.json");
		String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
		JSONObject payload = new JSONObject(json);
		classRegistryService.register(payload);
	}

	@Test
	public void testSuccessfulNamedQueryExecution() throws IOException {
		Resource r = resolver.getResource("classpath:TestSprocQuery.json");
		String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
		NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
		namedQueryService.create(namedQuery);

		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
		params.add("createdTime", tomorrow);
		String result = namedQueryService.get("sproc.getAttributesCreatedBefore", params);
		String[] expected = { "bigint", "varchar", "decimal", "datetime", "int", "text", "json", "boolean" };
		List<String> actual = JsonPath.given(result).getList("NAME");
		Assertions.assertTrue(actual.size() == 8, "Result should contain 8 attributes");
		Assertions.assertTrue(actual.containsAll(Arrays.asList(expected)));
	}

	@Test
	public void testNamedQueryNotFound() throws IOException {
	    Assertions.assertThrows(IllegalArgumentException.class, () ->  {
	        MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
	        Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
	        params.add("createdTime", tomorrow);
	        namedQueryService.get("sproc.getAttributesCreatedBefore", params);
	    });
	}

	@Test
	public void testNamedQueryNotExecutedBecauseItDidNotContainRequiredParamForExecution() throws IOException {
	    Assertions.assertThrows(IllegalArgumentException.class, () ->  {
        	    Resource r = resolver.getResource("classpath:TestSprocQuery.json");
        		String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        		NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
        		namedQueryService.create(namedQuery);

        		namedQueryService.get("sproc.getAttributesCreatedBefore", null);
	    });
	}

	@Test
	public void testNamedQueryNotExecutedBecauseParamSuppliedForExecutionNotCorrectlyNamed() throws IOException {
	    Assertions.assertThrows(IllegalArgumentException.class, () ->  {
        	    Resource r = resolver.getResource("classpath:TestSprocQuery.json");
        		String json = IOUtils.toString(r.getInputStream(), Charset.defaultCharset());
        		NamedQuery namedQuery = objectMapper.readValue(json, NamedQuery.class);
        		namedQueryService.create(namedQuery);

        		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
        		Timestamp tomorrow = Timestamp.valueOf(LocalDateTime.now().plusDays(1));
        		params.add("timeCreated", tomorrow);
        		namedQueryService.get("sproc.getAttributesCreatedBefore", params);
	    });
	}

	@AfterEach
	public void tearDown() {
		classRegistryService.deregister("TestType");
		namedQueryService.delete("sproc.getAttributesCreatedBefore");
	}
}


text:
r"""Entry point for evaluating agents on the Balloon Learning Environment.

"""

import json
import os
from typing import Sequence

from absl import app
from absl import flags
from balloon_learning_environment.env import balloon_env  # pylint: disable=unused-import
from balloon_learning_environment.env import generative_wind_field
from balloon_learning_environment.env import wind_field
from balloon_learning_environment.env.rendering import matplotlib_renderer
from balloon_learning_environment.eval import eval_lib
from balloon_learning_environment.eval import suites
from balloon_learning_environment.utils import run_helpers
import gym

flags.DEFINE_string('agent', 'dqn', 'The name of the agent to create.')
flags.DEFINE_enum('suite', 'big_eval',
                  suites.available_suites(),
                  'The evaluation suite to run.')
flags.DEFINE_string(
    'wind_field', 'generative',
    'The wind field type to use. See the _WIND_FIELDS dict below for options.')
flags.DEFINE_string('agent_gin_file', None, 'Gin file for agent configuration.')
flags.DEFINE_multi_string('gin_bindings', [],
                          'Gin bindings to override default values.')
flags.DEFINE_string('output_dir', '/tmp/ble/eval',
                    'The directory to output the json summary.')
flags.DEFINE_integer(
    'num_shards',
    1,
    'The number of per-agent shards to split the eval job into.',
    lower_bound=1)
flags.DEFINE_integer('shard_idx', 0, 'The index of the shard.', lower_bound=0)
flags.DEFINE_boolean('pretty_json', False,
                     'If true, it will write json files with an indent of 2.')
flags.DEFINE_string('checkpoint_dir', None,
                    'The directory to load checkpoints from.')
flags.DEFINE_integer('checkpoint_idx', None,
                     'The checkpoint iteration number to load.')
flags.DEFINE_string(
    'name_override', None,
    'If supplied, this will be the name used for the json output file.')
flags.DEFINE_string(
    'renderer', None,
    'The renderer to use. Note that it is fastest to have this set to None.')
flags.DEFINE_integer(
    'render_period', 10,
    'The period to render with. Only has an effect if renderer is not None.')
FLAGS = flags.FLAGS

_WIND_FIELDS = {
    'generative': generative_wind_field.GenerativeWindField,
    'simple': wind_field.SimpleStaticWindField,
}

_RENDERERS = {
    'matplotlib': matplotlib_renderer.MatplotlibRenderer,
}

def write_result(result: Sequence[eval_lib.EvaluationResult]) -> None:
  """Writes an evaluation result as a json file."""
  if FLAGS.name_override:
    file_name = FLAGS.name_override
  elif FLAGS.checkpoint_idx is not None:
    file_name = f'{FLAGS.agent}_{FLAGS.checkpoint_idx}'
  else:
    file_name = FLAGS.agent

  if FLAGS.num_shards > 1:
    file_name = f'{file_name}_{FLAGS.shard_idx}'
  file_name = f'{file_name}.json'

  dir_path = os.path.join(FLAGS.output_dir, FLAGS.suite)
  file_path = os.path.join(dir_path, file_name)

  indent = 2 if FLAGS.pretty_json else None

  os.makedirs(dir_path, exist_ok=True)
  with open(file_path, 'w') as f:
    json.dump(result, f, cls=eval_lib.EvalResultEncoder, indent=indent)

def main(argv: Sequence[str]) -> None:
  if len(argv) > 1:
    raise app.UsageError('Too many command-line arguments.')

  run_helpers.bind_gin_variables(FLAGS.agent,
                                 FLAGS.agent_gin_file,
                                 FLAGS.gin_bindings)

  renderer = None
  if FLAGS.renderer is not None:
    renderer = _RENDERERS[FLAGS.renderer]()

  wf = _WIND_FIELDS[FLAGS.wind_field]
  env = gym.make('BalloonLearningEnvironment-v0',
                 wind_field_factory=wf,
                 renderer=renderer)

  agent = run_helpers.create_agent(
      FLAGS.agent,
      env.action_space.n,
      observation_shape=env.observation_space.shape)
  if FLAGS.checkpoint_dir is not None and FLAGS.checkpoint_idx is not None:
    agent.load_checkpoint(FLAGS.checkpoint_dir, FLAGS.checkpoint_idx)

  eval_suite = suites.get_eval_suite(FLAGS.suite)

  if FLAGS.num_shards > 1:
    start = int(len(eval_suite.seeds) * FLAGS.shard_idx / FLAGS.num_shards)
    end = int(len(eval_suite.seeds) * (FLAGS.shard_idx + 1) / FLAGS.num_shards)
    eval_suite.seeds = eval_suite.seeds[start:end]

  eval_result = eval_lib.eval_agent(agent, env, eval_suite,
                                    render_period=FLAGS.render_period)
  write_result(eval_result)

if __name__ == '__main__':
  app.run(main)

redpajama_set_name: RedPajamaGithub


text:
//=================================================================================================

//=================================================================================================

#ifndef _BLAZE_MATH_TYPETRAITS_ISMATSERIALEXPR_H_
#define _BLAZE_MATH_TYPETRAITS_ISMATSERIALEXPR_H_

//*************************************************************************************************
// Includes
//*************************************************************************************************

#include <utility>
#include <blaze/math/expressions/MatSerialExpr.h>
#include <blaze/util/FalseType.h>
#include <blaze/util/TrueType.h>
#include <blaze/util/typetraits/RemoveCV.h>

namespace blaze {

//=================================================================================================
//
//  CLASS DEFINITION
//
//=================================================================================================

//*************************************************************************************************
/*! \cond BLAZE_INTERNAL */
/*!\brief Auxiliary helper struct for the IsMatSerialExpr type trait.
// \ingroup math_type_traits
*/
template< typename T >
struct IsMatSerialExprHelper
{
 private:
   //**********************************************************************************************
   template< typename MT >
   static TrueType test( const MatSerialExpr<MT>& );

   static FalseType test( ... );
   //**********************************************************************************************

 public:
   //**********************************************************************************************
   using Type = decltype( test( std::declval< RemoveCV_<T> >() ) );
   //**********************************************************************************************
};
/*! \endcond */
//*************************************************************************************************

//*************************************************************************************************
/*!\brief Compile time check whether the given type is a matrix serial evaluation expression template.
// \ingroup math_type_traits
//
// This type trait class tests whether or not the given type \a Type is a matrix serial evaluation
// expression template. In order to qualify as a valid matrix serial evaluation expression template,
// the given type has to derive publicly from the MatSerialExpr base class. In case the given type
// is a valid matrix serial evaluation expression template, the \a value member constant is set
// to \a true, the nested type definition \a Type is \a TrueType, and the class derives from
// \a TrueType. Otherwise \a value is set to \a false, \a Type is \a FalseType, and the class
// derives from \a FalseType.
*/
template< typename T >
struct IsMatSerialExpr
   : public IsMatSerialExprHelper<T>::Type
{};
//*************************************************************************************************

} // namespace blaze

#endif


text:
#pragma once

enum libmemcached_feature_t {
    LIBMEMCACHED_FEATURE_HAS_SASL,
    LIBMEMCACHED_FEATURE_MAX
};

#ifdef __cplusplus
extern "C" {
#endif

LIBMEMCACHED_API
bool libmemcached_has_feature(enum libmemcached_feature_t arg);

#ifdef __cplusplus
} // extern "C"
#endif


text:
This directory contains code modified from an example in the GNU Scientific
Library documentation (see [Numerical Integration Examples](
http://www.gnu.org/software/gsl/manual/html_node/QAGS-adaptive-integration-with-singularities.html#QAGS-adaptive-integration-with-singularities)).

The example problem to solve is to evaluate the definite integral

$$ \int_{0}^{1} \frac{\log(\alpha x)}{\sqrt{x}}\,dx $$

when $\alpha=1$. Notice that the integrand is singular at the left end point
of the integral.

The file ``function.c`` contains the implementation of the function $f$
using a pointer to a void parameter ``params`` to pass the value of $\alpha$.
The strength of this approach is that it readily generalises to integrands
with aribtrary values of $\alpha$ and, indeed, arbitrary integrands.


text:
require('./bootstrap');

module.exports = new Module('Doge', function() {
	this.metaclass.defineGetter('application', function() {
		if (!this._application && this.appClass) {
			this._application = this.appClass.instance;
		}

		return this._application;
	});

	this.metaclass.defineSetter('application', function(value) {
		this._application = value;
	});

	this.metaclass.defineGetter('configuration', function() {
		return this.application.config;
	});

	this.metaclass.defineGetter('root', function() {
		return this.application && this.application.root;
	});

	this.metaclass.defineGetter('env', function() {
		if (!this._env) {
			this._env = process.env.DOGE_ENV || 'development';
		}

		return this._env;
	});

	this.metaclass.defineSetter('env', function(value) {
		this._env = value;
	});

	this.appClass = this.application = null;
});

global.Doge = module.exports;


text:
require File.dirname(__FILE__) + '/../../../spec_helper'
require 'net/http'

describe "Net::HTTP.default_port" do
  it "returns 80" do
    Net::HTTP.http_default_port.should eql(80)
  end
end


text:
let React = require('react'),
    Actions = require('../actions/Actions');

class Modal extends React.Component {
    render() {
        return (

                {this.props.children}

        );
    }

    _close() {
        Actions.CLOSE_TOPMOST_MODAL.invoke();
    }
}

module.exports = Modal;


text:
require 'guard'
require 'guard/guard'
require 'guard/watcher'
require 'puppet-lint'

class PuppetLint

  attr_reader :messages

  def clear_messages
    @messages = []
  end

  def format_message(message)
    @messages << (log_format % message)
  end
end

module Guard
  class Puppetlint < Guard

    VERSION = '0.0.1'

    def initialize(watchers = [], options = {})
      options = { :syntax_check => true }.merge(options)
      @linter = PuppetLint.new
      super
    end

    # Calls #run_all if the :all_on_start option is present.
    def start
      run_all if options[:all_on_start]
    end

    # Call #run_on_change for all files which match this guard.
    def run_all
      run_on_change(Watcher.match_files(self, Dir.glob('{,**/}*{,.*}').uniq))
    end

    def prepend_filename(msg, file)
      if msg
        msg.map {|x| "#{file}: #{x}"}
      else
        []
      end
    end

    # Print the result of the command(s), if there are results to be printed.
    def run_on_change(res)
      messages = []
      res.each do |file|
        file = File.join( options[:watchdir].to_s,file ) if options[:watchdir]

        if options[:syntax_check]
          parser_messages = `puppet parser validate #{file} --color=false`.split("\n")
          parser_messages.reject! { |s| s =~ /puppet help parser validate/ }
          parser_messages.map! { |s| s.gsub 'err: Could not parse for environment production:', '' }

          messages += prepend_filename(parser_messages, file)
        end

        @linter.file = file
        @linter.clear_messages
        @linter.run
        linter_msg = @linter.messages.reject { |s| !options[:show_warnings] && s =~ /WARNING/ }
        messages += prepend_filename(linter_msg, file)
      end
      if messages.empty?
        messages = ["Files are ok:"] + res
        image = :success
      else
        image = :failed
      end
      Notifier.notify( messages.join("\n"), :title => "Puppet lint", :image => image )
    end
  end
end


text:
shared_context :classe_shared do
  let(:classe_valida_let) do
    create(:classe)
  end
  let(:classe_nova_let) do
    create(:classe, :nova)
  end

end


text:
<!DOCTYPE html>
<html class="borderbox">
	{% include head.html %}
	<body>
		<div id="wrapper">
			{% include header.html %}
			{{ content }}
			{% include footer.html %}
		</div>
	</body>
</html>


text:
package de.taimos.springcxfdaemon.remote;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface RemoteService {

	/**
	 * @return the name of the service. leave blank to use base URL
	 */
	String name() default "";

	/**
	 * @return the base URL to use. leave blank to use property resolution by service name
	 */
	String baseURL() default "";

}


text:
package com.ThirtyNineEighty.Game.ContentState.States;

import com.ThirtyNineEighty.Game.ContentState.ContentStateType;
import com.ThirtyNineEighty.Game.Menu.EditorImportMenu;
import com.ThirtyNineEighty.Game.TanksContext;

public class EditorImportState
  implements IContentState
{
  @Override
  public ContentStateType getType()
  {
    return ContentStateType.EDITOR_IMPORT;
  }

  @Override
  public void apply(IContentState prev)
  {
    if (prev == null)
      throw new IllegalArgumentException("Wrong prev state");

    switch (prev.getType())
    {
    case EDITOR:
      TanksContext.content.setMenu(new EditorImportMenu());
      return;
    }

    throw new IllegalArgumentException("Wrong prev state");
  }

  @Override
  public IContentState buildNext()
  {
    return null;
  }
}


text:
package org.apache.ambari.server.orm.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;

import org.apache.ambari.server.orm.RequiresSession;
import org.apache.ambari.server.orm.entities.ResourceTypeEntity;

import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.Singleton;
import com.google.inject.persist.Transactional;

/**
 * Resource Type Data Access Object.
 */
@Singleton
public class ResourceTypeDAO {
  /**
   * JPA entity manager
   */
  @Inject
  Provider<EntityManager> entityManagerProvider;
  @Inject
  DaoUtils daoUtils;

  /**
   * Find a resource type with the given id.
   *
   * @param id  type id
   *
   * @return  a matching resource type or null
   */
  @RequiresSession
  public ResourceTypeEntity findById(Integer id) {
    return entityManagerProvider.get().find(ResourceTypeEntity.class, id);
  }

  /**
   * Find a resource type with the given name.
   *
   * @param name  type name
   *
   * @return  a matching resource type or null
   */
  @RequiresSession
  public ResourceTypeEntity findByName(String name) {
    TypedQuery<ResourceTypeEntity> query = entityManagerProvider.get().createQuery(
        "SELECT resourceType FROM ResourceTypeEntity resourceType WHERE resourceType.name = ?1",
        ResourceTypeEntity.class);
    return daoUtils.selectSingle(query, name);
  }

  /**
   * Find all resource types.
   *
   * @return all resource types or an empty List
   */
  @RequiresSession
  public List<ResourceTypeEntity> findAll() {
    TypedQuery<ResourceTypeEntity> query = entityManagerProvider.get().createQuery("SELECT resourceType FROM ResourceTypeEntity resourceType", ResourceTypeEntity.class);
    return daoUtils.selectList(query);
  }

  /**
   * Make an instance managed and persistent.
   *
   * @param entity  entity to store
   */
  @Transactional
  public void create(ResourceTypeEntity entity) {
    entityManagerProvider.get().persist(entity);
  }

  /**
   * Merge the given entity.
   *
   * @param entity  the entity
   *
   * @return the managed entity
   */
  @Transactional
  public ResourceTypeEntity merge(ResourceTypeEntity entity) {
    return entityManagerProvider.get().merge(entity);
  }

}


text:
// Copyright (c) 2015, the Dart project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

#ifndef RUNTIME_VM_THREAD_H_
#define RUNTIME_VM_THREAD_H_

#if defined(SHOULD_NOT_INCLUDE_RUNTIME)
#error "Should not include runtime"
#endif

#include "include/dart_api.h"
#include "platform/assert.h"
#include "platform/atomic.h"
#include "platform/safe_stack.h"
#include "vm/bitfield.h"
#include "vm/compiler/runtime_api.h"
#include "vm/constants.h"
#include "vm/globals.h"
#include "vm/handles.h"
#include "vm/heap/pointer_block.h"
#include "vm/os_thread.h"
#include "vm/random.h"
#include "vm/runtime_entry_list.h"
#include "vm/thread_stack_resource.h"
#include "vm/thread_state.h"
namespace dart {

class AbstractType;
class ApiLocalScope;
class Array;
class CompilerState;
class Class;
class Code;
class Bytecode;
class Error;
class ExceptionHandlers;
class Field;
class Function;
class GrowableObjectArray;
class HandleScope;
class Heap;
class HierarchyInfo;
class Instance;
class Interpreter;
class Isolate;
class IsolateGroup;
class Library;
class Object;
class OSThread;
class JSONObject;
class PcDescriptors;
class RawBool;
class RawObject;
class RawCode;
class RawError;
class RawGrowableObjectArray;
class RawObjectPool;
class RawStackTrace;
class RawString;
class RuntimeEntry;
class Smi;
class StackResource;
class StackTrace;
class String;
class TimelineStream;
class TypeArguments;
class TypeParameter;
class TypeUsageInfo;
class Zone;

namespace compiler {
namespace target {
class Thread;
}  // namespace target
}  // namespace compiler

#define REUSABLE_HANDLE_LIST(V)                                                \
  V(AbstractType)                                                              \
  V(Array)                                                                     \
  V(Class)                                                                     \
  V(Code)                                                                      \
  V(Bytecode)                                                                  \
  V(Error)                                                                     \
  V(ExceptionHandlers)                                                         \
  V(Field)                                                                     \
  V(Function)                                                                  \
  V(GrowableObjectArray)                                                       \
  V(Instance)                                                                  \
  V(Library)                                                                   \
  V(Object)                                                                    \
  V(PcDescriptors)                                                             \
  V(Smi)                                                                       \
  V(String)                                                                    \
  V(TypeArguments)                                                             \
  V(TypeParameter)

#define CACHED_VM_STUBS_LIST(V)                                                \
  V(RawCode*, write_barrier_code_, StubCode::WriteBarrier().raw(), NULL)       \
  V(RawCode*, array_write_barrier_code_, StubCode::ArrayWriteBarrier().raw(),  \
    NULL)                                                                      \
  V(RawCode*, fix_callers_target_code_, StubCode::FixCallersTarget().raw(),    \
    NULL)                                                                      \
  V(RawCode*, fix_allocation_stub_code_,                                       \
    StubCode::FixAllocationStubTarget().raw(), NULL)                           \
  V(RawCode*, invoke_dart_code_stub_, StubCode::InvokeDartCode().raw(), NULL)  \
  V(RawCode*, invoke_dart_code_from_bytecode_stub_,                            \
    StubCode::InvokeDartCodeFromBytecode().raw(), NULL)                        \
  V(RawCode*, call_to_runtime_stub_, StubCode::CallToRuntime().raw(), NULL)    \
  V(RawCode*, null_error_shared_without_fpu_regs_stub_,                        \
    StubCode::NullErrorSharedWithoutFPURegs().raw(), NULL)                     \
  V(RawCode*, null_error_shared_with_fpu_regs_stub_,                           \
    StubCode::NullErrorSharedWithFPURegs().raw(), NULL)                        \
  V(RawCode*, null_arg_error_shared_without_fpu_regs_stub_,                    \
    StubCode::NullArgErrorSharedWithoutFPURegs().raw(), nullptr)               \
  V(RawCode*, null_arg_error_shared_with_fpu_regs_stub_,                       \
    StubCode::NullArgErrorSharedWithFPURegs().raw(), nullptr)                  \
  V(RawCode*, allocate_mint_with_fpu_regs_stub_,                               \
    StubCode::AllocateMintWithFPURegs().raw(), NULL)                           \
  V(RawCode*, allocate_mint_without_fpu_regs_stub_,                            \
    StubCode::AllocateMintWithoutFPURegs().raw(), NULL)                        \
  V(RawCode*, stack_overflow_shared_without_fpu_regs_stub_,                    \
    StubCode::StackOverflowSharedWithoutFPURegs().raw(), NULL)                 \
  V(RawCode*, stack_overflow_shared_with_fpu_regs_stub_,                       \
    StubCode::StackOverflowSharedWithFPURegs().raw(), NULL)                    \
  V(RawCode*, monomorphic_miss_stub_, StubCode::MonomorphicMiss().raw(), NULL) \
  V(RawCode*, optimize_stub_, StubCode::OptimizeFunction().raw(), NULL)        \
  V(RawCode*, deoptimize_stub_, StubCode::Deoptimize().raw(), NULL)            \
  V(RawCode*, lazy_deopt_from_return_stub_,                                    \
    StubCode::DeoptimizeLazyFromReturn().raw(), NULL)                          \
  V(RawCode*, lazy_deopt_from_throw_stub_,                                     \
    StubCode::DeoptimizeLazyFromThrow().raw(), NULL)                           \
  V(RawCode*, slow_type_test_stub_, StubCode::SlowTypeTest().raw(), NULL)      \
  V(RawCode*, lazy_specialize_type_test_stub_,                                 \
    StubCode::LazySpecializeTypeTest().raw(), NULL)                            \
  V(RawCode*, enter_safepoint_stub_, StubCode::EnterSafepoint().raw(), NULL)   \
  V(RawCode*, exit_safepoint_stub_, StubCode::ExitSafepoint().raw(), NULL)     \
  V(RawCode*, call_native_through_safepoint_stub_,                             \
    StubCode::CallNativeThroughSafepoint().raw(), NULL)

#define CACHED_NON_VM_STUB_LIST(V)                                             \
  V(RawObject*, object_null_, Object::null(), NULL)                            \
  V(RawBool*, bool_true_, Object::bool_true().raw(), NULL)                     \
  V(RawBool*, bool_false_, Object::bool_false().raw(), NULL)

// List of VM-global objects/addresses cached in each Thread object.
// Important: constant false must immediately follow constant true.
#define CACHED_VM_OBJECTS_LIST(V)                                              \
  CACHED_NON_VM_STUB_LIST(V)                                                   \
  CACHED_VM_STUBS_LIST(V)

// This assertion marks places which assume that boolean false immediate
// follows bool true in the CACHED_VM_OBJECTS_LIST
#define ASSERT_BOOL_FALSE_FOLLOWS_BOOL_TRUE()                                  \
  ASSERT((Thread::bool_true_offset() + kWordSize) ==                           \
         Thread::bool_false_offset());

#define CACHED_VM_STUBS_ADDRESSES_LIST(V)                                      \
  V(uword, write_barrier_entry_point_, StubCode::WriteBarrier().EntryPoint(),  \
    0)                                                                         \
  V(uword, array_write_barrier_entry_point_,                                   \
    StubCode::ArrayWriteBarrier().EntryPoint(), 0)                             \
  V(uword, call_to_runtime_entry_point_,                                       \
    StubCode::CallToRuntime().EntryPoint(), 0)                                 \
  V(uword, null_error_shared_without_fpu_regs_entry_point_,                    \
    StubCode::NullErrorSharedWithoutFPURegs().EntryPoint(), 0)                 \
  V(uword, null_error_shared_with_fpu_regs_entry_point_,                       \
    StubCode::NullErrorSharedWithFPURegs().EntryPoint(), 0)                    \
  V(uword, null_arg_error_shared_without_fpu_regs_entry_point_,                \
    StubCode::NullArgErrorSharedWithoutFPURegs().EntryPoint(), 0)              \
  V(uword, null_arg_error_shared_with_fpu_regs_entry_point_,                   \
    StubCode::NullArgErrorSharedWithFPURegs().EntryPoint(), 0)                 \
  V(uword, allocate_mint_with_fpu_regs_entry_point_,                           \
    StubCode::AllocateMintWithFPURegs().EntryPoint(), 0)                       \
  V(uword, allocate_mint_without_fpu_regs_entry_point_,                        \
    StubCode::AllocateMintWithoutFPURegs().EntryPoint(), 0)                    \
  V(uword, stack_overflow_shared_without_fpu_regs_entry_point_,                \
    StubCode::StackOverflowSharedWithoutFPURegs().EntryPoint(), 0)             \
  V(uword, stack_overflow_shared_with_fpu_regs_entry_point_,                   \
    StubCode::StackOverflowSharedWithFPURegs().EntryPoint(), 0)                \
  V(uword, megamorphic_call_checked_entry_,                                    \
    StubCode::MegamorphicCall().EntryPoint(), 0)                               \
  V(uword, monomorphic_miss_entry_, StubCode::MonomorphicMiss().EntryPoint(),  \
    0)                                                                         \
  V(uword, optimize_entry_, StubCode::OptimizeFunction().EntryPoint(), 0)      \
  V(uword, deoptimize_entry_, StubCode::Deoptimize().EntryPoint(), 0)          \
  V(uword, call_native_through_safepoint_entry_point_,                         \
    StubCode::CallNativeThroughSafepoint().EntryPoint(), 0)

#define CACHED_ADDRESSES_LIST(V)                                               \
  CACHED_VM_STUBS_ADDRESSES_LIST(V)                                            \
  V(uword, bootstrap_native_wrapper_entry_point_,                              \
    NativeEntry::BootstrapNativeCallWrapperEntry(), 0)                         \
  V(uword, no_scope_native_wrapper_entry_point_,                               \
    NativeEntry::NoScopeNativeCallWrapperEntry(), 0)                           \
  V(uword, auto_scope_native_wrapper_entry_point_,                             \
    NativeEntry::AutoScopeNativeCallWrapperEntry(), 0)                         \
  V(uword, interpret_call_entry_point_, RuntimeEntry::InterpretCallEntry(), 0) \
  V(RawString**, predefined_symbols_address_, Symbols::PredefinedAddress(),    \
    NULL)                                                                      \
  V(uword, double_nan_address_, reinterpret_cast<uword>(&double_nan_constant), \
    0)                                                                         \
  V(uword, double_negate_address_,                                             \
    reinterpret_cast<uword>(&double_negate_constant), 0)                       \
  V(uword, double_abs_address_, reinterpret_cast<uword>(&double_abs_constant), \
    0)                                                                         \
  V(uword, float_not_address_, reinterpret_cast<uword>(&float_not_constant),   \
    0)                                                                         \
  V(uword, float_negate_address_,                                              \
    reinterpret_cast<uword>(&float_negate_constant), 0)                        \
  V(uword, float_absolute_address_,                                            \
    reinterpret_cast<uword>(&float_absolute_constant), 0)                      \
  V(uword, float_zerow_address_,                                               \
    reinterpret_cast<uword>(&float_zerow_constant), 0)

#define CACHED_CONSTANTS_LIST(V)                                               \
  CACHED_VM_OBJECTS_LIST(V)                                                    \
  CACHED_ADDRESSES_LIST(V)

enum class ValidationPolicy {
  kValidateFrames = 0,
  kDontValidateFrames = 1,
};

// A VM thread; may be executing Dart code or performing helper tasks like
// garbage collection or compilation. The Thread structure associated with
// a thread is allocated by EnsureInit before entering an isolate, and destroyed
// automatically when the underlying OS thread exits. NOTE: On Windows, CleanUp
// must currently be called manually (issue 23474).
class Thread : public ThreadState {
 public:
  // The kind of task this thread is performing. Sampled by the profiler.
  enum TaskKind {
    kUnknownTask = 0x0,
    kMutatorTask = 0x1,
    kCompilerTask = 0x2,
    kMarkerTask = 0x4,
    kSweeperTask = 0x8,
    kCompactorTask = 0x10,
  };
  // Converts a TaskKind to its corresponding C-String name.
  static const char* TaskKindToCString(TaskKind kind);

  ~Thread();

  // The currently executing thread, or NULL if not yet initialized.
  static Thread* Current() {
#if defined(HAS_C11_THREAD_LOCAL)
    return static_cast<Thread*>(OSThread::CurrentVMThread());
#else
    BaseThread* thread = OSThread::GetCurrentTLS();
    if (thread == NULL || thread->is_os_thread()) {
      return NULL;
    }
    return static_cast<Thread*>(thread);
#endif
  }

  // Makes the current thread enter 'isolate'.
  static bool EnterIsolate(Isolate* isolate);
  // Makes the current thread exit its isolate.
  static void ExitIsolate();

  // A VM thread other than the main mutator thread can enter an isolate as a
  // "helper" to gain limited concurrent access to the isolate. One example is
  // SweeperTask (which uses the class table, which is copy-on-write).
  // TODO(koda): Properly synchronize heap access to expand allowed operations.
  static bool EnterIsolateAsHelper(Isolate* isolate,
                                   TaskKind kind,
                                   bool bypass_safepoint = false);
  static void ExitIsolateAsHelper(bool bypass_safepoint = false);

  // Empties the store buffer block into the isolate.
  void ReleaseStoreBuffer();
  void AcquireMarkingStack();
  void ReleaseMarkingStack();

  void SetStackLimit(uword value);
  void ClearStackLimit();

  // Access to the current stack limit for generated code. Either the true OS
  // thread's stack limit minus some headroom, or a special value to trigger
  // interrupts.
  uword stack_limit_address() const {
    return reinterpret_cast<uword>(&stack_limit_);
  }
  static intptr_t stack_limit_offset() {
    return OFFSET_OF(Thread, stack_limit_);
  }

  // The true stack limit for this OS thread.
  static intptr_t saved_stack_limit_offset() {
    return OFFSET_OF(Thread, saved_stack_limit_);
  }
  uword saved_stack_limit() const { return saved_stack_limit_; }

#if defined(USING_SAFE_STACK)
  uword saved_safestack_limit() const { return saved_safestack_limit_; }
  void set_saved_safestack_limit(uword limit) {
    saved_safestack_limit_ = limit;
  }
#endif
  static uword saved_shadow_call_stack_offset() {
    return OFFSET_OF(Thread, saved_shadow_call_stack_);
  }

  // Stack overflow flags
  enum {
    kOsrRequest = 0x1,  // Current stack overflow caused by OSR request.
  };

  uword write_barrier_mask() const { return write_barrier_mask_; }

  static intptr_t write_barrier_mask_offset() {
    return OFFSET_OF(Thread, write_barrier_mask_);
  }
  static intptr_t stack_overflow_flags_offset() {
    return OFFSET_OF(Thread, stack_overflow_flags_);
  }

  int32_t IncrementAndGetStackOverflowCount() {
    return ++stack_overflow_count_;
  }

  static uword stack_overflow_shared_stub_entry_point_offset(bool fpu_regs) {
    return fpu_regs
               ? stack_overflow_shared_with_fpu_regs_entry_point_offset()
               : stack_overflow_shared_without_fpu_regs_entry_point_offset();
  }

  static intptr_t safepoint_state_offset() {
    return OFFSET_OF(Thread, safepoint_state_);
  }

  static intptr_t callback_code_offset() {
    return OFFSET_OF(Thread, ffi_callback_code_);
  }

  TaskKind task_kind() const { return task_kind_; }

  // Retrieves and clears the stack overflow flags.  These are set by
  // the generated code before the slow path runtime routine for a
  // stack overflow is called.
  uword GetAndClearStackOverflowFlags();

  // Interrupt bits.
  enum {
    kVMInterrupt = 0x1,  // Internal VM checks: safepoints, store buffers, etc.
    kMessageInterrupt = 0x2,  // An interrupt to process an out of band message.

    kInterruptsMask = (kVMInterrupt | kMessageInterrupt),
  };

  void ScheduleInterrupts(uword interrupt_bits);
  void ScheduleInterruptsLocked(uword interrupt_bits);
  RawError* HandleInterrupts();
  uword GetAndClearInterrupts();
  bool HasScheduledInterrupts() const {
    return (stack_limit_ & kInterruptsMask) != 0;
  }

  // Monitor corresponding to this thread.
  Monitor* thread_lock() const { return &thread_lock_; }

  // The reusable api local scope for this thread.
  ApiLocalScope* api_reusable_scope() const { return api_reusable_scope_; }
  void set_api_reusable_scope(ApiLocalScope* value) {
    ASSERT(value == NULL || api_reusable_scope_ == NULL);
    api_reusable_scope_ = value;
  }

  // The api local scope for this thread, this where all local handles
  // are allocated.
  ApiLocalScope* api_top_scope() const { return api_top_scope_; }
  void set_api_top_scope(ApiLocalScope* value) { api_top_scope_ = value; }

  void EnterApiScope();
  void ExitApiScope();

  // The isolate that this thread is operating on, or nullptr if none.
  Isolate* isolate() const { return isolate_; }
  static intptr_t isolate_offset() { return OFFSET_OF(Thread, isolate_); }

  // The isolate group that this thread is operating on, or nullptr if none.
  IsolateGroup* isolate_group() const { return isolate_group_; }

  bool IsMutatorThread() const;
  bool CanCollectGarbage() const;

  // Offset of Dart TimelineStream object.
  static intptr_t dart_stream_offset() {
    return OFFSET_OF(Thread, dart_stream_);
  }

  // Is |this| executing Dart code?
  bool IsExecutingDartCode() const;

  // Has |this| exited Dart code?
  bool HasExitedDartCode() const;

  CompilerState& compiler_state() {
    ASSERT(compiler_state_ != nullptr);
    return *compiler_state_;
  }

  HierarchyInfo* hierarchy_info() const {
    ASSERT(isolate_ != NULL);
    return hierarchy_info_;
  }

  void set_hierarchy_info(HierarchyInfo* value) {
    ASSERT(isolate_ != NULL);
    ASSERT((hierarchy_info_ == NULL && value != NULL) ||
           (hierarchy_info_ != NULL && value == NULL));
    hierarchy_info_ = value;
  }

  TypeUsageInfo* type_usage_info() const {
    ASSERT(isolate_ != NULL);
    return type_usage_info_;
  }

  void set_type_usage_info(TypeUsageInfo* value) {
    ASSERT(isolate_ != NULL);
    ASSERT((type_usage_info_ == NULL && value != NULL) ||
           (type_usage_info_ != NULL && value == NULL));
    type_usage_info_ = value;
  }

#if !defined(DART_PRECOMPILED_RUNTIME)
  Interpreter* interpreter() const { return interpreter_; }
  void set_interpreter(Interpreter* value) { interpreter_ = value; }
#endif

  int32_t no_callback_scope_depth() const { return no_callback_scope_depth_; }

  void IncrementNoCallbackScopeDepth() {
    ASSERT(no_callback_scope_depth_ < INT_MAX);
    no_callback_scope_depth_ += 1;
  }

  void DecrementNoCallbackScopeDepth() {
    ASSERT(no_callback_scope_depth_ > 0);
    no_callback_scope_depth_ -= 1;
  }

  void StoreBufferAddObject(RawObject* obj);
  void StoreBufferAddObjectGC(RawObject* obj);
#if defined(TESTING)
  bool StoreBufferContains(RawObject* obj) const {
    return store_buffer_block_->Contains(obj);
  }
#endif
  void StoreBufferBlockProcess(StoreBuffer::ThresholdPolicy policy);
  static intptr_t store_buffer_block_offset() {
    return OFFSET_OF(Thread, store_buffer_block_);
  }

  bool is_marking() const { return marking_stack_block_ != NULL; }
  void MarkingStackAddObject(RawObject* obj);
  void DeferredMarkingStackAddObject(RawObject* obj);
  void MarkingStackBlockProcess();
  void DeferredMarkingStackBlockProcess();
  static intptr_t marking_stack_block_offset() {
    return OFFSET_OF(Thread, marking_stack_block_);
  }

  uword top_exit_frame_info() const { return top_exit_frame_info_; }
  void set_top_exit_frame_info(uword top_exit_frame_info) {
    top_exit_frame_info_ = top_exit_frame_info;
  }
  static intptr_t top_exit_frame_info_offset() {
    return OFFSET_OF(Thread, top_exit_frame_info_);
  }

  // Heap of the isolate that this thread is operating on.
  Heap* heap() const { return heap_; }
  static intptr_t heap_offset() { return OFFSET_OF(Thread, heap_); }

  void set_top(uword value) { top_ = value; }
  void set_end(uword value) { end_ = value; }

  uword top() { return top_; }
  uword end() { return end_; }

  bool HasActiveTLAB() { return end_ > 0; }

  static intptr_t top_offset() { return OFFSET_OF(Thread, top_); }
  static intptr_t end_offset() { return OFFSET_OF(Thread, end_); }

  bool bump_allocate() const { return bump_allocate_; }
  void set_bump_allocate(bool b) { bump_allocate_ = b; }

  int32_t no_safepoint_scope_depth() const {
#if defined(DEBUG)
    return no_safepoint_scope_depth_;
#else
    return 0;
#endif
  }

  void IncrementNoSafepointScopeDepth() {
#if defined(DEBUG)
    ASSERT(no_safepoint_scope_depth_ < INT_MAX);
    no_safepoint_scope_depth_ += 1;
#endif
  }

  void DecrementNoSafepointScopeDepth() {
#if defined(DEBUG)
    ASSERT(no_safepoint_scope_depth_ > 0);
    no_safepoint_scope_depth_ -= 1;
#endif
  }

#define DEFINE_OFFSET_METHOD(type_name, member_name, expr, default_init_value) \
  static intptr_t member_name##offset() {                                      \
    return OFFSET_OF(Thread, member_name);                                     \
  }
  CACHED_CONSTANTS_LIST(DEFINE_OFFSET_METHOD)
#undef DEFINE_OFFSET_METHOD

#if defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_ARM64) ||                  \
    defined(TARGET_ARCH_X64)
  static intptr_t write_barrier_wrappers_thread_offset(Register reg) {
    ASSERT((kDartAvailableCpuRegs & (1 << reg)) != 0);
    intptr_t index = 0;
    for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) {
      if ((kDartAvailableCpuRegs & (1 << i)) == 0) continue;
      if (i == reg) break;
      ++index;
    }
    return OFFSET_OF(Thread, write_barrier_wrappers_entry_points_) +
           index * sizeof(uword);
  }

  static intptr_t WriteBarrierWrappersOffsetForRegister(Register reg) {
    intptr_t index = 0;
    for (intptr_t i = 0; i < kNumberOfCpuRegisters; ++i) {
      if ((kDartAvailableCpuRegs & (1 << i)) == 0) continue;
      if (i == reg) {
        return index * kStoreBufferWrapperSize;
      }
      ++index;
    }
    UNREACHABLE();
    return 0;
  }
#endif

#define DEFINE_OFFSET_METHOD(name)                                             \
  static intptr_t name##_entry_point_offset() {                                \
    return OFFSET_OF(Thread, name##_entry_point_);                             \
  }
  RUNTIME_ENTRY_LIST(DEFINE_OFFSET_METHOD)
#undef DEFINE_OFFSET_METHOD

#define DEFINE_OFFSET_METHOD(returntype, name, ...)                            \
  static intptr_t name##_entry_point_offset() {                                \
    return OFFSET_OF(Thread, name##_entry_point_);                             \
  }
  LEAF_RUNTIME_ENTRY_LIST(DEFINE_OFFSET_METHOD)
#undef DEFINE_OFFSET_METHOD

  RawObjectPool* global_object_pool() const { return global_object_pool_; }
  void set_global_object_pool(RawObjectPool* raw_value) {
    global_object_pool_ = raw_value;
  }

  static bool CanLoadFromThread(const Object& object);
  static intptr_t OffsetFromThread(const Object& object);
  static bool ObjectAtOffset(intptr_t offset, Object* object);
  static intptr_t OffsetFromThread(const RuntimeEntry* runtime_entry);

#if defined(DEBUG)
  // For asserts only. Has false positives when running with a simulator or
  // SafeStack.
  bool TopErrorHandlerIsSetJump() const;
  bool TopErrorHandlerIsExitFrame() const;
#endif

  uword vm_tag() const { return vm_tag_; }
  void set_vm_tag(uword tag) { vm_tag_ = tag; }
  static intptr_t vm_tag_offset() { return OFFSET_OF(Thread, vm_tag_); }

  int64_t unboxed_int64_runtime_arg() const {
    return unboxed_int64_runtime_arg_;
  }
  void set_unboxed_int64_runtime_arg(int64_t value) {
    unboxed_int64_runtime_arg_ = value;
  }
  static intptr_t unboxed_int64_runtime_arg_offset() {
    return OFFSET_OF(Thread, unboxed_int64_runtime_arg_);
  }

  RawGrowableObjectArray* pending_functions();
  void clear_pending_functions();

  static intptr_t global_object_pool_offset() {
    return OFFSET_OF(Thread, global_object_pool_);
  }

  RawObject* active_exception() const { return active_exception_; }
  void set_active_exception(const Object& value);
  static intptr_t active_exception_offset() {
    return OFFSET_OF(Thread, active_exception_);
  }

  RawObject* active_stacktrace() const { return active_stacktrace_; }
  void set_active_stacktrace(const Object& value);
  static intptr_t active_stacktrace_offset() {
    return OFFSET_OF(Thread, active_stacktrace_);
  }

  uword resume_pc() const { return resume_pc_; }
  void set_resume_pc(uword value) { resume_pc_ = value; }
  static uword resume_pc_offset() { return OFFSET_OF(Thread, resume_pc_); }

  RawError* sticky_error() const;
  void set_sticky_error(const Error& value);
  void ClearStickyError();
  DART_WARN_UNUSED_RESULT RawError* StealStickyError();

  RawStackTrace* async_stack_trace() const;
  void set_async_stack_trace(const StackTrace& stack_trace);
  void set_raw_async_stack_trace(RawStackTrace* raw_stack_trace);
  void clear_async_stack_trace();
  static intptr_t async_stack_trace_offset() {
    return OFFSET_OF(Thread, async_stack_trace_);
  }

#if defined(DEBUG)
#define REUSABLE_HANDLE_SCOPE_ACCESSORS(object)                                \
  void set_reusable_##object##_handle_scope_active(bool value) {               \
    reusable_##object##_handle_scope_active_ = value;                          \
  }                                                                            \
  bool reusable_##object##_handle_scope_active() const {                       \
    return reusable_##object##_handle_scope_active_;                           \
  }
  REUSABLE_HANDLE_LIST(REUSABLE_HANDLE_SCOPE_ACCESSORS)
#undef REUSABLE_HANDLE_SCOPE_ACCESSORS

  bool IsAnyReusableHandleScopeActive() const {
#define IS_REUSABLE_HANDLE_SCOPE_ACTIVE(object)                                \
  if (reusable_##object##_handle_scope_active_) {                              \
    return true;                                                               \
  }
    REUSABLE_HANDLE_LIST(IS_REUSABLE_HANDLE_SCOPE_ACTIVE)
    return false;
#undef IS_REUSABLE_HANDLE_SCOPE_ACTIVE
  }
#endif  // defined(DEBUG)

  void ClearReusableHandles();

#define REUSABLE_HANDLE(object)                                                \
  object& object##Handle() const { return *object##_handle_; }
  REUSABLE_HANDLE_LIST(REUSABLE_HANDLE)
#undef REUSABLE_HANDLE

  /*
   * Fields used to support safepointing a thread.
   *
   * - Bit 0 of the safepoint_state_ field is used to indicate if the thread is
   *   already at a safepoint,
   * - Bit 1 of the safepoint_state_ field is used to indicate if a safepoint
   *   operation is requested for this thread.
   * - Bit 2 of the safepoint_state_ field is used to indicate that the thread
   *   is blocked for the safepoint operation to complete.
   *
   * The safepoint execution state (described above) for a thread is stored in
   * in the execution_state_ field.
   * Potential execution states a thread could be in:
   *   kThreadInGenerated - The thread is running jitted dart/stub code.
   *   kThreadInVM - The thread is running VM code.
   *   kThreadInNative - The thread is running native code.
   *   kThreadInBlockedState - The thread is blocked waiting for a resource.
   */
  static bool IsAtSafepoint(uword state) {
    return AtSafepointField::decode(state);
  }
  bool IsAtSafepoint() const {
    return AtSafepointField::decode(safepoint_state_);
  }
  static uword SetAtSafepoint(bool value, uword state) {
    return AtSafepointField::update(value, state);
  }
  void SetAtSafepoint(bool value) {
    ASSERT(thread_lock()->IsOwnedByCurrentThread());
    safepoint_state_ = AtSafepointField::update(value, safepoint_state_);
  }
  bool IsSafepointRequested() const {
    return SafepointRequestedField::decode(safepoint_state_);
  }
  static uword SetSafepointRequested(bool value, uword state) {
    return SafepointRequestedField::update(value, state);
  }
  uword SetSafepointRequested(bool value) {
    ASSERT(thread_lock()->IsOwnedByCurrentThread());
    if (value) {
      return safepoint_state_.fetch_or(SafepointRequestedField::encode(true),
                                       std::memory_order_relaxed);
    } else {
      return safepoint_state_.fetch_and(~SafepointRequestedField::encode(true),
                                        std::memory_order_relaxed);
    }
  }
  static bool IsBlockedForSafepoint(uword state) {
    return BlockedForSafepointField::decode(state);
  }
  bool IsBlockedForSafepoint() const {
    return BlockedForSafepointField::decode(safepoint_state_);
  }
  void SetBlockedForSafepoint(bool value) {
    ASSERT(thread_lock()->IsOwnedByCurrentThread());
    safepoint_state_ =
        BlockedForSafepointField::update(value, safepoint_state_);
  }
  bool BypassSafepoints() const {
    return BypassSafepointsField::decode(safepoint_state_);
  }
  static uword SetBypassSafepoints(bool value, uword state) {
    return BypassSafepointsField::update(value, state);
  }

  enum ExecutionState {
    kThreadInVM = 0,
    kThreadInGenerated,
    kThreadInNative,
    kThreadInBlockedState
  };

  ExecutionState execution_state() const {
    return static_cast<ExecutionState>(execution_state_);
  }
  void set_execution_state(ExecutionState state) {
    execution_state_ = static_cast<uword>(state);
  }
  static intptr_t execution_state_offset() {
    return OFFSET_OF(Thread, execution_state_);
  }

  virtual bool MayAllocateHandles() {
    return (execution_state() == kThreadInVM) ||
           (execution_state() == kThreadInGenerated);
  }

  static uword safepoint_state_unacquired() { return SetAtSafepoint(false, 0); }
  static uword safepoint_state_acquired() { return SetAtSafepoint(true, 0); }

  bool TryEnterSafepoint() {
    uword old_state = 0;
    uword new_state = SetAtSafepoint(true, 0);
    return safepoint_state_.compare_exchange_strong(old_state, new_state,
                                                    std::memory_order_acq_rel);
  }

  void EnterSafepoint() {
    ASSERT(no_safepoint_scope_depth() == 0);
    // First try a fast update of the thread state to indicate it is at a
    // safepoint.
    if (!TryEnterSafepoint()) {
      // Fast update failed which means we could potentially be in the middle
      // of a safepoint operation.
      EnterSafepointUsingLock();
    }
  }

  bool TryExitSafepoint() {
    uword old_state = SetAtSafepoint(true, 0);
    uword new_state = 0;
    return safepoint_state_.compare_exchange_strong(old_state, new_state,
                                                    std::memory_order_acq_rel);
  }

  void ExitSafepoint() {
    // First try a fast update of the thread state to indicate it is not at a
    // safepoint anymore.
    if (!TryExitSafepoint()) {
      // Fast update failed which means we could potentially be in the middle
      // of a safepoint operation.
      ExitSafepointUsingLock();
    }
  }

  void CheckForSafepoint() {
    ASSERT(no_safepoint_scope_depth() == 0);
    if (IsSafepointRequested()) {
      BlockForSafepoint();
    }
  }

  int32_t AllocateFfiCallbackId();

  // Store 'code' for the native callback identified by 'callback_id'.
  //
  // Expands the callback code array as necessary to accomodate the callback ID.
  void SetFfiCallbackCode(int32_t callback_id, const Code& code);

  // Ensure that 'callback_id' refers to a valid callback in this isolate.
  //
  // If "entry != 0", additionally checks that entry is inside the instructions
  // of this callback.
  //
  // Aborts if any of these conditions fails.
  void VerifyCallbackIsolate(int32_t callback_id, uword entry);

  Thread* next() const { return next_; }

  // Visit all object pointers.
  void VisitObjectPointers(ObjectPointerVisitor* visitor,
                           ValidationPolicy validate_frames);

  bool IsValidHandle(Dart_Handle object) const;
  bool IsValidLocalHandle(Dart_Handle object) const;
  intptr_t CountLocalHandles() const;
  int ZoneSizeInBytes() const;
  void UnwindScopes(uword stack_marker);

  void InitVMConstants();

  uint64_t GetRandomUInt64() { return thread_random_.NextUInt64(); }

  uint64_t* GetFfiMarshalledArguments(intptr_t size) {
    if (ffi_marshalled_arguments_size_ < size) {
      if (ffi_marshalled_arguments_size_ > 0) {
        free(ffi_marshalled_arguments_);
      }
      ffi_marshalled_arguments_ =
          reinterpret_cast<uint64_t*>(malloc(size * sizeof(uint64_t)));
    }
    return ffi_marshalled_arguments_;
  }

#ifndef PRODUCT
  void PrintJSON(JSONStream* stream) const;
#endif

 private:
  template <class T>
  T* AllocateReusableHandle();

  // Set the current compiler state and return the previous compiler state.
  CompilerState* SetCompilerState(CompilerState* state) {
    CompilerState* previous = compiler_state_;
    compiler_state_ = state;
    return previous;
  }

  // Accessed from generated code.
  // ** This block of fields must come first! **
  // For AOT cross-compilation, we rely on these members having the same offsets
  // in SIMARM(IA32) and ARM, and the same offsets in SIMARM64(X64) and ARM64.
  // We use only word-sized fields to avoid differences in struct packing on the
  // different architectures. See also CheckOffsets in dart.cc.
  uword stack_limit_;
  uword saved_stack_limit_;
  uword stack_overflow_flags_;
  uword write_barrier_mask_;
  Isolate* isolate_;
  Heap* heap_;
  uword top_;
  uword end_;
  uword volatile top_exit_frame_info_;
  StoreBufferBlock* store_buffer_block_;
  MarkingStackBlock* marking_stack_block_;
  MarkingStackBlock* deferred_marking_stack_block_;
  uword volatile vm_tag_;
  RawStackTrace* async_stack_trace_;
  // Memory location dedicated for passing unboxed int64 values from
  // generated code to runtime.
  // TODO(dartbug.com/33549): Clean this up when unboxed values
  // could be passed as arguments.
  ALIGN8 int64_t unboxed_int64_runtime_arg_;

// State that is cached in the TLS for fast access in generated code.
#define DECLARE_MEMBERS(type_name, member_name, expr, default_init_value)      \
  type_name member_name;
  CACHED_CONSTANTS_LIST(DECLARE_MEMBERS)
#undef DECLARE_MEMBERS

#define DECLARE_MEMBERS(name) uword name##_entry_point_;
  RUNTIME_ENTRY_LIST(DECLARE_MEMBERS)
#undef DECLARE_MEMBERS

#define DECLARE_MEMBERS(returntype, name, ...) uword name##_entry_point_;
  LEAF_RUNTIME_ENTRY_LIST(DECLARE_MEMBERS)
#undef DECLARE_MEMBERS

#if defined(TARGET_ARCH_ARM) || defined(TARGET_ARCH_ARM64) ||                  \
    defined(TARGET_ARCH_X64)
  uword write_barrier_wrappers_entry_points_[kNumberOfDartAvailableCpuRegs];
#endif

  // JumpToExceptionHandler state:
  RawObject* active_exception_;
  RawObject* active_stacktrace_;
  RawObjectPool* global_object_pool_;
  uword resume_pc_;
  uword saved_shadow_call_stack_ = 0;
  uword execution_state_;
  std::atomic<uword> safepoint_state_;
  RawGrowableObjectArray* ffi_callback_code_;

  // ---- End accessed from generated code. ----

  // The layout of Thread object up to this point should not depend
  // on DART_PRECOMPILED_RUNTIME, as it is accessed from generated code.
  // The code is generated without DART_PRECOMPILED_RUNTIME, but used with
  // DART_PRECOMPILED_RUNTIME.

  TaskKind task_kind_;
  TimelineStream* dart_stream_;
  IsolateGroup* isolate_group_ = nullptr;
  mutable Monitor thread_lock_;
  ApiLocalScope* api_reusable_scope_;
  ApiLocalScope* api_top_scope_;
  int32_t no_callback_scope_depth_;
#if defined(DEBUG)
  int32_t no_safepoint_scope_depth_;
#endif
  VMHandles reusable_handles_;
  intptr_t defer_oob_messages_count_;
  uint16_t deferred_interrupts_mask_;
  uint16_t deferred_interrupts_;
  int32_t stack_overflow_count_;
  bool bump_allocate_;

  // Compiler state:
  CompilerState* compiler_state_ = nullptr;
  HierarchyInfo* hierarchy_info_;
  TypeUsageInfo* type_usage_info_;
  RawGrowableObjectArray* pending_functions_;

  RawError* sticky_error_;

  Random thread_random_;

  intptr_t ffi_marshalled_arguments_size_ = 0;
  uint64_t* ffi_marshalled_arguments_;

// Reusable handles support.
#define REUSABLE_HANDLE_FIELDS(object) object* object##_handle_;
  REUSABLE_HANDLE_LIST(REUSABLE_HANDLE_FIELDS)
#undef REUSABLE_HANDLE_FIELDS

#if defined(DEBUG)
#define REUSABLE_HANDLE_SCOPE_VARIABLE(object)                                 \
  bool reusable_##object##_handle_scope_active_;
  REUSABLE_HANDLE_LIST(REUSABLE_HANDLE_SCOPE_VARIABLE);
#undef REUSABLE_HANDLE_SCOPE_VARIABLE
#endif  // defined(DEBUG)

  // Generated code assumes that AtSafepointField is the LSB.
  class AtSafepointField : public BitField<uword, bool, 0, 1> {};
  class SafepointRequestedField : public BitField<uword, bool, 1, 1> {};
  class BlockedForSafepointField : public BitField<uword, bool, 2, 1> {};
  class BypassSafepointsField : public BitField<uword, bool, 3, 1> {};

#if defined(USING_SAFE_STACK)
  uword saved_safestack_limit_;
#endif

#if !defined(DART_PRECOMPILED_RUNTIME)
  Interpreter* interpreter_;
#endif

  Thread* next_;  // Used to chain the thread structures in an isolate.

  explicit Thread(bool is_vm_isolate);

  void StoreBufferRelease(
      StoreBuffer::ThresholdPolicy policy = StoreBuffer::kCheckThreshold);
  void StoreBufferAcquire();

  void MarkingStackRelease();
  void MarkingStackAcquire();
  void DeferredMarkingStackRelease();
  void DeferredMarkingStackAcquire();

  void set_safepoint_state(uint32_t value) { safepoint_state_ = value; }
  void EnterSafepointUsingLock();
  void ExitSafepointUsingLock();
  void BlockForSafepoint();

  static void SetCurrent(Thread* current) { OSThread::SetCurrentTLS(current); }

  void DeferOOBMessageInterrupts();
  void RestoreOOBMessageInterrupts();

#define REUSABLE_FRIEND_DECLARATION(name)                                      \
  friend class Reusable##name##HandleScope;
  REUSABLE_HANDLE_LIST(REUSABLE_FRIEND_DECLARATION)
#undef REUSABLE_FRIEND_DECLARATION

  friend class ApiZone;
  friend class Interpreter;
  friend class InterruptChecker;
  friend class Isolate;
  friend class IsolateGroup;
  friend class IsolateTestHelper;
  friend class NoOOBMessageScope;
  friend class Simulator;
  friend class StackZone;
  friend class ThreadRegistry;
  friend class CompilerState;
  friend class compiler::target::Thread;
  DISALLOW_COPY_AND_ASSIGN(Thread);
};

#if defined(HOST_OS_WINDOWS)
// Clears the state of the current thread and frees the allocation.
void WindowsThreadCleanUp();
#endif

// Disable thread interrupts.
class DisableThreadInterruptsScope : public StackResource {
 public:
  explicit DisableThreadInterruptsScope(Thread* thread);
  ~DisableThreadInterruptsScope();
};

// Within a NoSafepointScope, the thread must not reach any safepoint. Used
// around code that manipulates raw object pointers directly without handles.
#if defined(DEBUG)
class NoSafepointScope : public ThreadStackResource {
 public:
  explicit NoSafepointScope(Thread* thread = nullptr)
      : ThreadStackResource(thread != nullptr ? thread : Thread::Current()) {
    this->thread()->IncrementNoSafepointScopeDepth();
  }
  ~NoSafepointScope() { thread()->DecrementNoSafepointScopeDepth(); }

 private:
  DISALLOW_COPY_AND_ASSIGN(NoSafepointScope);
};
#else   // defined(DEBUG)
class NoSafepointScope : public ValueObject {
 public:
  explicit NoSafepointScope(Thread* thread = nullptr) {}

 private:
  DISALLOW_COPY_AND_ASSIGN(NoSafepointScope);
};
#endif  // defined(DEBUG)

}  // namespace dart

#endif  // RUNTIME_VM_THREAD_H_


text:
'''Sparse State Representation.'''

from numpy import *
import numbers

__all__=['SparseState','visualize_sstate','vec2sstate','soverlap']

def _compact_form(ws,configs):
    '''Merge duplicate configs.'''
    ws,configs=asarray(ws),asarray(configs)
    order=lexsort(configs.T)
    configs=configs[order]
    ws=ws[order]
    row_mask = append([True],any(diff(configs,axis=0),1))  #unique rows
    ws=asarray([a.sum() for a in split(ws,where(row_mask)[0][1:])])
    configs=configs[row_mask]
    return ws,configs

class SparseState(object):
    '''sparse representation of state.'''
    def __init__(self,ws,configs):
        assert(len(ws)==len(configs))
        self.ws,self.configs=_compact_form(ws,configs)

    def __str__(self):
        return '\n'.join(['%.2f: %s'%(wi,list(ci)) for wi,ci in zip(self.ws,self.configs)])

    def __mul__(self,target):
        if isinstance(target,SparseState):
            return soverlap(self,target)
        elif isinstance(target,numbers.Number):
            return SparseState(self.ws*target,self.configs)
        else:
            return target.__rmul__(self)

    def __rmul__(self,target):
        if isinstance(target,SparseState):
            return target.__mul__(self)
        elif isinstance(target,numbers.Number):
            return SparseState(self.ws*target,self.configs)
        else:
            raise TypeError()

    def __iter__(self):
        for w,config in zip(self.ws,self.configs):
            yield w,config

    def tovec(self,spaceconfig):
        '''To vector.'''
        vec=zeros(spaceconfig.hndim,dtype=self.ws.dtype)
        inds=spaceconfig.config2ind((1-self.configs)/2)
        add.at(vec,inds,self.ws)
        return vec

    def tobra(self):
        '''Hermitian conjugate.'''
        return SparseState(self.ws.conj(),self.configs)

def visualize_sstate(sstate,**kwargs):
    '''Visualize SparseState.'''
    from matplotlib.pyplot import pcolormesh
    pcolormesh(sstate.configs*abs(sstate.ws[:,newaxis]),**kwargs)

def vec2sstate(vec,spaceconfig,tol=1e-8):
    '''Transform a vector into SparseState'''
    mask=abs(vec)>1e-8
    inds=where(mask)
    configs=1-2*spaceconfig.ind2config(inds[0])
    return SparseState(vec[mask],configs)

def soverlap(bra,ket):
    '''
    Sparse version overlap of bra and ket.
    '''
    j0=0
    res=0.
    for w1,config1 in zip(bra.ws,bra.configs):
        w1=conj(w1)
        for j,(w2,config2) in enumerate(zip(ket.ws,ket.configs[j0:])):
            if allclose(config1,config2):
                res=res+w1*w2
                j0=j+1
    return res


text:
class AddRandomToSetMemberSubjects < ActiveRecord::Migration
  def change
    add_column :set_member_subjects, :random, :decimal
    SetMemberSubject.find_each{ |sms| sms.update!(random: rand) }
    change_column :set_member_subjects, :random, :decimal, null: false
    add_index :set_member_subjects, :random
  end
end


text:
package org.ehcache.clustered.server.state;

import org.ehcache.clustered.common.ServerSideConfiguration;
import org.ehcache.clustered.common.internal.ServerStoreConfiguration;
import org.ehcache.clustered.common.internal.exceptions.ClusterException;
import org.ehcache.clustered.server.ServerStoreImpl;
import org.ehcache.clustered.server.repo.StateRepositoryManager;

import com.tc.classloader.CommonComponent;

import java.util.Map;
import java.util.Set;

@CommonComponent
public interface EhcacheStateService {

  String getDefaultServerResource();

  Map<String, ServerSideConfiguration.Pool> getSharedResourcePools();

  ResourcePageSource getSharedResourcePageSource(String name);

  ServerSideConfiguration.Pool getDedicatedResourcePool(String name);

  ResourcePageSource getDedicatedResourcePageSource(String name);

  ServerStoreImpl getStore(String name);

  Set<String> getStores();

  void destroy();

  void validate(ServerSideConfiguration configuration) throws ClusterException;

  void configure(ServerSideConfiguration configuration) throws ClusterException;

  ServerStoreImpl createStore(String name, ServerStoreConfiguration serverStoreConfiguration) throws ClusterException;

  void destroyServerStore(String name) throws ClusterException;

  boolean isConfigured();

  StateRepositoryManager getStateRepositoryManager() throws ClusterException;

  ClientMessageTracker getClientMessageTracker();

  InvalidationTracker getInvalidationTracker(String cacheId);

  void addInvalidationtracker(String cacheId);

  InvalidationTracker removeInvalidationtracker(String cacheId);

}


text:
<?php

namespace Melody\Validation\Constraints;

use Melody\Validation\Validator as v;

class LengthTest extends \PHPUnit_Framework_TestCase
{

    public function testValidStringShouldPass()
    {
        $this->assertTrue(v::length(5, 10)->validate('abcdef0123'));
    }

    public function testInvalidStringShouldFailValidation()
    {
        $this->assertFalse(v::length(2, 5)->validate('abcdef0123'));
        $this->assertFalse(v::length(2, 5)->validate(''));
    }

    /**
     * @expectedException Melody\Validation\Exceptions\InvalidParameterException
     */
    public function testInvalidMinParameterShouldRaiseAnException()
    {
        v::length("invalid argument", 5);
    }

    /**
     * @expectedException Melody\Validation\Exceptions\InvalidParameterException
     */
    public function testInvalidMaxParameterShouldRaiseAnException()
    {
        v::length(2, "invalid argument");
    }

    /**
     * @expectedException Melody\Validation\Exceptions\InvalidInputException
     */
    public function testInvalidInputShouldRaiseAnException()
    {
        v::length(2, 5)->validate(1);
    }
}


text:
import UIKit
import SwiftyJSON
import Bond
import CocoaLumberjack
import BXModel
import PromiseKit

{% for comment in comments %}
{{ comment }}
{% endfor %}

class {{ model.class_name }} : {{model.superclass}},BXBindable {
    {% for field in uifields %}
    {{ field.declare_stmt }}
    {% endfor %}
    {{ model.adapter_decl }}

    {% if 'TableViewCell' in model.superclass %}
    convenience init() {
        self.init(style: .Default, reuseIdentifier: "{{ model.class_name }}Cell")
    }
    override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        commonInit()
    }
    {% else %}
    override init(frame: CGRect) {
        super.init(frame: frame)
        commonInit()
    }
    {% endif %}

    func bind(item:{{model.vc_mname}}){
    {% for field in uifields %}
        {% if field.can_bind_value %}
        {{field.bind_value_stmt}}
        {% endif %}
    {% endfor %}
    }

    override func awakeFromNib() {
        super.awakeFromNib()
        commonInit()
    }

    {%  include 'uicommon_init.html' %}
}


text:
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

namespace ICSharpCode.NRefactory.Demo
{
	partial class MainForm
	{
		/// <summary>
		/// Designer variable used to keep track of non-visual components.
		/// </summary>
		private System.ComponentModel.IContainer components = null;

		/// <summary>
		/// Disposes resources used by the form.
		/// </summary>
		/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
		protected override void Dispose(bool disposing)
		{
			if (disposing) {
				if (components != null) {
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		/// <summary>
		/// This method is required for Windows Forms designer support.
		/// Do not change the method contents inside the source code editor. The Forms designer might
		/// not be able to load this method if it was changed manually.
		/// </summary>
		private void InitializeComponent()
		{
			this.miniToolStrip = new System.Windows.Forms.ToolStrip();
			this.tabPage1 = new System.Windows.Forms.TabPage();
			this.csDemo1 = new ICSharpCode.NRefactory.Demo.CSDemo();
			this.tabControl1 = new System.Windows.Forms.TabControl();
			this.tabPage2 = new System.Windows.Forms.TabPage();
			this.tabPage1.SuspendLayout();
			this.tabControl1.SuspendLayout();
			this.tabPage2.SuspendLayout();
			this.SuspendLayout();
			//
			// miniToolStrip
			//
			this.miniToolStrip.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.miniToolStrip.AutoSize = false;
			this.miniToolStrip.CanOverflow = false;
			this.miniToolStrip.Dock = System.Windows.Forms.DockStyle.None;
			this.miniToolStrip.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden;
			this.miniToolStrip.Location = new System.Drawing.Point(13, 3);
			this.miniToolStrip.Name = "miniToolStrip";
			this.miniToolStrip.Size = new System.Drawing.Size(16, 25);
			this.miniToolStrip.TabIndex = 3;
			//
			// tabPage1
			//
			this.tabPage1.Controls.Add(this.csDemo1);
			this.tabPage1.Location = new System.Drawing.Point(4, 22);
			this.tabPage1.Name = "tabPage1";
			this.tabPage1.Padding = new System.Windows.Forms.Padding(3);
			this.tabPage1.Size = new System.Drawing.Size(507, 458);
			this.tabPage1.TabIndex = 0;
			this.tabPage1.Text = "C#";
			this.tabPage1.UseVisualStyleBackColor = true;
			//
			// csDemo1
			//
			this.csDemo1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.csDemo1.Location = new System.Drawing.Point(3, 3);
			this.csDemo1.Name = "csDemo1";
			this.csDemo1.Size = new System.Drawing.Size(501, 452);
			this.csDemo1.TabIndex = 0;
			//
			// tabControl1
			//
			this.tabControl1.Controls.Add(this.tabPage1);
			this.tabControl1.Controls.Add(this.tabPage2);
			this.tabControl1.Dock = System.Windows.Forms.DockStyle.Fill;
			this.tabControl1.Location = new System.Drawing.Point(0, 0);
			this.tabControl1.Name = "tabControl1";
			this.tabControl1.SelectedIndex = 0;
			this.tabControl1.Size = new System.Drawing.Size(515, 484);
			this.tabControl1.TabIndex = 0;
			//
			// tabPage2
			//
			this.tabPage2.Location = new System.Drawing.Point(4, 22);
			this.tabPage2.Name = "tabPage2";
			this.tabPage2.Padding = new System.Windows.Forms.Padding(3);
			this.tabPage2.Size = new System.Drawing.Size(507, 458);
			this.tabPage2.TabIndex = 1;
			this.tabPage2.Text = "VB";
			this.tabPage2.UseVisualStyleBackColor = true;
			//
			// MainForm
			//
			this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
			this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
			this.ClientSize = new System.Drawing.Size(515, 484);
			this.Controls.Add(this.tabControl1);
			this.Name = "MainForm";
			this.Text = "NRefactory Demo";
			this.tabPage1.ResumeLayout(false);
			this.tabControl1.ResumeLayout(false);
			this.tabPage2.ResumeLayout(false);
			this.ResumeLayout(false);
		}
		private System.Windows.Forms.TabPage tabPage2;
		private ICSharpCode.NRefactory.Demo.CSDemo csDemo1;
		private System.Windows.Forms.ToolStrip miniToolStrip;
		private System.Windows.Forms.TabPage tabPage1;
		private System.Windows.Forms.TabControl tabControl1;
	}
}


text:
<?php

namespace backend\modules\system;

class module extends \yii\base\Module
{
    public $controllerNamespace = 'backend\modules\system\controllers';

    public function init()
    {
        parent::init();
    }
}


text:
// .NAME vtkGenericDataSetTessellator - tessellates generic, higher-order datasets into linear cells
// .SECTION Description

// vtkGenericDataSetTessellator is a filter that subdivides a
// vtkGenericDataSet into linear elements (i.e., linear VTK
// cells). Tetrahedras are produced from 3D cells; triangles from 2D cells;
// and lines from 1D cells. The subdivision process depends on the cell
// tessellator associated with the input generic dataset, and its associated
// error metric. (These can be specified by the user if necessary.)
//
// This filter is typically used to convert a higher-order, complex dataset
// represented by a vtkGenericDataSet into a conventional vtkDataSet that can
// be operated on by linear VTK graphics filters (end of pipeline for
// rendering).

// .SECTION See Also
// vtkGenericCellTessellator vtkGenericSubdivisionErrorMetric

#ifndef __vtkGenericDataSetTessellator_h
#define __vtkGenericDataSetTessellator_h

#include "vtkFiltersGenericModule.h" // For export macro
#include "vtkUnstructuredGridAlgorithm.h"

class vtkPointData;
class vtkIncrementalPointLocator;

class VTKFILTERSGENERIC_EXPORT vtkGenericDataSetTessellator : public vtkUnstructuredGridAlgorithm
{
public:
  // Description:
  // Standard VTK methods.
  static vtkGenericDataSetTessellator *New();
  vtkTypeMacro(vtkGenericDataSetTessellator,
                       vtkUnstructuredGridAlgorithm);
  void PrintSelf(ostream& os, vtkIndent indent);

  // Description
  // Turn on/off generation of a cell centered attribute with ids of the
  // original cells (as an input cell is tessellated into several linear
  // cells).
  // The name of the data array is "OriginalIds". It is true by default.
  vtkSetMacro(KeepCellIds, int);
  vtkGetMacro(KeepCellIds, int);
  vtkBooleanMacro(KeepCellIds, int);

  // Description:
  // Turn on/off merging of coincident points. Note that is merging is
  // on, points with different point attributes (e.g., normals) are merged,
  // which may cause rendering artifacts.
  vtkSetMacro(Merging,int);
  vtkGetMacro(Merging,int);
  vtkBooleanMacro(Merging,int);

  // Description:
  // Set / get a spatial locator for merging points. By
  // default an instance of vtkMergePoints is used.
  void SetLocator(vtkIncrementalPointLocator *locator);
  vtkGetObjectMacro(Locator,vtkIncrementalPointLocator);

  // Description:
  // Create default locator. Used to create one when none is specified.
  void CreateDefaultLocator();

  // Description:
  // Return the MTime also considering the locator.
  unsigned long GetMTime();

protected:
  vtkGenericDataSetTessellator();
  ~vtkGenericDataSetTessellator();

  int RequestData(vtkInformation *, vtkInformationVector **, vtkInformationVector *);

  int FillInputPortInformation(int, vtkInformation*);

  // See Set/Get KeepCellIds() for explanations.
  int KeepCellIds;

  // Used internal by vtkGenericAdaptorCell::Tessellate()
  vtkPointData *InternalPD;

  int Merging;
  vtkIncrementalPointLocator *Locator;

private:
  vtkGenericDataSetTessellator(const vtkGenericDataSetTessellator&);  // Not implemented.
  void operator=(const vtkGenericDataSetTessellator&);  // Not implemented.
};

#endif


text:
package cn.easyproject.easyee.sh.sys.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;

import cn.easyproject.easyee.sh.base.service.BaseService;
import cn.easyproject.easyee.sh.sys.entity.SysMenuPermission;
import cn.easyproject.easyee.sh.sys.service.SysMenuPermissionService;

/**
 *
 * @author easyproject.cn
 * @version 1.0
 *
 */
@Service("sysMenuPermissionService")
@SuppressWarnings({"unchecked"})
public class SysMenuPermissionServiceImpl extends BaseService implements
		SysMenuPermissionService {

	@Override
	public void add(SysMenuPermission sysMenuPermission) {
		commonDAO.persist(sysMenuPermission);
	}

	@Override
	public void update(SysMenuPermission sysMenuPermission) {
		commonDAO.merge(sysMenuPermission);
	}

	@Override
	public SysMenuPermission get(int id) {
		return commonDAO.find(SysMenuPermission.class, id);
	}

	@Override
	public List<SysMenuPermission> list() {

		List<SysMenuPermission> list = commonDAO.findByCache("from SysMenuPermission",
				"SysMenuPermission.list");
		for (SysMenuPermission sysMenuPermission : list) {
			commonDAO.initializeDeep(sysMenuPermission.getSysMenuPermissions());
		}
		return list;
	}

	@Override
	public List<SysMenuPermission> listAll() {
		List<SysMenuPermission> list = commonDAO.findByCache("from SysMenuPermission",
				"SysMenuPermission.list");
		for (SysMenuPermission sysMenuPermission : list) {
			commonDAO.initializeDeep(sysMenuPermission.getSysMenuPermissions());
			commonDAO.initializeDeep(sysMenuPermission.getSysOperationPermissions());
		}
		return list;
	}

	@Override
	public int getMaxSortNum(Integer parentId) {

		Object res = null;
		if (parentId != -1) { // 非根节点
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("parentId", parentId);

			res = commonDAO
					.findVal(
							"select max(sortNum) from SysMenuPermission where sysMenuPermission.menuPermissionId=:parentId",
							params);
		} else {
			// 根节点
			res = commonDAO
					.findVal("select max(s.sortNum) from SysMenuPermission s where s.sysMenuPermission is null");
		}

		return res != null ? Integer.valueOf(res.toString()) : 0;
	}

	@Override
	public int getSortNum(Integer menuPermissionId) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("menuPermissionId", menuPermissionId);
		Object res = commonDAO.findVal(
				"select sortNum from SysMenuPermission where menuPermissionId=:menuPermissionId",
				params);
		return res != null ? Integer.valueOf(res.toString()) : 0;
	}

	@Override
	public void move(Integer menuPermissionId, boolean up) {

		SysMenuPermission sysMenuPermission = commonDAO.find(SysMenuPermission.class,
				menuPermissionId);
		//查找上移或下移需要交换的相邻对象
		// 下移
		String hql = "from SysMenuPermission where sysMenuPermission.menuPermissionId=:parentId and sortNum=(select min(sortNum) from SysMenuPermission where sysMenuPermission.menuPermissionId=:parentId and sortNum>:sortNum)";
		if (up) {
			// 上移
			 hql = "from SysMenuPermission where sysMenuPermission.menuPermissionId=:parentId and sortNum=(select max(sortNum) from SysMenuPermission where sysMenuPermission.menuPermissionId=:parentId and sortNum<:sortNum)";
		}

		Integer parentId=null;
		//如果没有父菜单
		if(sysMenuPermission.getSysMenuPermission()!=null){
			parentId=sysMenuPermission.getSysMenuPermission().getMenuPermissionId();
		}
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("parentId", parentId);
		params.put("sortNum", sysMenuPermission.getSortNum());
		SysMenuPermission neighbour = commonDAO.findVal(
				hql,
				params);
		// 存在相邻节点,则更新
		if(sysMenuPermission!=null&&neighbour!=null){
			//如果需要交换,则交换次序
			if(neighbour.getMenuPermissionId()!=sysMenuPermission.getMenuPermissionId()){
				int temp=neighbour.getSortNum();
				neighbour.setSortNum(sysMenuPermission.getSortNum());
				sysMenuPermission.setSortNum(temp);
			}

			commonDAO.merge(sysMenuPermission);
			commonDAO.merge(neighbour);
		}

	}

	@Override
	public boolean hashChildMenu(Integer menuPermissionId) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("menuPermissionId", menuPermissionId);
		return commonDAO.findCount("select count(*) from SysMenuPermission where sysMenuPermission.menuPermissionId=:menuPermissionId", params)>0?true:false;
	}

	@Override
	public void delete(SysMenuPermission sysMenuPermission) {
		// 删除一对多,多方的操作权限
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("menuPermissionId", sysMenuPermission.getMenuPermissionId());
		commonDAO.updateByJpql("delete from SysOperationPermission where sysMenuPermission.menuPermissionId=:menuPermissionId", params);
		commonDAO.updateByJpql("delete from SysMenuPermission where menuPermissionId=:menuPermissionId",params);
	}

	@Override
	public List<String> getIdsByRoleId(Integer roleId) {
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("roleId", roleId);
		return commonDAO.findBySQL("select menu_Permission_Id from sys_role_menu where ROLE_ID=:roleId",params);
	}

	@Override
	public List<SysMenuPermission> listByUserId(int userId) {
		//SELECT t FROM Teacher t join t.students s join s.books b where b.name = 'a'
		// 查询用户启用的角色及其菜单权限
		Map<String, Object> params=new HashMap<String, Object>();
		params.put("userId", userId);
		List<SysMenuPermission> list = commonDAO.findByCache("select r.sysMenuPermissions from SysRole r join r.sysUsers u where u.userId=:userId and r.status=0",
				"SysMenuPermission.list",params);
		for (SysMenuPermission sysMenuPermission : list) {
			commonDAO.initializeDeep(sysMenuPermission.getSysMenuPermissions());
		}

		return list;
	}

}


text:
@interface AppDelegate ()

@end

@implementation AppDelegate

-(UIViewController *)createVCWithClass:(Class)class
                                 title:(NSString *)title
                           normalImage:(NSString *)normalImage
                         selectedImage:(NSString *)selectedImage
{
    UIViewController *VC=[[class alloc] init];
    UIImage *norImage=[UIImage imageNamed:normalImage];
    norImage=[norImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    UIImage *selImage=[UIImage imageNamed:selectedImage];
    selImage=[selImage imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];

    VC.tabBarItem=[[UITabBarItem alloc] initWithTitle:title image:norImage selectedImage:selImage];

    return VC;
}

-(UITabBarController *)createTabbarController
{
    PoeViewController *poeVC=(PoeViewController *)[self createVCWithClass:[PoeViewController class] title:@"诗歌" normalImage:@"poe.png" selectedImage:@"poe1.png"];
    UINavigationController *poeNav=[[UINavigationController alloc] initWithRootViewController:poeVC];

    OtherViewController *otherVC = (OtherViewController *)[self createVCWithClass:[OtherViewController class] title:@"其他" normalImage:@"未收藏.png" selectedImage:@"已收藏.png"];
    UINavigationController *otherNav=[[UINavigationController alloc] initWithRootViewController:otherVC];
    //美图美文
    BeaViewController *beaVC=(BeaViewController *)[self createVCWithClass:[BeaViewController class] title:@"美图文" normalImage:@"书本.png" selectedImage:@"书本2.png"];
    UINavigationController *beaNav=[[UINavigationController alloc]initWithRootViewController:beaVC];

    UITabBarController *tabbarVC=[[UITabBarController alloc] init];

    tabbarVC.viewControllers=@[beaNav,poeNav,otherNav];

    tabbarVC.selectedIndex=0;

    tabbarVC.tabBar.translucent=NO;

    return tabbarVC;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    // Override point for customization after application launch.
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];

    self.window.rootViewController = [self createTabbarController];
    [[UINavigationBar appearance] setTranslucent:NO];
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.389 green:0.603 blue:1.000 alpha:1.000]];

    [[UITabBar appearance] setBarTintColor:[UIColor colorWithRed:0.950 green:0.945 blue:1.000 alpha:1.000]];

    [[UITabBar appearance] setTranslucent:NO];
    return YES;
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

@end


text:
		!--txt_errors3--

!--temp_update_info--


text:
var async = require('async')
var path = require('path')

module.exports = function (api) {
  var utils = require(path.join(__dirname, '/../utils.js'))(api)

  var mget = function (alias, ids, cacheTime, callback) {
    if (typeof cacheTime === 'function') { callback = cacheTime; cacheTime = null }
    if (!cacheTime) { cacheTime = api.config.elasticsearch.cacheTime }

    var indexes = [] // we meed to scan each index directly, not the alias
    var jobs = []
    var results = []
    var fromCache

    utils.runWithLimitAndCache(api.elasticsearch.client.cat, 'aliases', [{
      name: alias
    }], cacheTime, function (error, _fromCache, data) {
      if (error) { return callback(error) }

      data = data.split('\n')
      data.forEach(function (d) {
        var words = d.split(' ')
        if (words.length > 1) { indexes.push(words[1]) }
      })

      if (indexes.length === 0) { indexes = [alias] }

      indexes.forEach(function (index) {
        jobs.push(function (done) {
          var query = {
            index: index,
            body: {
              ids: ids
            }
          }

          var next = function (error, _fromCache, data) {
            if (error) { return done(error) }
            fromCache = _fromCache
            data.docs.forEach(function (doc) {
              if (doc.found === true) {
                results.push(doc._source)
              }
            })

            done()
          }

          utils.runWithLimitAndCache(api.elasticsearch.client, 'mget', [query], cacheTime, next)
        })
      })

      async.series(jobs, function (error) {
        return callback(error, results, fromCache)
      })
    })
  }

  return mget
}


text:
`ReactiveSwift`'s `ValidatingProperty` is the ideal place to apply SwiftValidators. `SwiftValidatorsReactiveExtensions` provides a set of extensions that make working with `ValidatingProperty` easy.

## Contents
+ [Installation](#installation)
+ [Walkthrough](#walkthrough)
+ [Usage](#usage)
+ [Available validators](#supported-functions)
+ [License](#license-mit)

### Installation

`SwiftValidatorsReactiveExtensions` is available on CocoaPods for iOS 9.0+, Xcode 8 and Swift 3.0

````
pod 'SwiftValidatorsReactiveExtensions'
````

### Walkthrough
#### Usage

`SwiftValidatorsReactiveExtensions` exposes a `reactive` property in `Validator` that maps each available validator to a `ReactiveValidator`. A `ReactiveValidator` can validate a value that conforms to `StringConvertible` and the result will be `ValidatorOutput<StringConvertible?, ValidationError>`.

`ValidationError` is an enum that conform to `Swift.Error` and provides cases for all available validators in `SwiftValidators` and a special case `.notSpecified` for when the error is not specified.

```swift
Validator.reactive
.isEmail().apply("gkaimakas@gmail.com") // returns .valid

Validator.reactive
.isEmail().apply("abcd") // returns .invalid(.isEmail)
```

For more examples on how to call each validator you can look at the [unit tests](https://github.com/gkaimakas/SwiftValidatorsReactiveExtensions/blob/master/Example/Tests/Tests.swift).

#### Logical Operators

`ReactiveValidator` exposes the `combine` function both as a `static` function and as an `instance` function. The `combine` function is equivalent to a logical and meaning that all validators must be `.valid` for the combined validator to be `.valid`.

```swift
ReactiveValidator.combine(
Validator.reactive.isEmail(),
Validator.reactive.isLowercase()
) // variadic function

ReactiveValidator
.combine([
Validator.reactive.isEmail(),
Validator.reactive.isLowercase()
]) // array arguments

Validator.reactive
.isEmail()
.combine(with: Validator.reactive.isLowercase()) // instance function
```

#### Mapping

`SwiftValidatorsReactiveExtensions` provide a `map` function to map the result of a `ReactiveValidator` ValidatorOutput<StringConvertible?, ValidationError> to the exact ValidatorOutput that the `ValidatingProperty` expects.

```swift
email = ValidatingProperty<String?, ValidationError>(nil, { (value: String?) -> ValidatorOutput<String?, ValidationError> in
return ReactiveValidator.combine([
Validator.reactive.required(),
Validator.reactive.minLength(5),
Validator.reactive.maxLength(32),
Validator.reactive.isEmail()
])
.apply(value)
.map() { $0 as? String }
})
```

### Available Validators

All the Validators that are available in [`SwiftValidators`](https://github.com/gkaimakas/SwiftValidators#supported-functions).

### License MIT

````
Copyright (c) George Kaimakas gkaimakas@gmail.com

Permission is hereby granted, free of charge, to any person obtaining
acopy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
````


text:
namespace SccmTools.Library.Module.Commands.CreateApplication
{
    public abstract class File
    {
        protected File(string fileName)
        {
            FileName = fileName;
        }

        public string FileName { get; }

        public abstract bool IsNull();

    }
}


text:
require 'rails_helper'

RSpec.describe "Authors", :type => :request do
  describe "GET /authors" do
    it "works! (now write some real specs)" do
      get authors_path
      expect(response).to have_http_status(200)
    end
  end
end


text:
sea-c23-javascript
==================

Foundations 2: JavaScript October 2014

[![Gitter chat](https://badges.gitter.im/codefellows/sea-c23-javascript.png)](https://gitter.im/codefellows/sea-c23-javascript)

Check out the [Gitbook source](https://github.com/codefellows/F2-javascript-textbook)


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateShiftDataTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('shift_data', function (Blueprint $table)
        {
            $table->increments('id');
            $table->integer('event_id')->unsigned();
            $table->foreign('event_id')->references('id')->on('events')->onDelete('cascade');
            $table->integer('department_id')->unsigned();
            $table->foreign('department_id')->references('id')->on('departments')->onDelete('cascade');
            $table->string('name');
            $table->text('description');
            $table->text('roles')->nullable();
            $table->timestamps();
        });

        // Loop through existing shift names and transfer them to the shift data table
        $shifts = DB::table('shifts')->select('shifts.*', 'departments.event_id')->join('departments', 'shifts.department_id', '=', 'departments.id')->get();
        $uniqueNames = [];

        foreach($shifts as $shift)
        {
            // Prevent creating multiple shifts with the same name
            if(!isset($uniqueNames[$shift->department_id]))
            {
                $uniqueNames[$shift->department_id] = [];
            }

            // Use the saved shift_data ID if this shift name is a duplicate
            if(isset($uniqueNames[$shift->department_id][$shift->name]))
            {
                DB::table('shifts')->where('id', $shift->id)->update(['name' => $uniqueNames[$shift->department_id][$shift->name]]);
            }
            else
            {
                $shiftData =
                [
                    'event_id' => $shift->event_id,
                    'department_id' => $shift->department_id,
                    'name' => $shift->name,
                    'created_at' => $shift->created_at,
                    'updated_at' => $shift->updated_at
                ];

                $id = DB::table('shift_data')->insertGetId($shiftData);
                DB::table('shifts')->where('id', $shift->id)->update(['name' => $id]);

                $uniqueNames[$shift->department_id][$shift->name] = $id;
            }
        }

        // Now rename the shift name column
        Schema::table('shifts', function ($table)
        {
            $table->renameColumn('name', 'shift_data_id');
        });

        // And set up the foreign key
        Schema::table('shifts', function ($table)
        {
            $table->integer('shift_data_id')->unsigned()->change();
            $table->foreign('shift_data_id')->references('id')->on('shift_data')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        // Remove the shift data foreign key
        Schema::table('shifts', function ($table)
        {
            $table->dropForeign(['shift_data_id']);
        });

        // Now rename the column
        Schema::table('shifts', function ($table)
        {
            $table->renameColumn('shift_data_id', 'name');
        });

        // For some reason this has to be separate as well
        Schema::table('shifts', function ($table)
        {
            $table->string('name')->change();
        });

        // Loop through shift data to get original shift names
        $shifts = DB::table('shifts')->select('shifts.id', 'shift_data.name')->join('shift_data', 'shifts.name', '=', 'shift_data.id')->get();

        foreach($shifts as $shift)
        {
            DB::table('shifts')->where('id', $shift->id)->update(['name' => $shift->name]);
        }

        Schema::drop('shift_data');
    }
}