text:
require 'spec_helper'
require 'shared_examples/calculator_shared_examples'

describe Spree::Calculator::FlatPercentItemTotal, type: :model do
  let(:calculator) { Spree::Calculator::FlatPercentItemTotal.new }
  let(:line_item) { mock_model Spree::LineItem }

  it_behaves_like 'a calculator with a description'

  before { allow(calculator).to receive_messages preferred_flat_percent: 10 }

  context "compute" do
    it "should round result correctly" do
      allow(line_item).to receive_messages amount: 31.08
      expect(calculator.compute(line_item)).to eq 3.11

      allow(line_item).to receive_messages amount: 31.00
      expect(calculator.compute(line_item)).to eq 3.10
    end

    it 'returns object.amount if computed amount is greater' do
      allow(calculator).to receive_messages preferred_flat_percent: 110
      allow(line_item).to receive_messages amount: 30.00

      expect(calculator.compute(line_item)).to eq 30.0
    end
  end
end


text:
/*
 * Created on 24.03.2004
 *
 * To change the template for this generated file go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
package gui.util;

import gui.CharEditor;
import gui.FontCreatorColorChooser;
import gui.MainWindow;

import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.IndexColorModel;

import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.JToolBar;

/**
 * @author Fabian Maximilian Thiele
 */
public class FontCreatorSideToolBar extends JToolBar implements ActionListener {
	private MainWindow mainWnd;

	private FontCreatorColorChooser colorChooser;

	public FontCreatorSideToolBar(MainWindow mainWnd) {
		super(JToolBar.VERTICAL);
		this.mainWnd = mainWnd;

		initToolbar();
	}

	private void initToolbar() {
		colorChooser = new FontCreatorColorChooser(mainWnd);
		add(colorChooser);

		Insets toolButtonInsets = new Insets(3,3,3,3);

		JPanel tools = new JPanel(new GridLayout(6,1,5,5));

		JButton penTool = new JButton("Pen");
		penTool.setMargin(toolButtonInsets);
		penTool.setActionCommand("pen");
		penTool.addActionListener(this);
		penTool.setPreferredSize(new Dimension(40, 25));
		tools.add(penTool);

		JButton lineTool = new JButton("Line");
		lineTool.setMargin(toolButtonInsets);
		lineTool.setActionCommand("line");
		lineTool.addActionListener(this);
		lineTool.setPreferredSize(new Dimension(40, 25));
		tools.add(lineTool);

		JButton drawRectTool = new JButton("draR");
		drawRectTool.setMargin(toolButtonInsets);
		drawRectTool.setActionCommand("drawRect");
		drawRectTool.addActionListener(this);
		drawRectTool.setPreferredSize(new Dimension(40, 25));
		tools.add(drawRectTool);

		JButton fillRectTool = new JButton("fillR");
		fillRectTool.setMargin(toolButtonInsets);
		fillRectTool.setActionCommand("fillRect");
		fillRectTool.addActionListener(this);
		fillRectTool.setPreferredSize(new Dimension(40, 25));
		tools.add(fillRectTool);

		JButton drawOvalTool = new JButton("draO");
		drawOvalTool.setMargin(toolButtonInsets);
		drawOvalTool.setActionCommand("drawOval");
		drawOvalTool.addActionListener(this);
		drawOvalTool.setPreferredSize(new Dimension(40, 25));
		tools.add(drawOvalTool);

		JButton fillOvalTool = new JButton("fillO");
		fillOvalTool.setMargin(toolButtonInsets);
		fillOvalTool.setActionCommand("fillOval");
		fillOvalTool.addActionListener(this);
		fillOvalTool.setPreferredSize(new Dimension(40, 25));
		tools.add(fillOvalTool);

		tools.setMaximumSize(new Dimension(45,180));
		add(tools);
	}

	/* (non-Javadoc)
	 * @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
	 */
	public void actionPerformed(ActionEvent e) {
		String cmd = e.getActionCommand();
		if(cmd.equals("pen")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_FREEHAND);
		} else if(cmd.equals("line")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_STRAIGHT_LINES);
		} else if(cmd.equals("drawRect")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_DRAW_RECT);
		} else if(cmd.equals("fillRect")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_FILL_RECT);
		} else if(cmd.equals("drawOval")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_DRAW_OVAL);
		} else if(cmd.equals("fillOval")) {
			mainWnd.setActiveEditorTool(CharEditor.TOOL_FILL_OVAL);
		}
	}

	public void setColor(int color, IndexColorModel cm) {
		colorChooser.setColor(color, cm);
	}
}

redpajama_set_name: RedPajamaGithub


text:
CREATE TABLE project (
	projectId INT NOT NULL AUTO_INCREMENT PRIMARY KEY,

	groupId VARCHAR(255) NOT NULL,
	artifactId VARCHAR(255) NOT NULL,
	version VARCHAR(255) NOT NULL,

	firstSeen TIMESTAMP,
	lastUpdated TIMESTAMP,

	CONSTRAINT uniqueArtifactVersion UNIQUE(groupId, artifactId, version)
);


text:
from pymongo import MongoClient
import pymongo.errors

username, password, host, dbname = 'user0', 'pwd0', '127.0.0.1', 'test_db'
client = MongoClient('mongodb://%s:%s@%s/%s' % (username, password, host, dbname))

try:
  db = client.test_db
  col = db.MusicRecords

  for document in col.find({"year": {'$exists': True}}):
    print(document)

except pymongo.errors.OperationFailure as e:
  print("ERROR: %s" % (e))


text:
import hashlib
class sha1:

	def transform(self,input,params={}):
		hash_object = hashlib.sha1(input)
		return hash_object.hexdigest()


text:
import { Given } from '@cucumber/cucumber';

let retriesNeeded = 2;

Given('a step that eventually passes', function () {
    if (retriesNeeded > 0) {
        --retriesNeeded;

        throw new Error('Try again');
    }
});


text:
using base::android::AttachCurrentThread;
using base::android::JavaRef;
using base::android::ScopedJavaLocalRef;

namespace url {

namespace {

ScopedJavaLocalRef<jobject> CreateJavaParsed(JNIEnv* env,
                                             const Parsed& parsed,
                                             const JavaRef<jobject>& inner) {
  static constexpr bool is_signed =
      std::is_signed<decltype(parsed.scheme.begin)>::value;
  static constexpr size_t offset_size = sizeof(parsed.scheme.begin);
  static_assert((is_signed && sizeof(jint) >= offset_size) ||
                    (!is_signed && sizeof(jint) > offset_size),
                "Java size offsets for Parsed Components must be large enough "
                "to store the full C++ offset.");
  return Java_Parsed_Constructor(
      env, parsed.scheme.begin, parsed.scheme.len, parsed.username.begin,
      parsed.username.len, parsed.password.begin, parsed.password.len,
      parsed.host.begin, parsed.host.len, parsed.port.begin, parsed.port.len,
      parsed.path.begin, parsed.path.len, parsed.query.begin, parsed.query.len,
      parsed.ref.begin, parsed.ref.len, parsed.potentially_dangling_markup,
      inner);
}

}  // namespace

// static
ScopedJavaLocalRef<jobject> ParsedAndroid::InitFromParsed(
    JNIEnv* env,
    const Parsed& parsed) {
  ScopedJavaLocalRef<jobject> inner;
  if (parsed.inner_parsed())
    inner = CreateJavaParsed(env, *parsed.inner_parsed(), nullptr);
  return CreateJavaParsed(env, parsed, inner);
}

static jlong JNI_Parsed_CreateNative(JNIEnv* env,
                                     jint scheme_begin,
                                     jint scheme_length,
                                     jint username_begin,
                                     jint username_length,
                                     jint password_begin,
                                     jint password_length,
                                     jint host_begin,
                                     jint host_length,
                                     jint port_begin,
                                     jint port_length,
                                     jint path_begin,
                                     jint path_length,
                                     jint query_begin,
                                     jint query_length,
                                     jint ref_begin,
                                     jint ref_length,
                                     jboolean potentially_dangling_markup,
                                     jlong inner_parsed) {
  Parsed* parsed = new Parsed();
  parsed->scheme.begin = scheme_begin;
  parsed->scheme.len = scheme_length;
  parsed->username.begin = username_begin;
  parsed->username.len = username_length;
  parsed->password.begin = password_begin;
  parsed->password.len = password_length;
  parsed->host.begin = host_begin;
  parsed->host.len = host_length;
  parsed->port.begin = port_begin;
  parsed->port.len = port_length;
  parsed->path.begin = path_begin;
  parsed->path.len = path_length;
  parsed->query.begin = query_begin;
  parsed->query.len = query_length;
  parsed->ref.begin = ref_begin;
  parsed->ref.len = ref_length;
  parsed->potentially_dangling_markup = potentially_dangling_markup;
  Parsed* inner = reinterpret_cast<Parsed*>(inner_parsed);
  if (inner) {
    parsed->set_inner_parsed(*inner);
    delete inner;
  }
  return reinterpret_cast<intptr_t>(parsed);
}

}  // namespace url


text:
'use strict';

const expect = require('chai').expect;

const MockUI = require('console-ui/mock');
const MockAnalytics = require('../../helpers/mock-analytics');
const MockBroccoliWatcher = require('../../helpers/mock-broccoli-watcher');
const Watcher = require('../../../lib/models/watcher');
const EOL = require('os').EOL;
const chalk = require('chalk');
const BuildError = require('../../helpers/build-error');

describe('Watcher', function () {
  let ui;
  let subject;
  let builder;
  let analytics;
  let watcher;

  let mockResult = {
    totalTime: 12344000000,
    graph: {
      __heimdall__: {
        visitPreOrder(cb) {
          return cb({
            stats: {
              time: {
                self: 12344000000,
              },
            },
          });
        },
        visitPostOrder() {},
      },
    },
  };

  beforeEach(function () {
    ui = new MockUI();
    analytics = new MockAnalytics();

    watcher = new MockBroccoliWatcher();

    subject = new Watcher({
      ui,
      analytics,
      builder,
      watcher,
    });
  });

  describe('watcher strategy selection', function () {
    it('selects the events-based watcher by default', function () {
      subject.options = null;

      expect(subject.buildOptions()).to.deep.equal({
        verbose: true,
        poll: false,
        watchman: false,
        node: false,
      });
    });

    it('selects the events-based watcher when given events watcher option', function () {
      subject.options = {
        watcher: 'events',
      };

      expect(subject.buildOptions()).to.deep.equal({
        verbose: true,
        poll: false,
        watchman: true,
        node: false,
      });
    });

    it('selects the polling watcher when given polling watcher option', function () {
      subject.options = {
        watcher: 'polling',
      };

      expect(subject.buildOptions()).to.deep.equal({
        verbose: true,
        poll: true,
        watchman: false,
        node: false,
      });
    });
  });

  describe('underlining watcher properly logs change events', function () {
    it('logs that the file was added', function () {
      watcher.emit('change', 'add', 'foo.txt');
      expect(ui.output).to.equal(`file added foo.txt${EOL}`);
    });
    it('logs that the file was changed', function () {
      watcher.emit('change', 'change', 'foo.txt');
      expect(ui.output).to.equal(`file changed foo.txt${EOL}`);
    });
    it('logs that the file was deleted', function () {
      watcher.emit('change', 'delete', 'foo.txt');
      expect(ui.output).to.equal(`file deleted foo.txt${EOL}`);
    });
  });

  describe(`watcher:buildSuccess`, function () {
    beforeEach(function () {
      watcher.emit(`buildSuccess`, mockResult);
    });

    it('tracks events', function () {
      expect(analytics.tracks).to.deep.equal([
        {
          name: 'ember rebuild',
          message: 'broccoli rebuild time: 12344ms',
        },
      ]);
    });

    it('tracks timings', function () {
      expect(analytics.trackTimings).to.deep.equal([
        {
          category: 'rebuild',
          variable: 'rebuild time',
          label: 'broccoli rebuild time',
          value: 12344,
        },
      ]);
    });

    it('logs that the build was successful', function () {
      expect(ui.output).to.equal(EOL + chalk.green('Build successful (12344ms)') + EOL);
    });
  });

  describe('output', function () {
    this.timeout(40000);

    it('with ssl', function () {
      let subject = new Watcher({
        ui,
        analytics,
        builder,
        watcher,
        serving: true,
        options: {
          host: undefined,
          port: '1337',
          ssl: true,
          sslCert: 'tests/fixtures/ssl/server.crt',
          sslKey: 'tests/fixtures/ssl/server.key',
          environment: 'development',
          project: {
            config() {
              return {
                rootURL: '/',
              };
            },
          },
        },
      });

      subject.didChange(mockResult);

      let output = ui.output.trim().split(EOL);
      expect(output[0]).to.equal(`${chalk.green('Build successful (12344ms)')} – Serving on https://localhost:1337/`);
    });

    it('with baseURL', function () {
      let subject = new Watcher({
        ui,
        analytics,
        builder,
        watcher,
        serving: true,
        options: {
          host: undefined,
          port: '1337',
          environment: 'development',
          project: {
            config() {
              return {
                baseURL: '/foo',
              };
            },
          },
        },
      });

      subject.didChange(mockResult);

      let output = ui.output.trim().split(EOL);
      expect(output[0]).to.equal(
        `${chalk.green('Build successful (12344ms)')} – Serving on http://localhost:1337/foo/`
      );
      expect(output.length).to.equal(1, 'expected only one line of output');
    });

    it('with rootURL', function () {
      let subject = new Watcher({
        ui,
        analytics,
        builder,
        watcher,
        serving: true,
        options: {
          host: undefined,
          port: '1337',
          environment: 'development',
          project: {
            config() {
              return {
                rootURL: '/foo',
              };
            },
          },
        },
      });

      subject.didChange(mockResult);

      let output = ui.output.trim().split(EOL);

      expect(output[0]).to.equal(
        `${chalk.green('Build successful (12344ms)')} – Serving on http://localhost:1337/foo/`
      );
      expect(output.length).to.equal(1, 'expected only one line of output');
    });

    it('with empty rootURL', function () {
      let subject = new Watcher({
        ui,
        analytics,
        builder,
        watcher,
        serving: true,
        options: {
          host: undefined,
          port: '1337',
          rootURL: '',
          environment: 'development',
          project: {
            config() {
              return {
                rootURL: '',
              };
            },
          },
        },
      });

      subject.didChange(mockResult);

      let output = ui.output.trim().split(EOL);
      expect(output[0]).to.equal(`${chalk.green('Build successful (12344ms)')} – Serving on http://localhost:1337/`);
      expect(output.length).to.equal(1, 'expected only one line of output');
    });

    it('with customURL', function () {
      let subject = new Watcher({
        ui,
        analytics,
        builder,
        watcher,
        serving: true,
        options: {
          host: undefined,
          port: '1337',
          rootURL: '',
          environment: 'development',
          project: {
            config() {
              return {
                rootURL: '',
              };
            },
          },
        },
      });
      subject.serveURL = function () {
        return `http://customurl.com/`;
      };
      subject.didChange(mockResult);

      let output = ui.output.trim().split(EOL);
      expect(output[0]).to.equal(`${chalk.green('Build successful (12344ms)')} – Serving on http://customurl.com/`);
    });
  });

  describe('watcher:error', function () {
    it('tracks errors', function () {
      watcher.emit('error', {
        message: 'foo',
        stack: new Error().stack,
      });

      expect(analytics.trackErrors).to.deep.equal([
        {
          description: undefined,
        },
      ]);
    });

    it('watcher error', function () {
      watcher.emit('error', {
        message: 'foo',
        stack: new Error().stack,
      });

      expect(ui.output).to.equal('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('foo'));
    });

    it('watcher buildFailure', function () {
      watcher.emit('buildFailure', {
        isBuilderError: true,
        message: 'I am a build error',
        file: 'the-file.txt',
        stack: new Error().stack,
      });

      expect(ui.output).to.equal('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('File: the-file.txt'));
      expect(outs[2]).to.equal(chalk.red('I am a build error'));
    });

    it('emits without error.file', function () {
      subject.didError(
        new BuildError({
          file: 'someFile',
          message: 'buildFailed',
        })
      );

      expect(ui.output).to.equal('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('File: someFile'));
      expect(outs[2]).to.equal(chalk.red('buildFailed'));
    });

    it('emits with error.file with error.line without err.col', function () {
      subject.didError(
        new BuildError({
          file: 'someFile',
          line: 24,
          message: 'buildFailed',
        })
      );

      expect(ui.output).to.eql('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('File: someFile:24'));
      expect(outs[2]).to.equal(chalk.red('buildFailed'));
    });

    it('emits with error.file without error.line with err.col', function () {
      subject.didError(
        new BuildError({
          file: 'someFile',
          col: 80,
          message: 'buildFailed',
        })
      );

      expect(ui.output).to.eql('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('File: someFile'));
      expect(outs[2]).to.equal(chalk.red('buildFailed'));
    });

    it('emits with error.file with error.line with err.col', function () {
      subject.didError(
        new BuildError({
          file: 'someFile',
          line: 24,
          col: 80,
          message: 'buildFailed',
        })
      );

      expect(ui.output).to.eql('');

      let outs = ui.errors.split(EOL);

      expect(outs[0]).to.equal(chalk.red('File: someFile:24:80'));
      expect(outs[2]).to.equal(chalk.red('buildFailed'));
    });
  });

  describe('watcher:change afterError', function () {
    beforeEach(function () {
      watcher.emit('error', {
        message: 'foo',
        stack: new Error().stack,
      });

      watcher.emit(`buildSuccess`, mockResult);
    });

    it('log that the build was green', function () {
      expect(ui.output).to.match(/Build successful./, 'has successful build output');
    });

    it('keep tracking analytics', function () {
      expect(analytics.tracks).to.deep.equal([
        {
          name: 'ember rebuild',
          message: 'broccoli rebuild time: 12344ms',
        },
      ]);
    });
  });
});


text:
__Description__: On a per indiviudal ctr instance basis the user should be able to define a sort method for the compiled CSS

__Notes__

- There are four sort options
    + `len` -> smallest length to largest
    + `-len` -> largets length to smallest
    + `abc` -> alphablitcally
    + `-abc` -> reverse aplablitcally
    + `false` -> returns the same source order as its given
- The sort order can also be set globally through `ctrSetOption`


text:
package com.ztiany.main;

import com.ztiany.base.di.ActivityScope;
import com.ztiany.base.di.ViewComponentBuilder;
import com.ztiany.base.di.ViewKey;
import com.ztiany.main.main.CustomTextView;
import com.ztiany.main.main.CustomTextViewComponent;
import com.ztiany.main.main.MainActivity;
import com.ztiany.main.main.MainActivityComponent;
import com.ztiany.main.splash.SplashActivity;
import com.ztiany.main.splash.SplashModule;

import dagger.Binds;
import dagger.Module;
import dagger.android.AndroidInjector;
import dagger.android.ContributesAndroidInjector;
import dagger.multibindings.ClassKey;
import dagger.multibindings.IntoMap;

@Module(subcomponents = {
        MainActivityComponent.class,
        CustomTextViewComponent.class
})
public abstract class MainBuildersModule {

    @Binds
    @IntoMap
    @ClassKey(MainActivity.class)
    public abstract AndroidInjector.Factory<?> bindMainActivityFactory(MainActivityComponent.Builder builder);

    /**
     * ContributesAndroidInjector用在方法中,此方法必须是无参数的,且返回值为Android中具体的组件(Activity,Fragment,Service等),然后ContributesAndroidInjector
     * 根据方法的返回类型为其生成一个SubComponent,然后我们就不需要在写Component了
     */
    @ActivityScope
    @ContributesAndroidInjector(modules = SplashModule.class)
    abstract SplashActivity bindSplashActivity();

    @Binds
    @IntoMap
    @ViewKey(CustomTextView.class)
    public abstract ViewComponentBuilder bindCustomTextView(CustomTextViewComponent.Builder builder);

}


text:
class CreatePlatformTables < ActiveRecord::Migration
  def self.up
    create_table :platform_developers do |t|
      t.integer :user_id, :limit => 8, :null => false
      t.string  :name, :null => false
      t.text    :about
      t.string  :url
      t.string  :email
      t.string  :phone
      t.timestamps
    end
    add_index :platform_developers, :user_id, :name => 'platform_pd_u'
    add_index :platform_developers, :created_at, :name => 'platform_pd_c'

    create_table :platform_applications do |t|
      t.integer :developer_id
      t.string  :name
      t.text    :description
      t.string  :state,             :default => "new"
      t.string  :locale
      t.string  :url
      t.string  :site_domain
      t.string  :support_url
      t.string  :callback_url
      t.string  :contact_email
      t.string  :privacy_policy_url
      t.string  :terms_of_service_url
      t.string  :permissions
      t.string  :key
      t.string  :secret
      t.integer :icon_id
      t.integer :logo_id
      t.string  :canvas_name
      t.string  :canvas_url
      t.boolean :auto_resize
      t.boolean :auto_login
      t.string  :mobile_application_type
      t.string  :ios_bundle_id
      t.string  :itunes_app_store_id
      t.string  :android_key_hash
      t.integer :rank
      t.boolean :auto_signin
      t.string  :deauthorize_callback_url
      t.string  :version
      t.string  :api_version
      t.integer :parent_id
      t.timestamps
    end
    add_index :platform_applications, :developer_id, :name => 'platform_pa_d'
    add_index :platform_applications, :key, {:unique => true, :name => 'platform_pa_k'}
    add_index :platform_applications, :parent_id, :name => 'platform_pa_p'
    add_index :platform_applications, :created_at, :name => 'platform_pa_c'

    create_table :platform_application_logs do |t|
      t.integer     :application_id
      t.integer     :user_id
      t.string      :event
      t.string      :controller
      t.string      :action
      t.string      :request_method
      t.text        :data
      t.string      :user_agent
      t.integer     :duration
      t.string      :host
      t.string      :country
      t.string      :ip
      t.timestamps
    end
    add_index :platform_applications, :created_at, :name => 'platform_pal_c'
    add_index :platform_application_logs, [:application_id, :created_at], :name => 'platform_pal_ac'

    create_table :platform_application_metrics do |t|
      t.string    :type
      t.timestamp :interval
      t.integer   :application_id
      t.integer   :active_user_count
      t.integer   :new_user_count
      t.timestamps
    end
    add_index :platform_application_metrics, [:application_id, :interval], :name => "platform_pam_ai"
    add_index :platform_application_metrics, [:created_at], :name => "platform_pam_c"

    create_table :platform_application_usage_metrics do |t|
      t.string    :type
      t.timestamp :interval
      t.integer   :application_id
      t.string    :event
      t.integer   :count
      t.integer   :avg_response_time
      t.integer   :error_count
      t.timestamps
    end
    add_index :platform_application_usage_metrics, [:application_id, :interval], :name => "platform_paum_ai"
    add_index :platform_application_usage_metrics, [:created_at], :name => "platform_paum_c"

    create_table :platform_rollup_logs do |t|
      t.timestamp  :interval
      t.timestamp  :started_at
      t.timestamp  :finished_at
      t.timestamps
    end
    add_index :platform_rollup_logs, :interval, :name => "platform_prl_i"
    add_index :platform_rollup_logs, [:created_at], :name => "platform_prl_c"

    create_table :platform_media do |t|
      t.string  :type
      t.string  :file_location
      t.string  :content_type
      t.string  :file_name
      t.timestamps
    end
    add_index :platform_media, [:type], :name => "platform_pm_t"
    add_index :platform_media, [:created_at], :name => "platform_pm_c"

    create_table :platform_application_developers do |t|
      t.integer :application_id
      t.integer :developer_id
      t.timestamps
    end
    add_index :platform_application_developers, :application_id, :name => "platform_pad_a"
    add_index :platform_application_developers, :developer_id, :name => "platform_pad_d"

    create_table :platform_oauth_tokens do |t|
      t.string    :type
      t.integer   :user_id,         :limit=>8
      t.integer   :application_id
      t.string    :token,           :limit => 50
      t.string    :secret,          :limit => 50
      t.string    :verifier,        :limit => 20
      t.string    :callback_url
      t.string    :scope
      t.timestamp :valid_to
      t.timestamp :authorized_at, :invalidated_at
      t.timestamps
    end
    add_index :platform_oauth_tokens, [:application_id, :type], :name => "platform_pot_at"
    add_index :platform_oauth_tokens, :token, {:unique => true, :name => "platform_pot_tu"}
    add_index :platform_oauth_tokens, :created_at, :name => "platform_pot_c"

    create_table :platform_ratings do |t|
      t.integer   :user_id,         :limit => 8, :null => false
      t.string    :object_type
      t.integer   :object_id
      t.integer   :value
      t.text      :comment
      t.timestamps
    end
    add_index :platform_ratings, :user_id, :name => "platform_pr_u"
    add_index :platform_ratings, [:object_type, :object_id], :name => "platform_pr_oo"

    create_table :platform_categories do |t|
      t.string    :type
      t.string    :name
      t.string    :keyword
      t.integer   :position
      t.date      :enable_on
      t.date      :disable_on
      t.integer   :parent_id
      t.timestamps
    end
    add_index :platform_categories, :parent_id, :name => "platform_pc_p"

    create_table :platform_application_categories do |t|
      t.integer   :category_id,     :null => false
      t.integer   :application_id,  :null => false
      t.integer   :position
      t.boolean   :featured
      t.timestamps
    end
    add_index :platform_application_categories, :category_id, :name => "platform_pac_c"
    add_index :platform_application_categories, [:category_id, :application_id], :name => "platform_pac_ca"

    create_table :platform_forum_topics do |t|
      t.string  :subject_type
      t.integer :subject_id
      t.integer :user_id,         :null => false
      t.text    :topic,           :null => false
      t.timestamps
    end
    add_index :platform_forum_topics, [:subject_type, :subject_id], :name => "platform_pft_ss"
    add_index :platform_forum_topics, [:user_id], :name => "pftu", :name => "platform_pft_u"

    create_table :platform_forum_messages do |t|
      t.integer :forum_topic_id,  :null => false
      t.integer :user_id,         :null => false
      t.text    :message,         :null => false
      t.timestamps
    end
    add_index :platform_forum_messages, [:forum_topic_id], :name => "platform_pfm_f"
    add_index :platform_forum_messages, [:user_id], :name => "platform_pfm_u"

    create_table :platform_permissions do |t|
      t.string  :keyword,         :null => false
      t.text    :description,     :null => false
      t.timestamps
    end
    add_index :platform_permissions, [:keyword], :name => "platform_pp_k"

    create_table :platform_application_permissions do |t|
      t.integer :application_id
      t.integer :permission_id
      t.timestamps
    end
    add_index :platform_application_permissions, :application_id, :name => "platform_pap_a"

    create_table :platform_application_users do |t|
      t.integer :application_id,  :null => false
      t.integer :user_id,         :null => false
      t.text    :data
      t.timestamps
    end
    add_index :platform_application_users, [:application_id], :name => "platform_pau_a"
    add_index :platform_application_users, [:user_id], :name => "platform_pau_u"

    create_table :platform_logged_exceptions do |t|
      t.column :exception_class, :string
      t.column :controller_name, :string
      t.column :action_name,     :string
      t.column :server,          :string
      t.column :message,         :text
      t.column :backtrace,       :text
      t.column :environment,     :text
      t.column :request,         :text
      t.column :session,         :text
      t.column :cause,           :binary
      t.column :user_id,         :integer
      t.column :application_id,  :integer
      t.timestamps
    end
    add_index :platform_logged_exceptions, [:created_at], :name => "platform_ple_c"

    create_table :platform_roles do |t|
      t.string :name
      t.integer :level

      t.timestamps
    end

    create_table :platform_developer_roles do |t|
      t.integer :application_id
      t.integer :developer_id
      t.integer :role_id

      t.timestamps
    end

    add_index :platform_developer_roles, [:application_id, :developer_id], :name => "platform_pdr_a_d"

    create_table :platform_developer_activities do |t|
      t.integer   :developer_id
      t.string    :key
      t.text      :description
      t.string    :target_type
      t.integer   :target_id
      t.timestamps
    end

    add_index :platform_developer_activities, [:developer_id], :name => "platform_pda_d"
  end

  def self.down
    drop_table :platform_developers
    drop_table :platform_applications
    drop_table :platform_application_logs
    drop_table :platform_application_metrics
    drop_table :platform_rollup_logs
    drop_table :platform_application_developers
    drop_table :platform_oauth_tokens
    drop_table :platform_ratings
    drop_table :platform_categories
    drop_table :platform_category_items
    drop_table :platform_forum_topics
    drop_table :platform_forum_messages
    drop_table :platform_permissions
    drop_table :platform_application_permissions
    drop_table :platform_application_users
    drop_table :platform_logged_exceptions
    drop_table :platform_roles
    drop_table :platform_developer_roles
    drop_table :platform_developer_activities
  end
end


text:
# string-quotes

Specify single or double quotes around strings.

```css
a[id="foo"] { content: "x"; }
/**  ↑   ↑             ↑ ↑
 * These quotes and these quotes */
```

Quotes within comments are ignored.

```css
/* "This is fine" */
/* 'And this is also fine' */
```

Single quotes in a charset @-rule are ignored as using single quotes in this context is incorrect according the [CSS specification](https://www.w3.org/TR/CSS2/syndata.html#x57).

```css
@charset "utf-8"
/* fine regardless of configuration */
```

## Options

`string`: `"single"|"double"`

### `"single"`

Strings *must always* be wrapped with single quotes.

The following patterns are considered violations:

```css
a { content: "x"; }
```

```css
a[id="foo"] {}
```

The following patterns are *not* considered violations:

```css
a { content: 'x'; }
```

```css
a[id='foo'] {}
```

### `"double"`

Strings *must always* be wrapped with double quotes.

The following patterns are considered violations:

```css
a { content: 'x'; }
```

```css
a[id='foo'] {}
```

The following patterns are *not* considered violations:

```css
a { content: "x"; }
```

```css
a[id="foo"] {}
```


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/half_transparent"
    android:orientation="vertical" >

    <ScrollView
        android:id="@+id/scrollView1"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true" >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical" >

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_weight="0"
                android:orientation="vertical" >

                <TextView
                    android:id="@+id/tipView"
                    android:layout_width="match_parent"
                    android:layout_height="40dp"
                    android:layout_gravity="center"
                    android:gravity="center"
                    android:text="您今日还剩1条消息可群发给15位签约用户"
                    android:textSize="@dimen/text_size_12" />

                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="1dp"
                    android:layout_marginLeft="20dp"
                    android:layout_marginRight="20dp"
                    android:background="@color/background_727272" >

                </LinearLayout>

                <TextView
                    android:id="@+id/evaluateTextView"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="5dp"
                    android:layout_marginTop="20dp"
                    android:gravity="center"
                    android:text="2014-10-23 21:15"
                    android:textSize="@dimen/text_size_12" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/background_f0f0f0"
                android:orientation="vertical" >

                <EditText
                    android:id="@+id/et_reply"
                    style="@style/BaseEditText"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginLeft="@dimen/space_13"
                    android:layout_marginRight="@dimen/space_13"
                    android:layout_marginTop="@dimen/space_13"
                    android:layout_weight="0"
                    android:background="@drawable/shape_round_corner_white_stroke"
                    android:ems="10"
                    android:gravity="top"
                    android:hint="请输入您的群发信息"
                    android:minHeight="@dimen/space_120"
                    android:padding="@dimen/space_13"
                    android:textColorHint="@color/font_b2b2b2" >

                    <requestFocus />
                </EditText>

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/space_10"
                    android:layout_marginLeft="@dimen/space_13"
                    android:layout_marginRight="@dimen/space_13"
                    android:layout_marginTop="@dimen/space_10"
                    android:layout_weight="0" >

                    <ImageView
                        android:id="@+id/imageView_2"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_centerVertical="true"
                        android:layout_marginLeft="@dimen/space_20"
                        android:src="@drawable/icon_opinion_stock" />

                    <Button
                        android:id="@+id/bt_action"
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:background="@drawable/selector_button_answer"
                        android:paddingBottom="@dimen/space_5"
                        android:paddingLeft="@dimen/space_15"
                        android:paddingRight="@dimen/space_15"
                        android:paddingTop="@dimen/space_5"
                        android:text="群发消息"
                        android:textColor="@drawable/selector_button_answer" />

                </RelativeLayout>

            </LinearLayout>

        </LinearLayout>
    </ScrollView>

</LinearLayout>


text:
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Demo ZipEntry.prototype.getFileEntry (File)</title>
</head>
<body>
	<script type="text/javascript" src="../zip.js"></script>
	<script type="text/javascript" src="../zip-fs.js"></script>
	<script type="text/javascript" src="../zip-ext.js"></script>
	<script type="text/javascript" src="dataview.js"></script>
	<script type="text/javascript" src="test11.js"></script>
</body>
</html>


text:
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="ru.raliev.models.Order" table="order" schema="public" catalog="online_shop">
        <id name="id" column="id">
            <generator class="org.hibernate.id.enhanced.SequenceStyleGenerator">
                <param name="optimizer">none</param>
                <param name="increment_size">1</param>
                <param name="sequence_name">order_id_seq</param>
            </generator>
        </id>
        <property name="count">
            <column name="count" sql-type="integer"/>
        </property>
        <many-to-one name="customer" class="ru.raliev.models.User" cascade="all">
            <column name="userid"/>
        </many-to-one>
        <many-to-one name="product" class="ru.raliev.models.Product" cascade="all">
            <column name="productid"/>
        </many-to-one>
    </class>
</hibernate-mapping>


text:
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (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.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Original Code is JavaScript Engine testing utilities.
 *
 * The Initial Developer of the Original Code is
 * Mozilla Foundation.
 * Portions created by the Initial Developer are Copyright (C) 2006
 * the Initial Developer. All Rights Reserved.
 *
 * Contributor(s): Julien Lecomte
 *                 Igor Bukanov
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 *
 * ***** END LICENSE BLOCK ***** */

var gTestfile = 'regress-313967-02.js';
//-----------------------------------------------------------------------------
var BUGNUMBER = 313967;
var summary = 'Compile time of N functions should be O(N)';
var actual = '';
var expect = '';

printBugNumber(BUGNUMBER);
printStatus (summary);

function F(x, y) {
  var a = x+y;
  var b = x-y;
  var c = a+b;
  return ( 2*c-1 );
}

function test(N)
{
  var src = F.toSource(-1)+"\n";
  src = Array(N + 1).join(src);
  var counter = 0;
  src = src.replace(/F/g, function() { ++counter; return "F"+counter; })
    var now = Date.now;
  var t = now();
  eval(src);
  return now() - t;
}

var data = {X:[], Y:[]};
for (var i = 0; i != 10; ++i)
{
  data.X.push(i);
  data.Y.push(test(1000 + i * 2000));
  gc();
}

var order = BigO(data);

var msg = '';
for (var p = 0; p < data.X.length; p++)
{
  msg += '(' + data.X[p] + ', ' + data.Y[p] + '); ';
}

print(msg);

reportCompare(true, order < 2, summary + ': BigO ' + order + ' < 2');


text:
Department of Mathematics

Indian Institute of Science

Bangalore 560 012

SEMINAR

    Speaker

    :

 Prof. Kalyan B. Sinha

    Affiliation

    :

     JNCASR and IISc

    Subject Area

    :

    Mathematics

    Venue

    :

    Lecture Hall I, Department of Mathematics

    Time

    :

11.00 a.m.- 12.30 p.m.

    Date

    :

April1, 2011 (Friday)

    Title

    :

"Quantum Field Theory -- the Mathematics in it"

    Abstract

    :

 Beginning with the attempts of Heisenberg and Pauli in the 1920's, the subject grew at an astonishing speed, culminating in the remarkable
 predictive success of Quantum Electrodynamics. Different attempts to bring the subject to a sound mathematical footing (comparable to that
 of Quantum Mechanics) -- whether analytic, operator-algebraic or geometric --  have tasted only partial success. These talks will try to
 give a bird's-eye view of the  mathematical areas (ideas) spawned by these attempts,  keeping in view the recent book of Folland on this
 subject.


text:
var Operator = require('./lib/Operator');

var a = 5;
var b = 5;

console.log(Operator.add(a, b));
// 10


text:
import { Gender, MediaType } from '@oca/web-shared';

export const GENDER_OPTIONS = [
  { value: Gender.MALE_OR_FEMALE, label: 'oca.gender-male-female' },
  { value: Gender.MALE, label: 'oca.gender-male' },
  { value: Gender.FEMALE, label: 'oca.gender-female' },
];

export const NEWS_MEDIA_TYPE_OPTIONS = [
  { value: null, label: 'oca.none' },
  { value: MediaType.IMAGE, label: 'oca.image' },
  { value: MediaType.VIDEO_YOUTUBE, label: 'oca.video' },
];

export const BUDGET_RATE = 2.0;  // 10k views / 5000 cent


text:
/*
 * This file is part of netchan.
 *
 * It is licensed under the MIT license. The full license text can be found
 * in the License.txt file at the root of this project.
 */

package netchan

import (
	"crypto/aes"
	"crypto/cipher"
	crand "crypto/rand"
	"runtime"
	"sync"
	"unsafe"
)

type weakref [16]byte

type weakmap struct {
	mux    sync.Mutex
	refmap map[weakref]*_weaktup
	ptrmap map[uintptr]*_weaktup
	cnt    weakref
}

type _weaktup struct {
	ref weakref
	ptr [2]uintptr
}

func newWeakmap() *weakmap {
	return &weakmap{
		refmap: make(map[weakref]*_weaktup),
		ptrmap: make(map[uintptr]*_weaktup),
	}
}

func (self *weakmap) weakref(val interface{}) weakref {
	if nil == val {
		return weakref{}
	}

	ptr := *(*[2]uintptr)(unsafe.Pointer(&val))
	if 0 == ptr[1] {
		// non-nil interface with nil concrete data!
		return weakref{}
	}

	self.mux.Lock()
	defer self.mux.Unlock()

	tup := self.ptrmap[ptr[1]]
	if nil == tup {
		tup = &_weaktup{ptr: ptr}
		_weakmapCipher.Encrypt(tup.ref[:], self.cnt[:])
		self._addtup(tup)

		*(*uint64)(unsafe.Pointer(&self.cnt)) = *(*uint64)(unsafe.Pointer(&self.cnt)) + 1
	}

	return tup.ref
}

func (self *weakmap) strongref(ref weakref, newfn func() interface{}) interface{} {
	if (weakref{}) == ref {
		return nil
	}

	self.mux.Lock()
	defer self.mux.Unlock()

	tup := self.refmap[ref]
	if nil == tup {
		if nil == newfn {
			return nil
		}

		val := newfn()
		ptr := *(*[2]uintptr)(unsafe.Pointer(&val))

		tup = &_weaktup{ref: ref, ptr: ptr}
		self._addtup(tup)
	}

	/*
	 * Converting a uintptr to an unsafe.Pointer is not guaranteed to work in general.
	 * However it does work in the current go runtimes. See https://goo.gl/zqfXU7
	 */

	return *(*interface{})(unsafe.Pointer(&tup.ptr))
}

func (self *weakmap) _addtup(tup *_weaktup) {
	fin := func(interface{}) {
		self.mux.Lock()
		defer self.mux.Unlock()
		delete(self.refmap, tup.ref)
		delete(self.ptrmap, tup.ptr[1])
	}
	runtime.SetFinalizer((*struct{})(unsafe.Pointer(tup.ptr[1])), fin)

	self.refmap[tup.ref] = tup
	self.ptrmap[tup.ptr[1]] = tup
}

var _weakmapCipher = _newWeakmapCipher()

func _newWeakmapCipher() cipher.Block {
	var key [16]byte

	_, err := crand.Read(key[:])
	if nil != err {
		panic(err)
	}

	c, err := aes.NewCipher(key[:])
	if nil != err {
		panic(err)
	}

	return c
}


text:
// Copyright 2009 the Sputnik authors.  All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.

/*---
info: String.prototype.slice can't be used as constructor
es5id: 15.5.4.13_A7
description: Checking if creating the String.prototype.slice object fails
includes:
    - $PRINT.js
    - $FAIL.js
---*/

var __FACTORY = String.prototype.slice;

try {
  var __instance = new __FACTORY;
  $FAIL('#1: __FACTORY = String.prototype.slice; "__instance = new __FACTORY" lead to throwing exception');
} catch (e) {
  $PRINT(e);
}


text:
package gov.hhs.fha.nhinc.docretrieve.entity;

import gov.hhs.fha.nhinc.nhinclib.NhincConstants;
import gov.hhs.fha.nhinc.orchestration.OrchestrationContextBuilder;

public class OutboundDocRetrieveFactory {

    private static OutboundDocRetrieveFactory INSTANCE = new OutboundDocRetrieveFactory();

    private OutboundDocRetrieveFactory() {
    }

    public OrchestrationContextBuilder createOrchestrationContextBuilder(NhincConstants.GATEWAY_API_LEVEL apiLevel) {
        switch (apiLevel) {
        case LEVEL_g0:
            return new OutboundDocRetrieveOrchestrationContextBuilder_g0();
        case LEVEL_g1:
            return new OutboundDocRetrieveOrchestrationContextBuilder_g1();
        default:
            return null;
        }
    }

    public static OutboundDocRetrieveFactory getInstance() {
        return INSTANCE;
    }

}


text:
package com.voxeo.moho.event;

import com.voxeo.moho.Participant;

/**
 * This event fires when a unjoin operation is completed.
 *
 * @author wchen
 */
public interface UnjoinCompleteEvent extends Event<EventSource> {

  public enum Cause {
    DISCONNECT, SUCCESS_UNJOIN, FAIL_UNJOIN, NOT_JOINED, ERROR
  }

  Participant getParticipant();

  Cause getCause();

  Exception getException();

  boolean isInitiator();

}


text:
@implementation DBACCOUNTPhotoSourceArg

@synthesize base64Data = _base64Data;

#pragma mark - Constructors

- (instancetype)initWithBase64Data:(NSString *)base64Data {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTPhotoSourceArgBase64Data;
    _base64Data = base64Data;
  }
  return self;
}

- (instancetype)initWithOther {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTPhotoSourceArgOther;
  }
  return self;
}

#pragma mark - Instance field accessors

- (NSString *)base64Data {
  if (![self isBase64Data]) {
    [NSException raise:@"IllegalStateException"
                format:@"Invalid tag: required DBACCOUNTPhotoSourceArgBase64Data, but was %@.", [self tagName]];
  }
  return _base64Data;
}

#pragma mark - Tag state methods

- (BOOL)isBase64Data {
  return _tag == DBACCOUNTPhotoSourceArgBase64Data;
}

- (BOOL)isOther {
  return _tag == DBACCOUNTPhotoSourceArgOther;
}

- (NSString *)tagName {
  switch (_tag) {
  case DBACCOUNTPhotoSourceArgBase64Data:
    return @"DBACCOUNTPhotoSourceArgBase64Data";
  case DBACCOUNTPhotoSourceArgOther:
    return @"DBACCOUNTPhotoSourceArgOther";
  }

  @throw([NSException exceptionWithName:@"InvalidTag" reason:@"Tag has an unknown value." userInfo:nil]);
}

#pragma mark - Serialization methods

+ (nullable NSDictionary<NSString *, id> *)serialize:(id)instance {
  return [DBACCOUNTPhotoSourceArgSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary<NSString *, id> *)dict {
  return [DBACCOUNTPhotoSourceArgSerializer deserialize:dict];
}

#pragma mark - Debug Description method

- (NSString *)debugDescription {
  return [[DBACCOUNTPhotoSourceArgSerializer serialize:self] description];
}

#pragma mark - Copyable method

- (instancetype)copyWithZone:(NSZone *)zone {
#pragma unused(zone)
  /// object is immutable
  return self;
}

#pragma mark - Hash method

- (NSUInteger)hash {
  NSUInteger prime = 31;
  NSUInteger result = 1;

  switch (_tag) {
  case DBACCOUNTPhotoSourceArgBase64Data:
    result = prime * result + [self.base64Data hash];
    break;
  case DBACCOUNTPhotoSourceArgOther:
    result = prime * result + [[self tagName] hash];
    break;
  }

  return prime * result;
}

#pragma mark - Equality method

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (!other || ![other isKindOfClass:[self class]]) {
    return NO;
  }
  return [self isEqualToPhotoSourceArg:other];
}

- (BOOL)isEqualToPhotoSourceArg:(DBACCOUNTPhotoSourceArg *)aPhotoSourceArg {
  if (self == aPhotoSourceArg) {
    return YES;
  }
  if (self.tag != aPhotoSourceArg.tag) {
    return NO;
  }
  switch (_tag) {
  case DBACCOUNTPhotoSourceArgBase64Data:
    return [self.base64Data isEqual:aPhotoSourceArg.base64Data];
  case DBACCOUNTPhotoSourceArgOther:
    return [[self tagName] isEqual:[aPhotoSourceArg tagName]];
  }
  return YES;
}

@end

#pragma mark - Serializer Object

@implementation DBACCOUNTPhotoSourceArgSerializer

+ (NSDictionary<NSString *, id> *)serialize:(DBACCOUNTPhotoSourceArg *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  if ([valueObj isBase64Data]) {
    jsonDict[@"base64_data"] = valueObj.base64Data;
    jsonDict[@".tag"] = @"base64_data";
  } else if ([valueObj isOther]) {
    jsonDict[@".tag"] = @"other";
  } else {
    jsonDict[@".tag"] = @"other";
  }

  return [jsonDict count] > 0 ? jsonDict : nil;
}

+ (DBACCOUNTPhotoSourceArg *)deserialize:(NSDictionary<NSString *, id> *)valueDict {
  NSString *tag = valueDict[@".tag"];

  if ([tag isEqualToString:@"base64_data"]) {
    NSString *base64Data = valueDict[@"base64_data"];
    return [[DBACCOUNTPhotoSourceArg alloc] initWithBase64Data:base64Data];
  } else if ([tag isEqualToString:@"other"]) {
    return [[DBACCOUNTPhotoSourceArg alloc] initWithOther];
  } else {
    return [[DBACCOUNTPhotoSourceArg alloc] initWithOther];
  }
}

@end

#import "DBACCOUNTPhotoSourceArg.h"
#import "DBACCOUNTSetProfilePhotoArg.h"
#import "DBStoneSerializers.h"
#import "DBStoneValidators.h"

#pragma mark - API Object

@implementation DBACCOUNTSetProfilePhotoArg

#pragma mark - Constructors

- (instancetype)initWithPhoto:(DBACCOUNTPhotoSourceArg *)photo {
  [DBStoneValidators nonnullValidator:nil](photo);

  self = [super init];
  if (self) {
    _photo = photo;
  }
  return self;
}

#pragma mark - Serialization methods

+ (nullable NSDictionary<NSString *, id> *)serialize:(id)instance {
  return [DBACCOUNTSetProfilePhotoArgSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary<NSString *, id> *)dict {
  return [DBACCOUNTSetProfilePhotoArgSerializer deserialize:dict];
}

#pragma mark - Debug Description method

- (NSString *)debugDescription {
  return [[DBACCOUNTSetProfilePhotoArgSerializer serialize:self] description];
}

#pragma mark - Copyable method

- (instancetype)copyWithZone:(NSZone *)zone {
#pragma unused(zone)
  /// object is immutable
  return self;
}

#pragma mark - Hash method

- (NSUInteger)hash {
  NSUInteger prime = 31;
  NSUInteger result = 1;

  result = prime * result + [self.photo hash];

  return prime * result;
}

#pragma mark - Equality method

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (!other || ![other isKindOfClass:[self class]]) {
    return NO;
  }
  return [self isEqualToSetProfilePhotoArg:other];
}

- (BOOL)isEqualToSetProfilePhotoArg:(DBACCOUNTSetProfilePhotoArg *)aSetProfilePhotoArg {
  if (self == aSetProfilePhotoArg) {
    return YES;
  }
  if (![self.photo isEqual:aSetProfilePhotoArg.photo]) {
    return NO;
  }
  return YES;
}

@end

#pragma mark - Serializer Object

@implementation DBACCOUNTSetProfilePhotoArgSerializer

+ (NSDictionary<NSString *, id> *)serialize:(DBACCOUNTSetProfilePhotoArg *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  jsonDict[@"photo"] = [DBACCOUNTPhotoSourceArgSerializer serialize:valueObj.photo];

  return [jsonDict count] > 0 ? jsonDict : nil;
}

+ (DBACCOUNTSetProfilePhotoArg *)deserialize:(NSDictionary<NSString *, id> *)valueDict {
  DBACCOUNTPhotoSourceArg *photo = [DBACCOUNTPhotoSourceArgSerializer deserialize:valueDict[@"photo"]];

  return [[DBACCOUNTSetProfilePhotoArg alloc] initWithPhoto:photo];
}

@end

#import "DBACCOUNTSetProfilePhotoError.h"
#import "DBStoneSerializers.h"
#import "DBStoneValidators.h"

#pragma mark - API Object

@implementation DBACCOUNTSetProfilePhotoError

#pragma mark - Constructors

- (instancetype)initWithFileTypeError {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorFileTypeError;
  }
  return self;
}

- (instancetype)initWithFileSizeError {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorFileSizeError;
  }
  return self;
}

- (instancetype)initWithDimensionError {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorDimensionError;
  }
  return self;
}

- (instancetype)initWithThumbnailError {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorThumbnailError;
  }
  return self;
}

- (instancetype)initWithTransientError {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorTransientError;
  }
  return self;
}

- (instancetype)initWithOther {
  self = [super init];
  if (self) {
    _tag = DBACCOUNTSetProfilePhotoErrorOther;
  }
  return self;
}

#pragma mark - Instance field accessors

#pragma mark - Tag state methods

- (BOOL)isFileTypeError {
  return _tag == DBACCOUNTSetProfilePhotoErrorFileTypeError;
}

- (BOOL)isFileSizeError {
  return _tag == DBACCOUNTSetProfilePhotoErrorFileSizeError;
}

- (BOOL)isDimensionError {
  return _tag == DBACCOUNTSetProfilePhotoErrorDimensionError;
}

- (BOOL)isThumbnailError {
  return _tag == DBACCOUNTSetProfilePhotoErrorThumbnailError;
}

- (BOOL)isTransientError {
  return _tag == DBACCOUNTSetProfilePhotoErrorTransientError;
}

- (BOOL)isOther {
  return _tag == DBACCOUNTSetProfilePhotoErrorOther;
}

- (NSString *)tagName {
  switch (_tag) {
  case DBACCOUNTSetProfilePhotoErrorFileTypeError:
    return @"DBACCOUNTSetProfilePhotoErrorFileTypeError";
  case DBACCOUNTSetProfilePhotoErrorFileSizeError:
    return @"DBACCOUNTSetProfilePhotoErrorFileSizeError";
  case DBACCOUNTSetProfilePhotoErrorDimensionError:
    return @"DBACCOUNTSetProfilePhotoErrorDimensionError";
  case DBACCOUNTSetProfilePhotoErrorThumbnailError:
    return @"DBACCOUNTSetProfilePhotoErrorThumbnailError";
  case DBACCOUNTSetProfilePhotoErrorTransientError:
    return @"DBACCOUNTSetProfilePhotoErrorTransientError";
  case DBACCOUNTSetProfilePhotoErrorOther:
    return @"DBACCOUNTSetProfilePhotoErrorOther";
  }

  @throw([NSException exceptionWithName:@"InvalidTag" reason:@"Tag has an unknown value." userInfo:nil]);
}

#pragma mark - Serialization methods

+ (nullable NSDictionary<NSString *, id> *)serialize:(id)instance {
  return [DBACCOUNTSetProfilePhotoErrorSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary<NSString *, id> *)dict {
  return [DBACCOUNTSetProfilePhotoErrorSerializer deserialize:dict];
}

#pragma mark - Debug Description method

- (NSString *)debugDescription {
  return [[DBACCOUNTSetProfilePhotoErrorSerializer serialize:self] description];
}

#pragma mark - Copyable method

- (instancetype)copyWithZone:(NSZone *)zone {
#pragma unused(zone)
  /// object is immutable
  return self;
}

#pragma mark - Hash method

- (NSUInteger)hash {
  NSUInteger prime = 31;
  NSUInteger result = 1;

  switch (_tag) {
  case DBACCOUNTSetProfilePhotoErrorFileTypeError:
    result = prime * result + [[self tagName] hash];
    break;
  case DBACCOUNTSetProfilePhotoErrorFileSizeError:
    result = prime * result + [[self tagName] hash];
    break;
  case DBACCOUNTSetProfilePhotoErrorDimensionError:
    result = prime * result + [[self tagName] hash];
    break;
  case DBACCOUNTSetProfilePhotoErrorThumbnailError:
    result = prime * result + [[self tagName] hash];
    break;
  case DBACCOUNTSetProfilePhotoErrorTransientError:
    result = prime * result + [[self tagName] hash];
    break;
  case DBACCOUNTSetProfilePhotoErrorOther:
    result = prime * result + [[self tagName] hash];
    break;
  }

  return prime * result;
}

#pragma mark - Equality method

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (!other || ![other isKindOfClass:[self class]]) {
    return NO;
  }
  return [self isEqualToSetProfilePhotoError:other];
}

- (BOOL)isEqualToSetProfilePhotoError:(DBACCOUNTSetProfilePhotoError *)aSetProfilePhotoError {
  if (self == aSetProfilePhotoError) {
    return YES;
  }
  if (self.tag != aSetProfilePhotoError.tag) {
    return NO;
  }
  switch (_tag) {
  case DBACCOUNTSetProfilePhotoErrorFileTypeError:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  case DBACCOUNTSetProfilePhotoErrorFileSizeError:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  case DBACCOUNTSetProfilePhotoErrorDimensionError:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  case DBACCOUNTSetProfilePhotoErrorThumbnailError:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  case DBACCOUNTSetProfilePhotoErrorTransientError:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  case DBACCOUNTSetProfilePhotoErrorOther:
    return [[self tagName] isEqual:[aSetProfilePhotoError tagName]];
  }
  return YES;
}

@end

#pragma mark - Serializer Object

@implementation DBACCOUNTSetProfilePhotoErrorSerializer

+ (NSDictionary<NSString *, id> *)serialize:(DBACCOUNTSetProfilePhotoError *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  if ([valueObj isFileTypeError]) {
    jsonDict[@".tag"] = @"file_type_error";
  } else if ([valueObj isFileSizeError]) {
    jsonDict[@".tag"] = @"file_size_error";
  } else if ([valueObj isDimensionError]) {
    jsonDict[@".tag"] = @"dimension_error";
  } else if ([valueObj isThumbnailError]) {
    jsonDict[@".tag"] = @"thumbnail_error";
  } else if ([valueObj isTransientError]) {
    jsonDict[@".tag"] = @"transient_error";
  } else if ([valueObj isOther]) {
    jsonDict[@".tag"] = @"other";
  } else {
    jsonDict[@".tag"] = @"other";
  }

  return [jsonDict count] > 0 ? jsonDict : nil;
}

+ (DBACCOUNTSetProfilePhotoError *)deserialize:(NSDictionary<NSString *, id> *)valueDict {
  NSString *tag = valueDict[@".tag"];

  if ([tag isEqualToString:@"file_type_error"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithFileTypeError];
  } else if ([tag isEqualToString:@"file_size_error"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithFileSizeError];
  } else if ([tag isEqualToString:@"dimension_error"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithDimensionError];
  } else if ([tag isEqualToString:@"thumbnail_error"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithThumbnailError];
  } else if ([tag isEqualToString:@"transient_error"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithTransientError];
  } else if ([tag isEqualToString:@"other"]) {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithOther];
  } else {
    return [[DBACCOUNTSetProfilePhotoError alloc] initWithOther];
  }
}

@end

#import "DBACCOUNTSetProfilePhotoResult.h"
#import "DBStoneSerializers.h"
#import "DBStoneValidators.h"

#pragma mark - API Object

@implementation DBACCOUNTSetProfilePhotoResult

#pragma mark - Constructors

- (instancetype)initWithProfilePhotoUrl:(NSString *)profilePhotoUrl {
  [DBStoneValidators nonnullValidator:nil](profilePhotoUrl);

  self = [super init];
  if (self) {
    _profilePhotoUrl = profilePhotoUrl;
  }
  return self;
}

#pragma mark - Serialization methods

+ (nullable NSDictionary<NSString *, id> *)serialize:(id)instance {
  return [DBACCOUNTSetProfilePhotoResultSerializer serialize:instance];
}

+ (id)deserialize:(NSDictionary<NSString *, id> *)dict {
  return [DBACCOUNTSetProfilePhotoResultSerializer deserialize:dict];
}

#pragma mark - Debug Description method

- (NSString *)debugDescription {
  return [[DBACCOUNTSetProfilePhotoResultSerializer serialize:self] description];
}

#pragma mark - Copyable method

- (instancetype)copyWithZone:(NSZone *)zone {
#pragma unused(zone)
  /// object is immutable
  return self;
}

#pragma mark - Hash method

- (NSUInteger)hash {
  NSUInteger prime = 31;
  NSUInteger result = 1;

  result = prime * result + [self.profilePhotoUrl hash];

  return prime * result;
}

#pragma mark - Equality method

- (BOOL)isEqual:(id)other {
  if (other == self) {
    return YES;
  }
  if (!other || ![other isKindOfClass:[self class]]) {
    return NO;
  }
  return [self isEqualToSetProfilePhotoResult:other];
}

- (BOOL)isEqualToSetProfilePhotoResult:(DBACCOUNTSetProfilePhotoResult *)aSetProfilePhotoResult {
  if (self == aSetProfilePhotoResult) {
    return YES;
  }
  if (![self.profilePhotoUrl isEqual:aSetProfilePhotoResult.profilePhotoUrl]) {
    return NO;
  }
  return YES;
}

@end

#pragma mark - Serializer Object

@implementation DBACCOUNTSetProfilePhotoResultSerializer

+ (NSDictionary<NSString *, id> *)serialize:(DBACCOUNTSetProfilePhotoResult *)valueObj {
  NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] init];

  jsonDict[@"profile_photo_url"] = valueObj.profilePhotoUrl;

  return [jsonDict count] > 0 ? jsonDict : nil;
}

+ (DBACCOUNTSetProfilePhotoResult *)deserialize:(NSDictionary<NSString *, id> *)valueDict {
  NSString *profilePhotoUrl = valueDict[@"profile_photo_url"];

  return [[DBACCOUNTSetProfilePhotoResult alloc] initWithProfilePhotoUrl:profilePhotoUrl];
}

@end


text:
package com.test.example.model;

public class IncomingData {
	public int id;
	public int x;
	public int y;

	public IncomingData(int startId, int startX, int startY) {
		id = startId;
		x = startX;
		y = startY;
	}

	public void setId(int newValue) {
		id = newValue;
	}

	public void setX(int newValue) {
		x = newValue;
	}

	public void setY(int newValue) {
		y = newValue;
	}
}


text:
{% load widget_extras %}
{% load i18n %}
{% load object_extras %}
<script type="text/javascript">
    oMap = objGPWidget{{mapName}};

    {# widget OPTIONS object used to create the widget class #}
    var objWidgetOptions;

    {% for resource in widget.resources %}
      {#Use the DataStoreName to validate that the resource has a valid service type #}
      {% with resourceDatastore=resource|args:"featureserver"|call:"getDatastoreByType" %}

      {# If a DataStoreName was returned, that means the resource has a valid service type. #}
      {% if resourceDatastore %}

        {%with widgetTextOption=widget|args:"text"|call:"getOption"  %}

          {%with featurecontroloptionsOption=widget|args:"featurecontroloptions"|call:"getOption"  %}

            {# DataStoreText #}

            {% with datastoreTextOption=appSession|args:resourceDatastore|args:"text"|call:"getObjectOption" %}

            {% with initViewUrlFieldOption=resource|args:"initViewUrlField"|call:"getOption" %}

            {# get resource 'iconClsDelete' option, if any #}

            {%with iconClsDeleteOption=resource|args:"iconClsDelete"|call:"getOption"  %}

              {# get resource 'tooltipTextDelete' option, i18n supported #}

              {%with tooltipTextDeleteOption=resource|args:"tooltipTextDelete"|call:"getOption"  %}

              objWidgetOptions = {{widget.printOptions}};

              objWidgetOptions['resource'] = '{{resource.id}}';
              objWidgetOptions['id'] = '{{widget.id}}{{resource.id}}';

              {# tooltip text of the button #}
              var strTooltipText =
                {# if resource had a tooltipTextDelete option, then use it #}
                {% if tooltipTextDeleteOption %}
                  "{% trans tooltipTextDeleteOption %}";
                {% else %}
                  {# check the 'text' property in : 1) the widget options/text 2) the datastore params/text if none was provided, use the resource name instead #}
                    {% if widgetTextOption %}
                      '{{widgetTextOption}}'
                    {% else %}
                        {% if datastoreTextOption %}
                          "{{datastoreTextOption}}"
                        {% else %}
                          '{{resource.id}}'
                        {% endif %}
                    {% endif %};
                    {% if featurecontroloptionsOption %}
                      strTooltipText += " - " + "{% trans "Multiple selection (drag box)" %}";
                    {% else %}
                      strTooltipText += " - " + "{% trans "Single selection (point)" %}";
                    {% endif %}
                  strTooltipText = "{% trans "Delete features" %}" + " - "+ strTooltipText;
                {% endif %}

            {%endwith%}

          {# Widget object creation  #}
          var objGPWidget{{widget.id}} = new OpenLayers.Control.EditFeature_Delete(objWidgetOptions);

          {# GeoExt.Action object for the geoexttoolbar #}
          action = new GeoExt.Action({
            id: '{{widget.id}}{{resource.id}}',
            {% if iconClsDeleteOption %}
            iconCls: '{{iconClsDeleteOption}}',
            {% else %}
            iconCls: 'editfeature_delete',
            {% endif %}
            control: objGPWidget{{widget.id}},
            map: oMap,
            // button options
            toggleGroup: oMap.id,
            allowDepress: false,
            tooltip: strTooltipText,
            // check item options
            group: oMap.id
          });

          {# Push action in goEditFeatureActions['resource'] array  #}
          if (!goEditFeatureActions['{{resource.id}}'])
          {
              goEditFeatureActions['{{resource.id}}'] = [];
          }
          goEditFeatureActions['{{resource.id}}'].push(action);
          {%endwith%}
        {%endwith%}
        {%endwith%}
        {%endwith%}
        {%endwith%}
      {% endif %}
      {% endwith %}
    {% endfor %}
  </script>


text:
layout: default
comments: true
---

{{ page.title }}

    {{ content }}


text:
SYNONYM

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 43(2): 180 (1960)

#### Original name
Agaricus hepaticus Batsch, 1786

### Remarks
null


text:
/**
 * Autogenerated by Thrift
 *
 * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
 *  @generated
 */
#include "thrift/compiler/test/fixtures/qualified/gen-cpp/module2_constants.h"

#include <folly/Indestructible.h>

namespace MODULE2 {

Struct const &module2_constants::c2() {
  static folly::Indestructible<Struct> const instance{
    Struct(
      ::apache::thrift::detail::wrap_argument<1>( ::MODULE0::Struct( ::MODULE0::module0_constants::c0())),
      ::apache::thrift::detail::wrap_argument<2>( ::MODULE1::Struct( ::MODULE1::module1_constants::c1())))
  };
  return *instance;
}

} // namespace


text:
require 'test_helper'

class Integration::TaskTest < ActionDispatch::IntegrationTest
  setup do
    @user_a = User.make!(name: 'John Doe', password: 'pass123worD!')
    @user_b = User.make!(name: 'Jane Doe', password: 'pass123worD!')
  end

  test 'Task Index' do
    project_a = Project.make!(team: @user_a.team, )
    project_b = Project.make!(team: @user_b.team, )

    10.times { Task.make!(project: project_a) }
    10.times { Task.make!(project: project_b) }

    login_user(@user_a)

    visit '/tasks'
    Task.all.each do |task|
      assert page.has_xpath?("//*[@id='task-#{task.id}']")
    end
  end
end


text:
static int row;

// The cursor column (0...VID_COLS)

static int col;

// The video attribute (foreground color, background color, blink,
// etc.)

static char attr;

// Move the cursor to the beginning of the line.

static void cr() {
  col = 0;
}

// Move the cursor to the beginning of the next line.  If it goes off the bottom of the screen,
// scroll the screen.

static void nl() {
  cr();
  if(row == VID_ROWS - 1) {
    vid_scroll();
    vid_clear_row(VID_ROWS - 1);
  }
  else
    row += 1;
}

// Move the cursor to the right.  If it goes off the right end of the
// line, move it to the beginning of the next line.  If it goes off
// bottom the screen, scroll the screen.

static void cursor_right() {
  col += 1;
  if (col >= VID_COLS)
    nl();
}

// Initialize.  Must be called before other function in this module.

void vty_init() {
  vid_clear();
  row = 0;
  col = 0;
  attr = VID_DEFAULT_ATTR;
}

// Write a character at the cursor location and advance the cursor.
// Special characters:
//   '\r': Move to beginning of this line
//   '\n': Move to beginning of next line

void vty_putc(char c) {
  switch(c) {
  case '\r':
    cr();
    break;
  case '\n':
    nl();
    break;
  default:
    vid_poke(row, col, c, attr);
    cursor_right();
  }
}

// Write a string.  Special characters are interpreted (see vty_putc).

void vty_puts(char * s) {
  char c;
  while((c = *s++) != '\0')
    vty_putc(c);
}

// Write formatted.  Special characters are interpreted (see vty_putc).
// See vaprintf for formatting.

void vty_printf(const char * format, ...) {
  va_list varargs;
  va_start(varargs, format);
  char buffer[256];
  vsprintf(buffer, sizeof(buffer), format, varargs);
  vty_puts(buffer);
  va_end(varargs);
}


text:
<?php

declare(strict_types=1);

namespace Inowas\Common\Modflow;

class Extension
{

    protected $extension;

    public static function fromString(string $extension): Extension
    {
        $self = new self();
        $self->extension = $extension;
        return $self;
    }

    public static function fromArray(array $extension): Extension
    {
        $self = new self();
        $self->extension = $extension;
        return $self;
    }

    public static function fromValue($extension): Extension
    {
        $self = new self();
        $self->extension = $extension;
        return $self;
    }

    private function __construct(){}

    public function toString(): string
    {
        return $this->extension;
    }

    public function toValue()
    {
        return $this->extension;
    }

    public function sameAs($obj): bool
    {
        return $obj instanceof self && $obj->toValue() === $this->extension;
    }
}


text:
namespace Magellan.Framework
{
    public class BackResult : ActionResult
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="BackResult"/> class.
        /// </summary>
        public BackResult()
        {
        }

        /// <summary>
        /// When implemented in a derived class, performs the bulk of the action rendering.
        /// </summary>
        /// <param name="controllerContext">The controller context.</param>
        protected override void ExecuteInternal(ControllerContext controllerContext)
        {
            var navigator = controllerContext.Request.Navigator;
            navigator.GoBack();
        }
    }
}


text:
return {
	'array/too-deep',
	'constant/falso',
	'object/too-deep',
	'string/escaped-backslash-bad',
	'string/escaped-tab',
	'string/escaped-x',
	'string/injected-newline',
	'string/injected-nul',
	'string/surrogate-double1st',
	'string/surrogate-double2nd',
	'string/surrogate-notpair1',
	'string/surrogate-notpair2',
	'string/surrogate-only1st',
	'string/surrogate-only2nd',
	'string/unicode-literal-hex',
	'number/0-digits',
	'number/0-period',
	'number/digits-plus',
	'number/exp-period-num',
	'number/frac-period-num',
	'number/hex',
	'number/num-e',
	'number/num-period',
	'number/period-num',
	'number/plusminus',
}


text:
package grpcmon

import (
	"context"
	"math"
	"time"

	"go.opencensus.io/plugin/ocgrpc"
	gcode "google.golang.org/genproto/googleapis/rpc/code"
	"google.golang.org/grpc"
	"google.golang.org/grpc/stats"
	"google.golang.org/grpc/status"

	"go.chromium.org/luci/common/clock"
	"go.chromium.org/luci/common/tsmon/distribution"
	"go.chromium.org/luci/common/tsmon/field"
	"go.chromium.org/luci/common/tsmon/metric"
	"go.chromium.org/luci/common/tsmon/types"
)

var (
	// sizeBucket covers range of 1..4GiB
	//
	// This is used in the metrics of sent/received message sizes.
	sizeBucket = distribution.GeometricBucketer(math.Pow(32, 0.064), 100)

	grpcClientCount = metric.NewCounter(
		"grpc/client/count",
		"Total number of RPCs.",
		nil,
		field.String("method"),         // full name of the grpc method
		field.String("canonical_code")) // status.Code of the result in string

	grpcClientDuration = metric.NewCumulativeDistribution(
		"grpc/client/duration",
		"Distribution of client-side RPC duration (in milliseconds).",
		&types.MetricMetadata{Units: types.Milliseconds},
		distribution.DefaultBucketer,
		field.String("method"),
		field.String("canonical_code"))

	grpcClientSentMsg = metric.NewCumulativeDistribution(
		"grpc/client/sent_messages",
		"Count Distribution of sent messages per client-side RPC.",
		nil,
		// TODO(ddoman): tune bucket.
		distribution.DefaultBucketer,
		field.String("method"))

	grpcClientRecvMsg = metric.NewCumulativeDistribution(
		"grpc/client/received_messages",
		"Count distribution of received messages per client-side RPC.",
		nil,
		// TODO(ddoman): tune bucket.
		distribution.DefaultBucketer,
		field.String("method"))

	grpcClientSentByte = metric.NewCumulativeDistribution(
		"grpc/client/sent_bytes",
		"Size distribution of request protocol messages. Size is the actual number "+
			"of bytes sent on the wire, which may have been subject to compressions.",
		&types.MetricMetadata{Units: types.Bytes},
		sizeBucket,
		field.String("method"))

	grpcClientRecvByte = metric.NewCumulativeDistribution(
		"grpc/client/received_bytes",
		"Size distribution of response protocol messages. Size is the actual number "+
			"of bytes received on the wire, which may have been subject to compressions.",
		&types.MetricMetadata{Units: types.Bytes},
		sizeBucket,
		field.String("method"))

	rtKey = "Holds the current rpc tag"
)

// NewUnaryClientInterceptor returns an interceptor that gathers RPC call
// metrics and sends them to tsmon.
//
// It can be optionally chained with other interceptor. The reported metrics
// include time spent in this other interceptor too.
//
// Can be passed to a gRPC client via WithUnaryInterceptor(...) dial option.
//
// Use option.WithGRPCDialOption(grpc.WithUnaryInterceptor(...)) when
// instrumenting Google Cloud API clients.
//
// It assumes the RPC context has tsmon initialized already.
func NewUnaryClientInterceptor(next grpc.UnaryClientInterceptor) grpc.UnaryClientInterceptor {
	return func(ctx context.Context, method string, req, reply interface{}, cc *grpc.ClientConn, invoker grpc.UnaryInvoker, opts ...grpc.CallOption) (err error) {
		started := clock.Now(ctx)
		defer func() {
			reportClientRPCMetrics(ctx, method, err, clock.Now(ctx).Sub(started))
		}()
		if next != nil {
			return next(ctx, method, req, reply, cc, invoker, opts...)
		}
		return invoker(ctx, method, req, reply, cc, opts...)
	}
}

// reportClientRPCMetrics sends metrics after RPC call has finished.
func reportClientRPCMetrics(ctx context.Context, method string, err error, dur time.Duration) {
	code := status.Code(err)
	canon, ok := gcode.Code_name[int32(code)]
	if !ok {
		canon = code.String() // Code(%d)
	}
	grpcClientCount.Add(ctx, 1, method, canon)
	// dur.Milliseconds() is only available in go >=1.13, but not every chops apps are running
	// with go >= 1.13.
	grpcClientDuration.Add(ctx, float64(dur.Nanoseconds()/1e6), method, canon)
}

// WithClientRPCStatsMonitor returns a DialOption that specifies a chain of
// ClientRPCStatsMonitor and Opencensus' gRPC stats handler for all the outgoing
// gRPC traffic.
//
// ClientRPCStatsMonitor updates the grpcmon metrics, and Opencensus' handler
// propagates Google Cloud Trace contexts.
func WithClientRPCStatsMonitor() grpc.DialOption {
	return WithMultiStatsHandler(
		&ClientRPCStatsMonitor{},
		// https://github.com/googleapis/google-api-go-client/blob/6c8f9c553065cd8c92cb6f51c2eabea88ffb3407/transport/grpc/dial.go#L180
		&ocgrpc.ClientHandler{},
	)
}

// ClientRPCStatsMonitor implements stats.Handler to update tsmon metrics with
// RPC stats.
//
// Can be passed to a gRPC client via WithStatsHandler(...) dial option.
// To chain this with other stats handler, use WithMultiStatsHandler.
type ClientRPCStatsMonitor struct{}

// TagRPC creates a context for the RPC.
//
// The context used for the rest lifetime of the RPC will be derived
// from the returned context.
func (m *ClientRPCStatsMonitor) TagRPC(ctx context.Context, tag *stats.RPCTagInfo) context.Context {
	return context.WithValue(ctx, &rtKey, tag)
}

func methodNameFromTag(ctx context.Context) string {
	rt, ok := ctx.Value(&rtKey).(*stats.RPCTagInfo)
	if !ok {
		// This should never happen.
		panic("handleRPCEnd: missing rpc-tag")
	}
	return rt.FullMethodName
}

// handleRPCEnd updates the metrics for an RPC completion.
func (m *ClientRPCStatsMonitor) handleRPCEnd(ctx context.Context, e *stats.End) {
	reportClientRPCMetrics(ctx, methodNameFromTag(ctx), e.Error, e.EndTime.Sub(e.BeginTime))
}

// handleRPC updates the metrics with the information for an incoming payload.
func (m *ClientRPCStatsMonitor) handleRPCInPayload(ctx context.Context, p *stats.InPayload) {
	n := methodNameFromTag(ctx)
	grpcClientRecvMsg.Add(ctx, 1, n)
	grpcClientRecvByte.Add(ctx, float64(p.WireLength), n)
}

// handleRPC updates the metrics with the information for an outgoing payload.
func (m *ClientRPCStatsMonitor) handleRPCOutPayload(ctx context.Context, p *stats.OutPayload) {
	n := methodNameFromTag(ctx)
	grpcClientSentMsg.Add(ctx, 1, n)
	grpcClientSentByte.Add(ctx, float64(p.WireLength), n)
}

// HandleRPC processes the RPC stats.
func (m *ClientRPCStatsMonitor) HandleRPC(ctx context.Context, s stats.RPCStats) {
	switch event := s.(type) {
	case *stats.End:
		m.handleRPCEnd(ctx, event)
	case *stats.InPayload:
		m.handleRPCInPayload(ctx, event)
	case *stats.OutPayload:
		m.handleRPCOutPayload(ctx, event)
	default:
		// do nothing.
	}
}

// TagConn creates a context for the connection.
//
// The context passed to HandleConn will be derived from the returned context.
// The context passed to HandleRPC will NOT be derived from the returned context.
func (m *ClientRPCStatsMonitor) TagConn(ctx context.Context, t *stats.ConnTagInfo) context.Context {
	// do nothing
	return ctx
}

// HandleConn processes the Conn stats.
func (m *ClientRPCStatsMonitor) HandleConn(context.Context, stats.ConnStats) {
	// do nothing
}


text:
package com.havryliuk.itarticles.ui.search_dialog;

import com.havryliuk.itarticles.ui.base.Presenter;
import com.havryliuk.itarticles.utils.events.SearchParamEvent;

/**
 * Created by Igor Havrylyuk on 24.10.2017.
 */

public interface FilterDialogMvpPresenter<V extends FilterDialogMvpView> extends Presenter<V> {

    void onSubmitClick(SearchParamEvent event);

}


text:
#ifndef TELLIPTIC_BRUSH_P_H
#define TELLIPTIC_BRUSH_P_H

#include "tcurves.h"
#include "tstroke.h"
#include "tgl.h" //tglPixelSize
#include "tstrokeoutline.h"

namespace tellipticbrush
{

//!Tolerance parameter used somewhere throughout this code.
const double tolPar = 1e-6;

//********************************************************************************
//    Geometric Helper Functions
//********************************************************************************

double dist(const TPointD &P1, const TPointD &P2);
double dist(const TThickPoint &P1, const TThickPoint &P2);
double angle(const TPointD &v1, const TPointD &v2);

TPointD intersectionCoords(const TPointD &P0, const TPointD &d0, const TPointD &P1, const TPointD &d1,
						   double detTol = 1e-2);

void buildEnvelopeDirection(const TThickPoint &p, const TThickPoint &d, bool left, TPointD &res);
void buildEnvelopeDirections(const TThickPoint &p, const TThickPoint &d, TPointD &resL, TPointD &resR);
void buildEnvelopeVector(const TThickPoint &p, const TThickPoint &d, bool left, TPointD &res);
void buildEnvelopeVectors(const TThickPoint &p, const TThickPoint &d, TPointD &resL, TPointD &resR);

void buildAngularSubdivision(double radius, double angle, double err, int &nAngles);

TRectD computeBBox(const TStroke &stroke);

//********************************************************************************
//    Options structure
//********************************************************************************

/*
  Structure needed to hold both external and internal outlinization parameters.
*/
struct OutlinizationData {
	TOutlineUtil::OutlineParameter m_options;
	double m_pixSize;

	OutlinizationData() : m_options(), m_pixSize(0.0) {}
	OutlinizationData(const TOutlineUtil::OutlineParameter &options)
		: m_options(options), m_pixSize(sqrt(tglGetPixelSize2()))
	{
	}
};

//********************************************************************************
//    Centerline Point struct
//********************************************************************************

/*!
  CenterlinePoint contains the data a about a discretized centerline stroke point -
  which includes its position, and eventual forward and backward derivative-like
  directions. Thickness data is included in the structure.

  These informations are necessary and sufficient to build associated outline points,
  and eventual additional points related to caps.
*/
struct CenterlinePoint {
	int m_chunkIdx; //!< The quadratic chunk index containing this point
	double m_t;		//!< The quadratic parameter where this point can be found

	TThickPoint m_p; //!< The point's thick coordinates
	bool m_posBuilt; //!< Wheteher m_p has been calculated

	TThickPoint m_prevD; //!< The backward direction
	bool m_hasPrevD;	 //!< If the point has (envelopable) backward direction

	TThickPoint m_nextD; //!< The forward direction
	bool m_hasNextD;	 //!< If the point has (envelopable) forward direction

	bool m_dirsBuilt; //!< Whether directions have been calculated

	bool m_covered; //!< Whether this point's outline can't be seen

	int m_countIdx; //!< Additional index needed by some procedural style...

	CenterlinePoint() : m_chunkIdx(-1), m_posBuilt(false), m_dirsBuilt(false) {}
	CenterlinePoint(int chunk, double t) : m_chunkIdx(chunk), m_t(t), m_posBuilt(false), m_dirsBuilt(false), m_countIdx(0) {}

	~CenterlinePoint() {}

	void buildPos(const TStroke &stroke);
	void buildDirs(const TStroke &stroke);

	bool operator<(const CenterlinePoint &cp) const
	{
		return m_chunkIdx < cp.m_chunkIdx ? true : m_chunkIdx > cp.m_chunkIdx ? false : m_t < cp.m_t;
	}
};

//********************************************************************************
//    Linearizator Classes
//********************************************************************************

/*!
  The StrokeLinearizator class models a stroke linearization interface that
  extracts points of interest from a succession of stroke quadratics.
*/
class StrokeLinearizator
{
protected:
	const TStroke *m_stroke;

public:
	StrokeLinearizator(const TStroke *stroke) : m_stroke(stroke) {}
	virtual ~StrokeLinearizator() {}

	/*!
    Adds interesting stroke points to be discretized in the
    chunk-th TThickQuadratic stroke.

    \note The initial point (P0) of the quadratic is always added by the
    outlinization algorithm before these linearization functions are invoked
    (whereas P2 belongs to the next quadratic).
  */
	virtual void linearize(std::vector<CenterlinePoint> &cPoints, int chunk) = 0;
};

//********************************************************************************
//    Outline Builder classes
//********************************************************************************

/*!
  The OutlineBuilder class is the object used to translate centerline points
  into outline points. The purpose of this class is to take a CenterlinePoint
  instance and build a couple of outline points - at either side of the
  centerline - eventually adding (cap) points to form a smooth outline.
*/
class OutlineBuilder
{
	double m_pixSize;
	TStroke::OutlineOptions m_oOptions;

	int m_lastChunk;

private:
	typedef void (OutlineBuilder::*OutlineBuilderFunc)(
		std::vector<TOutlinePoint> &outPoints, const CenterlinePoint &cPoint);

	OutlineBuilderFunc m_addBeginCap;
	OutlineBuilderFunc m_addEndCap;
	OutlineBuilderFunc m_addSideCaps;

	typedef void (OutlineBuilder::*BBoxBuilderFunc)(
		TRectD &bbox, const CenterlinePoint &cPoint);

	BBoxBuilderFunc m_addBeginCap_ext;
	BBoxBuilderFunc m_addEndCap_ext;
	BBoxBuilderFunc m_addSideCaps_ext;

private:
	/*
    Type-specific outline container functions.
    Used with outline building sub-routines that may be used to supply
    different outline container types.
    For example, a TRectD may be considered a container class to be used
    when building the outline bbox.
  */
	template <typename T>
	void addEnvelopePoint(T &container, const TPointD &oPoint, int countIdx = 0);
	template <typename T>
	void addExtensionPoint(T &container, const TPointD &oPoint, int countIdx = 0);
	template <typename T>
	void addOutlineBuilderFunc(OutlineBuilder::OutlineBuilderFunc func,
							   T &container, const CenterlinePoint &cPoint);

public:
	OutlineBuilder(const OutlinizationData &data, const TStroke &stroke);
	~OutlineBuilder() {}

	/*!
    Transforms the specified centerline point into outline points, and adds them to
    the supplied outline points vector.
  */
	void buildOutlinePoints(
		std::vector<TOutlinePoint> &outPoints, const CenterlinePoint &cPoint);

	void buildOutlineExtensions(TRectD &bbox, const CenterlinePoint &cPoint);

private:
	void addCircle(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);
	void addCircularArcPoints(
		int idx, std::vector<TOutlinePoint> &outPoints,
		const TPointD &center, const TPointD &ray, double angle, int nAngles,
		int countIdx);

	void addRoundBeginCap(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);
	void addRoundEndCap(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);

	void addButtBeginCap(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);
	void addButtEndCap(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);

	template <typename T>
	void addProjectingBeginCap(T &oPoints, const CenterlinePoint &cPoint);
	template <typename T>
	void addProjectingEndCap(T &oPoints, const CenterlinePoint &cPoint);

	void addRoundSideCaps(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);
	void addBevelSideCaps(std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint);
	template <typename T>
	void addMiterSideCaps(T &oPoints, const CenterlinePoint &cPoint);
};

//********************************************************************************
//    Explicit specializations of OutlineBuilder's methods
//********************************************************************************

// Container of Outline Points (for common outline extraction)

template <>
inline void OutlineBuilder::addEnvelopePoint(std::vector<TOutlinePoint> &oPoints,
											 const TPointD &oPoint, int countIdx)
{
	oPoints.push_back(TOutlinePoint(oPoint, countIdx));
}

template <>
inline void OutlineBuilder::addExtensionPoint(std::vector<TOutlinePoint> &oPoints,
											  const TPointD &oPoint, int countIdx)
{
	oPoints.push_back(TOutlinePoint(oPoint, countIdx));
}

template <>
inline void OutlineBuilder::addOutlineBuilderFunc(
	OutlineBuilder::OutlineBuilderFunc func,
	std::vector<TOutlinePoint> &oPoints, const CenterlinePoint &cPoint)
{
	(this->*func)(oPoints, cPoint);
}

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

// Rect (for bounding box extraction)

template <>
inline void OutlineBuilder::addEnvelopePoint(TRectD &bbox, const TPointD &oPoint, int countIdx)
{
}

template <>
inline void OutlineBuilder::addExtensionPoint(TRectD &bbox, const TPointD &oPoint, int countIdx)
{
	bbox.x0 = tmin(bbox.x0, oPoint.x);
	bbox.y0 = tmin(bbox.y0, oPoint.y);
	bbox.x1 = tmax(bbox.x1, oPoint.x);
	bbox.y1 = tmax(bbox.y1, oPoint.y);
}

template <>
inline void OutlineBuilder::addOutlineBuilderFunc(
	OutlineBuilder::OutlineBuilderFunc func,
	TRectD &container, const CenterlinePoint &cPoint)
{
}

//********************************************************************************
//    Standard Outline Builder (from Centerline Points)
//********************************************************************************

void buildOutline(const TStroke &stroke, std::vector<CenterlinePoint> &cPoints,
				  TStrokeOutline &outline, const OutlinizationData &data);

} //namespace tellipticbrush

#endif //TELLIPTIC_BRUSH_P_H


text:
<?php

namespace WuCore\ProductBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use WuCore\FrontBundle\Entity\User;
use WuCore\FrontBundle\Entity\Post;
use WuCore\ProductBundle\Entity\Comparaison;
use WuCore\ProductBundle\Entity\Product;
use WuCore\ProductBundle\Entity\Specification;

/**
 * Vote
 *
 * @ORM\Table(name="vote")
 * @ORM\Entity
 */
class Vote
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer
     *
     * @ORM\Column(name="value", type="integer", nullable=false)
     */
    private $value;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="created_at", type="datetime", nullable=false)
     */
    private $createdAt;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="updated_at", type="datetime", nullable=false)
     */
    private $updatedAt;

    /**
     * @var \User
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * })
     */
    private $user;

    /**
     * @var \Post
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="post_id", referencedColumnName="id")
     * })
     */
    private $post;

    /**
     * @var \Comparaison
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="comparaison_id", referencedColumnName="id")
     * })
     */
    private $comparaison;

    /**
     * @var \Product
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="product_id", referencedColumnName="id")
     * })
     */
    private $product;

    /**
     * @var \Specification
     *
     *
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="specification_id", referencedColumnName="id")
     * })
     */
    private $specification;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set value
     *
     * @param integer $value
     * @return Vote
     */
    public function setValue($value)
    {
        $this->value = $value;

        return $this;
    }

    /**
     * Get value
     *
     * @return integer
     */
    public function getValue()
    {
        return $this->value;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Vote
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return Vote
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set user
     *
     * @param \WuCore\ProductBundle\Entity\User $user
     * @return Vote
     */
    public function setUser(\WuCore\ProductBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \WuCore\ProductBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }

    /**
     * Set post
     *
     * @param \WuCore\ProductBundle\Entity\Post $post
     * @return Vote
     */
    public function setPost(\WuCore\ProductBundle\Entity\Post $post = null)
    {
        $this->post = $post;

        return $this;
    }

    /**
     * Get post
     *
     * @return \WuCore\ProductBundle\Entity\Post
     */
    public function getPost()
    {
        return $this->post;
    }

    /**
     * Set comparaison
     *
     * @param \WuCore\ProductBundle\Entity\Comparaison $comparaison
     * @return Vote
     */
    public function setComparaison(\WuCore\ProductBundle\Entity\Comparaison $comparaison = null)
    {
        $this->comparaison = $comparaison;

        return $this;
    }

    /**
     * Get comparaison
     *
     * @return \WuCore\ProductBundle\Entity\Comparaison
     */
    public function getComparaison()
    {
        return $this->comparaison;
    }

    /**
     * Set product
     *
     * @param \WuCore\ProductBundle\Entity\Product $product
     * @return Vote
     */
    public function setProduct(\WuCore\ProductBundle\Entity\Product $product = null)
    {
        $this->product = $product;

        return $this;
    }

    /**
     * Get product
     *
     * @return \WuCore\ProductBundle\Entity\Product
     */
    public function getProduct()
    {
        return $this->product;
    }

    /**
     * Set specification
     *
     * @param \WuCore\ProductBundle\Entity\Specification $specification
     * @return Vote
     */
    public function setSpecification(\WuCore\ProductBundle\Entity\Specification $specification = null)
    {
        $this->specification = $specification;

        return $this;
    }

    /**
     * Get specification
     *
     * @return \WuCore\ProductBundle\Entity\Specification
     */
    public function getSpecification()
    {
        return $this->specification;
    }
}


text:
struct tcp_info;
using namespace walle::sys;
namespace walle {
namespace net {

class Channel;
class EventLoop;
class Socket;

///
/// TCP connection, for both client and server usage.
///
/// This is an interface class, so don't expose too much details.
class TcpConnection : std::noncopyable,
                      public std::enable_shared_from_this<TcpConnection>
{
 public:
  /// Constructs a TcpConnection with a connected sockfd
  ///
  /// User should not create this object.
  TcpConnection(EventLoop* loop,
                const string& name,
                int sockfd,
                const AddrInet& localAddr,
                const AddrInet& peerAddr);
  ~TcpConnection();

  EventLoop* getLoop() const { return _loop; }
  const string& name() const { return _name; }
  const AddrInet& localAddress() const { return _localAddr; }
  const AddrInet& peerAddress() const { return _peerAddr; }
  bool connected() const { return _state == kConnected; }
  // return true if success.
  bool getTcpInfo(struct tcp_info*) const;
  string getTcpInfoString() const;

  void send(const void* message, int len);
  void send(const StringPice& message);

  void send(Buffer* message);  // this one will swap data
  void shutdown();
  void forceClose();
  void forceCloseWithDelay(int64_t seconds);
  void setTcpNoDelay(bool on);

  void setContext(const std::any& context)
  { _context = context; }

  const std::any& getContext() const
  { return _context; }

  std::any* getMutableContext()
  { return &_context; }

  void setConnectionCallback(const ConnectionCallback& cb)
  { _connectionCallback = cb; }

  void setMessageCallback(const MessageCallback& cb)
  { _messageCallback = cb; }

  void setWriteCompleteCallback(const WriteCompleteCallback& cb)
  { _writeCompleteCallback = cb; }

  void setHighWaterMarkCallback(const HighWaterMarkCallback& cb, size_t
highWaterMark)
  { _highWaterMarkCallback = cb; _highWaterMark = highWaterMark; }

  /// Advanced interface
  Buffer* inputBuffer()
  { return &_inputBuffer; }

  Buffer* outputBuffer()
  { return &_outputBuffer; }

  /// Internal use only.
  void setCloseCallback(const CloseCallback& cb)
  { _closeCallback = cb; }

  // called when TcpServer accepts a new connection
  void connectEstablished();   // should be called only once
  // called when TcpServer has removed me from its map
  void connectDestroyed();  // should be called only once
  void enableTimerOut(int64_t secs) ;
  void disableTimerOut();
  bool timerSet() { return _timerWheelHandler.valid(); }
 private:
  enum StateE { kDisconnected, kConnecting, kConnected, kDisconnecting };
  void handleRead(Time receiveTime);
  void handleWrite();
  void handleClose();
  void handleError();
  // void sendInLoop(string&& message);
  void sendInLoop(const StringPice& message);
  void sendInLoop(const void* message, size_t len);
  void sendPiceInLoop(const StringPice& message);
  void shutdownInLoop();
  // void shutdownAndForceCloseInLoop(double seconds);
  void forceCloseInLoop();
  void setState(StateE s) { _state = s; }
  void onTimerOut();

  Time                       _lastactive;
  int64_t                    _timerOutSec;
  EventLoop*                 _loop;
  const string               _name;
  StateE                     _state;
  std::scoped_ptr<Socket>    _socket;
  std::scoped_ptr<Channel>   _channel;
  ConnectionCallback         _connectionCallback;
  MessageCallback            _messageCallback;
  WriteCompleteCallback      _writeCompleteCallback;
  HighWaterMarkCallback      _highWaterMarkCallback;
  CloseCallback              _closeCallback;
  Buffer                     _inputBuffer;
  Buffer                     _outputBuffer;
  std::any                   _context;
  AddrInet                   _localAddr;
  AddrInet                   _peerAddr;
  size_t                     _highWaterMark;
  TimerWheelHander           _timerWheelHandler;
};

typedef std::shared_ptr<TcpConnection> TcpConnectionPtr;

}
}
#endif