text:
using base::SharedMemory;
using testing::_;
using testing::DoAll;
using testing::Return;
using testing::SetArgumentPointee;
using testing::StrictMock;

namespace gpu {

class CommandBufferServiceTest : public testing::Test {
 protected:
  void SetUp() override {
    {
      TransferBufferManager* manager = new TransferBufferManager(nullptr);
      transfer_buffer_manager_ = manager;
      EXPECT_TRUE(manager->Initialize());
    }
    command_buffer_.reset(
        new CommandBufferService(transfer_buffer_manager_.get()));
    EXPECT_TRUE(command_buffer_->Initialize());
  }

  int32 GetGetOffset() {
    return command_buffer_->GetLastState().get_offset;
  }

  int32 GetPutOffset() {
    return command_buffer_->GetPutOffset();
  }

  int32 GetToken() {
    return command_buffer_->GetLastState().token;
  }

  int32 GetError() {
    return command_buffer_->GetLastState().error;
  }

  bool Initialize(size_t size) {
    int32 id;
    command_buffer_->CreateTransferBuffer(size, &id);
    EXPECT_GT(id, 0);
    command_buffer_->SetGetBuffer(id);
    return true;
  }

  scoped_refptr<TransferBufferManagerInterface> transfer_buffer_manager_;
  scoped_ptr<CommandBufferService> command_buffer_;
};

TEST_F(CommandBufferServiceTest, InitializesCommandBuffer) {
  EXPECT_TRUE(Initialize(1024));
  CommandBuffer::State state = command_buffer_->GetLastState();
  EXPECT_EQ(0, state.get_offset);
  EXPECT_EQ(0, command_buffer_->GetPutOffset());
  EXPECT_EQ(0, state.token);
  EXPECT_EQ(error::kNoError, state.error);
}

namespace {

class CallbackTest {
 public:
  virtual void PutOffsetChanged() = 0;
  virtual bool GetBufferChanged(int32 id) = 0;
};

class MockCallbackTest : public CallbackTest {
 public:
   MOCK_METHOD0(PutOffsetChanged, void());
   MOCK_METHOD1(GetBufferChanged, bool(int32));
};

}  // anonymous namespace

TEST_F(CommandBufferServiceTest, CanSyncGetAndPutOffset) {
  Initialize(1024);

  scoped_ptr<StrictMock<MockCallbackTest> > change_callback(
      new StrictMock<MockCallbackTest>);
  command_buffer_->SetPutOffsetChangeCallback(
      base::Bind(
          &CallbackTest::PutOffsetChanged,
          base::Unretained(change_callback.get())));

  EXPECT_CALL(*change_callback, PutOffsetChanged());
  command_buffer_->Flush(2);
  EXPECT_EQ(0, GetGetOffset());
  EXPECT_EQ(2, GetPutOffset());

  EXPECT_CALL(*change_callback, PutOffsetChanged());
  command_buffer_->Flush(4);
  EXPECT_EQ(0, GetGetOffset());
  EXPECT_EQ(4, GetPutOffset());

  command_buffer_->SetGetOffset(2);
  EXPECT_EQ(2, GetGetOffset());
  EXPECT_CALL(*change_callback, PutOffsetChanged());
  command_buffer_->Flush(6);

  command_buffer_->Flush(-1);
  EXPECT_NE(error::kNoError, GetError());
  command_buffer_->Flush(1024);
  EXPECT_NE(error::kNoError, GetError());
}

TEST_F(CommandBufferServiceTest, SetGetBuffer) {
  int32 ring_buffer_id;
  command_buffer_->CreateTransferBuffer(1024, &ring_buffer_id);
  EXPECT_GT(ring_buffer_id, 0);

  scoped_ptr<StrictMock<MockCallbackTest> > change_callback(
      new StrictMock<MockCallbackTest>);
  command_buffer_->SetGetBufferChangeCallback(
      base::Bind(
          &CallbackTest::GetBufferChanged,
          base::Unretained(change_callback.get())));

  EXPECT_CALL(*change_callback, GetBufferChanged(ring_buffer_id))
      .WillOnce(Return(true));

  command_buffer_->SetGetBuffer(ring_buffer_id);
  EXPECT_EQ(0, GetGetOffset());
}

TEST_F(CommandBufferServiceTest, DefaultTokenIsZero) {
  EXPECT_EQ(0, GetToken());
}

TEST_F(CommandBufferServiceTest, CanSetToken) {
  command_buffer_->SetToken(7);
  EXPECT_EQ(7, GetToken());
}

TEST_F(CommandBufferServiceTest, DefaultParseErrorIsNoError) {
  EXPECT_EQ(0, GetError());
}

TEST_F(CommandBufferServiceTest, CanSetParseError) {
  command_buffer_->SetParseError(error::kInvalidSize);
  EXPECT_EQ(1, GetError());
}
}  // namespace gpu


text:
import typeOf from 'ramda/src/type';
import type {ValidationResult} from "./ValidationResult";
import type {Validator} from "./Validator";

var anyValidator: Validator = {
  isValid: function(val: mixed): boolean {
    return true;
  },

  getValidationResult: function(val: mixed): ValidationResult {
    return {
      isValid: 'true'
    }
  },
};

export default anyValidator;

redpajama_set_name: RedPajamaGithub


text:
package com.amazonaws.services.opsworks.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum VolumeType {

    Gp2("gp2"),
    Io1("io1"),
    Standard("standard");

    private String value;

    private VolumeType(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return VolumeType corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static VolumeType fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (VolumeType enumEntry : VolumeType.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
Additional header content

\[Missing  documentation for "P:iTin.Export.Model.TableModel.Alias"\]\[Missing <include> target documentation in 'P:iTin.Export.Model.TableModel.Alias'.  File: '..\..\iTin.Export.Documentation.xml' Path: 'Model/Table/Public/Properties/Property[@name="Alias"]/*'\]

**Namespace:** iTin.Export.Model
**Assembly:** iTin.Export.Core (in iTin.Export.Core.dll) Version: 2.0.0.0 (2.0.0.0)

## Syntax

**C#**

``` C#
public string Alias { get; set; }
```

**VB**

``` VB
Public Property Alias As String
	Get
	Set
```

#### Property Value
Type: String
\[Missing <value> documentation for "P:iTin.Export.Model.TableModel.Alias"\]

## Remarks
\[Missing <remarks> documentation for "P:iTin.Export.Model.TableModel.Alias"\]

## See Also

#### Reference
TableModel Class
iTin.Export.Model Namespace


text:
<?xml version="1.0" encoding="utf-8"?>
<androidx.preference.PreferenceScreen
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="prefs_addons_screen">

    <Preference
        android:key="settings_key_ext_kbd_top_row_key"
        android:persistent="false"
        android:summary="@string/top_generic_row_summary"
        android:title="@string/top_generic_row_group" />

    <Preference
        android:key="settings_key_ext_kbd_bottom_row_key"
        android:persistent="false"
        android:summary="@string/bottom_generic_row_summary"
        android:title="@string/bottom_generic_row_group" />

    <androidx.preference.CheckBoxPreference
        android:defaultValue="@bool/settings_default_allow_layouts_to_provide_generic_rows"
        android:key="@string/settings_key_allow_layouts_to_provide_generic_rows"
        android:persistent="true"
        android:summaryOff="@string/allow_layouts_to_provide_generic_rows_off_summary"
        android:summaryOn="@string/allow_layouts_to_provide_generic_rows_on_summary"
        android:title="@string/allow_layouts_to_provide_generic_rows" />

    <Preference
        android:key="settings_key_supported_row_modes"
        android:persistent="false"
        android:summary="@string/supported_keyboard_row_modes_summary"
        android:title="@string/supported_keyboard_row_modes_title" />

    <Preference
        android:key="@string/tweaks_group_key"
        android:title="@string/tweaks_group" />
</androidx.preference.PreferenceScreen>


text:
var React = require('react-native');

var {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
} = React;

class NavBar extends React.Component {
  constructor(props){
    super(props);

  }
  handleBackPress() {
    if(this.props.onBack) {
      this.props.onBack();
    } else {
      this.props.navi.pop();
    }
  }
  logout(){
    // this.state.socket.emit('studentLeavingClass', {userId: this.state.userId, classId:this.state.class.id});
    if(this.props.beforeLogout) {
      this.props.beforeLogout();
    }
    this.props.navi.popToTop();
  }
  render () {
    var backButton = '<<'
    return (
      <View>
        <View style={styles.nav}>
          <TouchableOpacity style={styles.back}onPress={this.handleBackPress.bind(this)}>
            <View>
              <Text style={styles.textSize}> {backButton} </Text>
            </View>
          </TouchableOpacity>
          <View>
            <Text style={styles.textSizeOne}>{this.props.children}</Text>
          </View>
         <TouchableOpacity style={styles.logout} onPress={this.logout.bind(this)}>
            <View>
              <Text style={styles.textSize}>Logout</Text>
            </View>
          </TouchableOpacity>
        </View>
      </View>
    )
  }
}
const styles = StyleSheet.create({
  nav: {
    flex: 0.2,
    marginTop: 0,
    paddingTop: 20,
    height: 75,
    flexDirection: 'row',
    justifyContent: 'space-between',
    backgroundColor: '#03a9f4',
    alignItems: 'center',
  },
  back: {
    height: 50,
    width: 50,
    justifyContent: 'center',
  },
  logout:{
    height: 50,
    width: 55,
    justifyContent: 'center',
  },
  textSize: {
    justifyContent: 'center',
    fontSize: 15,
    fontWeight: 'bold',
    color: '#fafafa',
  },
  textSizeOne: {
    fontSize: 25,
    justifyContent: 'center',
    color: '#fafafa',
  },
})

module.exports = NavBar;


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package tags;

import dataAccessLayer.Repozitorij;
import helpers.FloatFunkcije;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.BodyTagSupport;

/**
 *
 * @author Jurica
 */
public class ProizvodCijena extends BodyTagSupport {

    private PageContext pageContext;
    private int proizvodId;
    private int kolicina;

    @Override
    public int doStartTag() throws JspException {
        float cijena = Repozitorij.getProizvodiDatabaseInstance().getProizvod(proizvodId).getCijena();
        float ukupnaCijena = kolicina * cijena;

        try {
            pageContext.getOut().print("Cijena jednoga:
" + "Cijena x " + kolicina + "	");
            pageContext.getOut().print(" " + FloatFunkcije.getCijena(cijena, 2) + " KN
" + FloatFunkcije.getCijena(ukupnaCijena, 2) + " KN");
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
        return EVAL_BODY_BUFFERED;
    }

    /**
     * @return the pageContext
     */
    public PageContext getPageContext() {
        return pageContext;
    }

    /**
     * @param pageContext the pageContext to set
     */
    public void setPageContext(PageContext pageContext) {
        this.pageContext = pageContext;
    }

    /**
     * @return the proizvodId
     */
    public int getProizvodId() {
        return proizvodId;
    }

    /**
     * @param proizvodId the proizvodId to set
     */
    public void setProizvodId(int proizvodId) {
        this.proizvodId = proizvodId;
    }

    /**
     * @return the kolicina
     */
    public int getKolicina() {
        return kolicina;
    }

    /**
     * @param kolicina the kolicina to set
     */
    public void setKolicina(int kolicina) {
        this.kolicina = kolicina;
    }

}


text:
'use strict';

describe('Filter: task', function () {

  // load the filter's module
  beforeEach(module('tomTomApp'));

  // initialize a new instance of the filter before each test
  var task;
  beforeEach(inject(function ($filter) {
    task = $filter('task');
  }));

  it('should return the input prefixed with "task filter:"', function () {
    var text = 'angularjs';
    expect(task(text)).toBe('task filter: ' + text);
  });

});


text:
Easily listen for NSQ messages and pass them to the relevant handler.

## Installation

Add this line to your application's Gemfile:

```ruby
gem 'nsq_subscriber'
```

And then execute:

    $ bundle

Or install it yourself as:

    $ gem install nsq_subscriber

## Usage

Define one or more handler classes:

```ruby
class ExampleHandler
  def initialize(json_message, opts)
    @message = json_message
    @logger  = opts.fetch(:logger) { Logger.new(STDOUT) }
  end

  def call
    @logger.info "TODO: Handle message: #{@message}"
  end
end
```

Then instanciate an `NsqSubscriber` specifying the NSQLookupd, topic and channel:

```ruby
subscriber = NsqSubscriber.new(
  lookupd: "http://127.0.0.1:4161",
  topic: "example_topic",
  channel: "test_app",
  handler_options: {"oauth_provider": "http://www.example.com"}
)
subscriber["test_this"] = ExampleHandler
subscriber.listen
```

This will listen to events about the "example_topic" topic and when one of them
is in the following format it will trigger `ExampleHandler#call`.

```ruby
{
  "meta": {
    "event": "test_this"
  },
  "data": {
    "meaning": 42
  }
}
```

The `:handler_options` key will be passed to the handler when a relevant message
will be received.

## Running the tests

To run the tests:

```bash
$ bundle exec rspec
```

NOTE: nsqd and nsqlookupd will need to be running locally. Follow the instructions on NSQ documentation: http://nsq.io/overview/quick_start.html

## Development

After checking out the repo, run `bin/setup` to install dependencies. Then, run `bin/console` for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release` to create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).

## Contributing

1. Fork it ( https://github.com/[my-github-username]/nsq_subscriber/fork )
2. Create your feature branch (`git checkout -b my-new-feature`)
3. Commit your changes (`git commit -am 'Add some feature'`)
4. Push to the branch (`git push origin my-new-feature`)
5. Create a new Pull Request


text:
using namespace sequoia::render;
using namespace sequoia::core;
using namespace sequoia::unittest;
using namespace sequoia::math;

namespace {

class TestRenderer : public Renderer {
  std::vector<std::string> changes_;

protected:
  using Base = Renderer;

#define RENDER_STATE(Type, Name, DefaultValue)                                                     \
  virtual bool Name##Changed(Type value) override {                                                \
    changes_.emplace_back(#Name);                                                                  \
    return true;                                                                                \
  }
#include "sequoia-engine/Render/RenderState.inc"
#undef RENDER_STATE

  bool ProgramChanged(Program* program) override {
    changes_.emplace_back("Program");
    return true;
  }

  bool VertexDataChanged(VertexData* Data) override {
    changes_.emplace_back("VertexData");
    return true;
  }

  bool TextureChanged(int textureUnit, Texture* texture, bool enable) override {
    changes_.emplace_back("Texture" + std::to_string(textureUnit) + "_" +
                          (enable ? "enabled" : "disabled"));
    return true;
  }

  bool UniformVariableChanged(Program* program, const std::string& name,
                              const UniformVariable& value) override {
    changes_.emplace_back("UniformVariable_" + name);
    return true;
  }

  virtual bool ViewportChanged(int x, int y, int width, int height) override {
    changes_.emplace_back("Viewport");
    return true;
  }

  bool clearRenderBuffers(const std::set<RenderBuffer::RenderBufferKind>& buffersToClear) override {
    for(auto buffer : buffersToClear) {
      switch(buffer) {
      case RenderBuffer::RK_Color:
        changes_.emplace_back("ColorBuffer_cleared");
        break;
      case RenderBuffer::RK_Depth:
        changes_.emplace_back("DepthBuffer_cleared");
        break;
      case RenderBuffer::RK_Stencil:
        changes_.emplace_back("StencilBuffer_cleared");
        break;
      default:
        sequoia_unreachable("invalid RenderBuffer::RenderBufferKind");
      }
    }
    return true;
  }

  virtual bool draw(const DrawCommand& drawCommand) override { return true; }

  virtual std::pair<std::string, std::string> toStringImpl() const override {
    return std::make_pair("TestRenderer",
                          format("{}"
                                 "changes = {}\n",
                                 Base::toStringImpl().second,
                                 changes_.empty() ? "null" : toStringRange(changes_)));
  }

public:
  void forceClearRenderBuffers(const std::set<RenderBuffer::RenderBufferKind>& buffersToClear) {
    clearRenderBuffers(buffersToClear);
  }

  TestRenderer() : Renderer(RK_Invalid) {}
  const std::vector<std::string>& getChanges() const { return changes_; }
  void resetChanges() { changes_.clear(); }
};

class TestRenderTechnique : public RenderTechnique {
public:
  class TestRenderPass : public RenderPass {
  public:
    TestRenderPass(Program* program) : program_(program) {}

    void setUp(DrawCallContext& ctx) override {
      // Modify pipeline
      ctx.Pipeline.DepthTest = !ctx.Pipeline.DepthTest;
      ctx.Pipeline.Program = program_;

      // Set some uniforms
      ctx.Uniforms["two"] = UniformVariable(2.0f);
      ctx.Uniforms["five"] = UniformVariable(5);

      // Don't clear depth buffer
      ctx.BuffersToClear.erase(RenderBuffer::RK_Depth);
    }
    const char* getName() const noexcept override { return "TestRenderPass"; }

  private:
    Program* program_;
  };

  TestRenderTechnique(Program* program) { pass_ = std::make_unique<TestRenderPass>(program); }

  void render(std::function<void(RenderPass*)> renderer) override { renderer(pass_.get()); }

  const char* getName() const noexcept override { return "TestRenderTechnique"; }

private:
  std::unique_ptr<TestRenderPass> pass_;
};

static std::shared_ptr<VertexData> makeNullVertexData() {
  RenderSystem& rsys = RenderSystem::getSingleton();
  VertexDataParameter param(VertexData::DM_Triangles, VertexLayout{}, 0, 0,
                            Buffer::UH_StaticWriteOnly);
  return rsys.createVertexData(param);
}

SEQUOIA_TESTCASEFIXTURE(RendererTest, RenderSetup);

TEST_F(RendererTest, PipelineChange) {
  RenderSystem& rsys = RenderSystem::getSingleton();

  auto renderer = std::make_unique<TestRenderer>();
  auto program = rsys.createProgram({});

  RenderPipeline pipeline;
  pipeline.Program = program.get();

  // Check *all* change methods are called to set the initial state
  renderer->resetChanges();
  renderer->setRenderPipeline(pipeline);

  {
    const std::vector<std::string>& c = renderer->getChanges();
#define RENDER_STATE(Type, Name, DefaultValue)                                                     \
  EXPECT_TRUE(std::find(c.begin(), c.end(), #Name) != c.end())                                     \
      << "initial state '" #Name "' not set.";
#include "sequoia-engine/Render/RenderState.inc"
#undef RENDER_STATE

    EXPECT_TRUE(std::find(c.begin(), c.end(), "Program") != c.end())
        << "initial state 'Program' not set.";
  }

  // Check that only the correct change function is invoked
  pipeline.DepthTest = !pipeline.DepthTest;

  renderer->resetChanges();
  renderer->setRenderPipeline(pipeline);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 1);
    EXPECT_STREQ(c[0].c_str(), "DepthTest");
  }
}

TEST_F(RendererTest, VertexDataChange) {
  auto renderer = std::make_unique<TestRenderer>();
  auto vertexdata0 = makeNullVertexData();
  auto vertexdata1 = makeNullVertexData();

  // Bind for drawing
  renderer->resetChanges();
  renderer->setVertexData(vertexdata0.get());

  {
    const std::vector<std::string>& changes = renderer->getChanges();
    ASSERT_EQ(changes.size(), 1);
    EXPECT_STREQ(changes[0].c_str(), "VertexData");
  }

  // Rebind same vertex data -> nothing should happen
  renderer->resetChanges();
  renderer->setVertexData(vertexdata0.get());
  ASSERT_EQ(renderer->getChanges().size(), 0);

  // Bind another vertex-data
  renderer->resetChanges();
  renderer->setVertexData(vertexdata1.get());

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 1);
    EXPECT_STREQ(c[0].c_str(), "VertexData");
  }
}

TEST_F(RendererTest, RenderBufferChange) {
  auto renderer = std::make_unique<TestRenderer>();

  // Clear all buffers
  std::set<RenderBuffer::RenderBufferKind> buffersToClear = {
      RenderBuffer::RK_Color, RenderBuffer::RK_Depth, RenderBuffer::RK_Stencil};

  renderer->resetChanges();
  renderer->forceClearRenderBuffers(buffersToClear);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 3);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "ColorBuffer_cleared") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "DepthBuffer_cleared") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "StencilBuffer_cleared") != c.end());
  }

  // Don't clear depth buffer
  buffersToClear.erase(RenderBuffer::RK_Depth);

  renderer->resetChanges();
  renderer->forceClearRenderBuffers(buffersToClear);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 2);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "ColorBuffer_cleared") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "StencilBuffer_cleared") != c.end());
  }
}

TEST_F(RendererTest, TextureChange) {
  RenderSystem& rsys = RenderSystem::getSingleton();

  auto renderer = std::make_unique<TestRenderer>();

  std::unordered_map<int, Texture*> textures;
  auto tex0 = rsys.createTexture(nullptr);
  auto tex1 = rsys.createTexture(nullptr);
  auto tex2 = rsys.createTexture(nullptr);

  // Unit 0 & 1 are enabled
  textures[0] = tex0.get();
  textures[1] = tex1.get();

  renderer->resetChanges();
  renderer->setTextures(textures);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 2);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Texture0_enabled") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Texture1_enabled") != c.end());
  }

  // Unit 0 & 3 are enabled (requires 1 to be disabled)
  textures[2] = tex2.get();
  textures.erase(1);

  renderer->resetChanges();
  renderer->setTextures(textures);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 2);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Texture1_disabled") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Texture2_enabled") != c.end());
  }
}

TEST_F(RendererTest, UniformChange) {
  RenderSystem& rsys = RenderSystem::getSingleton();
  auto renderer = std::make_unique<TestRenderer>();

  auto program = rsys.createProgram({});
  UniformVariable two(2.0f);
  UniformVariable three(3.0f);
  UniformVariable five(5);

  // five and two are set
  renderer->resetChanges();
  renderer->setUniformVariable(program.get(), "two", two);
  renderer->setUniformVariable(program.get(), "five", five);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 2);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_two") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_five") != c.end());
  }

  // two changes value (five remains)
  renderer->resetChanges();
  renderer->setUniformVariable(program.get(), "two", three);
  renderer->setUniformVariable(program.get(), "five", five);

  {
    const std::vector<std::string>& changes = renderer->getChanges();
    ASSERT_EQ(changes.size(), 1);
    EXPECT_TRUE(std::find(changes.begin(), changes.end(), "UniformVariable_two") != changes.end());
  }

  // two and five have to be reset as we are going to reset the per program cache
  renderer->resetChanges();

  renderer->resetUniforms(program.get());
  renderer->setUniformVariable(program.get(), "two", three);
  renderer->setUniformVariable(program.get(), "five", five);

  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 2);
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_two") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_five") != c.end());
  }
}

TEST_F(RendererTest, Draw) {
  RenderSystem& rsys = RenderSystem::getSingleton();

  auto renderer = std::make_unique<TestRenderer>();
  auto target = rsys.getMainWindow();
  auto program = rsys.createProgram({});

  auto technique = std::make_unique<TestRenderTechnique>(program.get());
  auto vertexdata = makeNullVertexData();

  auto camera = std::make_shared<Camera>();
  auto viewport = std::make_shared<Viewport>(target, 0, 0, 80, 80);
  viewport->setCamera(camera.get());
  target->setViewport(viewport);

  DrawCommand drawCmd(vertexdata.get(), mat4(5.0f));

  RenderCommand renderCmd(target);
  renderCmd.Techniques = {technique.get()};
  renderCmd.DrawCommands = {drawCmd};

  renderer->resetChanges();
  renderer->render(renderCmd);

  // Check all changes are applied
  {
    const std::vector<std::string>& c = renderer->getChanges();
    ASSERT_EQ(c.size(), 10);

    // Pipeline
    EXPECT_TRUE(std::find(c.begin(), c.end(), "DepthTest") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "DepthFunc") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Program") != c.end());

    // RenderBuffers
    EXPECT_TRUE(std::find(c.begin(), c.end(), "ColorBuffer_cleared") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "StencilBuffer_cleared") != c.end());

    // Viewport
    EXPECT_TRUE(std::find(c.begin(), c.end(), "Viewport") != c.end());

    // VertexData
    EXPECT_TRUE(std::find(c.begin(), c.end(), "VertexData") != c.end());

    // Uniforms
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_u_matMVP") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_two") != c.end());
    EXPECT_TRUE(std::find(c.begin(), c.end(), "UniformVariable_five") != c.end());
  }
}

} // anonymous namespace


text:
### 受控

<!--start-code-->

```js
/**
 * import data from
 * https://github.com/rsuite/rsuite/blob/master/docs/public/data/users-role.json
 */

class Demo extends React.Component {
  constructor() {
    super();
    this.state = {
      value: null
    };
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(value) {
    this.setState({
      value
    });
  }
  render() {
    return (
      <InputPicker
        value={this.state.value}
        onChange={this.handleChange}
        data={data}
        style={{ width: 224 }}
      />
    );
  }
}

ReactDOM.render(<Demo />);
```

<!--end-code-->


text:
type: post121
title:  Consistency Biased
categories: XAP121ADM, PRM
parent: leader-election.html
weight: 200
---

{{% ssummary %}} {{% /ssummary %}}

 In this mode the Active Election process requires that a quorum of Zookeeper nodes, each space instance is elected as primary/backup according to the Zookeeper right image.

**Dependencies**

In order to use this feature, include the `${XAP_HOME}/lib/platform/zookeeper/xap-zookeeper.jar` file on your classpath or use maven dependencies:

```xml
<dependency>
    <groupId>com.gigaspaces</groupId>
    <artifactId>xap-zookeeper</artifactId>
    <version>{{%version maven-version%}}</version>
</dependency>
```
{{%refer%}}
For more information on dependencies see [Maven Artifacts]({{%currentjavaurl%}}/maven-artifacts.html)
{{%/refer%}}

# What is Zookeeper?

ZooKeeper is a distributed, hierarchical file system that facilitates loose coupling between clients and provides an eventually consistent view of its znodes, which are like files and directories in a traditional file system. It provides basic operations such as creating, deleting, and checking existence of znodes, also It provides an event-driven model in which clients can watch for changes to specific znodes. ZooKeeper achieves high availability by running multiple ZooKeeper servers, called an ensemble, with each server holding an in-memory copy of the distributed file system to service client read requests. Each server also holds a persistent copy on disk.
ZooKeeper is already used by Apache HBase, HDFS, and other Apache Hadoop projects to provide highly-available services.

# Zookeeper leader selector
XAP is using Apache Curator [leader selector](http://curator.apache.org/curator-recipes/leader-election.html) recipe which implements a distributed lock with notifications mechanism using Zookeeper.

{{%align center%}}
![image](/attachment_files/zookeeper-based-leader-selector.png)
{{%/align%}}

- A znode, say "/participants/partitionX"
- All participants of the election process create an ephemeral-sequential node on the same election path.
- The node with the smallest  sequence number is the leader.
- Each "follower" node listens to the node with the next lower seq number.
- Upon leader removal go to election path and find a new leader, or become the leader if it has the lowest sequence number.
- Upon session expiration (disconnection) check the election state and go to election if needed, in case of disconnection the primary space instance is moved to Quiese mode and will be restarted.

# Configuration
The first step is to [configure and run Zookeeper servers](./zookeeper.html).

Then add to your pu.xml the following leader-selector configuration:
{{% tabs %}}
{{% tab "Namespace" %}}
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:os-core="http://www.openspaces.org/schema/core"
      xmlns:leader-selector="http://www.openspaces.org/schema/zookeeper"
      xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-{{%version "spring"%}}.xsd
      http://www.openspaces.org/schema/core http://www.openspaces.org/schema/{{%currentversion%}}/core/openspaces-core.xsd
      http://www.openspaces.org/schema/zookeeper http://www.openspaces.org/schema/{{%currentversion%}}/zookeeper/openspaces-zookeeper.xsd">

   <leader-selector:zookeeper id="zookeeper"/>

    <os-core:embedded-space id="space" space-name="mySpace">
        <os-core:leader-selector ref="zookeeper"/>
    </os-core:embedded-space>

   <os-core:giga-space id="gigaSpace" space="space" />

</beans>
```
{{% /tab %}}
{{% /tabs %}}

| Property               | Description                                               | Default | Use |
|:-----------------------|:----------------------------------------------------------|:--------|:--------|
| <nobr>connection-timeout <nobr>| curator connection timeout. | 15000 millisecond | optional |
| session-timeout | curator session timeout | 10000 millisecond | optional |
| session-timeout | curator session timeout | 10000 millisecond | optional |
| retries | curator number of retries. Operations on a ZooKeeper cluster can fail. Best practices dictate that these operations should be retried. Curator has a Retry Loop mechanism. | 10 | optional |
| <nobr>sleep-between-retries<nobr> | curator sleep between retrie | 1000 millisecond | optional |

# Partition Split-Brain
Zookeeper leader selector avoids split-brain instances, through quorum, If the primary is not in the majority, that primary is frozen(or Quiesce) until the network is connected and the frozen primary is terminated automatically.


text:
rm -f /var/lib/rpm/__db.*
rpm --rebuilddb

systemctl daemon-reload

puppet apply --debug --verbose --color false --detailed-exitcodes \
  --logdest /var/log/puppet/ostf.log \
  /etc/puppet/modules/nailgun/examples/ostf-only.pp


text:
var helpers = require('../helpers');
var AWS = helpers.AWS;
var Buffer = AWS.util.Buffer;

describe('AWS.IotData', function() {
  var blobPayloadOutputOps = [
    'deleteThingShadow',
    'getThingShadow',
    'updateThingShadow'
  ];

  for (var i = 0; i < blobPayloadOutputOps.length; i++) {
    describe(blobPayloadOutputOps[i], (function(operation) {
      return function() {
        it('converts the body to a string', function(done) {
          var client = new AWS.IotData({endpoint: 'localhost'});
          var shadow = JSON.stringify({foo: 'bar', fizz: ['buzz', 'pop']});
          var body = AWS.util.buffer.toBuffer(shadow);
          helpers.mockHttpResponse(200, {}, body);
          client[operation]({thingName: 'thing'}, function(err, data) {
            expect(Buffer.isBuffer(data.payload)).to.be.false;
            expect(data.payload).to.eql(shadow);
            done();
          });
        });
      };
    })(blobPayloadOutputOps[i]));
  }
});


text:
package main

import (
	"bytes"
	"encoding/binary"
	"flag"
	"fmt"
	"log"
	"net/http"
	_ "net/http/pprof"
	"os"
	"regexp"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	as "github.com/archsaber/aerospike-client-go"
	asl "github.com/archsaber/aerospike-client-go/logger"
	ast "github.com/archsaber/aerospike-client-go/types"
)

type TStats struct {
	Exit       bool
	W, R       int // write and read counts
	WE, RE     int // write and read errors
	WTO, RTO   int // write and read timeouts
	WMin, WMax int64
	RMin, RMax int64
	WLat, RLat int64
	Wn, Rn     []int64
}

var countReportChan chan *TStats

var host = flag.String("h", "127.0.0.1", "Aerospike server seed hostnames or IP addresses")
var port = flag.Int("p", 3000, "Aerospike server seed hostname or IP address port number.")
var namespace = flag.String("n", "test", "Aerospike namespace.")
var set = flag.String("s", "testset", "Aerospike set name.")
var keyCount = flag.Int("k", 1000000, "Key/record count or key/record range.")

var user = flag.String("U", "", "User name.")
var password = flag.String("P", "", "User password.")

var binDef = flag.String("o", "I", "Bin object specification.\n\tI\t: Read/write integer bin.\n\tB:200\t: Read/write byte array bin of length 200.\n\tS:50\t: Read/write string bin of length 50.")
var concurrency = flag.Int("c", 32, "Number of goroutines to generate load.")
var workloadDef = flag.String("w", "I:100", "Desired workload.\n\tI:60\t: Linear 'insert' workload initializing 60% of the keys.\n\tRU:80\t: Random read/update workload with 80% reads and 20% writes.")
var latency = flag.String("L", "", "Latency <columns>,<shift>.\n\tShow transaction latency percentages using elapsed time ranges.\n\t<columns> Number of elapsed time ranges.\n\t<shift>   Power of 2 multiple between each range starting at column 3.")
var throughput = flag.Int64("g", 0, "Throttle transactions per second to a maximum value.\n\tIf tps is zero, do not throttle throughput.")
var timeout = flag.Int("T", 0, "Read/Write timeout in milliseconds.")
var maxRetries = flag.Int("maxRetries", 2, "Maximum number of retries before aborting the current transaction.")
var connQueueSize = flag.Int("queueSize", 4096, "Maximum number of connections to pool.")

var randBinData = flag.Bool("R", false, "Use dynamically generated random bin values instead of default static fixed bin values.")
var useMarshalling = flag.Bool("M", false, "Use marshaling a struct instead of simple key/value operations")
var debugMode = flag.Bool("d", false, "Run benchmarks in debug mode.")
var profileMode = flag.Bool("profile", false, "Run benchmarks with profiler active on port 6060.")
var showUsage = flag.Bool("u", false, "Show usage information.")

// parsed data
var binDataType string
var binDataSize int
var workloadType string
var workloadPercent int
var latBase, latCols int

// group mutex to wait for all load generating go routines to finish
var wg sync.WaitGroup

// throughput counter
var currThroughput int64
var lastReport int64

// Underscores are there so that the field name is the same as key/value mode
type dataStruct struct {
	I int64
	S string
	B []byte
}

var logger *log.Logger

func main() {
	var buf bytes.Buffer
	logger = log.New(&buf, "", log.LstdFlags|log.Lshortfile)
	logger.SetOutput(os.Stdout)

	// use all cpus in the system for concurrency
	log.Printf("Setting number of CPUs to use: %d", runtime.NumCPU())
	runtime.GOMAXPROCS(runtime.NumCPU())
	readFlags()

	countReportChan = make(chan *TStats, 4*(*concurrency)) // async chan

	if *debugMode {
		asl.Logger.SetLogger(logger)
		asl.Logger.SetLevel(asl.DEBUG)
	}

	// launch profiler if in profile mode
	if *profileMode {
		runtime.SetBlockProfileRate(1)
		go func() {
			logger.Println(http.ListenAndServe(":6060", nil))
		}()
	}

	printBenchmarkParams()

	clientPolicy := as.NewClientPolicy()
	// cache lots  connections
	clientPolicy.ConnectionQueueSize = *connQueueSize
	clientPolicy.User = *user
	clientPolicy.Password = *password
	clientPolicy.Timeout = 10 * time.Second
	client, err := as.NewClientWithPolicy(clientPolicy, *host, *port)
	if err != nil {
		logger.Fatal(err)
	}

	logger.Println("Nodes Found:", client.GetNodeNames())

	go reporter()

	switch workloadType {
	case "I":
		wg.Add(*concurrency)
		for i := 1; i < *concurrency; i++ {
			go runBench_I(client, i-1, *keyCount / *concurrency)
		}
		go runBench_I(client, *concurrency-1, *keyCount / *concurrency + *keyCount%*concurrency)
		wg.Wait()
	case "RU":
		for i := 1; i < *concurrency; i++ {
			go runBench_RU(client, i-1, *keyCount / *concurrency)
		}
		runBench_RU(client, *concurrency-1, *keyCount / *concurrency + *keyCount%*concurrency)
	default:
		log.Fatal("Invalid workload type " + workloadType)
	}

	// send term to reporter, and wait for it to terminate
	countReportChan <- &TStats{Exit: true}
	time.Sleep(10 * time.Millisecond)
	<-countReportChan
}

func workloadToString() string {
	switch workloadType {
	case "RU":
		return fmt.Sprintf("Read %d%%, Write %d%%", workloadPercent, 100-workloadPercent)
	default:
		return fmt.Sprintf("Initialize %d%% of records", workloadPercent)
	}
}

func throughputToString() string {
	if *throughput <= 0 {
		return "unlimited"
	}
	return fmt.Sprintf("%d", *throughput)
}

func printBenchmarkParams() {
	logger.Printf("hosts:\t\t%s", *host)
	logger.Printf("port:\t\t%d", *port)
	logger.Printf("namespace:\t\t%s", *namespace)
	logger.Printf("set:\t\t%s", *set)
	logger.Printf("keys/records:\t%d", *keyCount)
	logger.Printf("object spec:\t%s, size: %d", binDataType, binDataSize)
	logger.Printf("random bin values\t%v", *randBinData)
	logger.Printf("workload:\t\t%s", workloadToString())
	logger.Printf("concurrency:\t%d", *concurrency)
	logger.Printf("max throughput\t%s", throughputToString())
	logger.Printf("timeout\t\t%v ms", *timeout)
	logger.Printf("max retries\t\t%d", *maxRetries)
	logger.Printf("debug:\t\t%v", *debugMode)
	logger.Printf("latency:\t\t%d:%d", latBase, latCols)
}

// parses an string of (key:value) type
func parseValuedParam(param string) (string, *int) {
	re := regexp.MustCompile(`(\w+)([:,](\d+))?`)
	values := re.FindStringSubmatch(param)

	parStr := strings.ToUpper(strings.Trim(values[1], " "))

	// see if the value is supplied
	if len(values) > 3 && strings.Trim(values[3], " ") != "" {
		if value, err := strconv.Atoi(strings.Trim(values[3], " ")); err == nil {
			return parStr, &value
		}
	}

	return parStr, nil
}

func parseLatency(param string) (int, int) {
	re := regexp.MustCompile(`(\d+)[:,](\d+)`)
	values := re.FindStringSubmatch(param)

	// see if the value is supplied
	if len(values) > 2 && strings.Trim(values[1], " ") != "" && strings.Trim(values[2], " ") != "" {
		if value1, err := strconv.Atoi(strings.Trim(values[1], " ")); err == nil {
			if value2, err := strconv.Atoi(strings.Trim(values[2], " ")); err == nil {
				return value1, value2
			}
		}
	}

	logger.Fatal("Wrong latency values requested.")
	return 0, 0
}

// reads input flags and interprets the complex ones
func readFlags() {
	flag.Parse()

	if *showUsage {
		flag.Usage()
		os.Exit(0)
	}

	if *debugMode {
		asl.Logger.SetLevel(asl.INFO)
	}

	if *latency != "" {
		latCols, latBase = parseLatency(*latency)
	}

	var binDataSz, workloadPct *int

	binDataType, binDataSz = parseValuedParam(*binDef)
	if binDataSz != nil {
		binDataSize = *binDataSz
	} else {
		switch binDataType {
		case "B":
			binDataSize = 200
		case "S":
			binDataSize = 50
		}
	}

	workloadType, workloadPct = parseValuedParam(*workloadDef)
	if workloadPct != nil {
		workloadPercent = *workloadPct
	} else {
		switch workloadType {
		case "I":
			workloadPercent = 100
		case "RU":
			workloadPercent = 50
		}
	}
}

// new random bin generator based on benchmark specs
func getRandValue(xr *XorRand) as.Value {
	switch binDataType {
	case "B":
		return as.NewBytesValue(randBytes(binDataSize, xr))
	case "S":
		return as.NewStringValue(string(randBytes(binDataSize, xr)))
	default:
		return as.NewLongValue(xr.Int64())
	}
}

// new random bin generator based on benchmark specs
func getBin(xr *XorRand) *as.Bin {
	var bin *as.Bin
	switch binDataType {
	case "B":
		bin = &as.Bin{Name: "B", Value: getRandValue(xr)}
	case "S":
		bin = &as.Bin{Name: "S", Value: getRandValue(xr)}
	default:
		bin = &as.Bin{Name: "I", Value: getRandValue(xr)}
	}

	return bin
}

func setBin(bin *as.Bin, xr *XorRand) {
	switch binDataType {
	case "B":
		bin.Value = getRandValue(xr)
	case "S":
		bin.Value = getRandValue(xr)
	default:
		bin.Value = getRandValue(xr)
	}
}

// new random bin generator based on benchmark specs
func getDataStruct(xr *XorRand) *dataStruct {
	var ds *dataStruct
	switch binDataType {
	case "B":
		ds = &dataStruct{B: randBytes(binDataSize, xr)}
	case "S":
		ds = &dataStruct{S: string(randBytes(binDataSize, xr))}
	default:
		ds = &dataStruct{I: xr.Int64()}
	}

	return ds
}

// new random bin generator based on benchmark specs
func setDataStruct(ds *dataStruct, xr *XorRand) {
	switch binDataType {
	case "B":
		ds.B = randBytes(binDataSize, xr)
	case "S":
		ds.S = string(randBytes(binDataSize, xr))
	default:
		ds.I = xr.Int64()
	}
}

const random_alpha_num = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
const l = 62

func randBytes(size int, xr *XorRand) []byte {
	buf := make([]byte, size, size)
	xr.Read(buf)
	return buf
}

func incOnError(op, timeout *int, err error) {
	if ae, ok := err.(ast.AerospikeError); ok && ae.ResultCode() == ast.TIMEOUT {
		*timeout++
	} else {
		*op++
	}
}

func runBench_I(client *as.Client, ident int, times int) {
	defer wg.Done()

	xr := NewXorRand()

	var err error
	var forceReport bool = false

	writepolicy := as.NewWritePolicy(0, 0)
	writepolicy.Timeout = time.Duration(*timeout) * time.Millisecond
	writepolicy.MaxRetries = *maxRetries

	defaultBin := getBin(xr)
	defaultObj := getDataStruct(xr)

	t := time.Now()
	var WCount int
	var writeErr int
	var writeTOErr int

	var tm time.Time
	var wLat int64
	var wLatTotal int64
	var wMinLat int64
	var wMaxLat int64

	wLatList := make([]int64, latCols+1)

	bin := defaultBin
	obj := defaultObj
	key, _ := as.NewKey(*namespace, *set, 0)
	partition := ident * times
	for i := 1; i <= times; i++ {
		wLat = 0
		key.SetValue(as.IntegerValue(partition + (i % times)))
		WCount++
		if !*useMarshalling {
			// if randomBin data has been requested
			if *randBinData {
				setBin(bin, xr)
			}
			tm = time.Now()
			if err = client.PutBins(writepolicy, key, bin); err != nil {
				incOnError(&writeErr, &writeTOErr, err)
			}
		} else {
			// if randomBin data has been requested
			if *randBinData {
				setDataStruct(obj, xr)
			}
			tm = time.Now()
			if err = client.PutObject(writepolicy, key, obj); err != nil {
				incOnError(&writeErr, &writeTOErr, err)
			}
		}
		wLat = int64(time.Now().Sub(tm) / time.Millisecond)
		wLatTotal += wLat

		// under 1 ms
		if wLat <= int64(latBase) {
			wLatList[0]++
		}

		for i := 1; i <= latCols; i++ {
			if wLat > int64(latBase<<uint(i-1)) {
				wLatList[i]++
			}
		}

		wMinLat = min(wLat, wMinLat)
		wMaxLat = max(wLat, wMaxLat)

		// if throughput is set, check for threshold. All goroutines add a record on first iteration,
		// so take that into account as well
		if *throughput > 0 {
			forceReport = atomic.LoadInt64(&currThroughput) >= (*throughput - int64(*concurrency))
			if !forceReport {
				atomic.AddInt64(&currThroughput, 1)
			}
		}

		if forceReport || (time.Now().Sub(t) > (99 * time.Millisecond)) {
			countReportChan <- &TStats{false, WCount, 0, writeErr, 0, writeTOErr, 0, wMinLat, wMaxLat, 0, 0, wLatTotal, 0, wLatList, nil}
			WCount = 0
			writeErr = 0
			writeTOErr = 0

			// reset stats
			wLatTotal = 0
			wMinLat, wMaxLat = 0, 0

			wLatList = make([]int64, latCols+1)

			t = time.Now()
		}

		if forceReport {
			forceReport = false
			// sleep till next report
			time.Sleep(time.Second - time.Duration(time.Now().UnixNano()-atomic.LoadInt64(&lastReport)))
		}
	}
	countReportChan <- &TStats{false, WCount, 0, writeErr, 0, writeTOErr, 0, wMinLat, wMaxLat, 0, 0, wLatTotal, 0, wLatList, nil}
}

func runBench_RU(client *as.Client, ident int, times int) {
	defer wg.Done()

	xr := NewXorRand()

	// var r *as.Record

	var err error
	var forceReport bool = false

	writepolicy := as.NewWritePolicy(0, 0)
	writepolicy.Timeout = time.Duration(*timeout) * time.Millisecond
	writepolicy.MaxRetries = *maxRetries

	readpolicy := writepolicy.GetBasePolicy()

	defaultBin := getBin(xr)
	defaultObj := getDataStruct(xr)

	t := time.Now()
	var WCount, RCount int
	var writeErr, readErr int
	var writeTOErr, readTOErr int

	var tm time.Time
	var wLat, rLat int64
	var wLatTotal, rLatTotal int64
	var wMinLat, rMinLat int64
	var wMaxLat, rMaxLat int64

	wLatList := make([]int64, latCols+1)
	rLatList := make([]int64, latCols+1)

	bin := defaultBin
	obj := defaultObj
	i := 0
	key, _ := as.NewKey(*namespace, *set, 0)
	partition := ident * times
	for {
		i++
		rLat, wLat = 0, 0
		key.SetValue(as.IntegerValue(partition + (i % times)))
		// key, _ := as.NewKey(*namespace, *set, as.IntegerValue(partition+(i%times)))
		if int(xr.Uint64()%100) >= workloadPercent {
			WCount++
			if !*useMarshalling {
				// if randomBin data has been requested
				if *randBinData {
					setBin(bin, xr)
				}
				tm = time.Now()
				err = client.PutBins(writepolicy, key, bin)
			} else {
				// if randomBin data has been requested
				if *randBinData {
					setDataStruct(obj, xr)
				}
				tm = time.Now()
				err = client.PutObject(writepolicy, key, obj)
			}
			wLat = int64(time.Now().Sub(tm) / time.Millisecond)
			wLatTotal += wLat
			if err != nil {
				incOnError(&writeErr, &writeTOErr, err)
			}

			// under 1 ms
			if wLat <= int64(latBase) {
				wLatList[0]++
			}

			for i := 1; i <= latCols; i++ {
				if wLat > int64(latBase<<uint(i-1)) {
					wLatList[i]++
				}
			}

			wMinLat = min(wLat, wMinLat)
			wMaxLat = max(wLat, wMaxLat)
		} else {
			RCount++
			if !*useMarshalling {
				tm = time.Now()
				_, err = client.Get(readpolicy, key, bin.Name)
			} else {
				tm = time.Now()
				err = client.GetObject(readpolicy, key, obj)
			}
			rLat = int64(time.Now().Sub(tm) / time.Millisecond)
			rLatTotal += rLat
			if err != nil {
				incOnError(&readErr, &readTOErr, err)
			}

			// under 1 ms
			if rLat <= int64(latBase) {
				rLatList[0]++
			}

			for i := 1; i <= latCols; i++ {
				if rLat > int64(latBase<<uint(i-1)) {
					rLatList[i]++
				}
			}

			rMinLat = min(rLat, rMinLat)
			rMaxLat = max(rLat, rMaxLat)
		}

		// if throughput is set, check for threshold. All goroutines add a record on first iteration,
		// so take that into account as well
		if *throughput > 0 {
			forceReport = atomic.LoadInt64(&currThroughput) >= (*throughput - int64(*concurrency))
			if !forceReport {
				atomic.AddInt64(&currThroughput, 1)
			}
		}

		if forceReport || (time.Now().Sub(t) > (99 * time.Millisecond)) {
			countReportChan <- &TStats{false, WCount, RCount, writeErr, readErr, writeTOErr, readTOErr, wMinLat, wMaxLat, rMinLat, rMaxLat, wLatTotal, rLatTotal, wLatList, rLatList}
			WCount, RCount = 0, 0
			writeErr, readErr = 0, 0
			writeTOErr, readTOErr = 0, 0

			// reset stats
			wLatTotal, rLatTotal = 0, 0
			wMinLat, wMaxLat = 0, 0
			rMinLat, rMaxLat = 0, 0

			wLatList = make([]int64, latCols+1)
			rLatList = make([]int64, latCols+1)

			t = time.Now()
		}

		if forceReport {
			forceReport = false
			// sleep till next report
			time.Sleep(time.Second - time.Duration(time.Now().UnixNano()-atomic.LoadInt64(&lastReport)))
		}
	}
	countReportChan <- &TStats{false, WCount, RCount, writeErr, readErr, writeTOErr, readTOErr, wMinLat, wMaxLat, rMinLat, rMaxLat, wLatTotal, rLatTotal, wLatList, rLatList}
}

// calculates transactions per second
func calcTPS(count int, duration time.Duration) int {
	return int(float64(count) / (float64(duration) / float64(time.Second)))
}

func max(a, b int64) int64 {
	if a > b {
		return a
	}
	return b
}

func min(a, b int64) int64 {
	if a < b {
		return a
	}
	return b
}

// listens to transaction report channel, and print them out on intervals
func reporter() {
	var totalWCount, totalRCount int
	var totalWErrCount, totalRErrCount int
	var totalWTOCount, totalRTOCount int
	var totalCount, totalTOCount, totalErrCount int
	lastReportTime := time.Now()

	var memStats = new(runtime.MemStats)
	var lastTotalAllocs, lastPauseNs uint64

	// var wLat, rLat int64
	var wTotalLat, rTotalLat int64
	var wMinLat, rMinLat int64
	var wMaxLat, rMaxLat int64
	wLatList := make([]int64, latCols+1)
	rLatList := make([]int64, latCols+1)

	var strBuff bytes.Buffer

	memProfileStr := func() string {
		var res string
		if *debugMode {
			// GC stats
			runtime.ReadMemStats(memStats)
			allocMem := (memStats.TotalAlloc - lastTotalAllocs) / (1024)
			pauseNs := (memStats.PauseTotalNs - lastPauseNs) / 1e6
			res = fmt.Sprintf(" (malloc (KiB): %d, GC pause(ms): %d)",
				allocMem,
				pauseNs,
			)
			// GC
			lastPauseNs = memStats.PauseTotalNs
			lastTotalAllocs = memStats.TotalAlloc
		}

		return res
	}

Loop:
	for {
		select {
		case stats := <-countReportChan:
			totalWCount += stats.W
			totalRCount += stats.R

			totalWErrCount += stats.WE
			totalRErrCount += stats.RE

			totalWTOCount += stats.WTO
			totalRTOCount += stats.RTO

			totalCount += (stats.W + stats.R)
			totalErrCount += (stats.WE + stats.RE)
			totalTOCount += (stats.WTO + stats.RTO)

			wTotalLat += stats.WLat
			rTotalLat += stats.RLat

			for i := 0; i <= latCols; i++ {
				if stats.Wn != nil {
					wLatList[i] += stats.Wn[i]
				}
				if stats.Rn != nil {
					rLatList[i] += stats.Rn[i]
				}
			}

			if stats.RMax > rMaxLat {
				rMaxLat = stats.RMax
			}
			if stats.RMin < rMinLat {
				rMinLat = stats.RMin
			}
			if stats.WMax > wMaxLat {
				wMaxLat = stats.WMax
			}
			if stats.WMin < wMinLat {
				wMinLat = stats.WMin
			}

			if stats.Exit || time.Now().Sub(lastReportTime) >= time.Second {
				// reset throughput
				atomic.StoreInt64(&currThroughput, 0)
				atomic.StoreInt64(&lastReport, time.Now().UnixNano())

				if workloadType == "I" {
					logger.Printf("write(tps=%d timeouts=%d errors=%d totalCount=%d)%s",
						totalWCount, totalTOCount, totalErrCount, totalCount,
						memProfileStr(),
					)
				} else {
					logger.Printf(
						"write(tps=%d timeouts=%d errors=%d) read(tps=%d timeouts=%d errors=%d) total(tps=%d timeouts=%d errors=%d, count=%d)%s",
						totalWCount, totalWTOCount, totalWErrCount,
						totalRCount, totalRTOCount, totalRErrCount,
						totalWCount+totalRCount, totalTOCount, totalErrCount, totalCount,
						memProfileStr(),
					)
				}

				if *latency != "" {
					strBuff.WriteString(fmt.Sprintf("\t\tMin(ms)\tAvg(ms)\tMax(ms)\t|<=%4d ms\t", latBase))
					for i := 0; i < latCols; i++ {
						strBuff.WriteString(fmt.Sprintf("|>%4d ms\t", latBase<<uint(i)))
					}
					logger.Println(strBuff.String())
					strBuff.Reset()

					strBuff.WriteString(fmt.Sprintf("\tREAD\t%d\t%3.3f\t%d", rMinLat, float64(rTotalLat)/float64(totalRCount+1), rMaxLat))
					for i := 0; i <= latCols; i++ {
						strBuff.WriteString(fmt.Sprintf("\t|%7d/%4.2f%%", rLatList[i], float64(rLatList[i])/float64(totalRCount+1)*100))
					}
					logger.Println(strBuff.String())
					strBuff.Reset()

					strBuff.WriteString(fmt.Sprintf("\tWRITE\t%d\t%3.3f\t%d", wMinLat, float64(wTotalLat)/float64(totalWCount+1), wMaxLat))
					for i := 0; i <= latCols; i++ {
						strBuff.WriteString(fmt.Sprintf("\t|%7d/%4.2f%%", wLatList[i], float64(wLatList[i])/float64(totalWCount+1)*100))
					}
					logger.Println(strBuff.String())
					strBuff.Reset()
				}

				// reset stats
				wTotalLat, rTotalLat = 0, 0
				wMinLat, wMaxLat = 0, 0
				rMinLat, rMaxLat = 0, 0
				for i := 0; i <= latCols; i++ {
					wLatList[i] = 0
					rLatList[i] = 0
				}

				totalWCount, totalRCount = 0, 0
				totalWErrCount, totalRErrCount = 0, 0
				totalTOCount, totalWTOCount, totalRTOCount = 0, 0, 0
				lastReportTime = time.Now()

				if stats.Exit {
					break Loop
				}
			}
		}
	}
	countReportChan <- &TStats{}
}

type XorRand struct {
	src [2]uint64
}

func NewXorRand() *XorRand {
	return &XorRand{[2]uint64{uint64(time.Now().UnixNano()), uint64(time.Now().UnixNano())}}
}

func (r *XorRand) Int64() int64 {
	return int64(r.Uint64())
}

func (r *XorRand) Uint64() uint64 {
	s1 := r.src[0]
	s0 := r.src[1]
	r.src[0] = s0
	s1 ^= s1 << 23
	r.src[1] = (s1 ^ s0 ^ (s1 >> 17) ^ (s0 >> 26))
	return r.src[1] + s0
}

func (r *XorRand) Read(p []byte) (n int, err error) {
	l := len(p) / 8
	for i := 0; i < l; i += 8 {
		binary.PutUvarint(p[i:], r.Uint64())
	}
	return len(p), nil
}


text:
hubble
======

A data service provide data collect ,monitor and analysis


text:
using System;
using System.Collections.Generic;

namespace Delver
{
    [Serializable]
    internal class EventInfo
    {
        public EventInfo()
        {
        }

        public EventInfo(Zone validZone)
        {
            ValidInZone = validZone;
        }

        public Zone ValidInZone { get; private set; }
        public Zone FromZone { get; set; }
        public Zone ToZone { get; set; }

        public Context Context { get; set; }

        public Card SourceCard { get; set; }
        public Player SourcePlayer { get; set; }
        public Card TriggerCard { get; set; }
        public Player TriggerPlayer { get; set; }
        public GameObjectReferance Following { get; set; }

        public GameObjectReferance Enchanted => Following.Card?.Current.EnchantedObject;

        public List<GameObject> Targets { get; set; }

        public bool Match(EventInfo info)
        {
            var match = GetType().IsSameOrSubclass(info.GetType());
            return match;
        }

        public EventInfo Clone(Card source)
        {
            var newInfo = (EventInfo)MemberwiseClone();
            newInfo.SourceCard = source;
            newInfo.SourcePlayer = source.Controller;
            return newInfo;
        }

        public void AddDelayedTrigger(string text, EventListener listener, Action<EventInfo> callback, params ITarget[] targets)
        {
            listener.Text = text;
            var effect = new CallbackEffect(callback);
            effect.AddTarget(targets);
            listener.Effect = effect;
            Context.Methods.AddDelayedTrigger(SourceCard, listener);
        }

        public void AddToken(Card token, Player player = null)
        {
            Context.Methods.AddToken(player ?? SourcePlayer, token);
        }
    }
}


text:
package de.invidit.design.creational.singleton;

/**
 * @author Michael Weber
 * @since 24.02.2016
 */
public class SynchronizedLogger {

    private static SynchronizedLogger instance;

    private SynchronizedLogger() {
    }

    public synchronized static SynchronizedLogger getLogger() {
        if (instance == null) {
            instance = new SynchronizedLogger();
        }
        return instance;
    }

    public void Log(Object textToLog) {
        System.out.println(textToLog);
    }
}


text:
Function(treeId, treeNode)setting.callback.beforeCollapse

Overview[ depends on jquery.ztree.core js ]

Specify callback function to be called before collapse node, The return value controls the  collapse node.

Default: null

Function Parameter Descriptions

treeIdString

zTree unique identifier: treeId.

treeNodeJSON

JSON data object of the node to be collapsed

Return Boolean

return true or false

If return false, zTree will not collapse node, and will not trigger the 'onCollapse' callback.

Examples of setting & function

1. disabled to collapse node which is expanded

function myBeforeCollapse(treeId, treeNode) {
    return false;
};
var setting = {
	callback: {
		beforeCollapse: myBeforeCollapse
	}
};
......


text:
CALL \Projects\Theas\venv_py34_theas\scripts\activate.bat
del \Projects\Theas\dist\*.*
cd \Projects\Theas
python setup.py py2exe
cd \Projects\Theas\dist
PAUSE


text:
import * as React from 'react';
import * as classNames from 'classnames';

import './ui-grid-row.styl';

interface UIGridRowProps { children?: any; mod?: string; }

export const UIGridRow = (props: UIGridRowProps) => {
    return <div
        className={classNames({
            'row': true,
            [`ui-grid-row_${props.mod}`]: !!props.mod
        })}
    >
        {props.children}
    </div>;
};


text:
import { NgModule } from '@angular/core';
import { IonicPageModule } from 'ionic-angular';
import { FlashCardComponent } from './flash-card';

@NgModule({
  declarations: [
    FlashCardComponent,
  ],
  imports: [
    IonicPageModule.forChild(FlashCardComponent),
  ],
  exports: [
    FlashCardComponent
  ]
})
export class FlashCardComponentModule {}


text:
{{ .Title }}

    {{ if .Description }}

{{ .Description }}

    {{ end }}

        Published <time datetime="{{ .Date.Format "2006-01-02" }}" itemprop="datePublished">{{ dateFormat (default "Mon, Jan 2, 2006" .Site.Params.dateFormat) .Date }}</time>
        by

                {{ .Params.author | default .Site.Author.name }}


text:
require 'spec_helper'

describe 'Winged' do

	before(:each) do
		@r = WingedObject.new
		3.times do
			@w = WingedObject.new display: 'block'
			2.times do
				@l = WingedObject.new
				@l[:class] = 'elle'
				@w << @l
			end
			@r << @w
		end
		@k = WingedText.new 'Text goes here', color: 'blue'
		@w << @k
	end

	describe "Builder" do

		before(:each) do
			@b = WingedBuilder.new @r
			@html = @b.to_html
		end

		it "should build an html document" do
			@html.should match /html/
			@html.should match /head/
			@html.should match /style/
			@html.should match /title/
			@html.should match /doctype/i
		end

		it "should style properly" do
			@html.should match /class="elle"/
		end

		it "should attribute properly" do
			@html.should match /style="display:block;/
		end

		it 'should display text properly' do
			@html.should match /<span.*>Text goes here<\/span>/
		end

	end

	describe 'Text' do

		before(:each) do
			@t = WingedText.new 'hello', display: 'block', border: 'none'
			@l = WingedObject.new 'size' => 'large'
			@t << @l
			@w << @t
			@b = WingedBuilder.new @r
			@html = @b.to_html
		end

		it 'should have children elements' do
			@html.should match /<span.*>hello<div.*><\/div><\/span>/
		end

	end

end


text:
layout: post
title: 278 - First Bad Version
date: 2015-10-21 02:28:07.000000000 -04:00
tags:
- Leetcode
categories:
- Binary Search Tree
author: Jason
---
**The code base version is an integer start from 1 to n. One day, someone committed a bad version in the code case, so it caused this version and the following versions are all failed in the unit tests. Find the first bad version.**

``` python
class Solution:
    def firstBadVersion(self, n: int):

        lo, hi = 1, n
        while lo <= hi:
            mid = (lo + hi) // 2
            if isBadVersion(mid):
                hi = mid - 1
            else:
                lo = mid + 1
        return lo
```


text:
<!--
# license: Licensed to the Apache Software Foundation (ASF) under one
#         or more contributor license agreements.  See the NOTICE file
#         distributed with this work for additional information
#         regarding copyright ownership.  The ASF licenses this file
#         to you under the Apache License, Version 2.0 (the
#         "License"); you may not use this file except in compliance
#         with the License.  You may obtain a copy of the License at
#
#           http://www.apache.org/licenses/LICENSE-2.0
#
#         Unless required by applicable law or agreed to in writing,
#         software distributed under the License is distributed on an
#         "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
#         KIND, either express or implied.  See the License for the
#         specific language governing permissions and limitations
#         under the License.
-->

[![Build Status](https://travis-ci.org/apache/cordova-plugin-dialogs.svg?branch=master)](https://travis-ci.org/apache/cordova-plugin-dialogs)

# cordova-plugin-dialogs

This plugin provides access to some native dialog UI elements
via a global `navigator.notification` object.

Although the object is attached to the global scoped `navigator`, it is not available until after the `deviceready` event.

    document.addEventListener("deviceready", onDeviceReady, false);
    function onDeviceReady() {
        console.log(navigator.notification);
    }

Report issues on the [Apache Cordova issue tracker](https://issues.apache.org/jira/issues/?jql=project%20%3D%20CB%20AND%20status%20in%20%28Open%2C%20%22In%20Progress%22%2C%20Reopened%29%20AND%20resolution%20%3D%20Unresolved%20AND%20component%20%3D%20%22Plugin%20Dialogs%22%20ORDER%20BY%20priority%20DESC%2C%20summary%20ASC%2C%20updatedDate%20DESC)

## Installation

    cordova plugin add cordova-plugin-dialogs

## Methods

- `navigator.notification.alert`
- `navigator.notification.confirm`
- `navigator.notification.prompt`
- `navigator.notification.beep`

## navigator.notification.alert

Shows a custom alert or dialog box.  Most Cordova implementations use a native
dialog box for this feature, but some platforms use the browser's `alert`
function, which is typically less customizable.

    navigator.notification.alert(message, alertCallback, [title], [buttonName])

- __message__: Dialog message. _(String)_

- __alertCallback__: Callback to invoke when alert dialog is dismissed. _(Function)_

- __title__: Dialog title. _(String)_ (Optional, defaults to `Alert`)

- __buttonName__: Button name. _(String)_ (Optional, defaults to `OK`)

### Example

    function alertDismissed() {
        // do something
    }

    navigator.notification.alert(
        'You are the winner!',  // message
        alertDismissed,         // callback
        'Game Over',            // title
        'Done'                  // buttonName
    );

### Supported Platforms

- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows

### Windows Phone 7 and 8 Quirks

- There is no built-in browser alert, but you can bind one as follows to call `alert()` in the global scope:

        window.alert = navigator.notification.alert;

- Both `alert` and `confirm` are non-blocking calls, results of which are only available asynchronously.

### Firefox OS Quirks:

Both native-blocking `window.alert()` and non-blocking `navigator.notification.alert()` are available.

### BlackBerry 10 Quirks
`navigator.notification.alert('text', callback, 'title', 'text')` callback parameter is passed the number 1.

## navigator.notification.confirm

Displays a customizable confirmation dialog box.

    navigator.notification.confirm(message, confirmCallback, [title], [buttonLabels])

- __message__: Dialog message. _(String)_

- __confirmCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_

- __title__: Dialog title. _(String)_ (Optional, defaults to `Confirm`)

- __buttonLabels__: Array of strings specifying button labels. _(Array)_  (Optional, defaults to [`OK,Cancel`])

### confirmCallback

The `confirmCallback` executes when the user presses one of the
buttons in the confirmation dialog box.

The callback takes the argument `buttonIndex` _(Number)_, which is the
index of the pressed button. Note that the index uses one-based
indexing, so the value is `1`, `2`, `3`, etc.

### Example

    function onConfirm(buttonIndex) {
        alert('You selected button ' + buttonIndex);
    }

    navigator.notification.confirm(
        'You are the winner!', // message
         onConfirm,            // callback to invoke with index of button pressed
        'Game Over',           // title
        ['Restart','Exit']     // buttonLabels
    );

### Supported Platforms

- Amazon Fire OS
- Android
- BlackBerry 10
- Firefox OS
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8
- Windows

### Windows Phone 7 and 8 Quirks

- There is no built-in browser function for `window.confirm`, but you can bind it by assigning:

        window.confirm = navigator.notification.confirm;

- Calls to `alert` and `confirm` are non-blocking, so the result is only available asynchronously.

### Windows Quirks

- On Windows8/8.1 it is not possible to add more than three buttons to MessageDialog instance.

- On Windows Phone 8.1 it's not possible to show dialog with more than two buttons.

### Firefox OS Quirks:

Both native-blocking `window.confirm()` and non-blocking `navigator.notification.confirm()` are available.

## navigator.notification.prompt

Displays a native dialog box that is more customizable than the browser's `prompt` function.

    navigator.notification.prompt(message, promptCallback, [title], [buttonLabels], [defaultText])

- __message__: Dialog message. _(String)_

- __promptCallback__: Callback to invoke with index of button pressed (1, 2, or 3) or when the dialog is dismissed without a button press (0). _(Function)_

- __title__: Dialog title _(String)_ (Optional, defaults to `Prompt`)

- __buttonLabels__: Array of strings specifying button labels _(Array)_ (Optional, defaults to `["OK","Cancel"]`)

- __defaultText__: Default textbox input value (`String`) (Optional, Default: empty string)

### promptCallback

The `promptCallback` executes when the user presses one of the buttons
in the prompt dialog box. The `results` object passed to the callback
contains the following properties:

- __buttonIndex__: The index of the pressed button. _(Number)_ Note that the index uses one-based indexing, so the value is `1`, `2`, `3`, etc.

- __input1__: The text entered in the prompt dialog box. _(String)_

### Example

    function onPrompt(results) {
        alert("You selected button number " + results.buttonIndex + " and entered " + results.input1);
    }

    navigator.notification.prompt(
        'Please enter your name',  // message
        onPrompt,                  // callback to invoke
        'Registration',            // title
        ['Ok','Exit'],             // buttonLabels
        'Jane Doe'                 // defaultText
    );

### Supported Platforms

- Amazon Fire OS
- Android
- Firefox OS
- iOS
- Windows Phone 7 and 8
- Windows 8
- Windows

### Android Quirks

- Android supports a maximum of three buttons, and ignores any more than that.

- On Android 3.0 and later, buttons are displayed in reverse order for devices that use the Holo theme.

### Windows Quirks

- On Windows prompt dialog is html-based due to lack of such native api.

### Firefox OS Quirks:

Both native-blocking `window.prompt()` and non-blocking `navigator.notification.prompt()` are available.

## navigator.notification.beep

The device plays a beep sound.

    navigator.notification.beep(times);

- __times__: The number of times to repeat the beep. _(Number)_

### Example

    // Beep twice!
    navigator.notification.beep(2);

### Supported Platforms

- Amazon Fire OS
- Android
- BlackBerry 10
- iOS
- Tizen
- Windows Phone 7 and 8
- Windows 8

### Amazon Fire OS Quirks

- Amazon Fire OS plays the default __Notification Sound__ specified under the __Settings/Display & Sound__ panel.

### Android Quirks

- Android plays the default __Notification ringtone__ specified under the __Settings/Sound & Display__ panel.

### Windows Phone 7 and 8 Quirks

- Relies on a generic beep file from the Cordova distribution.

### Tizen Quirks

- Tizen implements beeps by playing an audio file via the media API.

- The beep file must be short, must be located in a `sounds` subdirectory of the application's root directory, and must be named `beep.wav`.


text:
/*
 * Utility class copied from http://transdroid.googlecode.com with the authorization from Eric Kok to redistribute it under Apache Software License.
 */
package org.acra.util;

import org.apache.http.conn.scheme.LayeredSocketFactory;
import org.apache.http.conn.scheme.SocketFactory;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.TrustManager;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;

public class FakeSocketFactory implements SocketFactory, LayeredSocketFactory {

    private SSLContext sslcontext = null;

    private static SSLContext createEasySSLContext() throws IOException {
        try {
            final SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[] { new NaiveTrustManager() }, null);
            return context;
        } catch (Exception e) {
            throw new IOException(e.getMessage());
        }
    }

    private SSLContext getSSLContext() throws IOException {
        if (this.sslcontext == null) {
            this.sslcontext = createEasySSLContext();
        }
        return this.sslcontext;
    }

    @Override
    public Socket connectSocket(Socket sock, String host, int port, InetAddress localAddress, int localPort, HttpParams params) throws IOException {
        final int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
        final int soTimeout = HttpConnectionParams.getSoTimeout(params);

        final InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
        final SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());

        if ((localAddress != null) || (localPort > 0)) {
            // we need to bind explicitly
            if (localPort < 0) {
                localPort = 0; // indicates "any"
            }
            final InetSocketAddress isa = new InetSocketAddress(localAddress, localPort);
            sslsock.bind(isa);
        }

        sslsock.connect(remoteAddress, connTimeout);
        sslsock.setSoTimeout(soTimeout);

        return sslsock;
    }

    @Override
    public Socket createSocket() throws IOException {
        return getSSLContext().getSocketFactory().createSocket();
    }

    @Override
    public boolean isSecure(Socket arg0) throws IllegalArgumentException {
        return true;
    }

    @Override
    public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException {
        return getSSLContext().getSocketFactory().createSocket(socket, host, port, autoClose);
    }

}


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

package org.chromium.chrome.browser.feed.library.piet;

import static org.chromium.chrome.browser.feed.library.common.testing.RunnableSubject.assertThatRunnable;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

import org.chromium.components.feed.core.proto.ui.piet.ErrorsProto.ErrorCode;

/** Tests of the NoKeyOverwriteHashMap */
@RunWith(JUnit4.class)
public class NoKeyOverwriteHashMapTest {
    private final NoKeyOverwriteHashMap<String, String> mMap =
            new NoKeyOverwriteHashMap<>("Acronym", ErrorCode.ERR_DUPLICATE_BINDING_VALUE);

    @Test
    public void testPutTwoDifferentKeys() {
        mMap.put("CPA", "Certified Public Accountant");
        mMap.put("CPU", "Central Processing Unit");
    }

    @Test
    public void testPutTwoSameKeysThrows() {
        mMap.put("CD", "Compact Disc");
        assertThatRunnable(() -> mMap.put("CD", "Certificate of Deposit"))
                .throwsAnExceptionOfType(PietFatalException.class)
                .that()
                .hasMessageThat()
                .contains("Acronym key 'CD' already defined");
    }
}


text:
package target

import (
	"context"

	"github.com/mafredri/cdp/protocol/internal"
	"github.com/mafredri/cdp/rpcc"
)

// domainClient is a client for the Target domain. Supports additional targets
// discovery and allows to attach to them.
type domainClient struct{ conn *rpcc.Conn }

// NewClient returns a client for the Target domain with the connection set to conn.
func NewClient(conn *rpcc.Conn) *domainClient {
	return &domainClient{conn: conn}
}

// ActivateTarget invokes the Target method. Activates (focuses) the target.
func (d *domainClient) ActivateTarget(ctx context.Context, args *ActivateTargetArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.activateTarget", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.activateTarget", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "ActivateTarget", Err: err}
	}
	return
}

// AttachToTarget invokes the Target method. Attaches to the target with given
// id.
func (d *domainClient) AttachToTarget(ctx context.Context, args *AttachToTargetArgs) (reply *AttachToTargetReply, err error) {
	reply = new(AttachToTargetReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.attachToTarget", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.attachToTarget", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "AttachToTarget", Err: err}
	}
	return
}

// CloseTarget invokes the Target method. Closes the target. If the target is
// a page that gets closed too.
func (d *domainClient) CloseTarget(ctx context.Context, args *CloseTargetArgs) (reply *CloseTargetReply, err error) {
	reply = new(CloseTargetReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.closeTarget", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.closeTarget", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "CloseTarget", Err: err}
	}
	return
}

// CreateBrowserContext invokes the Target method. Creates a new empty
// BrowserContext. Similar to an incognito profile but you can have more than
// one.
func (d *domainClient) CreateBrowserContext(ctx context.Context) (reply *CreateBrowserContextReply, err error) {
	reply = new(CreateBrowserContextReply)
	err = rpcc.Invoke(ctx, "Target.createBrowserContext", nil, reply, d.conn)
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "CreateBrowserContext", Err: err}
	}
	return
}

// CreateTarget invokes the Target method. Creates a new page.
func (d *domainClient) CreateTarget(ctx context.Context, args *CreateTargetArgs) (reply *CreateTargetReply, err error) {
	reply = new(CreateTargetReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.createTarget", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.createTarget", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "CreateTarget", Err: err}
	}
	return
}

// DetachFromTarget invokes the Target method. Detaches session with given id.
func (d *domainClient) DetachFromTarget(ctx context.Context, args *DetachFromTargetArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.detachFromTarget", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.detachFromTarget", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "DetachFromTarget", Err: err}
	}
	return
}

// DisposeBrowserContext invokes the Target method. Deletes a BrowserContext,
// will fail of any open page uses it.
func (d *domainClient) DisposeBrowserContext(ctx context.Context, args *DisposeBrowserContextArgs) (reply *DisposeBrowserContextReply, err error) {
	reply = new(DisposeBrowserContextReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.disposeBrowserContext", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.disposeBrowserContext", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "DisposeBrowserContext", Err: err}
	}
	return
}

// GetTargetInfo invokes the Target method. Returns information about a
// target.
func (d *domainClient) GetTargetInfo(ctx context.Context, args *GetTargetInfoArgs) (reply *GetTargetInfoReply, err error) {
	reply = new(GetTargetInfoReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.getTargetInfo", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.getTargetInfo", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "GetTargetInfo", Err: err}
	}
	return
}

// GetTargets invokes the Target method. Retrieves a list of available
// targets.
func (d *domainClient) GetTargets(ctx context.Context) (reply *GetTargetsReply, err error) {
	reply = new(GetTargetsReply)
	err = rpcc.Invoke(ctx, "Target.getTargets", nil, reply, d.conn)
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "GetTargets", Err: err}
	}
	return
}

// SendMessageToTarget invokes the Target method. Sends protocol message over
// session with given id.
func (d *domainClient) SendMessageToTarget(ctx context.Context, args *SendMessageToTargetArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.sendMessageToTarget", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.sendMessageToTarget", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "SendMessageToTarget", Err: err}
	}
	return
}

// SetAttachToFrames invokes the Target method.
func (d *domainClient) SetAttachToFrames(ctx context.Context, args *SetAttachToFramesArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.setAttachToFrames", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.setAttachToFrames", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "SetAttachToFrames", Err: err}
	}
	return
}

// SetAutoAttach invokes the Target method. Controls whether to automatically
// attach to new targets which are considered to be related to this one. When
// turned on, attaches to all existing related targets as well. When turned
// off, automatically detaches from all currently attached targets.
func (d *domainClient) SetAutoAttach(ctx context.Context, args *SetAutoAttachArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.setAutoAttach", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.setAutoAttach", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "SetAutoAttach", Err: err}
	}
	return
}

// SetDiscoverTargets invokes the Target method. Controls whether to discover
// available targets and notify via
// `targetCreated/targetInfoChanged/targetDestroyed` events.
func (d *domainClient) SetDiscoverTargets(ctx context.Context, args *SetDiscoverTargetsArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.setDiscoverTargets", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.setDiscoverTargets", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "SetDiscoverTargets", Err: err}
	}
	return
}

// SetRemoteLocations invokes the Target method. Enables target discovery for
// the specified locations, when `setDiscoverTargets` was set to `true`.
func (d *domainClient) SetRemoteLocations(ctx context.Context, args *SetRemoteLocationsArgs) (err error) {
	if args != nil {
		err = rpcc.Invoke(ctx, "Target.setRemoteLocations", args, nil, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "Target.setRemoteLocations", nil, nil, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "Target", Op: "SetRemoteLocations", Err: err}
	}
	return
}

func (d *domainClient) AttachedToTarget(ctx context.Context) (AttachedToTargetClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.attachedToTarget", d.conn)
	if err != nil {
		return nil, err
	}
	return &attachedToTargetClient{Stream: s}, nil
}

type attachedToTargetClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *attachedToTargetClient) GetStream() rpcc.Stream { return c.Stream }

func (c *attachedToTargetClient) Recv() (*AttachedToTargetReply, error) {
	event := new(AttachedToTargetReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "AttachedToTarget Recv", Err: err}
	}
	return event, nil
}

func (d *domainClient) DetachedFromTarget(ctx context.Context) (DetachedFromTargetClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.detachedFromTarget", d.conn)
	if err != nil {
		return nil, err
	}
	return &detachedFromTargetClient{Stream: s}, nil
}

type detachedFromTargetClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *detachedFromTargetClient) GetStream() rpcc.Stream { return c.Stream }

func (c *detachedFromTargetClient) Recv() (*DetachedFromTargetReply, error) {
	event := new(DetachedFromTargetReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "DetachedFromTarget Recv", Err: err}
	}
	return event, nil
}

func (d *domainClient) ReceivedMessageFromTarget(ctx context.Context) (ReceivedMessageFromTargetClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.receivedMessageFromTarget", d.conn)
	if err != nil {
		return nil, err
	}
	return &receivedMessageFromTargetClient{Stream: s}, nil
}

type receivedMessageFromTargetClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *receivedMessageFromTargetClient) GetStream() rpcc.Stream { return c.Stream }

func (c *receivedMessageFromTargetClient) Recv() (*ReceivedMessageFromTargetReply, error) {
	event := new(ReceivedMessageFromTargetReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "ReceivedMessageFromTarget Recv", Err: err}
	}
	return event, nil
}

func (d *domainClient) TargetCreated(ctx context.Context) (CreatedClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.targetCreated", d.conn)
	if err != nil {
		return nil, err
	}
	return &createdClient{Stream: s}, nil
}

type createdClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *createdClient) GetStream() rpcc.Stream { return c.Stream }

func (c *createdClient) Recv() (*CreatedReply, error) {
	event := new(CreatedReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "TargetCreated Recv", Err: err}
	}
	return event, nil
}

func (d *domainClient) TargetDestroyed(ctx context.Context) (DestroyedClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.targetDestroyed", d.conn)
	if err != nil {
		return nil, err
	}
	return &destroyedClient{Stream: s}, nil
}

type destroyedClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *destroyedClient) GetStream() rpcc.Stream { return c.Stream }

func (c *destroyedClient) Recv() (*DestroyedReply, error) {
	event := new(DestroyedReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "TargetDestroyed Recv", Err: err}
	}
	return event, nil
}

func (d *domainClient) TargetInfoChanged(ctx context.Context) (InfoChangedClient, error) {
	s, err := rpcc.NewStream(ctx, "Target.targetInfoChanged", d.conn)
	if err != nil {
		return nil, err
	}
	return &infoChangedClient{Stream: s}, nil
}

type infoChangedClient struct{ rpcc.Stream }

// GetStream returns the original Stream for use with cdp.Sync.
func (c *infoChangedClient) GetStream() rpcc.Stream { return c.Stream }

func (c *infoChangedClient) Recv() (*InfoChangedReply, error) {
	event := new(InfoChangedReply)
	if err := c.RecvMsg(event); err != nil {
		return nil, &internal.OpError{Domain: "Target", Op: "TargetInfoChanged Recv", Err: err}
	}
	return event, nil
}


text:
package com.twu.biblioteca.Model;

import java.util.ArrayList;
import org.apache.commons.lang3.StringUtils;

public class AuthorList {
    private ArrayList<Author> authorList;

    public AuthorList() {
        authorList = new ArrayList<Author>();
    }

    public void addNewAuthor(Author author) {
        authorList.add(author);
    }

    public AuthorList(Author... author) {
        authorList = new ArrayList<Author>();

        for(Author eachAuthor : author) {
            authorList.add(eachAuthor);
        }
    }

    public String getAuthorNames() {
        ArrayList<String> authorNames = new ArrayList<String>();

        for(Author eachAuthor : authorList) {
            authorNames.add(eachAuthor.getFullName());
        }

        return StringUtils.join(authorNames, ", ");
    }

    public int getNumberOfAuthors() {
        return authorList.size();
    }
}


text:
package com.macro.mall.mapper;

import com.macro.mall.model.SmsFlashPromotionLog;
import com.macro.mall.model.SmsFlashPromotionLogExample;
import java.util.List;
import org.apache.ibatis.annotations.Param;

public interface SmsFlashPromotionLogMapper {
    long countByExample(SmsFlashPromotionLogExample example);

    int deleteByExample(SmsFlashPromotionLogExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(SmsFlashPromotionLog record);

    int insertSelective(SmsFlashPromotionLog record);

    List<SmsFlashPromotionLog> selectByExample(SmsFlashPromotionLogExample example);

    SmsFlashPromotionLog selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") SmsFlashPromotionLog record, @Param("example") SmsFlashPromotionLogExample example);

    int updateByExample(@Param("record") SmsFlashPromotionLog record, @Param("example") SmsFlashPromotionLogExample example);

    int updateByPrimaryKeySelective(SmsFlashPromotionLog record);

    int updateByPrimaryKey(SmsFlashPromotionLog record);
}