text:
<?php
namespace Utility\Net\External\ContentAPI;

use Web\Page\API;

class Remote {
	protected $server;
	protected $module;

	function __construct($server,$module){
		$this->server = $server;
		$this->module = $module;
	}
	function fetch($id){
		$query = array('module'=>$this->module,'id'=>$id);

		$api = new API\APICall($this->server);
		$data = $api->Call('External', 'getById', $query,'ps');

		return $data;
	}
}


text:
id: V-38553
status: exception - manual intervention
tag: network
---

Adding IPv6 firewalling on OpenStack hosts is left up to the deployer to
configure. Deployers are urged to use proper network segmentation between
their OpenStack infrastructure and virtual machines, which will mitigate
many of the most critical threats.

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Runtime.InteropServices;
using DirtyMagic.WinAPI.Structures;

namespace DirtyMagic.Exceptions
{
    public class MagicException : Exception
    {
        public ErrorCodes LastError { get; }
        public MagicException(string Message) : base(Message) { LastError = (ErrorCodes)Marshal.GetLastWin32Error(); }
    }
}


text:
var util = require('util');
var bleno = require('bleno');
var mraa = require('mraa');

var BlenoCharacteristic = bleno.Characteristic;

// Initialize BLE Characteristic
var FirstCharacteristic = function() {
  FirstCharacteristic.super_.call(this, {
    uuid: 'fc0f',
    properties: ['read', 'write', 'notify'],
    value: null
  });
  this._value = new Buffer("OFF", "utf-8");
  console.log("Characterisitic's value: "+this._value);
  this._light = new mraa.Gpio(3);
  this._light.dir(mraa.DIR_OUT);
  this._light.write(0);
  this._updateValueCallback = null;
};

// Inherit the BlenoCharacteristic
util.inherits(FirstCharacteristic, BlenoCharacteristic);

// BLE Read request
FirstCharacteristic.prototype.onReadRequest = function(offset, callback) {
  console.log('FirstCharacteristic - onReadRequest: value = ' + this._value.toString("utf-8"), offset);
  callback(this.RESULT_SUCCESS, this._value);
};

// BLE write request
FirstCharacteristic.prototype.onWriteRequest = function(data, offset, withoutResponse, callback) {
  this._value = data;
  if (data == "ON") {
    this._light.write(1);
  }
  else {
    this._light.write(0);
  }
  console.log('FirstCharacteristic - onWriteRequest: value = ' + this._value.toString("utf-8"));

  if (this._updateValueCallback) {
    console.log('FirstCharacteristic - onWriteRequest: notifying');

    this._updateValueCallback(this._value);
  }

  callback(this.RESULT_SUCCESS);
};

// BLE subscribe
FirstCharacteristic.prototype.onSubscribe = function(maxValueSize, updateValueCallback) {
  console.log('FirstCharacteristic - onSubscribe');
  this._updateValueCallback = updateValueCallback;
};

// BLE unsubscribe
FirstCharacteristic.prototype.onUnsubscribe = function() {
  console.log('FirstCharacteristic - onUnsubscribe');
  this._updateValueCallback = null;
};

module.exports = FirstCharacteristic;


text:
var config = require("../config.js");
var utility = require("../utility.js");
var post = require("../slack.js").post;
var request = require('request');
var xml2js = require('xml2js');

module.exports = {
	synopsis: "wolfram {search string}",
	description: "search wolfram alpha",
	pattern: /^wolfram\s+(.+)/i,
	reply: function(match, context, callback) {
		request(encodeURI("http://api.wolframalpha.com/v2/query?appid=" + config.wolframAlphaToken + "&input=" + match[1]),
			function(error, response, body) {
				if (!error && response.statusCode == 200) {
					xml2js.parseString(body, function (error, result) {
						if (result.queryresult.$.success == "true" && result.queryresult.pod) {
							post([].concat.apply([], result.queryresult.pod.map(function(p) {
								var podText = [].concat.apply([], p.subpod.map(function(sp) {
									return sp.plaintext[0].split("\n").map(function(t) { return t || null; });
								})).filter(function(t) { return t != null; }).join("\n");
								return podText ? p.$.title + ": \n```\n" + podText + "\n```" : null;
							})).filter(function(t) { return t != null; }).join("\n"), context, callback);
						}
						else post("No wolfram results found", context, callback);
					});
				}
				else {
					utility.log("Error requesting wolfram alpha information: " + JSON.stringify(error || response) + "\n");
				}
			});
	}
};


text:
<html>
<head>
    <title>Boolean Attribute Selected</title>
</head>
<body>
<form method="get" action="#" name="myForm">
    <select name="myDropdown">
        <option value="one">One</option>
        <option selected value="two">Two</option>
        <option value="four">Four</option>
    </select>
</body>
</html>


text:
use lib 'lib';
use strict;
use warnings;
use utf8;
use File::Slurp; # From CPAN
use JSON;

use AsposeStorageCloud::StorageApi;
use AsposeStorageCloud::ApiClient;
use AsposeStorageCloud::Configuration;

use AsposeSlidesCloud::SlidesApi;
use AsposeSlidesCloud::ApiClient;
use AsposeSlidesCloud::Configuration;

my $configFile = '../Config/config.json';
my $configPropsText = read_file($configFile);
my $configProps = decode_json($configPropsText);
my $data_path = '../../../Data/';
my $out_path = $configProps->{'out_folder'};

$AsposeSlidesCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeSlidesCloud::Configuration::api_key = $configProps->{'api_key'};
$AsposeSlidesCloud::Configuration::debug = 1;

$AsposeStorageCloud::Configuration::app_sid = $configProps->{'app_sid'};
$AsposeStorageCloud::Configuration::api_key = $configProps->{'api_key'};

# Instantiate Aspose.Storage and Aspose.Slides API SDK
my $storageApi = AsposeStorageCloud::StorageApi->new();
my $slidesApi = AsposeSlidesCloud::SlidesApi->new();

# Set input file name
my $filename = "sample";
my $name = $filename . ".pptx";
my $format = "pdf";
my $jpegQuality = 50;

# Upload file to aspose cloud storage
my $response = $storageApi->PutCreate(Path => $name, file => $data_path.$name);

# Invoke Aspose.Slides Cloud SDK API to save a presentation to different other formats with additional settings
$response = $slidesApi->GetSlidesDocumentWithFormat(name => $name, format => $format, jpegQuality=>$jpegQuality);

if($response->{'Status'} eq 'OK'){
	#save converted format file from response
	my $output_file = $out_path. $filename . '.' . $format;
	write_file($output_file, { binmode => ":raw" }, $response->{'Content'});
}
#ExEnd:1


text:
/**
 */
/*
 * Created on 19.11.2004
 *
 */
package org.apache.harmony.test.func.api.java.io.share.Writer;

import java.io.IOException;
import java.io.Writer;

import org.apache.harmony.test.func.api.java.io.share.IOMultiCase;
import org.apache.harmony.test.func.api.java.io.share.MockWriter;
import org.apache.harmony.test.func.api.java.io.share.MultiThreadRunner;
import org.apache.harmony.share.Result;

public class WriterTestShared extends IOMultiCase {

    protected Writer getTestedWriter() throws IOException {
        return new MockWriter();
    }

    protected Writer getTestedWriter(Object lock) {
        return new MockWriter(lock);
    }

    protected String getWriterAsString(Writer w) throws IOException {
        return w.toString();
    }

    public Result testWriteInt() throws IOException {
        Writer w = getTestedWriter();
        try {
            MultiThreadRunner.waitAtBarrier();

            w.write('a');
            w.write((0xFFFF << 16) | (int) 'b');
            w.close();

            if (getWriterAsString(w).equals("ab")) {
                return passed();
            }
        } finally {
            w.close();
        }

        return failed("expected another value: " + getWriterAsString(w));
    }

    public Result testWriteNullArray() throws IOException {
        Writer w = getTestedWriter();

        try {
            w.write((char[]) null);
        } catch (NullPointerException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected NullPointerException");
    }

    public Result testWriteNullString() throws IOException {
        Writer w = getTestedWriter();

        try {
            w.write((String) null);
        } catch (NullPointerException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected NullPointerException");
    }

    public Result testWriteArray() throws IOException {
        Writer w = getTestedWriter();

        try {
            char[] buf = { 'a', 'b', 'c' };

            MultiThreadRunner.waitAtBarrier();

            w.write(buf);
            w.close();

            if ("abc".equals(getWriterAsString(w))) {
                return passed();
            }
        } finally {
            w.close();
        }

        return failed("expected another value");
    }

    public Result testWriteString() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();

            w.write("abc\u0000");
            w.close();

            if ("abc\u0000".equals(getWriterAsString(w))) {
                return passed();
            }
        } finally {
            w.close();
        }

        return failed("expected another value");
    }

    public Result testWriteArraySlice() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();

            w.write(new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }, 2, 3);
            w.close();

            if ("cde".equals(getWriterAsString(w))) {
                return passed();
            }
        } finally {
            w.close();
        }

        return failed("expected another value");
    }

    public Result testWriteStringSlice() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();

            w.write("abcdef", 2, 3);

            w.close();

            if ("cde".equals(getWriterAsString(w))) {
                return passed();
            }
        } finally {
            w.close();
        }

        return failed("expected another value");
    }

    public Result testWriteArrayNegativeStart() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write(new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }, -2, 3);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } catch(Throwable e) {
            e.printStackTrace();
            failed("expected IndexOutOfBoundsException");
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testWriteArrayNegativeLength() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write(new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }, 0, -5);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testWriteArrayBigLength() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write(new char[] { 'a', 'b', 'c', 'd', 'e', 'f' }, 4, 3);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testWriteStringNegativeStart() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write("qwerty", -2, 3);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testWriteStringNegativeLength() throws IOException {
        Writer w = getTestedWriter();

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write("qwwety", 0, -5);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } catch (NegativeArraySizeException e) {
            return passed();
        } catch(Throwable e) {
            e.printStackTrace();
            return failed("expected IndexOutOfBoundsException");
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testWriteStringBigLength() throws IOException {
        Writer w = getTestedWriter();

        String s;

        try {
            MultiThreadRunner.waitAtBarrier();
            w.write("qwerty", 4, 3);
        } catch (IndexOutOfBoundsException e) {
            return passed();
        } finally {
            w.close();
        }

        return failed("expected IndexOutOfBoundsException");
    }

    public Result testClose() throws IOException {
        MultiThreadRunner.waitAtBarrier();
        getTestedWriter().close();
        return passed();
    }

    public Result testFlush() throws IOException {
        Writer w = getTestedWriter();
        try {
            MultiThreadRunner.waitAtBarrier();
            w.flush();
        } finally {
            w.close();
        }
        return passed();
    }
}


text:
  <button class="btn btn-md btn-search-tool dropdown-toggle {{ 'disabled' if not toolsEnabled }}"
      type="button" data-toggle="dropdown" aria-expanded="true">
    Select by Boundary

  </button>

  {% for item in predefinedShapeTypes %}

          {{ item.display }}

  {% endfor %}


text:
package com.xmomen.module.wx.model.requestModel.event;

import java.io.Serializable;

/**
 * 自定义菜单二维码扫描请求封装类
 */
public class RequestMessageEventScanCode extends RequestMessageEventBase implements Serializable {
    //扫描信息
    private ScanCodeInfo scanCodeInfo;

    public ScanCodeInfo getScanCodeInfo() {
        return scanCodeInfo;
    }

    public void setScanCodeInfo(ScanCodeInfo scanCodeInfo) {
        this.scanCodeInfo = scanCodeInfo;
    }

    public class ScanCodeInfo {
        //扫描类型,一般是qrcode
        private String scanType;

        //扫描结果,即二维码对应的字符串信息
        private String scanResult;

        public String getScanType() {
            return scanType;
        }

        public void setScanType(String scanType) {
            this.scanType = scanType;
        }

        public String getScanResult() {
            return scanResult;
        }

        public void setScanResult(String scanResult) {
            this.scanResult = scanResult;
        }
    }
}


text:
This js-compressor is base on [YUI Compressor for .NET](https://github.com/PureKrome/YUICompressor.NET "YUICompressor.NET").

[Original author](http://www.cnblogs.com/zjfree/archive/2010/10/19/1855687.html) designed a winform GUI for it.
I just did some modification based on the original version.


text:
package edu.vt.alerts.android.library.callbacks;

import java.util.List;

import edu.vt.alerts.android.library.api.domain.summary.AlertSummary;

/**
 * Callback used by the AlertService whenever a list of Alert summaries is
 * requested.
 *
 * @author Michael Irwin
 */
public interface AlertSummaryCallback {

	/**
	 * Callback used when the alerts were retrieved.
	 * @param alerts The retrieved alerts.
	 */
	void alertsRetrieved(List<AlertSummary> alerts);

	/**
	 * Callback used when the alerts were unable to be retrieved, due to an
	 * exception.
	 * @param exception The exception that was thrown.
	 */
	void exceptionThrown(Exception exception);

}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;
using Windows.Storage;

namespace Fotografix
{
    [TestClass]
    public class PhotoTest
    {
        private StorageFile content;

        [TestInitialize]
        public async Task Initialize()
        {
            this.content = await TestData.GetFileAsync("Photos\\Barn.jpg");
        }

        [TestMethod]
        public async Task ReturnsDefaultThumbnailWhenSidecarDoesNotExist()
        {
            var sidecar = new StorageFileReference(ApplicationData.Current.TemporaryFolder, "non-existent-file");
            var photo = new Photo(content, sidecar);

            Assert.IsFalse(await photo.HasAdjustmentAsync());

            using (var thumbnail = await photo.GetThumbnailAsync())
            {
                await BitmapAssert.VerifyAsync(thumbnail, "Barn_thumbnail.jpg");
            }
        }

        [TestMethod]
        public async Task ReturnsThumbnailFromSidecarWhenAvailable()
        {
            var sidecar = await TestData.GetFileReferenceAsync("Barn_exposure_thumbnail.jpg");
            var photo = new Photo(content, sidecar);

            Assert.IsTrue(await photo.HasAdjustmentAsync());

            using (var thumbnail = await photo.GetThumbnailAsync())
            {
                await BitmapAssert.VerifyAsync(thumbnail, "Barn_exposure_thumbnail.jpg");
            }
        }
    }
}


text:
harmony
=======

gart site


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

using System.Collections.Immutable;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Text;

namespace Microsoft.CodeAnalysis.EditAndContinue
{
    internal interface IEditAndContinueWorkspaceService : IWorkspaceService
    {
        /// <summary>
        /// Returns base active statement spans contained in each specified document.
        /// </summary>
        /// <returns>
        /// <see langword="default"/> if called outside of an edit session.
        /// The length of the returned array matches the length of <paramref name="documentIds"/> otherwise.
        /// </returns>
        Task<ImmutableArray<ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>>> GetBaseActiveStatementSpansAsync(Solution solution, ImmutableArray<DocumentId> documentIds, CancellationToken cancellationToken);

        /// <summary>
        /// Returns the adjusted active statements in the specified <paramref name="document"/> snapshot.
        /// </summary>
        /// <returns>
        /// <see langword="default"/> if called outside of an edit session, or active statements for the document can't be determined for some reason
        /// (e.g. the document has syntax errors or is out-of-sync).
        /// </returns>
        Task<ImmutableArray<(LinePositionSpan, ActiveStatementFlags)>> GetAdjustedActiveStatementSpansAsync(Document document, DocumentActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken);

        Task<ImmutableArray<Diagnostic>> GetDocumentDiagnosticsAsync(Document document, DocumentActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken);
        Task<bool> HasChangesAsync(Solution solution, SolutionActiveStatementSpanProvider activeStatementSpanProvider, string? sourceFilePath, CancellationToken cancellationToken);
        Task<(SolutionUpdateStatus Summary, ImmutableArray<Deltas> Deltas)> EmitSolutionUpdateAsync(Solution solution, SolutionActiveStatementSpanProvider activeStatementSpanProvider, CancellationToken cancellationToken);

        void CommitSolutionUpdate();
        void DiscardSolutionUpdate();

        bool IsDebuggingSessionInProgress { get; }
        void OnSourceFileUpdated(Document document);

        void StartDebuggingSession(Solution solution);
        void StartEditSession(ActiveStatementProvider activeStatementProvider);
        void EndEditSession();
        void EndDebuggingSession();

        Task<bool?> IsActiveStatementInExceptionRegionAsync(Solution solution, ActiveInstructionId instructionId, CancellationToken cancellationToken);
        Task<LinePositionSpan?> GetCurrentActiveStatementPositionAsync(Solution solution, SolutionActiveStatementSpanProvider activeStatementSpanProvider, ActiveInstructionId instructionId, CancellationToken cancellationToken);

        void ReportApplyChangesException(Solution solution, string message);
    }
}


text:
class User < ActiveRecord::Base
  resourcify

  serialize :role_ids, Array

  # Include default devise modules.
  devise :database_authenticatable, :registerable,
          :recoverable, :rememberable, :trackable, :validatable,
          :confirmable, :omniauthable, :lockable
  include DeviseTokenAuth::Concerns::User

  validates :name, presence: true
  validates_confirmation_of :password

  def admin?
    has_role? 'Admin'
  end

  def manager?
    has_role? 'Manager'
  end

  def clerk?
    has_role? 'Clerk'
  end

  def has_role?(role_name)
    roles.map(&:name).include?(role_name)
  end

  def roles
    Role.unscoped.where id: self.role_ids
  end

  def permissions
    if self.admin?
      Permission.pluck(:name)
    else
      self.roles.map(&:permissions).flatten
    end
  end

  def has_permission?(permission)
    if Permission.where(name: permission).exists?
      self.roles.map(&:permissions).flatten.include? permission
    else
      false
    end
  end

  def token_validation_response
    UserTokenValidationSerializer.new(self, root: false)
  end
end


text:
module RbNaCl
  # The library's version
  VERSION = "7.1.1"
end


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

/*============================================================
** Source : test4.c
**
** Purpose: Test for SetEnvironmentVariableA() function
**          Create environment variables that differ only
**          in case and verify that they return the appropriate
**          value in the WIN32 Environment
**

**
===========================================================*/

#include <palsuite.h>

int __cdecl main(int argc, char *argv[])
{

#if WIN32

    /* Define some buffers needed for the function */
    char * pResultBuffer = NULL;

    char FirstEnvironmentVariable[] = {"PALTEST"};
    char FirstEnvironmentValue[] = {"FIRST"};
    char ModifiedEnvVar[] = {"paltest"};

    DWORD size = 0;
    BOOL bRc = TRUE;

    /*
     * Initialize the PAL and return FAILURE if this fails
     */

    if(0 != (PAL_Initialize(argc, argv)))
    {
        return FAIL;
    }

    /* Set the first environment variable */
    bRc = SetEnvironmentVariableA(FirstEnvironmentVariable,
                            FirstEnvironmentValue);

    if(!bRc)
    {
        Fail("ERROR: SetEnvironmentVariable failed to set a "
            "proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Normal case, PATH should fit into this buffer */
    size = GetEnvironmentVariableA(ModifiedEnvVar,
                                  pResultBuffer,
                                  0);

    /* To account for the null character at the end of the string */
    size = size + 1;

    pResultBuffer = malloc(sizeof(char)*size);
    if ( pResultBuffer == NULL )
    {
        Fail("ERROR: Failed to allocate memory for pResultBuffer pointer.\n");
    }

    /* Try to retrieve the value of the first environment variable */
    GetEnvironmentVariableA(ModifiedEnvVar,
                           pResultBuffer,
                           size);

    if ( pResultBuffer == NULL )
    {
        free(pResultBuffer);
        Fail("ERROR: GetEnvironmentVariable failed to return a value "
            "from a proper environment variable with error %u.\n",
            GetLastError());
    }

    /* Compare the strings to see that the correct variable was returned */
    if(strcmp(pResultBuffer,FirstEnvironmentValue) != 0)
    {
        Trace("ERROR: The value in the buffer should have been '%s' but "
             "was really '%s'.\n",FirstEnvironmentValue, pResultBuffer);
        free(pResultBuffer);
        Fail("");
    }

    free(pResultBuffer);

    PAL_Terminate();
    return PASS;

#else

    return PASS;
#endif
}


text:
#define HI_MASK 0xFFFF0000
#define LO_MASK (~HI_MASK)

#define HI(N) ((u_int16_t)(((N) & HI_MASK) >> 16))
#define LO(N) ((u_int16_t)((N) & LO_MASK))

/* Constants for big key page overhead information. */
#define NUMSHORTS	0
#define KEYLEN		1
#define DATALEN 	2
#define NEXTPAGE 	3

/*
 * Hash pages store meta-data beginning at the top of the page (offset 0)
 * and key/data values beginning at the bottom of the page (offset pagesize).
 * Fields are always accessed via macros so that we can change the page
 * format without too much pain.  The only changes that will require massive
 * code changes are if we no longer store key/data offsets next to each
 * other (since we use that fact to compute key lengths).  In the accessor
 * macros below, P means a pointer to the page, I means an index of the
 * particular entry being accessed.
 *
 * Hash base page format
 * BYTE ITEM			NBYTES 	TYPE		ACCESSOR MACRO
 * ---- ------------------	------	--------	--------------
 * 0	previous page number 	4	db_pgno_t		PREV_PGNO(P)
 * 4	next page number	4	db_pgno_t		NEXT_PGNO(P)
 * 8	# pairs on page		2	indx_t		NUM_ENT(P)
 * 10	page type		1	u_int8_t	TYPE(P)
 * 11	padding			1	u_int8_t	none
 * 12	highest free byte	2	indx_t		OFFSET(P)
 * 14	key offset 0		2	indx_t		KEY_OFF(P, I)
 * 16	data offset 0		2	indx_t		DATA_OFF(P, I)
 * 18	key  offset 1		2	indx_t		KEY_OFF(P, I)
 * 20	data offset 1		2	indx_t		DATA_OFF(P, I)
 * ...etc...
 */

/* Indices (in bytes) of the beginning of each of these entries */
#define I_PREV_PGNO	 0
#define I_NEXT_PGNO	 4
#define I_ENTRIES	 8
#define I_TYPE		10
#define I_HF_OFFSET	12

/* Overhead is everything prior to the first key/data pair. */
#define PAGE_OVERHEAD	(I_HF_OFFSET + sizeof(indx_t))

/* To allocate a pair, we need room for one key offset and one data offset. */
#define PAIR_OVERHEAD	((sizeof(indx_t) << 1))

/* Use this macro to extract a value of type T from page P at offset O. */
#define REFERENCE(P, T, O)  (((T *)(void *)((u_int8_t *)(void *)(P) + O))[0])

/*
 * Use these macros to access fields on a page; P is a PAGE16 *.
 */
#define NUM_ENT(P)	(REFERENCE((P), indx_t, I_ENTRIES))
#define PREV_PGNO(P)	(REFERENCE((P), db_pgno_t, I_PREV_PGNO))
#define NEXT_PGNO(P)	(REFERENCE((P), db_pgno_t, I_NEXT_PGNO))
#define TYPE(P)		(REFERENCE((P), u_int8_t, I_TYPE))
#define OFFSET(P)	(REFERENCE((P), indx_t, I_HF_OFFSET))
/*
 * We need to store a page's own address on each page (unlike the Btree
 * access method which needs the previous page).  We use the PREV_PGNO
 * field to store our own page number.
 */
#define ADDR(P)		(PREV_PGNO((P)))

/* Extract key/data offsets and data for a given index. */
#define DATA_OFF(P, N) \
	REFERENCE(P, indx_t, PAGE_OVERHEAD + N * PAIR_OVERHEAD + sizeof(indx_t))
#define KEY_OFF(P, N) \
	REFERENCE(P, indx_t, PAGE_OVERHEAD + N * PAIR_OVERHEAD)

#define KEY(P, N)	(((PAGE8 *)(P)) + KEY_OFF((P), (N)))
#define DATA(P, N)	(((PAGE8 *)(P)) + DATA_OFF((P), (N)))

/*
 * Macros used to compute various sizes on a page.
 */
#define	PAIRSIZE(K, D)	(PAIR_OVERHEAD + (K)->size + (D)->size)
#define BIGOVERHEAD	(4 * sizeof(u_int16_t))
#define KEYSIZE(K)	(4 * sizeof(u_int16_t) + (K)->size);
#define OVFLSIZE	(2 * sizeof(u_int16_t))
#define BIGPAGEOVERHEAD (4 * sizeof(u_int16_t))
#define BIGPAGEOFFSET   4
#define BIGPAGESIZE(P)	((P)->BSIZE - BIGPAGEOVERHEAD)

#define PAGE_META(N)	(((N) + 3) * sizeof(u_int16_t))
#define MINFILL 0.75
#define ISBIG(N, P)	(((N) > ((P)->hdr.bsize * MINFILL)) ? 1 : 0)

#define ITEMSIZE(I)    (sizeof(u_int16_t) + (I)->size)

/*
 * Big key/data pages use a different page format.  They have a single
 * key/data "pair" containing the length of the key and data instead
 * of offsets.
 */
#define BIGKEYLEN(P)	(KEY_OFF((P), 0))
#define BIGDATALEN(P)	(DATA_OFF((P), 0))
#define BIGKEY(P)	(((PAGE8 *)(P)) + PAGE_OVERHEAD + PAIR_OVERHEAD)
#define BIGDATA(P) \
	(((PAGE8 *)(P)) + PAGE_OVERHEAD + PAIR_OVERHEAD + KEY_OFF((P), 0))

#define OVFLPAGE	0
#define BIGPAIR		0
#define INVALID_PGNO	0xFFFFFFFF

typedef unsigned short PAGE16;
typedef unsigned char  PAGE8;

#define A_BUCKET	0
#define A_OVFL		1
#define A_BITMAP	2
#define A_RAW		4
#define A_HEADER	5

#define PAIRFITS(P,K,D)	((PAIRSIZE((K),(D))) <= FREESPACE((P)))
#define BIGPAIRFITS(P)	((FREESPACE((P)) >= PAIR_OVERHEAD))
/*
 * Since these are all unsigned, we need to guarantee that we never go
 * negative.  Offset values are 0-based and overheads are one based (i.e.
 * one byte of overhead is 1, not 0), so we need to convert OFFSETs to
 * 1-based counting before subtraction.
 */
#define FREESPACE(P) \
	((OFFSET((P)) + 1 - PAGE_OVERHEAD - (NUM_ENT((P)) * PAIR_OVERHEAD)))

/*
 * Overhead on header pages is just one word -- the length of the
 * header info stored on that page.
 */
#define HEADER_OVERHEAD 4

#define HASH_PAGE	2
#define HASH_BIGPAGE	3
#define HASH_OVFLPAGE	4


text:
using NUnit.Framework;
using AOC2021.Day06;
using FluentAssertions;

namespace AocTests
{
    public class Day06Tests
    {
        private static readonly string[] _testInput = new string[]
        {
            "3,4,3,1,2",
        };

        private readonly Puzzle _puzzle = new(_testInput);

        [Test]
        public void Solution1Test()
        {
            _puzzle.Solution1().Should().Be(5934);
        }

        [Test]
        public void Solution2Test()
        {
            _puzzle.Solution2().Should().Be(26984457539);
        }
    }
}


text:
package agouti_test

import (
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/sclevine/agouti"
	"github.com/sclevine/agouti/api"
	. "github.com/sclevine/agouti/internal/matchers"
	"github.com/sclevine/agouti/internal/mocks"
)

var _ = Describe("Selection Frames", func() {
	var (
		selection         *Selection
		session           *mocks.Session
		elementRepository *mocks.ElementRepository
	)

	BeforeEach(func() {
		session = &mocks.Session{}
		elementRepository = &mocks.ElementRepository{}
		selection = NewTestSelection(session, elementRepository, "#selector")
	})

	Describe("#SwitchToFrame", func() {
		var apiElement *api.Element

		BeforeEach(func() {
			apiElement = &api.Element{}
			elementRepository.GetExactlyOneCall.ReturnElement = apiElement
		})

		It("should successfully switch to the frame indicated by the selection", func() {
			Expect(selection.SwitchToFrame()).To(Succeed())
			Expect(session.FrameCall.Frame).To(ExactlyEqual(apiElement))
		})

		Context("when there is an error retrieving exactly one element", func() {
			It("should return an error", func() {
				elementRepository.GetExactlyOneCall.Err = errors.New("some error")
				err := selection.SwitchToFrame()
				Expect(err).To(MatchError("failed to select element from selection 'CSS: #selector [single]': some error"))
			})
		})

		Context("when the session fails to switch frames", func() {
			It("should return an error", func() {
				session.FrameCall.Err = errors.New("some error")
				err := selection.SwitchToFrame()
				Expect(err).To(MatchError("failed to switch to frame referred to by selection 'CSS: #selector [single]': some error"))
			})
		})
	})
})


text:
package com.datagre.apps.omicron.config;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.support.SpringBootServletInitializer;

/**
 * Created by ycaihua on 2017/4/6.
 * https://github.com/ycaihua/omicron
 */
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.sources(ConfigServiceApplication.class);
    }
}


text:
package com.orientechnologies.orient.core.sql.query;

import java.util.ArrayList;
import java.util.List;

import com.orientechnologies.orient.core.command.OCommandResultListener;
import com.orientechnologies.orient.core.db.record.OIdentifiable;
import com.orientechnologies.orient.core.id.ORID;
import com.orientechnologies.orient.core.id.ORecordId;
import com.orientechnologies.orient.core.serialization.OMemoryStream;

/**
 * SQL synchronous query. When executed the caller wait for the result.
 *
 * @author Luca Garulli
 *
 * @param <T>
 * @see OSQLAsynchQuery
 */
@SuppressWarnings({ "unchecked", "serial" })
public class OSQLSynchQuery<T extends Object> extends OSQLAsynchQuery<T> implements OCommandResultListener {
  protected ORID nextPageRID;

	protected final List<T>	result	= new ArrayList<T>();

	public OSQLSynchQuery() {
		resultListener = this;
	}

	public OSQLSynchQuery(final String iText) {
		super(iText);
		resultListener = this;
	}

	public OSQLSynchQuery(final String iText, final int iLimit) {
		super(iText, iLimit, null);
		resultListener = this;
	}

	@Override
	public void reset() {
		result.clear();
	}

	public boolean result(final Object iRecord) {
		result.add((T) iRecord);
		return true;
	}

  @Override
	public List<T> run(Object... iArgs) {
		if (!result.isEmpty()) {
    	result.clear();
		}

		super.run(iArgs);

    if(!result.isEmpty()) {
      final ORID lastRid = ((OIdentifiable)result.get(result.size() - 1)).getIdentity();
      nextPageRID = new ORecordId(lastRid.next());
    }
		return result;
	}

	public Object getResult() {
		return result;
	}

  @Override
  protected OMemoryStream queryToStream() {
    final OMemoryStream buffer =  super.queryToStream();

    buffer.set(nextPageRID != null ? nextPageRID.toString() : "");

    return buffer;
  }

  @Override
  protected void queryFromStream(OMemoryStream buffer) {
    super.queryFromStream(buffer);

    final String rid = buffer.getAsString();
    if ("".equals(rid))
      nextPageRID = null;
    else
      nextPageRID = new ORecordId(rid);
  }

  /**
   * @return RID of the record that will be processed first during pagination mode.
   */
  public ORID getNextPageRID() {
    return nextPageRID;
  }
}


text:
require "stripe_local/engine"
require "stripe_local/webhook"
require "stripe_local/instance_delegation"
require "stripe_local/association_methods"

module StripeLocal
  mattr_accessor :model_class

  def stripe_customer
    include InstanceDelegation
    include AssociationMethods

    has_one :customer,  inverse_of:  :model,
                        foreign_key: :model_id,
                        class_name:  'StripeLocal::Customer'

    StripeLocal::model_class = self
  end
end

ActiveRecord::Base.extend StripeLocal


text:
<?php if($data['galleries']['total']): ?>
<?php $data['galleries']['list'] = array_chunk($data['galleries']['list'], 6); ?>
<?php endif ?>

<?php echo _('Gallery') ?>

	<?php if($data['galleries']['total']): ?>

		<?php foreach($data['galleries']['list'] as $index=>$value): ?>
		<li data-target="#sl_main_gallery" data-slide-to="<?php echo $index ?>" <?php if(!$index): ?>class="active"<?php endif ?>>

		<?php endforeach ?>
		<?php unset($index) ?>
		<?php unset($value) ?>

	<?php endif ?>
	<?php if($data['galleries']['total']): ?>

		<?php foreach($data['galleries']['list'] as $index=>$value): ?>
		<div class="item<?php if(!$index): ?> active<?php endif ?>">
			<?php foreach($value as $index2=>$gallery): ?>
			<?php echo anchor('/galleries/'.$gallery['id'],img(array('src'=>'images/ajax-loader.gif','data-original'=>sl_get_thumb($gallery['photo_url'],'small'),'width'=>100,'height'=>100,'alt'=>$gallery['title'],'class'=>'lazy')),array('class'=>'col-xs-4 col-lg-2')) ?>

				<?php echo anchor('/galleries/'.$gallery['id'],img(array('src'=>sl_get_thumb($gallery['photo_url'],'small'),'width'=>100,'height'=>100,'alt'=>$gallery['title'])),array('class'=>'col-xs-4 col-lg-2')) ?>

			<?php endforeach ?>

	<?php endforeach ?>

	<?php else: ?>

<?php echo _('no_data') ?>

	<?php endif ?>

    Previous

    Next

  <?php echo anchor('galleries',_('more'),array('class'=>'more','title'=>_('more'))) ?>


text:
#include <memory>
#include <string>

#include <ReactCommon/JavaTurboModule.h>
#include <ReactCommon/TurboModule.h>
#include <ReactCommon/TurboModuleManagerDelegate.h>
#include <fbjni/fbjni.h>

namespace facebook {
namespace react {

class DefaultTurboModuleManagerDelegate : public jni::HybridClass<
                                              DefaultTurboModuleManagerDelegate,
                                              TurboModuleManagerDelegate> {
 public:
  static constexpr auto kJavaDescriptor =
      "Lcom/facebook/react/defaults/DefaultTurboModuleManagerDelegate;";

  static jni::local_ref<jhybriddata> initHybrid(jni::alias_ref<jhybridobject>);

  static void registerNatives();

  static std::function<std::shared_ptr<TurboModule>(
      const std::string &,
      const JavaTurboModule::InitParams &)>
      moduleProvidersFromEntryPoint;

  std::shared_ptr<TurboModule> getTurboModule(
      const std::string &name,
      const std::shared_ptr<CallInvoker> &jsInvoker) override;
  std::shared_ptr<TurboModule> getTurboModule(
      const std::string &name,
      const JavaTurboModule::InitParams &params) override;

 private:
  friend HybridBase;
  using HybridBase::HybridBase;
};

} // namespace react
} // namespace facebook


text:
package com.gelvt.gofdp;

import com.gelvt.gofdp.facade.DefaultImageProcessFacade;
import com.gelvt.gofdp.facade.ImageProcessFacade;

import java.io.File;
import java.io.IOException;

/**
 * Desc: Client
 * Author: Elvin Zeng
 * Date: 17-6-21.
 */
public class App {
    public static void main(String[] args) throws IOException,
            InterruptedException {
        ImageProcessFacade imageProcessFacade =
                new DefaultImageProcessFacade(getCurrentUserId());

        for (int i = 0; i < 10; i++){
            System.out.println("--------------------");
            //  创建一张用于测试的"图片"
            File testImage = File.createTempFile("com.gelvt.gofdp.facade.test",
                    ".png");

            imageProcessFacade.scaleImage(testImage, 100, 120);
            imageProcessFacade.watermark(testImage, "My name is Elvin Zeng");
        }
    }

    private static Integer getCurrentUserId(){
        //  这里获取当前登录的用户的用户id
        return 1993;
    }
}


text:
package com.zimbra.cs.service.admin;

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

import com.zimbra.common.service.ServiceException;
import com.zimbra.common.soap.Element;
import com.zimbra.cs.account.Provisioning;
import com.zimbra.cs.account.accesscontrol.AdminRight;
import com.zimbra.cs.account.accesscontrol.Rights.Admin;
import com.zimbra.cs.volume.VolumeManager;
import com.zimbra.soap.JaxbUtil;
import com.zimbra.soap.ZimbraSoapContext;
import com.zimbra.soap.admin.message.DeleteVolumeRequest;
import com.zimbra.soap.admin.message.DeleteVolumeResponse;

public final class DeleteVolume extends AdminDocumentHandler {

    @Override
    public Element handle(Element req, Map<String, Object> ctx) throws ServiceException {
        ZimbraSoapContext zsc = getZimbraSoapContext(ctx);
        return zsc.jaxbToElement(handle((DeleteVolumeRequest) JaxbUtil.elementToJaxb(req), ctx));
    }

    private DeleteVolumeResponse handle(DeleteVolumeRequest req, Map<String, Object> ctx) throws ServiceException {
        ZimbraSoapContext zsc = getZimbraSoapContext(ctx);
        checkRight(zsc, ctx, Provisioning.getInstance().getLocalServer(), Admin.R_manageVolume);

        VolumeManager mgr = VolumeManager.getInstance();
        mgr.getVolume(req.getId()); // make sure the volume exists before doing anything heavyweight...
        mgr.delete(req.getId());
        return new DeleteVolumeResponse();
    }

    @Override
    public void docRights(List<AdminRight> relatedRights, List<String> notes) {
        relatedRights.add(Admin.R_manageVolume);
    }

}


text:
Last updated on 06 November 2022. Check out the `/legacy` folder for earlier versions.

![Passport](passport.png)

### About datasets

There are 6 datasets with identical visa requirements data. Three datasets are matrix and three are long (tidy) format. Each comes in 3 versions: with country codes as specified in ISO-2 (two-letter codes), ISO-3 (three-letter codes), and full country names from no particular standard.

* In distance matrices (files with `matrix` in the filename), the first column represents a passport (=from), each remaining column represents a destination (=to).
* Files in tidy format (with `tidy` in filename) have three columns: passport (from), destination (to), and the requirement.

### Dataset values

For visa-free regimes, the number of days (a positive integer) is specified whenever available. When not available, `visa free` code is used (for example, in the EU countries with the freedom of movement days are not limited).

| Value | Explanation |
|---|---|
|`7`-`360`| Number of visa-free days, where available |
|`visa free`| Visa-free travel (where number of days is unknown or not applicable, such as freedom of movement), including tourist registration requirement for Seychelles|
|`visa on arrival`| Destinations that grant visa on arrival, basically visa-free |
|`e-visa`| Includes  [ESTA](https://esta.cbp.dhs.gov/) (Electronic System for Travel Authorization for the USA) and [eTA](https://www.canada.ca/en/immigration-refugees-citizenship/services/visit-canada/eta.html) (Electronic Travel Authorization for Canada), eVisas, [eVisitors](https://immi.homeaffairs.gov.au/visas/getting-a-visa/visa-listing/evisitor-651) in Australia, [eTourist cards](https://www.surinametourism.sr/tourist-card/) for Suriname, pre-enrollment for Ivory Coast, and UK's [electronic visa waivers](https://www.gov.uk/get-electronic-visa-waiver) |
|`visa required`| Obtaining a visa is required for travel. Includes Cuba's tourist cards |
|`covid ban`| Travelling is banned for most people. This is perhaps the most dynamic category right now, with varying exemptions|
|`no admission`| Includes rare tricky situations, such as war conflicts |
|`Hayya Entry Permit`| Fan ID for the FIFA World Cup 2022 to enter Qatar in Nov-Dec 2022 |
|`-1`| where passport=destination|

### Update data with Jupyter notebook
You should be able to run the Jupyter notebook to update datasets whenever you want.

### Use CLI instead
Check out this [visa-cli](https://github.com/rand-net/visa-cli) tool by [@rand-net](https://github.com/rand-net) to get data for specific countries directly from your terminal.

### Source & License
Since "Passport Index is a free tool, built with publicly available information and with content contributed by fans and government agencies around the world", feel free to use the dataset under the MIT license.

Source: https://www.passportindex.org


text:
using content::BrowserContext;
using content::BrowserMessageFilter;
using content::BrowserThread;
using content::ChildProcessHostImpl;
using content::PluginServiceFilter;
using content::ResourceDispatcherHostImpl;
using content::UserMetricsAction;
using net::CookieStore;

namespace {

const int kPluginsRefreshThresholdInSeconds = 3;

// When two CPU usage queries arrive within this interval, we sample the CPU
// usage only once and send it as a response for both queries.
static const int64 kCPUUsageSampleIntervalMs = 900;

// Common functionality for converting a sync renderer message to a callback
// function in the browser. Derive from this, create it on the heap when
// issuing your callback. When done, write your reply parameters into
// reply_msg(), and then call SendReplyAndDeleteThis().
class RenderMessageCompletionCallback {
 public:
  RenderMessageCompletionCallback(RenderMessageFilter* filter,
                                  IPC::Message* reply_msg)
      : filter_(filter),
        reply_msg_(reply_msg) {
  }

  virtual ~RenderMessageCompletionCallback() {
  }

  RenderMessageFilter* filter() { return filter_.get(); }
  IPC::Message* reply_msg() { return reply_msg_; }

  void SendReplyAndDeleteThis() {
    filter_->Send(reply_msg_);
    delete this;
  }

 private:
  scoped_refptr<RenderMessageFilter> filter_;
  IPC::Message* reply_msg_;
};

class OpenChannelToPpapiPluginCallback
    : public RenderMessageCompletionCallback,
      public PpapiPluginProcessHost::PluginClient {
 public:
  OpenChannelToPpapiPluginCallback(RenderMessageFilter* filter,
                                   content::ResourceContext* context,
                                   IPC::Message* reply_msg)
      : RenderMessageCompletionCallback(filter, reply_msg),
        context_(context) {
  }

  virtual void GetChannelInfo(base::ProcessHandle* renderer_handle,
                              int* renderer_id) {
    *renderer_handle = filter()->peer_handle();
    *renderer_id = filter()->render_process_id();
  }

  virtual void OnChannelOpened(base::ProcessHandle plugin_process_handle,
                               const IPC::ChannelHandle& channel_handle) {
    ViewHostMsg_OpenChannelToPepperPlugin::WriteReplyParams(
        reply_msg(), plugin_process_handle, channel_handle);
    SendReplyAndDeleteThis();
  }

  virtual content::ResourceContext* GetResourceContext() {
    return context_;
  }

 private:
  content::ResourceContext* context_;
};

class OpenChannelToPpapiBrokerCallback
    : public PpapiPluginProcessHost::BrokerClient {
 public:
  OpenChannelToPpapiBrokerCallback(RenderMessageFilter* filter,
                                   int routing_id,
                                   int request_id)
      : filter_(filter),
        routing_id_(routing_id),
        request_id_(request_id) {
  }

  virtual ~OpenChannelToPpapiBrokerCallback() {}

  virtual void GetChannelInfo(base::ProcessHandle* renderer_handle,
                              int* renderer_id) {
    *renderer_handle = filter_->peer_handle();
    *renderer_id = filter_->render_process_id();
  }

  virtual void OnChannelOpened(base::ProcessHandle broker_process_handle,
                               const IPC::ChannelHandle& channel_handle) {
    filter_->Send(new ViewMsg_PpapiBrokerChannelCreated(routing_id_,
                                                        request_id_,
                                                        broker_process_handle,
                                                        channel_handle));
    delete this;
  }

 private:
  scoped_refptr<RenderMessageFilter> filter_;
  int routing_id_;
  int request_id_;
};

}  // namespace

class RenderMessageFilter::OpenChannelToNpapiPluginCallback
    : public RenderMessageCompletionCallback,
      public PluginProcessHost::Client {
 public:
  OpenChannelToNpapiPluginCallback(RenderMessageFilter* filter,
                                   content::ResourceContext* context,
                                   IPC::Message* reply_msg)
      : RenderMessageCompletionCallback(filter, reply_msg),
        context_(context),
        host_(NULL),
        sent_plugin_channel_request_(false) {
  }

  virtual int ID() OVERRIDE {
    return filter()->render_process_id();
  }

  virtual content::ResourceContext* GetResourceContext() OVERRIDE {
    return context_;
  }

  virtual bool OffTheRecord() OVERRIDE {
    if (filter()->OffTheRecord())
      return true;
    if (content::GetContentClient()->browser()->AllowSaveLocalState(context_))
      return false;

    // For now, only disallow storing data for Flash <http://crbug.com/97319>.
    for (size_t i = 0; i < info_.mime_types.size(); ++i) {
      if (info_.mime_types[i].mime_type == kFlashPluginSwfMimeType)
        return true;
    }
    return false;
  }

  virtual void SetPluginInfo(const webkit::WebPluginInfo& info) OVERRIDE {
    info_ = info;
  }

  virtual void OnFoundPluginProcessHost(PluginProcessHost* host) OVERRIDE {
    DCHECK(host);
    host_ = host;
  }

  virtual void OnSentPluginChannelRequest() OVERRIDE {
    sent_plugin_channel_request_ = true;
  }

  virtual void OnChannelOpened(const IPC::ChannelHandle& handle) OVERRIDE {
    WriteReplyAndDeleteThis(handle);
  }

  virtual void OnError() OVERRIDE {
    WriteReplyAndDeleteThis(IPC::ChannelHandle());
  }

  PluginProcessHost* host() const {
    return host_;
  }

  bool sent_plugin_channel_request() const {
    return sent_plugin_channel_request_;
  }

  void Cancel() {
    delete this;
  }

 private:
  void WriteReplyAndDeleteThis(const IPC::ChannelHandle& handle) {
    ViewHostMsg_OpenChannelToPlugin::WriteReplyParams(reply_msg(),
                                                      handle, info_);
    filter()->OnCompletedOpenChannelToNpapiPlugin(this);
    SendReplyAndDeleteThis();
  }

  content::ResourceContext* context_;
  webkit::WebPluginInfo info_;
  PluginProcessHost* host_;
  bool sent_plugin_channel_request_;
};

RenderMessageFilter::RenderMessageFilter(
    int render_process_id,
    PluginServiceImpl* plugin_service,
    content::BrowserContext* browser_context,
    net::URLRequestContextGetter* request_context,
    RenderWidgetHelper* render_widget_helper,
    content::MediaObserver* media_observer)
    : resource_dispatcher_host_(ResourceDispatcherHostImpl::Get()),
      plugin_service_(plugin_service),
      browser_context_(browser_context),
      request_context_(request_context),
      resource_context_(browser_context->GetResourceContext()),
      render_widget_helper_(render_widget_helper),
      incognito_(browser_context->IsOffTheRecord()),
      dom_storage_context_(static_cast<DOMStorageContextImpl*>(
          BrowserContext::GetDOMStorageContext(browser_context))),
      render_process_id_(render_process_id),
      cpu_usage_(0),
      media_observer_(media_observer) {
  DCHECK(request_context_);

  render_widget_helper_->Init(render_process_id_, resource_dispatcher_host_);
}

RenderMessageFilter::~RenderMessageFilter() {
  // This function should be called on the IO thread.
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(plugin_host_clients_.empty());
}

void RenderMessageFilter::OnChannelClosing() {
  BrowserMessageFilter::OnChannelClosing();
  for (std::set<OpenChannelToNpapiPluginCallback*>::iterator it =
       plugin_host_clients_.begin(); it != plugin_host_clients_.end(); ++it) {
    OpenChannelToNpapiPluginCallback* client = *it;
    if (client->host()) {
      if (client->sent_plugin_channel_request()) {
        client->host()->CancelSentRequest(client);
      } else {
        client->host()->CancelPendingRequest(client);
      }
    } else {
      plugin_service_->CancelOpenChannelToNpapiPlugin(client);
    }
    client->Cancel();
  }
  plugin_host_clients_.clear();
}

void RenderMessageFilter::OnChannelConnected(int32 peer_id) {
  BrowserMessageFilter::OnChannelConnected(peer_id);
  base::ProcessHandle handle = peer_handle();
#if defined(OS_MACOSX)
  process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(handle,
                                                                    NULL));
#else
  process_metrics_.reset(base::ProcessMetrics::CreateProcessMetrics(handle));
#endif
  cpu_usage_ = process_metrics_->GetCPUUsage(); // Initialize CPU usage counters
  cpu_usage_sample_time_ = base::TimeTicks::Now();
}

bool RenderMessageFilter::OnMessageReceived(const IPC::Message& message,
                                            bool* message_was_ok) {
  bool handled = true;
  IPC_BEGIN_MESSAGE_MAP_EX(RenderMessageFilter, message, *message_was_ok)
#if defined(OS_WIN) && !defined(USE_AURA)
    // On Windows, we handle these on the IO thread to avoid a deadlock with
    // plugins.  On non-Windows systems, we need to handle them on the UI
    // thread.
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetWindowRect, OnGetWindowRect)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetRootWindowRect, OnGetRootWindowRect)
#endif
    IPC_MESSAGE_HANDLER(ViewHostMsg_GenerateRoutingID, OnGenerateRoutingID)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWindow, OnMsgCreateWindow)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateWidget, OnMsgCreateWidget)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CreateFullscreenWidget,
                        OnMsgCreateFullscreenWidget)
    IPC_MESSAGE_HANDLER(ViewHostMsg_SetCookie, OnSetCookie)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetCookies, OnGetCookies)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetRawCookies, OnGetRawCookies)
    IPC_MESSAGE_HANDLER(ViewHostMsg_DeleteCookie, OnDeleteCookie)
    IPC_MESSAGE_HANDLER(ViewHostMsg_CookiesEnabled, OnCookiesEnabled)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ViewHostMsg_LoadFont, OnLoadFont)
#endif
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_GetPlugins, OnGetPlugins)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetPluginInfo, OnGetPluginInfo)
    IPC_MESSAGE_HANDLER(ViewHostMsg_DownloadUrl, OnDownloadUrl)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_OpenChannelToPlugin,
                                    OnOpenChannelToPlugin)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_OpenChannelToPepperPlugin,
                                    OnOpenChannelToPepperPlugin)
    IPC_MESSAGE_HANDLER(ViewHostMsg_OpenChannelToPpapiBroker,
                        OnOpenChannelToPpapiBroker)
    IPC_MESSAGE_HANDLER_GENERIC(ViewHostMsg_UpdateRect,
        render_widget_helper_->DidReceiveUpdateMsg(message))
    IPC_MESSAGE_HANDLER(ViewHostMsg_UpdateIsDelayed, OnUpdateIsDelayed)
    IPC_MESSAGE_HANDLER(DesktopNotificationHostMsg_CheckPermission,
                        OnCheckNotificationPermission)
    IPC_MESSAGE_HANDLER(ChildProcessHostMsg_SyncAllocateSharedMemory,
                        OnAllocateSharedMemory)
#if defined(OS_MACOSX)
    IPC_MESSAGE_HANDLER(ViewHostMsg_AllocTransportDIB, OnAllocTransportDIB)
    IPC_MESSAGE_HANDLER(ViewHostMsg_FreeTransportDIB, OnFreeTransportDIB)
#endif
    IPC_MESSAGE_HANDLER(ViewHostMsg_DidGenerateCacheableMetadata,
                        OnCacheableMetadataAvailable)
    IPC_MESSAGE_HANDLER_DELAY_REPLY(ViewHostMsg_Keygen, OnKeygen)
    IPC_MESSAGE_HANDLER(ViewHostMsg_AsyncOpenFile, OnAsyncOpenFile)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetCPUUsage, OnGetCPUUsage)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetHardwareBufferSize,
                        OnGetHardwareBufferSize)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetHardwareInputSampleRate,
                        OnGetHardwareInputSampleRate)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetHardwareSampleRate,
                        OnGetHardwareSampleRate)
    IPC_MESSAGE_HANDLER(ViewHostMsg_GetHardwareInputChannelLayout,
                        OnGetHardwareInputChannelLayout)
    IPC_MESSAGE_HANDLER(ViewHostMsg_MediaLogEvent, OnMediaLogEvent)
    IPC_MESSAGE_UNHANDLED(handled = false)
  IPC_END_MESSAGE_MAP_EX()

  return handled;
}

void RenderMessageFilter::OnDestruct() const {
  BrowserThread::DeleteOnIOThread::Destruct(this);
}

bool RenderMessageFilter::OffTheRecord() const {
  return incognito_;
}

void RenderMessageFilter::OnMsgCreateWindow(
    const ViewHostMsg_CreateWindow_Params& params,
    int* route_id,
    int* surface_id,
    int64* cloned_session_storage_namespace_id) {
  if (!content::GetContentClient()->browser()->CanCreateWindow(
          GURL(params.opener_url), GURL(params.opener_security_origin),
          params.window_container_type, resource_context_,
          render_process_id_)) {
    *route_id = MSG_ROUTING_NONE;
    *surface_id = 0;
    return;
  }

#ifdef ENABLE_NEW_DOM_STORAGE_BACKEND
  // TODO(michaeln): Fix this.
  // This is a bug in the existing impl, session storage is effectively
  // leaked when created thru this code path (window.open()) since there
  // is no balancing DeleteSessionStorage() for this Clone() call anywhere
  // in the codebase. I'm replicating the bug for now.
  *cloned_session_storage_namespace_id =
      dom_storage_context_->LeakyCloneSessionStorage(
          params.session_storage_namespace_id);
#else
  *cloned_session_storage_namespace_id =
      dom_storage_context_->CloneSessionStorage(
          params.session_storage_namespace_id);
#endif

  render_widget_helper_->CreateNewWindow(params,
                                         peer_handle(),
                                         route_id,
                                         surface_id);
}

void RenderMessageFilter::OnMsgCreateWidget(int opener_id,
                                            WebKit::WebPopupType popup_type,
                                            int* route_id,
                                            int* surface_id) {
  render_widget_helper_->CreateNewWidget(
      opener_id, popup_type, route_id, surface_id);
}

void RenderMessageFilter::OnMsgCreateFullscreenWidget(int opener_id,
                                                      int* route_id,
                                                      int* surface_id) {
  render_widget_helper_->CreateNewFullscreenWidget(
      opener_id, route_id, surface_id);
}

void RenderMessageFilter::OnSetCookie(const IPC::Message& message,
                                      const GURL& url,
                                      const GURL& first_party_for_cookies,
                                      const std::string& cookie) {
  ChildProcessSecurityPolicyImpl* policy =
      ChildProcessSecurityPolicyImpl::GetInstance();
  if (!policy->CanUseCookiesForOrigin(render_process_id_, url))
    return;

  net::CookieOptions options;
  if (content::GetContentClient()->browser()->AllowSetCookie(
          url, first_party_for_cookies, cookie,
          resource_context_, render_process_id_, message.routing_id(),
          &options)) {
    net::URLRequestContext* context = GetRequestContextForURL(url);
    // Pass a null callback since we don't care about when the 'set' completes.
    context->cookie_store()->SetCookieWithOptionsAsync(
        url, cookie, options, net::CookieMonster::SetCookiesCallback());
  }
}

void RenderMessageFilter::OnGetCookies(const GURL& url,
                                       const GURL& first_party_for_cookies,
                                       IPC::Message* reply_msg) {
  ChildProcessSecurityPolicyImpl* policy =
      ChildProcessSecurityPolicyImpl::GetInstance();
  if (!policy->CanUseCookiesForOrigin(render_process_id_, url)) {
    SendGetCookiesResponse(reply_msg, std::string());
    return;
  }

  // If we crash here, figure out what URL the renderer was requesting.
  // http://crbug.com/99242
  char url_buf[128];
  base::strlcpy(url_buf, url.spec().c_str(), arraysize(url_buf));
  base::debug::Alias(url_buf);

  net::URLRequestContext* context = GetRequestContextForURL(url);
  net::CookieMonster* cookie_monster =
      context->cookie_store()->GetCookieMonster();
  cookie_monster->GetAllCookiesForURLAsync(
      url, base::Bind(&RenderMessageFilter::CheckPolicyForCookies, this, url,
                      first_party_for_cookies, reply_msg));
}

void RenderMessageFilter::OnGetRawCookies(
    const GURL& url,
    const GURL& first_party_for_cookies,
    IPC::Message* reply_msg) {
  ChildProcessSecurityPolicyImpl* policy =
      ChildProcessSecurityPolicyImpl::GetInstance();
  // Only return raw cookies to trusted renderers or if this request is
  // not targeted to an an external host like ChromeFrame.
  // TODO(ananta) We need to support retreiving raw cookies from external
  // hosts.
  if (!policy->CanReadRawCookies(render_process_id_) ||
      !policy->CanUseCookiesForOrigin(render_process_id_, url)) {
    SendGetRawCookiesResponse(reply_msg, net::CookieList());
    return;
  }

  // We check policy here to avoid sending back cookies that would not normally
  // be applied to outbound requests for the given URL.  Since this cookie info
  // is visible in the developer tools, it is helpful to make it match reality.
  net::URLRequestContext* context = GetRequestContextForURL(url);
  net::CookieMonster* cookie_monster =
      context->cookie_store()->GetCookieMonster();
  cookie_monster->GetAllCookiesForURLAsync(
      url, base::Bind(&RenderMessageFilter::SendGetRawCookiesResponse,
                      this, reply_msg));
}

void RenderMessageFilter::OnDeleteCookie(const GURL& url,
                                         const std::string& cookie_name) {
  ChildProcessSecurityPolicyImpl* policy =
      ChildProcessSecurityPolicyImpl::GetInstance();
  if (!policy->CanUseCookiesForOrigin(render_process_id_, url))
    return;

  net::URLRequestContext* context = GetRequestContextForURL(url);
  context->cookie_store()->DeleteCookieAsync(url, cookie_name, base::Closure());
}

void RenderMessageFilter::OnCookiesEnabled(
    const GURL& url,
    const GURL& first_party_for_cookies,
    bool* cookies_enabled) {
  // TODO(ananta): If this render view is associated with an automation channel,
  // aka ChromeFrame then we need to retrieve cookie settings from the external
  // host.
  *cookies_enabled = content::GetContentClient()->browser()->AllowGetCookie(
      url, first_party_for_cookies, net::CookieList(), resource_context_,
      render_process_id_, MSG_ROUTING_CONTROL);
}

#if defined(OS_MACOSX)
void RenderMessageFilter::OnLoadFont(const FontDescriptor& font,
                                     uint32* handle_size,
                                     base::SharedMemoryHandle* handle,
                                     uint32* font_id) {
  base::SharedMemory font_data;
  uint32 font_data_size = 0;
  bool ok = FontLoader::LoadFontIntoBuffer(font.ToNSFont(), &font_data,
                &font_data_size, font_id);
  if (!ok || font_data_size == 0 || *font_id == 0) {
    LOG(ERROR) << "Couldn't load font data for " << font.font_name <<
        " ok=" << ok << " font_data_size=" << font_data_size <<
        " font id=" << *font_id;
    *handle_size = 0;
    *handle = base::SharedMemory::NULLHandle();
    *font_id = 0;
    return;
  }

  *handle_size = font_data_size;
  font_data.GiveToProcess(base::GetCurrentProcessHandle(), handle);
}
#endif  // OS_MACOSX

void RenderMessageFilter::OnGetPlugins(
    bool refresh,
    IPC::Message* reply_msg) {
  // Don't refresh if the specified threshold has not been passed.  Note that
  // this check is performed before off-loading to the file thread.  The reason
  // we do this is that some pages tend to request that the list of plugins be
  // refreshed at an excessive rate.  This instigates disk scanning, as the list
  // is accumulated by doing multiple reads from disk.  This effect is
  // multiplied when we have several pages requesting this operation.
  if (refresh) {
    const base::TimeDelta threshold = base::TimeDelta::FromSeconds(
        kPluginsRefreshThresholdInSeconds);
    const base::TimeTicks now = base::TimeTicks::Now();
    if (now - last_plugin_refresh_time_ >= threshold) {
      // Only refresh if the threshold hasn't been exceeded yet.
      PluginServiceImpl::GetInstance()->RefreshPlugins();
      last_plugin_refresh_time_ = now;
    }
  }

  PluginServiceImpl::GetInstance()->GetPlugins(
      base::Bind(&RenderMessageFilter::GetPluginsCallback, this, reply_msg));
}

void RenderMessageFilter::GetPluginsCallback(
    IPC::Message* reply_msg,
    const std::vector<webkit::WebPluginInfo>& all_plugins) {
  // Filter the plugin list.
  content::PluginServiceFilter* filter =
      PluginServiceImpl::GetInstance()->GetFilter();
  std::vector<webkit::WebPluginInfo> plugins;

  int child_process_id = -1;
  int routing_id = MSG_ROUTING_NONE;
  for (size_t i = 0; i < all_plugins.size(); ++i) {
    // Copy because the filter can mutate.
    webkit::WebPluginInfo plugin(all_plugins[i]);
    if (!filter || filter->ShouldUsePlugin(child_process_id,
                                           routing_id,
                                           resource_context_,
                                           GURL(),
                                           GURL(),
                                           &plugin)) {
      plugins.push_back(plugin);
    }
  }

  ViewHostMsg_GetPlugins::WriteReplyParams(reply_msg, plugins);
  Send(reply_msg);
}

void RenderMessageFilter::OnGetPluginInfo(
    int routing_id,
    const GURL& url,
    const GURL& page_url,
    const std::string& mime_type,
    bool* found,
    webkit::WebPluginInfo* info,
    std::string* actual_mime_type) {
  bool allow_wildcard = true;
  *found = plugin_service_->GetPluginInfo(
      render_process_id_, routing_id, resource_context_,
      url, page_url, mime_type, allow_wildcard,
      NULL, info, actual_mime_type);
}

void RenderMessageFilter::OnOpenChannelToPlugin(int routing_id,
                                                const GURL& url,
                                                const GURL& policy_url,
                                                const std::string& mime_type,
                                                IPC::Message* reply_msg) {
  OpenChannelToNpapiPluginCallback* client =
      new OpenChannelToNpapiPluginCallback(this, resource_context_, reply_msg);
  DCHECK(!ContainsKey(plugin_host_clients_, client));
  plugin_host_clients_.insert(client);
  plugin_service_->OpenChannelToNpapiPlugin(
      render_process_id_, routing_id,
      url, policy_url, mime_type, client);
}

void RenderMessageFilter::OnOpenChannelToPepperPlugin(
    const FilePath& path,
    IPC::Message* reply_msg) {
  plugin_service_->OpenChannelToPpapiPlugin(
      path,
      new OpenChannelToPpapiPluginCallback(
          this, resource_context_, reply_msg));
}

void RenderMessageFilter::OnOpenChannelToPpapiBroker(int routing_id,
                                                     int request_id,
                                                     const FilePath& path) {
  plugin_service_->OpenChannelToPpapiBroker(
      path, new OpenChannelToPpapiBrokerCallback(this, routing_id, request_id));
}

void RenderMessageFilter::OnGenerateRoutingID(int* route_id) {
  *route_id = render_widget_helper_->GetNextRoutingID();
}

void RenderMessageFilter::OnGetCPUUsage(int* cpu_usage) {
  base::TimeTicks now = base::TimeTicks::Now();
  int64 since_last_sample_ms = (now - cpu_usage_sample_time_).InMilliseconds();
  if (since_last_sample_ms > kCPUUsageSampleIntervalMs) {
    cpu_usage_sample_time_ = now;
    cpu_usage_ = static_cast<int>(process_metrics_->GetCPUUsage());
  }
  *cpu_usage = cpu_usage_;
}

void RenderMessageFilter::OnGetHardwareBufferSize(uint32* buffer_size) {
  *buffer_size = static_cast<uint32>(media::GetAudioHardwareBufferSize());
}

void RenderMessageFilter::OnGetHardwareInputSampleRate(int* sample_rate) {
  // TODO(henrika): add support for all available input devices.
  *sample_rate = media::GetAudioInputHardwareSampleRate(
      AudioManagerBase::kDefaultDeviceId);
}

void RenderMessageFilter::OnGetHardwareSampleRate(int* sample_rate) {
  *sample_rate = media::GetAudioHardwareSampleRate();
}

void RenderMessageFilter::OnGetHardwareInputChannelLayout(
    ChannelLayout* layout) {
  // TODO(henrika): add support for all available input devices.
  *layout = media::GetAudioInputHardwareChannelLayout(
      AudioManagerBase::kDefaultDeviceId);
}

void RenderMessageFilter::OnDownloadUrl(const IPC::Message& message,
                                        const GURL& url,
                                        const GURL& referrer,
                                        const string16& suggested_name) {
  content::DownloadSaveInfo save_info;
  save_info.suggested_name = suggested_name;
  scoped_ptr<net::URLRequest> request(new net::URLRequest(url, NULL));
  request->set_referrer(referrer.spec());
  download_stats::RecordDownloadSource(download_stats::INITIATED_BY_RENDERER);
  resource_dispatcher_host_->BeginDownload(
      request.Pass(),
      resource_context_,
      render_process_id_,
      message.routing_id(),
      false,
      save_info,
      ResourceDispatcherHostImpl::DownloadStartedCallback());
}

void RenderMessageFilter::OnCheckNotificationPermission(
    const GURL& source_origin, int* result) {
  *result = content::GetContentClient()->browser()->
      CheckDesktopNotificationPermission(source_origin, resource_context_,
                                         render_process_id_);
}

void RenderMessageFilter::OnAllocateSharedMemory(
    uint32 buffer_size,
    base::SharedMemoryHandle* handle) {
  ChildProcessHostImpl::AllocateSharedMemory(
      buffer_size, peer_handle(), handle);
}

net::URLRequestContext* RenderMessageFilter::GetRequestContextForURL(
    const GURL& url) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  net::URLRequestContext* context =
      content::GetContentClient()->browser()->OverrideRequestContextForURL(
          url, resource_context_);
  if (!context)
    context = request_context_->GetURLRequestContext();

  return context;
}

#if defined(OS_MACOSX)
void RenderMessageFilter::OnAllocTransportDIB(
    size_t size, bool cache_in_browser, TransportDIB::Handle* handle) {
  render_widget_helper_->AllocTransportDIB(size, cache_in_browser, handle);
}

void RenderMessageFilter::OnFreeTransportDIB(
    TransportDIB::Id dib_id) {
  render_widget_helper_->FreeTransportDIB(dib_id);
}
#endif

bool RenderMessageFilter::CheckPreparsedJsCachingEnabled() const {
  static bool checked = false;
  static bool result = false;
  if (!checked) {
    const CommandLine& command_line = *CommandLine::ForCurrentProcess();
    result = command_line.HasSwitch(switches::kEnablePreparsedJsCaching);
    checked = true;
  }
  return result;
}

void RenderMessageFilter::OnCacheableMetadataAvailable(
    const GURL& url,
    double expected_response_time,
    const std::vector<char>& data) {
  if (!CheckPreparsedJsCachingEnabled())
    return;

  net::HttpCache* cache = request_context_->GetURLRequestContext()->
      http_transaction_factory()->GetCache();
  DCHECK(cache);

  scoped_refptr<net::IOBuffer> buf(new net::IOBuffer(data.size()));
  memcpy(buf->data(), &data.front(), data.size());
  cache->WriteMetadata(
      url, base::Time::FromDoubleT(expected_response_time), buf, data.size());
}

void RenderMessageFilter::OnKeygen(uint32 key_size_index,
                                   const std::string& challenge_string,
                                   const GURL& url,
                                   IPC::Message* reply_msg) {
  // Map displayed strings indicating level of keysecurity in the <keygen>
  // menu to the key size in bits. (See SSLKeyGeneratorChromium.cpp in WebCore.)
  int key_size_in_bits;
  switch (key_size_index) {
    case 0:
      key_size_in_bits = 2048;
      break;
    case 1:
      key_size_in_bits = 1024;
      break;
    default:
      DCHECK(false) << "Illegal key_size_index " << key_size_index;
      ViewHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
      Send(reply_msg);
      return;
  }

  VLOG(1) << "Dispatching keygen task to worker pool.";
  // Dispatch to worker pool, so we do not block the IO thread.
  if (!base::WorkerPool::PostTask(
           FROM_HERE,
           base::Bind(
               &RenderMessageFilter::OnKeygenOnWorkerThread, this,
               key_size_in_bits, challenge_string, url, reply_msg),
           true)) {
    NOTREACHED() << "Failed to dispatch keygen task to worker pool";
    ViewHostMsg_Keygen::WriteReplyParams(reply_msg, std::string());
    Send(reply_msg);
    return;
  }
}

void RenderMessageFilter::OnKeygenOnWorkerThread(
    int key_size_in_bits,
    const std::string& challenge_string,
    const GURL& url,
    IPC::Message* reply_msg) {
  DCHECK(reply_msg);

  // Generate a signed public key and challenge, then send it back.
  net::KeygenHandler keygen_handler(key_size_in_bits, challenge_string, url);

#if defined(USE_NSS)
  // Attach a password delegate so we can authenticate.
  keygen_handler.set_crypto_module_password_delegate(
      content::GetContentClient()->browser()->GetCryptoPasswordDelegate(url));
#endif  // defined(USE_NSS)

  ViewHostMsg_Keygen::WriteReplyParams(
      reply_msg,
      keygen_handler.GenKeyAndSignChallenge());
  Send(reply_msg);
}

void RenderMessageFilter::OnAsyncOpenFile(const IPC::Message& msg,
                                          const FilePath& path,
                                          int flags,
                                          int message_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (!ChildProcessSecurityPolicyImpl::GetInstance()->HasPermissionsForFile(
          render_process_id_, path, flags)) {
    DLOG(ERROR) << "Bad flags in ViewMsgHost_AsyncOpenFile message: " << flags;
    content::RecordAction(UserMetricsAction("BadMessageTerminate_AOF"));
    BadMessageReceived();
    return;
  }

  BrowserThread::PostTask(
      BrowserThread::FILE, FROM_HERE, base::Bind(
          &RenderMessageFilter::AsyncOpenFileOnFileThread, this,
          path, flags, message_id, msg.routing_id()));
}

void RenderMessageFilter::AsyncOpenFileOnFileThread(const FilePath& path,
                                                    int flags,
                                                    int message_id,
                                                    int routing_id) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE));
  base::PlatformFileError error_code = base::PLATFORM_FILE_OK;
  base::PlatformFile file = base::CreatePlatformFile(
      path, flags, NULL, &error_code);
  IPC::PlatformFileForTransit file_for_transit =
      file != base::kInvalidPlatformFileValue ?
          IPC::GetFileHandleForProcess(file, peer_handle(), true) :
          IPC::InvalidPlatformFileForTransit();

  IPC::Message* reply = new ViewMsg_AsyncOpenFile_ACK(
      routing_id, error_code, file_for_transit, message_id);
  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(base::IgnoreResult(&RenderMessageFilter::Send), this, reply));
}

void RenderMessageFilter::OnMediaLogEvent(const media::MediaLogEvent& event) {
  if (media_observer_)
    media_observer_->OnMediaEvent(render_process_id_, event);
}

void RenderMessageFilter::CheckPolicyForCookies(
    const GURL& url,
    const GURL& first_party_for_cookies,
    IPC::Message* reply_msg,
    const net::CookieList& cookie_list) {
  net::URLRequestContext* context = GetRequestContextForURL(url);
  // Check the policy for get cookies, and pass cookie_list to the
  // TabSpecificContentSetting for logging purose.
  if (content::GetContentClient()->browser()->AllowGetCookie(
          url, first_party_for_cookies, cookie_list, resource_context_,
          render_process_id_, reply_msg->routing_id())) {
    // Gets the cookies from cookie store if allowed.
    context->cookie_store()->GetCookiesWithOptionsAsync(
        url, net::CookieOptions(),
        base::Bind(&RenderMessageFilter::SendGetCookiesResponse,
                   this, reply_msg));
  } else {
    SendGetCookiesResponse(reply_msg, std::string());
  }
}

void RenderMessageFilter::SendGetCookiesResponse(IPC::Message* reply_msg,
                                                 const std::string& cookies) {
  ViewHostMsg_GetCookies::WriteReplyParams(reply_msg, cookies);
  Send(reply_msg);
}

void RenderMessageFilter::SendGetRawCookiesResponse(
    IPC::Message* reply_msg,
    const net::CookieList& cookie_list) {
  std::vector<webkit_glue::WebCookie> cookies;
  for (size_t i = 0; i < cookie_list.size(); ++i)
    cookies.push_back(webkit_glue::WebCookie(cookie_list[i]));
  ViewHostMsg_GetRawCookies::WriteReplyParams(reply_msg, cookies);
  Send(reply_msg);
}

void RenderMessageFilter::OnCompletedOpenChannelToNpapiPlugin(
    OpenChannelToNpapiPluginCallback* client) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  DCHECK(ContainsKey(plugin_host_clients_, client));
  plugin_host_clients_.erase(client);
}

void RenderMessageFilter::OnUpdateIsDelayed(const IPC::Message& msg) {
  // When not in accelerated compositing mode, in certain cases (e.g. waiting
  // for a resize or if no backing store) the RenderWidgetHost is blocking the
  // UI thread for some time, waiting for an UpdateRect from the renderer. If we
  // are going to switch to accelerated compositing, the GPU process may need
  // round-trips to the UI thread before finishing the frame, causing deadlocks
  // if we delay the UpdateRect until we receive the OnSwapBuffersComplete. So
  // the renderer sent us this message, so that we can unblock the UI thread.
  // We will simply re-use the UpdateRect unblock mechanism, just with a
  // different message.
  render_widget_helper_->DidReceiveUpdateMsg(msg);
}


text:
//
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//

//
// Win32 Resource extractor
//
#include "ildasmpch.h"

#include "debugmacros.h"
#include "corpriv.h"
#include "dasmenum.hpp"
#include "dasmgui.h"
#include "formattype.h"
#include "dis.h"
#include "resource.h"
#include "ilformatter.h"
#include "outstring.h"

#include "ceeload.h"
#include "dynamicarray.h"
extern IMAGE_COR20_HEADER *    g_CORHeader;
extern IMDInternalImport*      g_pImport;
extern PELoader * g_pPELoader;
extern IMetaDataImport2*        g_pPubImport;
extern char g_szAsmCodeIndent[];
extern unsigned g_uConsoleCP;

struct ResourceHeader
{
    DWORD   dwDataSize;
    DWORD   dwHeaderSize;
    DWORD   dwTypeID;
    DWORD   dwNameID;
    DWORD   dwDataVersion;
    WORD    wMemFlags;
    WORD    wLangID;
    DWORD   dwVersion;
    DWORD   dwCharacteristics;
    ResourceHeader()
    {
        memset(this,0,sizeof(ResourceHeader));
        dwHeaderSize = sizeof(ResourceHeader);
        dwTypeID = dwNameID = 0xFFFF;
    };
};

struct ResourceNode
{
    ResourceHeader  ResHdr;
    IMAGE_RESOURCE_DATA_ENTRY DataEntry;
    WCHAR* wzType;
    WCHAR* wzName;
    ResourceNode(DWORD tid, DWORD nid, DWORD lid, DWORD dataOffset, BYTE* ptrBase)
    {
        if(tid & 0x80000000)
        {
            ResHdr.dwTypeID = 0;
            tid &= 0x7FFFFFFF;
            WORD L = *((WORD*)(ptrBase+tid));
            wzType = new WCHAR[L+1];
            memcpy(wzType,ptrBase+tid+sizeof(WORD),L*sizeof(WCHAR));
            wzType[L]=0;
        }
        else
        {
            ResHdr.dwTypeID = (0xFFFF |((tid & 0xFFFF)<<16));
            wzType = NULL;
        }

        if(nid & 0x80000000)
        {
            ResHdr.dwNameID = 0;
            nid &= 0x7FFFFFFF;
            WORD L = *((WORD*)(ptrBase+nid));
            wzName = new WCHAR[L+1];
            memcpy(wzName, ptrBase+nid+sizeof(WORD), L*sizeof(WCHAR));
            wzName[L]=0;
        }
        else
        {
            ResHdr.dwNameID = (0xFFFF |((nid & 0xFFFF)<<16));
            wzName = NULL;
        }

        //ResHdr.dwTypeID = (tid & 0x80000000) ? tid : (0xFFFF |((tid & 0xFFFF)<<16));
        //ResHdr.dwNameID = (nid & 0x80000000) ? nid : (0xFFFF |((nid & 0xFFFF)<<16));
        ResHdr.wLangID = (WORD)lid;
        if(ptrBase) memcpy(&DataEntry,(ptrBase+dataOffset),sizeof(IMAGE_RESOURCE_DATA_ENTRY));
        ResHdr.dwDataSize = DataEntry.Size;
    };
    ~ResourceNode()
    {
        if(wzType) VDELETE(wzType);
        if(wzName) VDELETE(wzName);
    };
    void Save(FILE* pF)
    {
        // Dump them to pF
        BYTE* pbData;
        DWORD   dwFiller = 0;
        BYTE    bNil[3] = {0,0,0};
        // For each resource write header and data
        if(g_pPELoader->getVAforRVA(VAL32(DataEntry.OffsetToData), (void **) &pbData))
        {
            //fwrite(&(g_prResNodePtr[i]->ResHdr),g_prResNodePtr[i]->ResHdr.dwHeaderSize,1,pF);
            ResHdr.dwHeaderSize = sizeof(ResourceHeader);
            if(wzType) ResHdr.dwHeaderSize += (DWORD)((wcslen(wzType) + 1)*sizeof(WCHAR) - sizeof(DWORD));
            if(wzName) ResHdr.dwHeaderSize += (DWORD)((wcslen(wzName) + 1)*sizeof(WCHAR) - sizeof(DWORD));

            //---- Constant part of the header: DWORD,DWORD
            fwrite(&ResHdr.dwDataSize, sizeof(DWORD),1,pF);
            fwrite(&ResHdr.dwHeaderSize, sizeof(DWORD),1,pF);
            //--- Variable part of header: type and name
            if(wzType)
            {
                fwrite(wzType,(wcslen(wzType) + 1)*sizeof(WCHAR), 1, pF);
                dwFiller += (DWORD)wcslen(wzType) + 1;
            }
            else
                fwrite(&ResHdr.dwTypeID,sizeof(DWORD),1,pF);
            if(wzName)
            {
                fwrite(wzName,(wcslen(wzName) + 1)*sizeof(WCHAR), 1, pF);
                dwFiller += (DWORD)wcslen(wzName) + 1;
            }
            else
                fwrite(&ResHdr.dwNameID,sizeof(DWORD),1,pF);

            // Align remaining fields on DWORD
            if(dwFiller & 1)
                fwrite(bNil,2,1,pF);

            //---- Constant part of the header: DWORD,WORD,WORD,DWORD,DWORD
            fwrite(&ResHdr.dwDataVersion,8*sizeof(WORD),1,pF);
            //---- Header done, now data
            fwrite(pbData,VAL32(DataEntry.Size),1,pF);
            dwFiller = VAL32(DataEntry.Size) & 3;
            if(dwFiller)
            {
                dwFiller = 4 - dwFiller;
                fwrite(bNil,dwFiller,1,pF);
            }
        }
    };
};

#define RES_FILE_DUMP_ENABLED

DWORD   DumpResourceToFile(__in __nullterminated WCHAR*   wzFileName)
{

    BYTE*   pbResBase;
    FILE*   pF = NULL;
    DWORD ret = 0;
    DWORD   dwResDirRVA;
    DWORD   dwResDirSize;
    unsigned ulNumResNodes=0;
    DynamicArray<ResourceNode*> g_prResNodePtr;

    if (g_pPELoader->IsPE32())
    {
        IMAGE_OPTIONAL_HEADER32 *pOptHeader = &(g_pPELoader->ntHeaders32()->OptionalHeader);

        dwResDirRVA = VAL32(pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
        dwResDirSize = VAL32(pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
    }
    else
    {
        IMAGE_OPTIONAL_HEADER64 *pOptHeader = &(g_pPELoader->ntHeaders64()->OptionalHeader);

        dwResDirRVA = VAL32(pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].VirtualAddress);
        dwResDirSize = VAL32(pOptHeader->DataDirectory[IMAGE_DIRECTORY_ENTRY_RESOURCE].Size);
    }

    if(dwResDirRVA && dwResDirSize)
    {
        if(g_pPELoader->getVAforRVA(dwResDirRVA, (void **) &pbResBase))
        {
            // First, pull out all resource nodes (tree leaves), see ResourceNode struct
            PIMAGE_RESOURCE_DIRECTORY pirdType = (PIMAGE_RESOURCE_DIRECTORY)pbResBase;
            PIMAGE_RESOURCE_DIRECTORY_ENTRY pirdeType = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pbResBase+sizeof(IMAGE_RESOURCE_DIRECTORY));
            DWORD	dwTypeID;
            unsigned short i = 0,N = pirdType->NumberOfNamedEntries+pirdType->NumberOfIdEntries;
            PAL_CPP_TRY {
                for(i=0; i < N; i++, pirdeType++)
                {
                    dwTypeID = VAL32(IMAGE_RDE_NAME(pirdeType));
                    if(IMAGE_RDE_OFFSET_FIELD(pirdeType, DataIsDirectory))
                    {
                        BYTE*   pbNameBase = pbResBase + VAL32(IMAGE_RDE_OFFSET_FIELD(pirdeType, OffsetToDirectory));
                        PIMAGE_RESOURCE_DIRECTORY pirdName = (PIMAGE_RESOURCE_DIRECTORY)pbNameBase;
                        PIMAGE_RESOURCE_DIRECTORY_ENTRY pirdeName = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pbNameBase+sizeof(IMAGE_RESOURCE_DIRECTORY));
                        DWORD   dwNameID;
                        unsigned short i,N = VAL16(pirdName->NumberOfNamedEntries)+VAL16(pirdName->NumberOfIdEntries);

                        for(i=0; i < N; i++, pirdeName++)
                        {
                            dwNameID = VAL32(IMAGE_RDE_NAME(pirdeName));
                            if(IMAGE_RDE_OFFSET_FIELD(pirdeName, DataIsDirectory))
                            {
                                BYTE*   pbLangBase = pbResBase + VAL32(IMAGE_RDE_OFFSET_FIELD(pirdeName, OffsetToDirectory));
                                PIMAGE_RESOURCE_DIRECTORY pirdLang = (PIMAGE_RESOURCE_DIRECTORY)pbLangBase;
                                PIMAGE_RESOURCE_DIRECTORY_ENTRY pirdeLang = (PIMAGE_RESOURCE_DIRECTORY_ENTRY)(pbLangBase+sizeof(IMAGE_RESOURCE_DIRECTORY));
                                DWORD   dwLangID;
                                unsigned short i,N = VAL16(pirdLang->NumberOfNamedEntries)+VAL16(pirdLang->NumberOfIdEntries);

                                for(i=0; i < N; i++, pirdeLang++)
                                {
                                    dwLangID = VAL32(IMAGE_RDE_NAME(pirdeLang));
                                    if(IMAGE_RDE_OFFSET_FIELD(pirdeLang, DataIsDirectory))
                                    {
                                        _ASSERTE(!"Resource hierarchy exceeds three levels");
                                    }
                                    else
                                    {
                                        g_prResNodePtr[ulNumResNodes++] = new ResourceNode(dwTypeID,dwNameID,dwLangID, VAL32(IMAGE_RDE_OFFSET(pirdeLang)),pbResBase);
                                    }
                                }
                            }
                            else
                            {
                                g_prResNodePtr[ulNumResNodes++] = new ResourceNode(dwTypeID,dwNameID,0,VAL32(IMAGE_RDE_OFFSET(pirdeName)),pbResBase);
                            }
                        }
                    }
                    else
                    {
                        g_prResNodePtr[ulNumResNodes++] = new ResourceNode(dwTypeID,0,0,VAL32(IMAGE_RDE_OFFSET(pirdeType)),pbResBase);
                    }
                }
            } PAL_CPP_CATCH_ALL {
                ret= 0xDFFFFFFF;
                ulNumResNodes = 0;
            }
            PAL_CPP_ENDTRY
            // OK, all tree leaves are in ResourceNode structs, and ulNumResNodes ptrs are in g_prResNodePtr
            if(ulNumResNodes)
            {
                ret = 1;
#ifdef RES_FILE_DUMP_ENABLED

                _wfopen_s(&pF,wzFileName,L"wb");
                if(pF)
                {
                    // Dump them to pF
                    // Write dummy header
                    ResourceHeader  *pRH = new ResourceHeader();
                    fwrite(pRH,sizeof(ResourceHeader),1,pF);
                    SDELETE(pRH);
                    // For each resource write header and data
                    PAL_CPP_TRY {
                        for(i=0; i < ulNumResNodes; i++)
                        {
                            /*
                            sprintf_s(szString,SZSTRING_SIZE,"// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
                                i+1,
                                g_prResNodePtr[i]->ResHdr.dwTypeID,
                                g_prResNodePtr[i]->ResHdr.dwNameID,
                                g_prResNodePtr[i]->ResHdr.wLangID,
                                VAL32(g_prResNodePtr[i]->DataEntry.OffsetToData),
                                VAL32(g_prResNodePtr[i]->DataEntry.Size));
                            printLine(NULL,szString);
                            */
                            g_prResNodePtr[i]->Save(pF);
                            SDELETE(g_prResNodePtr[i]);
                        }
                    }
                    PAL_CPP_CATCH_ALL {
                        ret= 0xDFFFFFFF;
                    }
                    PAL_CPP_ENDTRY
                    fclose(pF);
                }// end if file opened
                else ret = 0xEFFFFFFF;
#else
                // Dump to text, using wzFileName as GUICookie
                //char szString[4096];
                void* GUICookie = (void*)wzFileName;
                BYTE* pbData;
                printLine(GUICookie,"");
                sprintf(szString,"// ========== Win32 Resource Entries (%d) ========",ulNumResNodes);
                for(i=0; i < ulNumResNodes; i++)
                {
                    printLine(GUICookie,"");
                    sprintf(szString,"// Res.# %d Type=0x%X Name=0x%X Lang=0x%X DataOffset=0x%X DataLength=%d",
                        i+1,
                        g_prResNodePtr[i]->ResHdr.dwTypeID,
                        g_prResNodePtr[i]->ResHdr.dwNameID,
                        g_prResNodePtr[i]->ResHdr.wLangID,
                        VAL32(g_prResNodePtr[i]->DataEntry.OffsetToData),
                        VAL32(g_prResNodePtr[i]->DataEntry.Size));
                    printLine(GUICookie,szString);
                    if(g_pPELoader->getVAforRVA(VAL32(g_prResNodePtr[i]->DataEntry.OffsetToData), (void **) &pbData))
                    {
                        strcat(g_szAsmCodeIndent,"//  ");
                        strcpy(szString,g_szAsmCodeIndent);
                        DumpByteArray(szString,pbData,VAL32(g_prResNodePtr[i]->DataEntry.Size),GUICookie);
                        printLine(GUICookie,szString);
                        g_szAsmCodeIndent[strlen(g_szAsmCodeIndent)-4] = 0;
                    }
                    SDELETE(g_prResNodePtr[i]);
                }
                ret = 1;
#endif
            } // end if there are nodes
        }// end if got ptr to resource
        else ret = 0xFFFFFFFF;
    } // end if there is resource
    else ret = 0;

    return ret;
}


text:
using System;
using System.Collections.Generic;
using Infusion.Packets;
using Infusion.Packets.Client;

namespace Infusion.Gumps
{
    public sealed class GumpResponseBuilder
    {
        private readonly Gump gump;
        private readonly Action<GumpMenuSelectionRequest> triggerGump;
        private readonly List<GumpControlId> selectedCheckBoxes = new List<GumpControlId>();
        private readonly List<Tuple<ushort, string>> textEntries = new List<Tuple<ushort, string>>();

        internal GumpResponseBuilder(Gump gump, Action<GumpMenuSelectionRequest> triggerGump)
        {
            this.gump = gump;
            this.triggerGump = triggerGump;
        }

        public void Trigger(GumpControlId triggerId)
        {
            new TriggerGumpResponse(gump, triggerId, triggerGump, selectedCheckBoxes.ToArray(), textEntries.ToArray()).Execute();
        }

        public void PushButton(string buttonLabel, GumpLabelPosition labelPosition)
        {
            var processor = new SelectControlByLabelGumpParserProcessor(buttonLabel, labelPosition, GumpControls.Button);
            var parser = new GumpParser(processor);
            parser.Parse(gump);

            if (processor.SelectedControldId.HasValue)
            {
                new TriggerGumpResponse(gump, processor.SelectedControldId.Value, triggerGump, selectedCheckBoxes.ToArray(), textEntries.ToArray()).Execute();
                return;
            }

            new GumpFailureResponse(gump, $"Cannot find button '{buttonLabel}'.").Execute();
        }

        public void Cancel()
        {
            new CancelGumpResponse(gump, triggerGump).Execute();
        }

        public GumpResponseBuilder SelectCheckBox(string checkBoxLabel, GumpLabelPosition labelPosition)
        {
            var processor = new SelectControlByLabelGumpParserProcessor(checkBoxLabel, labelPosition, GumpControls.CheckBox);
            var parser = new GumpParser(processor);
            parser.Parse(gump);

            if (processor.SelectedControldId.HasValue)
                return SelectCheckBox(processor.SelectedControldId.Value);

            return this;
        }

        public GumpResponseBuilder SelectCheckBox(GumpControlId id)
        {
            selectedCheckBoxes.Add(id);

            return this;
        }

        public GumpResponseBuilder SetTextEntry(string textEntryLabel, string value, GumpLabelPosition labelPosition)
        {
            var processor = new SelectControlByLabelGumpParserProcessor(textEntryLabel, labelPosition, GumpControls.TextEntry);
            var parser = new GumpParser(processor);
            parser.Parse(gump);

            return processor.SelectedControldId.HasValue ? SetTextEntry(processor.SelectedControldId.Value, value) : this;
        }

        public GumpResponseBuilder SetTextEntry(GumpControlId id, string value)
        {
            textEntries.Add(new Tuple<ushort, string>((ushort)id.Value, value));

            return this;
        }
    }
}


text:
if (status != MStatus::kSuccess) \
{\
  status.perror(#stat); \
}


text:
using mzxrules.Helper;
using mzxrules.OcaLib.Actor;

namespace mzxrules.ZActor.OActors
{
    class KaeporaGaeboraActor : ActorRecord_Wrapper
    {
        SwitchFlag flag;
        byte type;
        public KaeporaGaeboraActor(short[] record, params int[] p)
            : base(record)
        {
            objectDependencies = p;
            flag    = Shift.AsByte(Variable, 0x003F);
            type    = Shift.AsByte(Variable, 0x0FC0);
        }
        protected override string GetActorName()
        {
            return "Kaepora Gaebora";
        }
        protected override string GetVariable()
        {
            return string.Format("Type {0}, {1}",
                type,
                flag);
        }
    }
}


text:
package com.example.chun.studentssystem.network;

import com.example.chun.studentssystem.bean.Info;
import com.example.chun.studentssystem.bean.StudentInfo;

import java.util.Map;

import retrofit2.http.GET;
import retrofit2.http.Query;
import retrofit2.http.QueryMap;
import rx.Observable;

/**
 * Created by Chun on 17/9/7.
 */

public interface StudentsApi {
    //添加数据
    @GET("/student/add")
    Observable<Info>addInfo(@QueryMap Map<String,String>datas);

    //通过名字查询数据
    @GET("/student/search")
    Observable<StudentInfo>searchInfoFromName(@Query("name") String name);

    //查询数据
    @GET("/student/data")
    Observable<StudentInfo>getInfo(@Query("page") int page );

    //通过名字删除数据
    @GET("/student/remove")
    Observable<Info>removeInfoFromName(@Query("name")String name);

    //通过名字更新数据
    @GET("/student/updata")
    Observable<Info>updataInfoFromName(@Query("name")String name,@Query("grade")String grade);
}


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

#include "platform/platform.h"
#include "platformX86UNIX/platformX86UNIX.h"
#include "console/console.h"
#include "core/stringTable.h"
#include "core/strings/stringFunctions.h"
#include <math.h>

Platform::SystemInfo_struct Platform::SystemInfo;

extern void PlatformBlitInit();
extern void SetProcessorInfo(Platform::SystemInfo_struct::Processor& pInfo,
   char* vendor, U32 processor, U32 properties, U32 properties2); // platform/platformCPU.cc

// asm cpu detection routine from platform code
extern "C"
{
void detectX86CPUInfo(char *vendor, U32 *processor, U32 *properties);
}

/* used in the asm */
static U32 time[2];
static char vendor[13] = {0,};
static U32 properties = 0;
static U32 processor  = 0;
U32 clockticks = 0;
U32 timeHi = 0;
U32 timeLo = 0;

void Processor::init()
{
   // Reference:
   //    www.cyrix.com
   //    www.amd.com
   //    www.intel.com
   //       http://developer.intel.com/design/PentiumII/manuals/24512701.pdf
   Platform::SystemInfo.processor.type = CPU_X86Compatible;
   Platform::SystemInfo.processor.name = StringTable->insert("Unknown x86 Compatible");
   Platform::SystemInfo.processor.mhz  = 0;
   Platform::SystemInfo.processor.properties = CPU_PROP_C;

   clockticks = properties = processor = time[0] = 0;
   dStrcpy(vendor, "");

   detectX86CPUInfo(vendor, &processor, &properties);
   SetProcessorInfo(Platform::SystemInfo.processor,
      vendor, processor, properties, 0);

   //--------------------------------------
   // if RDTSC support calculate the aproximate Mhz of the CPU
   if (Platform::SystemInfo.processor.properties & CPU_PROP_RDTSC &&
       Platform::SystemInfo.processor.properties & CPU_PROP_FPU)
   {
      const U32 MS_INTERVAL = 750;

#if defined(TORQUE_COMPILER_GCC) && ((__GNUC__ >= 3) && (__GNUC_MINOR__ >=4)) || ((__GNUC__ >= 4) && (__GNUC_MINOR__ >=0))
      asm("rdtsc" : "=a" (timeLo), "=d" (timeHi));
#else
      __asm__(
         "pushl  %eax\n"
         "pushl  %edx\n"
         "rdtsc\n"
         "movl   %eax, (time)\n"
         "movl   %edx, (time+4)\n"
         "popl   %edx\n"
         "popl   %eax\n"
         );
#endif
      U32 ms = Platform::getRealMilliseconds();
      while ( Platform::getRealMilliseconds() < ms+MS_INTERVAL )
      { /* empty */ }
      ms = Platform::getRealMilliseconds()-ms;
#if defined(TORQUE_COMPILER_GCC) && ((__GNUC__ >= 3) && (__GNUC_MINOR__ >= 4)) || ((__GNUC__ >= 4) && (__GNUC_MINOR__ >=0))
      asm(
         "pushl  %eax\n"
         "pushl  %edx\n"
         "rdtsc\n"
         "sub    (timeHi), %edx\n"
         "sbb    (timeLo), %eax\n"
         "mov    %eax, (clockticks)\n"
         "popl   %edx\n"
         "popl   %eax\n"
         );
#else
      asm(
         "pushl  %eax\n"
         "pushl  %edx\n"
         "rdtsc\n"
         "sub    (time+4), %edx\n"
         "sbb    (time), %eax\n"
         "mov    %eax, (clockticks)\n"
         "popl   %edx\n"
         "popl   %eax\n"
         );
#endif
      U32 mhz = static_cast<U32>(F32(clockticks) / F32(ms) / 1000.0f);

      // catch-22 the timing method used above to calc Mhz is generally
      // wrong by a few percent so we want to round to the nearest clock
      // multiple but we also want to be careful to not touch overclocked
      // results

      // measure how close the Raw Mhz number is to the center of each clock
      // bucket
      U32 bucket25 = mhz % 25;
      U32 bucket33 = mhz % 33;
      U32 bucket50 = mhz % 50;

      if (bucket50 < 8 || bucket50 > 42)
         Platform::SystemInfo.processor.mhz =
            U32((mhz+(50.0f/2.0f))/50.0f) * 50;
      else if (bucket25 < 5 || bucket25 > 20)
         Platform::SystemInfo.processor.mhz =
            U32((mhz+(25.0f/2.0f))/25.0f) * 25;
      else if (bucket33 < 5 || bucket33 > 28)
         Platform::SystemInfo.processor.mhz =
            U32((mhz+(33.0f/2.0f))/33.0f) * 33;
      else
         Platform::SystemInfo.processor.mhz = U32(mhz);
   }

   Con::printf("Processor Init:");
   Con::printf("   %s, %d Mhz", Platform::SystemInfo.processor.name, Platform::SystemInfo.processor.mhz);
   if (Platform::SystemInfo.processor.properties & CPU_PROP_FPU)
      Con::printf("   FPU detected");
   if (Platform::SystemInfo.processor.properties & CPU_PROP_MMX)
      Con::printf("   MMX detected");
   if (Platform::SystemInfo.processor.properties & CPU_PROP_3DNOW)
      Con::printf("   3DNow detected");
   if (Platform::SystemInfo.processor.properties & CPU_PROP_SSE)
      Con::printf("   SSE detected");
   Con::printf(" ");

   PlatformBlitInit();
}