text:
/* globals JQClass */
/*! Simple JavaScript Inheritance
 * By John Resig http://ejohn.org/
 * MIT Licensed.
 */
// Inspired by base2 and Prototype
(function(){
	'use strict';
	var initializing = false;

	// The base JQClass implementation (does nothing)
	window.JQClass = function(){};

	// Collection of derived classes
	JQClass.classes = {};

	// Create a new JQClass that inherits from this class
	JQClass.extend = function extender(prop) {
		var base = this.prototype;

		// Instantiate a base class (but only create the instance, don't run the init constructor)
		initializing = true;
		var prototype = new this();
		initializing = false;

		// Copy the properties over onto the new prototype
		for (var name in prop) { // jshint loopfunc:true
			// Check if we're overwriting an existing function
			if (typeof prop[name] === 'function' && typeof base[name] === 'function') {
				prototype[name] = (function (name, fn) {
					return function () {
						var __super = this._super;
						// Add a new ._super() method that is the same method but on the super-class
						this._super = function (args) {
							return base[name].apply(this, args || []);
						};
						var ret = fn.apply(this, arguments);
						// The method only needs to be bound temporarily, so we remove it when we're done executing
						this._super = __super;
						return ret;
					};
				})(name, prop[name]);
			// Check if we're overwriting existing default options.
			} else if (typeof prop[name] === 'object' && typeof base[name] === 'object' && name === 'defaultOptions') {
				var obj1 = base[name];
				var obj2 = prop[name];
				var obj3 = {};
				var key;
				for (key in obj1) { // jshint forin:false
					obj3[key] = obj1[key];
				}
				for (key in obj2) { // jshint forin:false
					obj3[key] = obj2[key];
				}
				prototype[name] = obj3;
			} else {
				prototype[name] = prop[name];
			}
		}

		// The dummy class constructor
		function JQClass() {
			// All construction is actually done in the init method
			if (!initializing && this._init) {
				this._init.apply(this, arguments);
			}
		}

		// Populate our constructed prototype object
		JQClass.prototype = prototype;

		// Enforce the constructor to be what we expect
		JQClass.prototype.constructor = JQClass;

		// And make this class extendable
		JQClass.extend = extender;

		return JQClass;
	};
})();
/*! Abstract base class for collection plugins v1.0.2.
	Written by Keith Wood (wood.keith{at}optusnet.com.au) December 2013.
	Licensed under the MIT license (http://keith-wood.name/licence.html). */
(function($) { // Ensure $, encapsulate
	'use strict';

	/**
Abstract base class for collection plugins v1.0.2.

Written by Keith Wood (wood.keith{at}optusnet.com.au) December 2013.

Licensed under the MIT license (http://keith-wood.name/licence.html).

Use {@link $.JQPlugin.createPlugin} to create new plugins using this framework.

This base class provides common functionality such as:

Creates jQuery bridge - allowing you to invoke your plugin on a collection of elements.

Handles initialisation including reading settings from metadata -
				an instance object is attached to the affected element(s) containing all the necessary data.

Handles option retrieval and update - options can be set through default values,
				through inline metadata, or through instantiation settings.

				Metadata is specified as an attribute on the element:
				data-<pluginName>="<option name>: '<value>', ...".
				Dates should be specified as strings in this format: 'new Date(y, m-1, d)'.

Handles method calling - inner functions starting with '_'are inaccessible,
				whereas others can be called via $(selector).pluginName('functionName').

Handles plugin destruction - removing all trace of the plugin.

		@module JQPlugin
		@abstract */
	JQClass.classes.JQPlugin = JQClass.extend({

		/** Name to identify this plugin.
			@example name: 'tabs' */
		name: 'plugin',

		/** Default options for instances of this plugin (default: {}).
			@example defaultOptions: {
  selectedClass: 'selected',
  triggers: 'click'
} */
		defaultOptions: {},

		/** Options dependent on the locale.
			Indexed by language and (optional) country code, with '' denoting the default language (English/US).
			Normally additional languages would be provided as separate files to all them to be included as needed.
			@example regionalOptions: {
  '': {
    greeting: 'Hi'
  }
} */
		regionalOptions: {},

		/** Whether or not a deep merge should be performed when accumulating options.
			The default is true but can be overridden in a sub-class. */
		deepMerge: true,

		/** Retrieve a marker class for affected elements.
			In the format: is-<pluginName>.
			@protected
			@return {string} The marker class. */
		_getMarker: function() {
			return 'is-' + this.name;
		},

		/** Initialise the plugin.
			Create the jQuery bridge - plugin name xyz
			produces singleton $.xyz and collection function $.fn.xyz.
			@protected */
		_init: function() {
			// Apply default localisations
			$.extend(this.defaultOptions, (this.regionalOptions && this.regionalOptions['']) || {});
			// Camel-case the name
			var jqName = camelCase(this.name);
			// Expose jQuery singleton manager
			$[jqName] = this;
			// Expose jQuery collection plugin
			$.fn[jqName] = function(options) {
				var otherArgs = Array.prototype.slice.call(arguments, 1);
				var inst = this;
				var returnValue = this;
				this.each(function () {
					if (typeof options === 'string') {
						if (options[0] === '_' || !$[jqName][options]) {
							throw 'Unknown method: ' + options;
						}
						var methodValue = $[jqName][options].apply($[jqName], [this].concat(otherArgs));
						if (methodValue !== inst && methodValue !== undefined) {
							returnValue = methodValue;
							return false;
						}
					} else {
						$[jqName]._attach(this, options);
					}
				});
				return returnValue;
			};
		},

		/** Set default options for all subsequent instances.
			@param {object} options The new default options.
			@example $.pluginName.setDefaults({name: value, ...}) */
		setDefaults: function(options) {
			$.extend(this.defaultOptions, options || {});
		},

		/** Initialise an element. Called internally only.
			Adds an instance object as data named for the plugin.
			Override {@linkcode module:JQPlugin~_postAttach|_postAttach} for plugin-specific processing.
			@private
			@param {Element} elem The element to enhance.
			@param {object} options Overriding settings. */
		_attach: function(elem, options) {
			elem = $(elem);
			if (elem.hasClass(this._getMarker())) {
				return;
			}
			elem.addClass(this._getMarker());
			options = $.extend(this.deepMerge, {}, this.defaultOptions, this._getMetadata(elem), options || {});
			var inst = $.extend({name: this.name, elem: elem, options: options}, this._instSettings(elem, options));
			elem.data(this.name, inst); // Save instance against element
			this._postAttach(elem, inst);
			this.option(elem, options);
		},

		/** Retrieve additional instance settings.
			Override this in a sub-class to provide extra settings.
			These are added directly to the instance object.
			Default attributes of an instance object are shown as properties below:
			@protected
			@param {jQuery} elem The current jQuery element.
			@param {object} options The instance options.
			@return {object} Any extra instance values.
			@property {Element} elem The element to which this instance applies.
			@property {string} name The name of this plugin.
			@property {object} options The accumulated options for this instance.
			@example _instSettings: function(elem, options) {
  return {nav: elem.find(options.navSelector)};
} */
		_instSettings: function(elem, options) { // jshint unused:false
			return {};
		},

		/** Plugin specific post initialisation.
			Override this in a sub-class to perform extra activities.
			This is where you would implement your plugin's main functionality.
			@protected
			@param {jQuery} elem The current jQuery element.
			@param {object} inst The instance settings.
			@example _postAttach: function(elem, inst) {
  elem.on('click.' + this.name, function() {
    ...
  });
} */
		_postAttach: function(elem, inst) { // jshint unused:false
		},

		/** Retrieve metadata configuration from the element.
			Metadata is specified as an attribute:
			data-<pluginName>="<option name>: '<value>', ...".
			Dates should be specified as strings in this format: 'new Date(y, m-1, d)'.
			@private
			@param {jQuery} elem The source element.
			@return {object} The inline configuration or {}. */
		_getMetadata: function(elem) {
			try {
				var data = elem.data(this.name.toLowerCase()) || '';
				data = data.replace(/(\\?)'/g, function(e, t) {
					return t ? '\'' : '"';
				}).replace(/([a-zA-Z0-9]+):/g, function(match, group, i) {
					var count = data.substring(0, i).match(/"/g); // Handle embedded ':'
					return (!count || count.length % 2 === 0 ? '"' + group + '":' : group + ':');
				}).replace(/\\:/g, ':');
				data = $.parseJSON('{' + data + '}');
				for (var key in data) {
					if (data.hasOwnProperty(key)) {
						var value = data[key];
						if (typeof value === 'string' && value.match(/^new Date\(([-0-9,\s]*)\)$/)) { // Convert dates
							data[key] = eval(value); // jshint ignore:line
						}
					}
				}
				return data;
			}
			catch (e) {
				return {};
			}
		},

		/** Retrieve the instance data for element.
			@protected
			@param {Element} elem The source element.
			@return {object} The instance data or {} if none. */
		_getInst: function(elem) {
			return $(elem).data(this.name) || {};
		},

		/** Retrieve or reconfigure the settings for a plugin.
			If new settings are provided they are applied to the instance options.
			If an option name only is provided the value of that option is returned.
			If no name or value is provided, all options are returned.
			Override {@linkcode module:JQPlugin~_optionsChanged|_optionsChanged}
			for plugin-specific processing when option values change.
			@param {Element} elem The source element.
			@param {object|string} [name] The collection of new option values or the name of a single option.
			@param {any} [value] The value for a single named option.
			@return {any|object} If retrieving a single value or all options.
			@example $(selector).plugin('option', 'name', value) // Set one option
$(selector).plugin('option', {name: value, ...}) // Set multiple options
var value = $(selector).plugin('option', 'name') // Get one option
var options = $(selector).plugin('option') // Get all options */
		option: function(elem, name, value) {
			elem = $(elem);
			var inst = elem.data(this.name);
			var options = name || {};
			if  (!name || (typeof name === 'string' && typeof value === 'undefined')) {
				options = (inst || {}).options;
				return (options && name ? options[name] : options);
			}
			if (!elem.hasClass(this._getMarker())) {
				return;
			}
			if (typeof name === 'string') {
				options = {};
				options[name] = value;
			}
			this._optionsChanged(elem, inst, options);
			$.extend(inst.options, options);
		},

		/** Plugin specific options processing.
			Old value available in inst.options[name], new value in options[name].
			Override this in a sub-class to perform extra activities.
			@protected
			@param {jQuery} elem The current jQuery element.
			@param {object} inst The instance settings.
			@param {object} options The new options.
			@example _optionsChanged: function(elem, inst, options) {
  if (options.name != inst.options.name) {
    elem.removeClass(inst.options.name).addClass(options.name);
  }
} */
		_optionsChanged: function(elem, inst, options) { // jshint unused:false
		},

		/** Remove all trace of the plugin.
			Override {@linkcode module:JQPlugin~_preDestroy|_preDestroy} for plugin-specific processing.
			@param {Element} elem The source element.
			@example $(selector).plugin('destroy') */
		destroy: function(elem) {
			elem = $(elem);
			if (!elem.hasClass(this._getMarker())) {
				return;
			}
			this._preDestroy(elem, this._getInst(elem));
			elem.removeData(this.name).removeClass(this._getMarker());
		},

		/** Plugin specific pre destruction.
			It is invoked as part of the {@linkcode module:JQPlugin~destroy|destroy} processing.
			Override this in a sub-class to perform extra activities and undo everything that was
			done in the {@linkcode module:JQPlugin~_postAttach|_postAttach} or
			{@linkcode module:JQPlugin~_optionsChanged|_optionsChanged} functions.
			@protected
			@param {jQuery} elem The current jQuery element.
			@param {object} inst The instance settings.
			@example _preDestroy: function(elem, inst) {
  elem.off('.' + this.name);
} */
		_preDestroy: function(elem, inst) { // jshint unused:false
		}
	});

	/** Convert names from hyphenated to camel-case.
		@private
		@param {string} value The original hyphenated name.
		@return {string} The camel-case version. */
	function camelCase(name) {
		return name.replace(/-([a-z])/g, function(match, group) {
			return group.toUpperCase();
		});
	}

	/** Expose the plugin base.
		@namespace $.JQPlugin */
	$.JQPlugin = {

		/** Create a new collection plugin.
			@memberof $.JQPlugin
			@param {string} [superClass='JQPlugin'] The name of the parent class to inherit from.
			@param {object} overrides The property/function overrides for the new class.
				See {@link module:JQPlugin|JQPlugin} for the base functionality.
			@example $.JQPlugin.createPlugin({ // Define the plugin
  name: 'tabs',
  defaultOptions: {selectedClass: 'selected'},
  _initSettings: function(elem, options) { return {...}; },
  _postAttach: function(elem, inst) { ... }
});
$('selector').tabs(); // And instantiate it */
		createPlugin: function(superClass, overrides) {
			if (typeof superClass === 'object') {
				overrides = superClass;
				superClass = 'JQPlugin';
			}
			superClass = camelCase(superClass);
			var className = camelCase(overrides.name);
			JQClass.classes[className] = JQClass.classes[superClass].extend(overrides);
			new JQClass.classes[className](); // jshint ignore:line
		}
	};

})(jQuery);


text:
extern crate quasi_codegen;
extern crate rustc_plugin;

#[plugin_registrar]
#[doc(hidden)]
pub fn plugin_registrar(reg: &mut rustc_plugin::Registry) {
    quasi_codegen::register(reg);
}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

require Rails.root.join('db', 'migrate', '20200212014653_rename_security_dashboard_feature_flag_to_instance_security_dashboard.rb')

RSpec.describe RenameSecurityDashboardFeatureFlagToInstanceSecurityDashboard do
  let(:feature_gates) { table(:feature_gates) }

  subject(:migration) { described_class.new }

  describe '#up' do
    it 'copies the security_dashboard feature gate to a new instance_security_dashboard gate' do
      feature_gates.create!(feature_key: :security_dashboard, key: :actors, value: 'Project:1')
      feature_gates.create!(feature_key: :security_dashboard, key: :boolean, value: 'false')

      migration.up

      instance_security_dashboard_feature = feature_gates.find_by(feature_key: :instance_security_dashboard, key: :boolean)
      expect(instance_security_dashboard_feature.value).to eq('false')
    end

    context 'when there is no security_dashboard gate' do
      it 'does nothing' do
        migration.up

        instance_security_dashboard_feature = feature_gates.find_by(feature_key: :instance_security_dashboard, key: :boolean)
        expect(instance_security_dashboard_feature).to be_nil
      end
    end

    context 'when there is already an instance_security_dashboard gate' do
      it 'does nothing' do
        feature_gates.create!(feature_key: :security_dashboard, key: 'boolean', value: 'false')
        feature_gates.create!(feature_key: :instance_security_dashboard, key: 'boolean', value: 'false')

        expect { migration.up }.not_to raise_error
      end
    end
  end

  describe '#down' do
    it 'removes the instance_security_dashboard gate' do
      actors_instance_security_dashboard_feature = feature_gates.create!(feature_key: :instance_security_dashboard, key: :actors, value: 'Project:1')
      instance_security_dashboard_feature = feature_gates.create!(feature_key: :instance_security_dashboard, key: :boolean, value: 'false')

      migration.down

      expect { instance_security_dashboard_feature.reload }.to raise_error(ActiveRecord::RecordNotFound)
      expect(actors_instance_security_dashboard_feature.reload).to be_present
    end
  end
end


text:
require 'google/protobuf'

require 'test/cpp/interop/empty'
require 'test/cpp/interop/messages'
Google::Protobuf::DescriptorPool.generated_pool.build do
end

module Grpc
  module Testing
  end
end


text:
# This file is copied to spec/ when you run 'rails generate rspec:install'
ENV["RAILS_ENV"] ||= 'test'
#require File.expand_path("../../config/environment", __FILE__)

require 'shoulda-matchers'
require 'simple_rsa'

# Requires supporting ruby files with custom matchers and macros, etc,
# in spec/support/ and its subdirectories.
Dir["./spec/support/**/*.rb"].each {|f| require f }

RSpec.configure do |config|
  config.mock_with :rspec

  config.before(:each) do
    # we need a fresh tmp directory for our tests
    FileUtils.rm_rf './tmp' if File.exist?('./tmp')
    Dir::mkdir('./tmp')
  end
end


text:
@interface UserInfoManager : NSObject

// 创建单例
+ (instancetype)defaultManager;

// 保存用户的auth
+ (void)saveUserAuth:(NSString *)userauth;
// 获取用户的userauth
+ (NSString *)getUserAuth;
// 取消用户的userauth
+ (void)cancelUserAuth;

// 保存用户的uname
+ (void)saveUserName:(NSString *)username;
// 获取用户的uname
+ (NSString *)getUserName;

// 保存用户的uid
+ (void)saveUserID:(NSString *)userid;
// 获取用户的uid
+ (NSString *)getUserID;
// 取消用户的uid
+ (void)cancelUserID;

// 保存用户的icon
+ (void)saveUserIcon:(NSString *)icon;
// 获取用户的icon
+ (NSString *)getUserIcon;

@end


text:
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

/**
 * AppKernel class
 */
class AppKernel extends Kernel
{
    /**
     * Register bundles
     */
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            // Doctrine
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Doctrine\Bundle\MigrationsBundle\DoctrineMigrationsBundle(),
            // SensioLabs
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
            // Sonata
            new Sonata\AdminBundle\SonataAdminBundle(),
            new Sonata\BlockBundle\SonataBlockBundle(),
            new Sonata\CoreBundle\SonataCoreBundle(),
            new Sonata\DoctrineORMAdminBundle\SonataDoctrineORMAdminBundle(),
            new Sonata\UserBundle\SonataUserBundle('FOSUserBundle'),
            // Vendors
            new AncaRebeca\FullCalendarBundle\FullCalendarBundle(),
            new Artgris\Bundle\FileManagerBundle\ArtgrisFileManagerBundle(),
            new EWZ\Bundle\RecaptchaBundle\EWZRecaptchaBundle(),
            new Fenrizbes\ColorPickerTypeBundle\FenrizbesColorPickerTypeBundle(),
            new FOS\JsRoutingBundle\FOSJsRoutingBundle(),
            new FOS\UserBundle\FOSUserBundle(),
            new Hautelook\AliceBundle\HautelookAliceBundle(),
            new Hampe\Bundle\ZurbInkBundle\HampeZurbInkBundle(),
            new Ivory\CKEditorBundle\IvoryCKEditorBundle(),
            new Knp\Bundle\MenuBundle\KnpMenuBundle(),
            new Liip\ImagineBundle\LiipImagineBundle(),
            new Presta\SitemapBundle\PrestaSitemapBundle(),
            new SaadTazi\GChartBundle\SaadTaziGChartBundle(),
            new Stof\DoctrineExtensionsBundle\StofDoctrineExtensionsBundle(),
            new Vich\UploaderBundle\VichUploaderBundle(),
            new WhiteOctober\TCPDFBundle\WhiteOctoberTCPDFBundle(),
            // App
            new AppBundle\AppBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'), true)) {
            $bundles[] = new Cypress\GitElephantBundle\CypressGitElephantBundle();
            $bundles[] = new Liip\FunctionalTestBundle\LiipFunctionalTestBundle();
            $bundles[] = new Symfony\Bundle\DebugBundle\DebugBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    /**
     * @param LoaderInterface $loader
     */
    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load($this->getRootDir().'/config/config_'.$this->getEnvironment().'.yml');
    }
}


text:
//
// Copyright (c) 2019 Autodesk, Inc.
//
// 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.
//
/*jshint esversion: 9 */

const fs = require('fs');
const _path = require('path');
const ForgeSDK = require('../src/index');

// ForgeSDK.ApiClient.instance.switchServerPath('https://developer-stg.api.autodesk.com');
// const StgApiClient = new ForgeSDK.ApiClient('https://developer-stg.api.autodesk.com');
// const bucketsApiStg = new ForgeSDK.BucketsApi(StgApiClient);
// const oAuth2TwoLeggedStg = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, ['data:read'], true, StgApiClient);
// const oAuth2TwoLeggedtest = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET, ['data:read'], true); // back to prod

// TODO - insert your CLIENT_ID and CLIENT_SECRET
const FORGE_CLIENT_ID = process.env.FORGE_CLIENT_ID || 'your forge client id';
const FORGE_CLIENT_SECRET = process.env.FORGE_CLIENT_SECRET || 'your forge client secret';

// TODO - Choose a bucket key - a unique name to assign to a bucket. It must be globally unique across all applications and
// regions, otherwise the call will fail. Possible values: -_.a-z0-9 (between 3-128 characters in
// length). Note that you cannot change a bucket key.
const BUCKET_KEY = 'forge_sample_' + FORGE_CLIENT_ID.toLowerCase();

// TODO - Choose a filename - a key for the uploaded object
const FILE_NAME = 'test.nwd';

// TODO - specify the full filename and path
const FILE_PATH = _path.resolve(__dirname + '/test.nwd');

const bucketsApi = new ForgeSDK.BucketsApi(),
	objectsApi = new ForgeSDK.ObjectsApi(),
	derivativesApi = new ForgeSDK.DerivativesApi(/* undefined, ForgeSDK.JobPayloadDestination.RegionEnum.EMEA */);

// Initialize the 2-legged oauth2 client
const oAuth2TwoLegged = new ForgeSDK.AuthClientTwoLegged(FORGE_CLIENT_ID, FORGE_CLIENT_SECRET,
	['data:write', 'data:read', 'bucket:read', 'bucket:update', 'bucket:create'], true);

/**
 * General error handling method
 * @param err
 */
function defaultHandleError (err) {
	console.error('\x1b[31m Error:', err, '\x1b[0m');
}

/**
 * Gets the details of an object specified by a bucketKey / objectKey.
 * Uses the oAuth2TwoLegged object that you retrieved previously.
 * @param {String} bucketKey
 * @param {String} objectKey
 * @returns {Promise}
 */
const getObjectDetails = function (bucketKey, objectKey) {
	console.log("**** Get object details :", bucketKey, objectKey);
	return objectsApi.getObjectDetails(bucketKey, objectKey, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};

/**
 * Gets the resource manifest.
 * Uses the oAuth2TwoLegged object that you retrieved previously.
 * @param {String} urn
 * @returns {Promise}
 */
const getManifest = function (urn) {
	console.log("**** Get resource manifest:", urn);
	return derivativesApi.getManifest(urn, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};

/**
 * Gets the resource metadata.
 * Uses the oAuth2TwoLegged object that you retrieved previously.
 * @param {String} urn
 * @returns {Promise}
 */
const getMetadata = function (urn) {
	console.log("**** Get resource metadata:", urn);
	return derivativesApi.getMetadata(urn, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};

/**
 * Delete the file uploaded by the application.
 * Uses the oAuth2TwoLegged object that you retrieved previously.
 * @param {String} bucketKey
 * @param {String} fileName
 * @returns {Promise}
 */
const deleteFile = function (bucketKey, fileName) {
	console.log("**** Deleting file from bucket:" + bucketKey + ", filename:" + fileName);
	return objectsApi.deleteObject(bucketKey, fileName, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};

/**
 * Create OBJ.
 * Uses the oAuth2TwoLegged object that you retrieved previously.
 * @param {String} urn
 * @param {String} guid
 * @returns {Promise}
 */
const createObj = function (urn, guid) {
	console.log("**** Creating OBJ : " + urn);

	const job = new ForgeSDK.JobPayload({
		input: new ForgeSDK.JobPayloadInput(urn),
		output: new ForgeSDK.JobPayloadOutput(
			[
				new ForgeSDK.JobObjOutputPayload('obj',
					{
						advanced: new ForgeSDK.JobObjOutputPayloadAdvanced(
							{
								unit: ForgeSDK.JobObjOutputPayloadAdvanced.UnitEnum.meter,
								modelGuid: guid,
								objectIds: [-1]
							})
					}),
			],
			{
				destination: new ForgeSDK.JobPayloadDestination(ForgeSDK.JobPayloadDestination.RegionEnum.US)
			}
		),
		//misc: new ForgeSDK.JobPayloadMisc ()
	});

	return derivativesApi.translate(job, {}, oAuth2TwoLegged, oAuth2TwoLegged.getCredentials());
};

/**
 * Create an access token and run the API calls.
 */
oAuth2TwoLegged.authenticate()
	.then(function (credentials) {

		console.log("**** Got Credentials", credentials);

		getObjectDetails(BUCKET_KEY, FILE_NAME)
			.then(function (details) {
				console.log("**** Object details:", details.body);

				const _details = new ForgeSDK.ObjectDetails(details.body); // ObjectFullDetails
				const urn = Buffer.from(_details.objectId).toString('base64')
					.replace(/\+/g, '-') // Convert '+' to '-'
					.replace(/\//g, '_') // Convert '/' to '_'
					.replace(/=+$/, '');

				getMetadata (urn)
					.then (function (metadata) {
						console.log("**** Metadata requested:", metadata.body);

						const _metadata = ForgeSDK.Metadata.constructFromObject (metadata.body);
						const guid = _metadata.data.metadata [0].guid;

						createObj(urn, guid)
							.then(function (reponse) {
								console.log("**** OBJ requested:", reponse.body);

								getManifest(urn)
									.then(function (manifest) {
										console.log("**** Manifest:", manifest.body);

										const _manifest = new ForgeSDK.Manifest.constructFromObject(manifest.body);
										console.log("**** Manifest:", _manifest);

									}, defaultHandleError);

							}, defaultHandleError);

					}, defaultHandleError);

			}, defaultHandleError);

	}, defaultHandleError)

	.catch(defaultHandleError);


text:
filename: /packages/material-ui/src/IconButton/IconButton.js
---

# IconButton

Refer to the [Icons](/style/icons) section of the documentation
regarding the available icon options.

## Props

| Name | Type | Default | Description |
|:-----|:-----|:--------|:------------|
| children | node |  | The icon element. |
| classes | object |  | Useful to extend the style applied to components. |
| color | enum: 'default' |
 'inherit' |
 'primary' |
 'secondary'
 | 'default' | The color of the component. It supports those theme colors that make sense for this component. |
| disabled | bool | false | If `true`, the button will be disabled. |
| disableRipple | bool |  | If `true`, the ripple will be disabled. |

Any other properties supplied will be [spread to the root element](/guides/api#spread).

## CSS API

You can override all the class names injected by Material-UI thanks to the `classes` property.
This property accepts the following keys:
- `root`
- `colorInherit`
- `colorPrimary`
- `colorSecondary`
- `disabled`
- `label`

Have a look at [overriding with classes](/customization/overrides#overriding-with-classes) section
and the [implementation of the component](https://github.com/mui-org/material-ui/tree/v1-beta/packages/material-ui/src/IconButton/IconButton.js)
for more detail.

If using the `overrides` key of the theme as documented
[here](/customization/themes#customizing-all-instances-of-a-component-type),
you need to use the following style sheet name: `MuiIconButton`.

## Inheritance

The properties of the [ButtonBase](/api/button-base) component are also available.

## Demos

- [Buttons](/demos/buttons)
- [Grid List](/demos/grid-list)


text:
layout: relation
title: 'cop'
shortdef: 'copula'
udver: '2'
---

A copula is the relation between the nominal predicate _(přísudek jmenný)_ and
the copular verb _být_ "to be" (or its variants _bývat, bývávat_).
The verb _stát se_ "to become", despite being counted among copular verbs by some authors,
is not analyzed as `cop`.

We normally take a copula as a dependent of its complement (the nominal predicate).
The nominal predicate is usually a [noun](cs-pos/NOUN), an [adjective](cs-pos/ADJ)
or a participle.

~~~ sdparse
Ondřej je čestný muž . \n Ondřej is honest man .
cop(muž, je)
cop(man, is)
~~~

~~~ sdparse
Ondřej je čestný . \n Ondřej is honest .
cop(čestný, je)
cop(honest, is)
~~~

Note that the passive participle may be also used as nominal predicate with copula.
Hence it may be difficult to distinguish a passive construction from a copula construction.
The former focuses on the process while the latter emphasizes the result.

- Passive: _Smlouva byla.`AUX` podepsána v Bílém domě._   "The contract was signed in the White House."
- Copula: _Smlouva byla.`VERB` podepsána červeným inkoustem._   "The contract was signed in red ink."

~~~ sdparse
Smlouva byla podepsána v Bílém domě . \n Contract was signed in White House .
aux:pass(podepsána, byla)
aux:pass(signed, was)
~~~

~~~ sdparse
Smlouva byla podepsána červeným inkoustem . \n Contract was signed in-red ink .
cop(podepsána, byla)
cop(signed, was)
~~~

The nominal predicate may also be expressed using a prepositional phrase.
Phrases expressing the state of the subject are clear predicates, e.g. _Lenka je v kondici_ "Lenka is in shape".
Under the v2 guidelines, prepositional phrases expressing locations are also considered predicates, to increase parallelism across languages.

Thus the following sentences receive parallel analyses:

- _Lenka je skvělá._ "Lenka is brilliant."
- _Lenka je v kondici._ "Lenka is in shape."
- _Lenka je v kuchyni._ "Lenka is in the kitchen."

In contrast, the following two are no longer parallel:

- _Lenka je v kuchyni._ "Lenka is in the kitchen."
- _Lenka zůstala v kuchyni._ "Lenka stayed in the kitchen."

~~~ sdparse
Lenka je v kondici . \n Lenka is in shape .
cop(kondici, je)
cop(shape, is)
case(kondici, v)
case(shape, in)
nsubj(kondici, Lenka-1)
nsubj(shape, Lenka-7)
~~~

~~~ sdparse
Lenka je v kuchyni . \n Lenka is in kitchen .
nsubj(kuchyni, Lenka-1)
nsubj(kitchen, Lenka-7)
cop(kuchyni, je)
cop(kitchen, is)
case(kuchyni, v)
case(kitchen, in)
~~~


text:
require 'spec_helper'
require 'switch_user/provider/restful_authentication'

class RestfulAuthenticationController < TestController
  attr_accessor :current_user

  def logout_killing_session!
    self.current_user = nil
  end
end

describe SwitchUser::Provider::RestfulAuthentication do
  let(:controller) { RestfulAuthenticationController.new }
  let(:provider) { SwitchUser::Provider::RestfulAuthentication.new(controller) }

  it_behaves_like "a provider"
end


text:
layout: post
title: April 2019 Release Notes - Version 19.4.0
published: true
post_author:
  display_name: Vladimir Kostyukov
  twitter: vkostyukov
tags: Releases, Finagle, Finatra, Util, Scrooge, TwitterServer
---

### Highlights

- After several years of continuous effort decoupling Finagle from Netty 3, we've finally got to the
  point the dependency can be dropped. As of this release, there is no Netty 3 artifacts on the
  classpath.
- Finagle HTTP now transmits trailing headers (trailers).
- Finagle HTTP has become more strict with headers validation and is now in compliance with
  RFC7230.

### [Finagle](https://github.com/twitter/finagle/) ###

#### New Features

-   finagle-core: Make `maxDepth` in `Namer` configurable. [03cc3197](https://github.com/twitter/finagle/commit/03cc319706182eb86ad1f4eb54041894a2599528)
    -   namerMaxDepth in Namer now configurable through a global flag (`namerMaxDepth`)
-   finagle-core: The newly renamed `SslSessionInfo` is now public. It is
    intended for providing information about a connection's SSL/TLS session.
    [811fe004](https://github.com/twitter/finagle/commit/811fe004a835620c834f2cac87dc69fa8b347d35)
-   finagle-core: Added the `c.t.finagle.DtabFlags` trait which defines a Flag and function for
    appending to the "base" `c.t.finagle.Dtab` delegation table. [675630df](https://github.com/twitter/finagle/commit/675630dfaace1a0f06104c4ac8719a581fa44851)
-   finagle-http: Finagle HTTP implementation now supports trailing headers (trailers). Use
    `c.t.f.http.Message.trailers` to access trailing headers on a fully-buffered message
    (isChunked == false) or `c.t.f.http.Message.chunkReader` on a message with chunked payload
    (isChunked == true). [351c43c1](https://github.com/twitter/finagle/commit/351c43c15861f644b77ca3c5e627a0225001c615)
-   finagle-http,thriftmux: Added tracing annotations to backup requests. [48f54e82](https://github.com/twitter/finagle/commit/48f54e82c2df35a5546a55c889286e99622b8b44)
    -   Binary annotation `srv/backup\_request\_processing`, when servers are processing backup requests.
-   finagle-http: Added new server metrics to keep track of inbound requests that are rejected due to
    their headers containing invalid characters (as seen by RFC-7230): `rejected_invalid_header_names`
    and `rejected_invalid_header_values`. [41bd061a](https://github.com/twitter/finagle/commit/41bd061a4b8afbd170c6bc108eb7de2b77a298d2)
-   finagle-http: Added stats of the duration in milliseconds of request/response streams:
    `request_stream_duration_ms` and `response_stream_duration_ms`. They are enabled by using
    `.withHttpStats` on `Http.Client` and `Http.Server` [916f4a26](https://github.com/twitter/finagle/commit/916f4a2683aef99bc5e0c29bbdad0523cebb7bc1)
-   finagle-mysql: A new toggle, `com.twitter.finagle.mysql.IncludeHandshakeInServiceAcquisition`, has
    been added. Turning on this toggle will move MySQL session establishment (connection phase) to be
    part of service acqusition. [fe4d8919](https://github.com/twitter/finagle/commit/fe4d8919922115cf5aa4d4c03305b04c89abb362)

#### Runtime Behavior Changes

-   finagle-core: Client-side nacking admission control now defaults on. See the documentation
    on `c.t.f.filter.NackAdmissionFilter` for details. This can be disabled by setting the
    global flag, `com.twitter.finagle.client.useNackAdmissionFilter`, to `false`.
    [aa36f56b](https://github.com/twitter/finagle/commit/aa36f56b7e47eb2af8fadca83f204fa57a38603e)
-   finagle-core: `LatencyCompensation` now applies to service acquisition. [1ec020a5](https://github.com/twitter/finagle/commit/1ec020a5b80b35f1d0158aac181b14d7942aaa66)
-   finagle-http: HTTP headers validation on the outbound path is now in compliance with RFC7230.
    [5b2e9f95](https://github.com/twitter/finagle/commit/5b2e9f9540b865983e060b65cb7dae83cbf93a22)
-   finagle-netty4: Netty's reference leak tracking now defaults to disabled.
    Set the flag `com.twitter.finagle.netty4.trackReferenceLeaks` to `true` to enable.
    [f63d7f7a](https://github.com/twitter/finagle/commit/f63d7f7a28157318f98ec8ca44821856aa7f550f)

#### Breaking API Changes

-   finagle: Dropped a dependency on Netty 3 [03c773a5](https://github.com/twitter/finagle/commit/03c773a506aa838c562e37a3e586fb862cfa1a6a):

    -   finagle-netty3 sub-project has been removed
    -   finagle-http-cookie sub-project has been removed
    -   `c.t.f.http.Cookie` no longer takes Netty's `DefaultCookie` in the constructor

-   finagle-core: The `peerCertificate` methods of `c.t.f.t.TransportContext` and `c.t.f.p.PushChannelHandle`
    have been replaced with the more robust `sslSessionInfo`. Users looking for just the functional
    equivalence of peerCertificate can use `sslSessionInfo.peerCertificates.headOption`.
    [dc4bfbcf](https://github.com/twitter/finagle/commit/dc4bfbcf226adc7b1a5f52366148f8ac36690a71)

-   finagle-core: The `com.twitter.finagle.core.UseClientNackAdmissionFilter` toggle has been replaced
    by a global flag, `com.twitter.finagle.client.useNackAdmissionFilter`.
    [aa36f56b](https://github.com/twitter/finagle/commit/aa36f56b7e47eb2af8fadca83f204fa57a38603e)

-   finagle-thrift: Allow users to specify `stringLengthLimit` and `containerLengthLimit`
    [233150a9](https://github.com/twitter/finagle/commit/233150a9f20dca50ed75c41b80f351674c17a862)
    -   method parameter readLength in `com.twitter.finagle.thrift.Protocols#binaryFactory` renamed to
        `stringLengthLimit` to reflect usage
    -   method parameter `containerLengthLimit` added to `com.twitter.finagle.thrift.Protocols#binaryFactory`

### [Finatra](<https://github.com/twitter/finatra/>) ###

#### Added

-   inject-server: Add `globalFlags` argument to `EmbeddedTwitterServer`, which will allow for scoping
    a `c.t.a.GlobalFlag` property change to the lifecycle of the underlying TwitterServer, as a
    `c.t.a.GlobalFlag` is normally scoped to the JVM/process. This change is also reflected in
    `EmbeddedHttpServer` and `EmbeddedThriftServer` constructors. [38a3180a](https://github.com/twitter/finatra/commit/38a3180a5d61d12fb1546dd572f075cfd2fb3dbf)
-   inject-utils: add `toOrderedMap` implicit conversion for `java.util.Map` [1686420c](https://github.com/twitter/finatra/commit/1686420c58506eddf3ef2fb4e75d8007bc27ee2e)
-   finatra-kafka-streams: Add flag `rocksdb.manifest.preallocation.size` with default value `4.megabytes`
    to `c.t.f.k.c.RocksDbFlags` and set value in `c.t.f.k.c.FinatraRocksDBConfig`. [0cac9785](https://github.com/twitter/finatra/commit/0cac9785bc90c421e49a7c0db08066cd0d7a61b9)
-   finatra-http: Add `commaSeparatedList` boolean parameter to `QueryParams`, for parsing comma-separated
    query parameters into collection types. [0ae425a2](https://github.com/twitter/finatra/commit/0ae425a2f50d0f764f39c80fddd8e11ee0f4bf8e)

#### Changed

-   finatra-kafka: Upgraded kafka libraries from 2.0.0 to 2.2.0 [9d22ee7e](https://github.com/twitter/finatra/commit/9d22ee7ea99f9db605882b90b0b6052e841e60ec)
    -   [Kafka 2.0.1 Release Notes](https://archive.apache.org/dist/kafka/2.0.1/RELEASE_NOTES.html)
    -   [Kafka 2.1.0 Release Notes](https://archive.apache.org/dist/kafka/2.1.0/RELEASE_NOTES.html)
    -   [Kafka 2.1.1 Release Notes](https://archive.apache.org/dist/kafka/2.1.1/RELEASE_NOTES.html)
    -   [Kafka 2.2.0 Release Notes](https://archive.apache.org/dist/kafka/2.2.0/RELEASE_NOTES.html)
-   finatra-thrift: Removed `c.t.finatra.thrift.exceptions.FinatraThriftExceptionMapper`,
    `c.t.finatra.thrift.filters.ClientIdAcceptlistFilter`,
    `c.t.finatra.thrift.modules.ClientIdAcceptlistModule`,
    `c.t.finatra.thrift.filters.ClientIdWhitelistFilter`,
    `c.t.finatra.thrift.modules.ClientIdWhitelistModule`,
    and the finatra/finatra\_thrift\_exceptions.thrift IDL. [caed5ec8](https://github.com/twitter/finatra/commit/caed5ec8c0aa38381853d8efb3a6717b78670dbc)
-   finatra-thrift: Constructing a ThriftRouter now requires serverName. [dc357fd8](https://github.com/twitter/finatra/commit/dc357fd8361f75e4831f464835581ce9ab38cdee)
-   finatra-examples: Updated `StreamingController` to use `Reader` instead of `AsyncStream`
    [3d5e3282](https://github.com/twitter/finatra/commit/3d5e3282cd860a1b4fa5b1c4a608098f97ca300a)
-   finatra-kafka-streams: Implement `FinatraKeyValueStore` as custom store. [cd38ddf6](https://github.com/twitter/finatra/commit/cd38ddf699872c48e4bbce2cfbda14c1a98d5864)
-   finatra-thrift: Constructing a `ThriftRouter` now requires `c.t.f.StackTransformer`.
    [a96312d2](https://github.com/twitter/finatra/commit/a96312d2fb3ee53ba56b2eda914245ef05c89c02)

#### Fixed

-   finatra-kafka: Ensure that `EmbeddedKafka` implementation of `beforeAll()` makes
    call to `super.beforeAll()` so hooks registered in super class get executed. [9404b28f](https://github.com/twitter/finatra/commit/9404b28f4477387872140a6d153196887213bb70)
-   finatra-kafka-streams: `FinatraTransformer.timerStore` config object references immutable
    map which causes exception thrown if user code calls `AbstractStoreBuilder.withLoggingDisabled`.
    Fixed `FinatraTransformer.timerStore` to convert from immutable map to mutable map before
    forwarding config object to kafka library. [827c4612](https://github.com/twitter/finatra/commit/827c46126dddc271e8b29b80f6275da3d852cb4d)

### [Twitter Server](<https://github.com/twitter/twitter-server/>) ###

-   Remove deprecated uses of `c.t.server.ShadowAdminServer`. [e94e8300](https://github.com/twitter/twitter-server/commit/e94e83006d24b26c63f279fa72ab22a95d406f4a)
-   Mix in the `c.t.finagle.DtabFlags` to allow servers to append to the "base" `c.t.finagle.Dtab`
    delegation table. Users can now call `c.t.finagle.DtabFlags\#addDtabs()` when they want to append
    the parsed `Flag` value to the `Dtab.base` delegation table. Users should note to only call this
    method _after_ Flag parsing has occurred (which is after **init** and before **premain**).
    We also update the `c.t.server.handler.DtabHandler` to always return a proper JSON response of
    the currently configured `c.t.finagle.Dtab.base`. [a00e3942](https://github.com/twitter/twitter-server/commit/a00e3942d95fd0a0e29e14b47fa0997c8e6b3799)

### [Util](<https://github.com/twitter/util/>) ###

-   util-app: Improve usage of `Flag.let` by providing a `Flag.letParse` method
    [0d9dded3](https://github.com/twitter/util/commit/0d9dded32b931d6fff7335b5f4c573c474b5b65a)


text:
#ifdef _MSC_VER
#include "stdafx.h"
#else
#include <stdint.h>
#endif

#include <vector>
#include "Map.h"

#ifndef MINIMALSECTORABSTRACTION_H
#define MINIMALSECTORABSTRACTION_H

const int maxNumParents    = 14;
const int parentBits       =  4;
//const int sectorSize       = 16;
extern int sectorSize;
const int sectorOffsetBits =  4;
const int maxNumEdges      =  7;

// each abstract node needs 32 bits...2^16 memory fixed = 64k
// number of parents/regions (8 bits)
// initial address in memory (16 bits)
// total number of edges (8 bits)

// each parent has (16 bits)
// sectorOffsetBits = 8 -- this is 0..16 the square in the sector
// edge end         = 8

// each edge has (8 bits)
// direction           = 2
// parent num          = 6

// pad everything to the word boundary
// abstraction size info = 2*parents + edges + (4-(2*parents + edges)%4)

struct sectorInfo {
  uint8_t numRegions;
  uint8_t numEdges;
  uint16_t memoryAddress;
};

struct tempEdgeData {
  int from, to, direction;
};

inline bool operator==(const tempEdgeData& x, const tempEdgeData& y)
{
  return ((x.to == y.to) && (x.from == y.from) && (x.direction == y.direction));
}

/**
* MinimalSectorAbstraction
 *
 * \brief Builds a map abstraction
 *
 * Builds a map abstraction as described in AI Game Programming Wisdom 4.
 *
 * The abstraction is optimized to use relatively little memory.
 * This is the first version of the abstraction that I wrote.
 * The code could be a bit cleaner...but it works
 */
class MinimalSectorAbstraction {
 public:
  MinimalSectorAbstraction(Map *map, int sectorSize);
  void OpenGLDraw();
  int GetSector(int x, int y);
  int GetRegion(int x, int y);
  void GetXYLocation(unsigned int sector, unsigned int region,
                     unsigned int &x, unsigned int &y);
  void GetNeighbors(unsigned int sector, unsigned int region,
            std::vector<tempEdgeData> &edges);
  int GetAdjacentSector(unsigned int sector, int direction);

  void OptimizeRegionLocations();
  void InitializeOptimization();
  bool PerformOneOptimizationStep();
	int GetAbstractionBytesUsed() { return sectors.size()*4+memory.size(); }
 private:
  void BuildAbstraction();
  void GetEdges(std::vector<std::vector<int> > &areas,
        int xSector, int ySector,
        std::vector<tempEdgeData> &edges);

  void GetEdgeHelper(std::vector<int> &startRegion,
             int startIndex, int startOffset,
             std::vector<int> &targetRegion,
             int tarGetIndex, int targetOffset,
             std::vector<tempEdgeData> &edges,
             int direction);
  int GetSectorRegions(std::vector<int> &area,
               int absXSector,
               int absYSector);
  void LabelRegion(std::vector<int> &area,
           int x, int y, int label);

  void StoreSectorInMemory(sectorInfo &si,
               std::vector<int> &area,
               std::vector<tempEdgeData> &edges);
  uint8_t GetAbstractEdge(tempEdgeData &data);
  uint8_t GetAbstractLocation(std::vector<int> area, int value);
  int FindParentRegion(int startLoc,
               std::vector<int> &parents,
               int mapXOffset, int mapYOffset);
  double GetRegionError(int fromSector, int fromRegion,
                        int sx, int sy, double limit);
  void MoveRegionCenter(int sector, int region);
  void ComputePotentialMemorySavings();
  void ResetAbstractCenter(int sector, int region);

  int numXSectors, numYSectors;
  std::vector<sectorInfo> sectors;
  std::vector<uint8_t> memory;
  std::vector<std::vector<double> > regionError;
  Map *map;
  std::vector<std::vector<int> > areas;

  int optimizationIndex;
};

#endif


text: default_app_config = 'autonag.apps.AutonagConfig'


text:
package org.spacehq.mc.protocol.packet.ingame.client.player;

import org.spacehq.packetlib.io.NetInput;
import org.spacehq.packetlib.io.NetOutput;
import org.spacehq.packetlib.packet.Packet;

import java.io.IOException;

public class ClientSteerVehiclePacket implements Packet {

    private float sideways;
    private float forward;
    private boolean jump;
    private boolean dismount;

    @SuppressWarnings("unused")
    private ClientSteerVehiclePacket() {
    }

    public ClientSteerVehiclePacket(float sideways, float forward, boolean jump, boolean dismount) {
        this.sideways = sideways;
        this.forward = forward;
        this.jump = jump;
        this.dismount = dismount;
    }

    public float getSideways() {
        return this.sideways;
    }

    public float getForward() {
        return this.forward;
    }

    public boolean getJumping() {
        return this.jump;
    }

    public boolean getDismounting() {
        return this.dismount;
    }

    @Override
    public void read(NetInput in) throws IOException {
        this.sideways = in.readFloat();
        this.forward = in.readFloat();
        int flags = in.readUnsignedByte();
        this.jump = (flags & 1) > 0;
        this.dismount = (flags & 2) > 0;
    }

    @Override
    public void write(NetOutput out) throws IOException {
        out.writeFloat(this.sideways);
        out.writeFloat(this.forward);
        byte flags = 0;
        if(this.jump) {
            flags = (byte) (flags | 1);
        }

        if(this.dismount) {
            flags = (byte) (flags | 2);
        }

        out.writeByte(flags);
    }

    @Override
    public boolean isPriority() {
        return false;
    }

}


text:
SpannaAPI
=========

API for Spanna, along with the Signature Scanning technology, which alows for easy version updating for developers.
Release soon, February 2015. Date will be confirmed sometime in January.

Currently unstable.


text:
<?php

declare(strict_types=1);

namespace Knp\DoctrineBehaviors\Contract\Entity;

interface TranslationInterface
{
    public static function getTranslatableEntityClass(): string;

    public function setTranslatable(TranslatableInterface $translatable): void;

    public function getTranslatable(): TranslatableInterface;

    public function setLocale(string $locale): void;

    public function getLocale(): string;

    public function isEmpty(): bool;
}


text:
<?php
// +----------------------------------------------------------------------
// | YunCMS
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://www.yunalading.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: chenqianhao <68527761@qq.com>
// +----------------------------------------------------------------------
namespace app\common\model;
/**
 * 友情链接
 * Class BaseMenusModel
 * @package app\common\model
 */
abstract class BaseMenusModel extends BaseModel {
    protected $name = 'menus';
}


text:
<!DOCTYPE html>

  <title>
   Closure Unit Tests - goog.style.bidi
  </title>

   bodyChild

    LTR

     elm

     elm.offsetParent.scrollLeft:

     bidi.getScrollLeft(...):

     bidi.getOffsetStart(...):

    <form name="formLtr" action="bidi_test.html#">
     goog.style.bidi.setScrollOffset:
     <input name="pixelsLtr" type="text" />

      set

    </form>

    RTL

     elm

     elm.offsetParent.scrollLeft:

     bidi.getScrollLeft(...):

     bidi.getOffsetStart(...):

    <form name="formRtl" action="bidi_test.html#">
     goog.style.setScrollOffset:
     <input name="pixelsRtl" type="text" />

      set

    </form>

    INNER


text:
<!DOCTYPE html>
<html>
<head>
    <title>Aurelia Webpack TypeScript Starter</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

</body>
</html>


text:
package org.apache.skywalking.oap.server.core.query.type;

import lombok.Getter;
import lombok.Setter;
import org.apache.skywalking.oap.server.core.management.ui.template.UITemplate;
import org.apache.skywalking.oap.server.library.util.BooleanUtils;

@Setter
@Getter
public class DashboardConfiguration {
    private String id;
    /**
     * Configuration in JSON format.
     */
    private String configuration;
    private boolean disabled;

    public DashboardConfiguration fromEntity(UITemplate templateEntity) {
        this.setId(templateEntity.getTemplateId());
        this.setConfiguration(templateEntity.getConfiguration());
        this.setDisabled(BooleanUtils.valueToBoolean(templateEntity.getDisabled()));
        return this;
    }
}


text:
namespace PR {
struct PluginSpecification;
struct PluginParamDescBlock;

namespace UI {
class PR_LIB_UI PropertyContainer : public QObject {
	Q_OBJECT
public:
	PropertyContainer();
	~PropertyContainer();

	void add(IProperty* property);
	void remove(IProperty* property);

	void addSpecification(const PluginSpecification& spec);

	const QVector<IProperty*>& topProperties() const;
	const QVector<IProperty*>& allProperties() const;

signals:
	void propertyChanged(IProperty* prop);
	void propertyStructureChanged(IProperty* prop);
	void valueChanged(IProperty* prop);

private slots:
	void propertyWasDestroyed(IProperty* prop);
	void propertyWasChanged(IProperty* obj);
	void propertyStructureWasChanged(IProperty* obj);
	void valueWasChanged(IProperty* obj);

private:
	void rec_add(IProperty* property);
	void addBlock(const PluginParamDescBlock& block, IProperty* parent);

	QVector<IProperty*> mAllProperties;
	QVector<IProperty*> mTopProperties;
};
} // namespace UI
} // namespace PR


text:
include(binutils.common)

function(nf_add_hex_bin_dump_targets target)
    if(EXECUTABLE_OUTPUT_PATH)
        set(FILENAME "${EXECUTABLE_OUTPUT_PATH}/${target}")
    else()
        set(FILENAME "${target}")
    endif()

	#get_filename_component(FNSHORT ${FILENAME} NAME_WE)
	string(REGEX REPLACE "\\.[^.]*$" "" FNSHORT ${FILENAME})

    # add targets for HEX, BIN and S19 formats with no output so they will always be built
    add_custom_target(${target}.hex DEPENDS ${target} COMMAND ${CMAKE_OBJCOPY} -Oihex ${FILENAME} ${FNSHORT}.hex)
    add_custom_target(${target}.s19 DEPENDS ${target} COMMAND ${CMAKE_OBJCOPY} -Osrec ${FILENAME} ${FNSHORT}.s19)
    add_custom_target(${target}.bin DEPENDS ${target} COMMAND ${CMAKE_OBJCOPY} -Obinary ${FILENAME} ${FNSHORT}.bin)
    add_custom_target(${target}.dump DEPENDS ${target} COMMAND ${CMAKE_OBJDUMP} -d -EL -S ${FILENAME} ${FNSHORT}.dump)
endfunction()

function(nf_print_target_size target)
    if(EXECUTABLE_OUTPUT_PATH)
      set(FILENAME "${EXECUTABLE_OUTPUT_PATH}/${target}")
    else()
      set(FILENAME "${target}")
    endif()
    add_custom_command(TARGET ${target} POST_BUILD COMMAND ${CMAKE_SIZE} -A -x ${FILENAME})
endfunction()

function(nf_set_linker_file target linker_file_name)

    # set linker file name
    set_target_properties(${target} PROPERTIES LINK_FLAGS "-T${linker_file_name}")

endfunction()


text:
![.NET standard 2.0](https://img.shields.io/badge/.NET-standard2.0-brightgreen)

## Goals

This library aims to provide interfaces and extensions that are being used by the rest of the framework.


text:
@interface XZXDateUtil : NSObject

+ (instancetype)sharedDateUtil;

// 当前本地日期(除去时间差)
+ (NSDate *)localDateOfDate:(NSDate *)date;

// 周
+ (NSInteger)weekdayOfDate:(NSDate *)date;

// 日期
+ (NSInteger)dayOfDate:(NSDate *)date;

// 时
+ (NSInteger)hourOfDate:(NSDate *)date;

+ (BOOL)isDateToday:(NSDate *)date;

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;

+ (NSDate *)dateWithYear:(NSInteger)year
                   month:(NSInteger)month
                     day:(NSInteger)day
                    hour:(NSInteger)hour
                  minute:(NSInteger)minute
                  second:(NSInteger)second;

+ (NSDate *)dateByAddingSeconds:(NSUInteger)seconds toDate:(NSDate *)formerDate;

//---------------------------
//Formatter
//---------------------------
+ (NSString *)dateStringOf24H:(NSDate *)date;

+ (NSString *)dateStringOfMonthAndDay:(NSDate *)date;

+ (NSString *)dateStringOfHomeTitleWithMouthOffset:(NSInteger)offset;

+ (NSString *)dateStringOfYMD:(NSDate *)date;

+ (NSString *)dateStringOfYYMMDD:(NSDate *)date;

+ (NSString *)dateStringOfYMDHM:(NSDate *)date;

+ (NSDate *)dateOfYMD:(NSDate *)date;
@end


text:
/*
Projector calibration for the AlloSphere

NOTES:

The clip space z and w can be calculated the same way as orthographic.
The xy (or uv) must be calculated from the vertex position v.

We know azimuth/elevation to the corners ABCD. From this we can derive their spatial locations.
Assume the allosphere is a unit sphere, then the result is simple polar to cartesian.
	This can be refined by modeling the sphere properly as two unit hemispheres joined by a cylinder of some width W.
	The adjustment W can be partially verified by ensuring that the normals of ABC and BCD are equal.
Calculate point Q as the center of ABCD (B.x-A.x, D.y-A.y)
	Again, two ways to calculate Q, which can be used to minimize error in the sphere model.
	Alternatively, we can measure Q empirically to further minimize error.
Assume a projector location F (or derive from measuring the lens position).

Vertex locations v must be projected into the view of the projector, which is a matrix multiplication.
We only care about the XY components of the result, but these must be scaled such that A is -1,-1 and C is 1, 1.
This can be achived by dividing by (the result of projecting QC into the view)

A view matrix can be constructed as:
		Matrix4(
			 ux[0], ux[1], ux[2], -(ux.dot(eyePos)),
			 uy[0], uy[1], uy[2], -(uy.dot(eyePos)),
			 uz[0], uz[1], uz[2], -(uz.dot(eyePos)),
			0, 0, 0, 1
		);

eye == F
R = norm(((B+C)/2) - Q)  // unit vector from Q to midpoint of BC
uz = norm(FQ)
ux = -cross(norm(cross(R, uz)), uz)
	or, since uz = parallel(R,uz) + perpendicular(R,uz):
	perpendicular(R,uz) = uz - parallel(R,uz)
	ux = uz - R*dot(R, uz)

uy = cross(ux, uz)

simplified:

u = dot(v-F, ux) / dot(QC-F, ux);
v = dot(v-F, uy) / dot(QC-F, uy);

note that denominator is a constant.
Not sure if v should be normalized or not, or whether this makes any difference at all.

*/

#include "allocore/al_Allocore.hpp"
#include "allocore/graphics/al_Shader.hpp"

using namespace al;

static const char * vLight = R"(
varying vec3 normal, lightDir, eyeVec;
void main(){
	normal = gl_NormalMatrix * gl_Normal;
	vec3 V = vec3(gl_ModelViewMatrix * gl_Vertex);
	eyeVec = normalize(-V);
	lightDir = normalize(vec3(gl_LightSource[0].position.xyz - V));
	gl_Position = ftransform();
}
)";

static const char * fLight = R"(
varying vec3 normal, lightDir, eyeVec;
void main(){
	vec4 final_color = gl_FrontMaterial.ambient
		* (gl_FrontLightModelProduct.sceneColor + gl_LightSource[0].ambient);
	vec3 N = normalize(normal);
	vec3 L = lightDir;
	float lambertTerm = dot(N,L);
	if(lambertTerm > 0.){
		final_color += gl_LightSource[0].diffuse
		               * gl_FrontMaterial.diffuse
					   * lambertTerm;
		vec3 E = eyeVec;
		vec3 R = reflect(-L, N);
		float spec = pow( max(dot(R, E), 0.),
		                 gl_FrontMaterial.shininess + 1e-20);
		final_color += gl_LightSource[0].specular
		               * gl_FrontMaterial.specular
					   * spec;
	}
	gl_FragColor = final_color;
}
)";

struct MyWindow : Window{

	ShaderProgram shaderP;
	Shader shaderV, shaderF;
	Mesh mesh;
	Graphics gl;
	Light light;
	Material material;
	double angle;
	bool useShader;
	bool bGrid;

	MyWindow(): angle(0), bGrid(true) {}

	bool onCreate(){
		shaderV.source(vLight, Shader::VERTEX).compile();
		shaderF.source(fLight, Shader::FRAGMENT).compile();
		shaderP.attach(shaderV).attach(shaderF).link();

		shaderV.printLog();
		shaderF.printLog();
		shaderP.printLog();

		return true;
	}

	void grid(float w, float h, int rep) {
		gl.color(HSV(1./rep, 1., 1.));
		for (int v=w; v<width(); v+=w*2) {
			gl.vertex(v, 1, 0);
			gl.vertex(v, height(), 0);
		}
		for (int v=h; v<height(); v+=h*2) {
			gl.vertex(1, v, 0);
			gl.vertex(width(), v, 0);

		}
		if (rep > 0) {
			grid(w/2, h/2, rep-1);
		}
	}

	void drawgrid() {
		gl.projection(Matrix4d::ortho(0, width(), 0, height(), -1, 1));
			gl.modelView(Matrix4d::identity());

			// draw grid
			//gl.lineWidth(0.5);
			gl.begin(gl.LINES);
			gl.color(0.5, 0.5, 0.5, 1);
			float w = width();
			float h = height();

			gl.color(1, 1, 1);
			gl.vertex(1, 1, 0);
			gl.vertex(1, height(), 0);
			gl.vertex(width(), 1, 0);
			gl.vertex(width(), height(), 0);
			gl.vertex(1, 1, 0);
			gl.vertex(width(), 0, 0);
			gl.vertex(1, height(), 0);
			gl.vertex(width(), height(), 0);

			grid(w/2, h/2, 2);

			gl.end();
	}

	bool onFrame(){
		gl.clearColor(0,0,0,1);
		gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
		gl.viewport(0,0, width(), height());

		if (bGrid) {
			gl.viewport(0,0, width(), height()/2);
			drawgrid();
			gl.viewport(0,height()/2, width(), height()/2);
			drawgrid();
		} else {
			gl.matrixMode(gl.PROJECTION);
			gl.loadMatrix(Matrix4d::perspective(45, aspect(), 0.1, 100));
			gl.matrixMode(gl.MODELVIEW);
			gl.loadMatrix(Matrix4d::lookAt(Vec3d(0,0,-2.5), Vec3d(0,0,0), Vec3d(0,1,0)));

			gl.depthTesting(true);

			// Create a shape
			mesh.reset();
			mesh.primitive(gl.TRIANGLES);
			//addIcosahedron(mesh);
			//addDodecahedron(mesh);
			addSphere(mesh, 1, 16, 16);

			if((angle+=0.003)>=M_2PI) angle-=M_2PI;

			Mat4f xfm;
			xfm.setIdentity();
			xfm.rotate(M_PI/2, 0,2).rotate(angle, 1,2).rotate(angle*8, 0,1);
			xfm.scale(Vec3f(0.5, 0.2, 1));

			mesh.transform(xfm);
			//mesh.decompress();
			mesh.generateNormals();

			// Render
			shaderP.begin();

				material.shininess(2);

				light.ambient(Color(0.1,0,0));
				light.diffuse(Color(0.9,0,0));
				light.specular(Color(0.5));

				material();
				light();
				gl.draw(mesh);

			shaderP.end();
		}

		return true;
	}

	virtual bool onKeyDown(const Keyboard& k){
		if(k.key('s')) shaderP.toggleActive();
		return true;
	}

};

MyWindow win1;

int main(){
	win1.add(new StandardWindowKeyControls);
	win1.create(Window::Dim(800, 600));

	MainLoop::start();
	return 0;
}


text:
"""Exceptions for the error-reporting surface."""

from googlecloudsdk.core import exceptions

class CannotOpenFileError(exceptions.Error):
  """Cannot open file."""

  def __init__(self, f, e):
    super(CannotOpenFileError, self).__init__(
        'Failed to open file [{f}]: {e}'.format(f=f, e=e))


text:
All

House

Site

Land

equipment


text:
package org.apache.hadoop.yarn.server.nodemanager.webapp;

import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES;
import static org.apache.hadoop.yarn.webapp.view.JQueryUI.DATATABLES_ID;
import static org.apache.hadoop.yarn.webapp.view.JQueryUI.initID;
import static org.apache.hadoop.yarn.webapp.view.JQueryUI.tableInit;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.yarn.api.records.ApplicationId;
import org.apache.hadoop.yarn.factories.RecordFactory;
import org.apache.hadoop.yarn.factory.providers.RecordFactoryProvider;
import org.apache.hadoop.yarn.server.nodemanager.Context;
import org.apache.hadoop.yarn.server.nodemanager.containermanager.application.Application;
import org.apache.hadoop.yarn.server.nodemanager.webapp.dao.AppInfo;
import org.apache.hadoop.yarn.util.ConverterUtils;
import org.apache.hadoop.yarn.webapp.SubView;
import org.apache.hadoop.yarn.webapp.YarnWebParams;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet;
import org.apache.hadoop.yarn.webapp.hamlet.Hamlet.TABLE;
import org.apache.hadoop.yarn.webapp.view.HtmlBlock;
import org.apache.hadoop.yarn.webapp.view.InfoBlock;

import com.google.inject.Inject;

public class ApplicationPage extends NMView implements YarnWebParams {

  @Override protected void preHead(Page.HTML<_> html) {
    commonPreHead(html);

    set(DATATABLES_ID, "containers");
    set(initID(DATATABLES, "containers"), containersTableInit());
    setTableStyles(html, "containers");
  }

  private String containersTableInit() {
    return tableInit().append(",aoColumns:[null]}").toString();
  }

  @Override
  protected Class<? extends SubView> content() {
    return ApplicationBlock.class;
  }

  public static class ApplicationBlock extends HtmlBlock implements
      YarnWebParams {

    private final Context nmContext;
    private final Configuration conf;
    private final RecordFactory recordFactory;

    @Inject
    public ApplicationBlock(Context nmContext, Configuration conf) {
      this.conf = conf;
      this.nmContext = nmContext;
      this.recordFactory = RecordFactoryProvider.getRecordFactory(this.conf);
    }

    @Override
    protected void render(Block html) {
      ApplicationId applicationID =
          ConverterUtils.toApplicationId(this.recordFactory,
              $(APPLICATION_ID));
      Application app = this.nmContext.getApplications().get(applicationID);
      AppInfo info = new AppInfo(app);
      info("Application's information")
            ._("ApplicationId", info.getId())
            ._("ApplicationState", info.getState())
            ._("User", info.getUser());
      TABLE<Hamlet> containersListBody = html._(InfoBlock.class)
          .table("#containers");
      for (String containerIdStr : info.getContainers()) {
        containersListBody
               .tr().td()
                 .a(url("container", containerIdStr), containerIdStr)
                 ._()._();
      }
      containersListBody._();
    }
  }
}


text:
from .analyses import cdg

class MergeSeekr(object):
    def __init__(self, cfg_, cdg_):
        self._cfg = cfg_
        self._cdg = cdg_

        self._path_merge_points = {}

        self._construct()

    def _construct(self):
        '''
        A merge point (or transition point, as is termed in Veritesting paper)
        should be an immediate post-dominator of a certain range of nodes.
        We can get the post-dominator information from CDG.
        '''
        post_doms = self._cdg.get_post_dominators()
        # Get all nodes in CFG that has two out degrees (means a branch)
        branching_nodes = self._cfg.get_branching_nodes()
        for node in branching_nodes:
            successors = self._cfg.get_successors(node)
            if node not in post_doms:
                continue
            post_dom = post_doms[node]
            if not isinstance(post_dom, cdg.TempNode):
                # DFS until the post dominator, and label all nodes on the way
                for succ in successors:
                    self._path_merge_points[succ.addr] = post_dom.addr

    def get_path_merge_points(self):
        return self._path_merge_points


text:
import type { Mock } from "mocks/types";
import type { OgModalAlert } from "og-components/og-modal-alert/types";

export default class AlertMockProvider implements Mock<OgModalAlert> {
	// Mock alert object
	public constructor(private readonly alert: OgModalAlert = {
		header: "Alert!",
		message: "alert message"
	}) {}

	public $get(): OgModalAlert {
		// Return the mock alert object
		return this.alert;
	}
}

AlertMockProvider.$inject = [];


text:
azure.mgmt.devtestlabs package
==========================

Submodules
----------

.. toctree::

   azure.mgmt.devtestlabs.models
   azure.mgmt.devtestlabs.operations

Module contents
---------------

.. automodule:: azure.mgmt.devtestlabs
    :members:
    :undoc-members:
    :show-inheritance:


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

GEN('#include "content/public/test/browser_test.h"');

/**
 * TestFixture for kiosk certification manager dialog WebUI testing.
 * @extends {testing.Test}
 * @constructor
 */
function CertificateManagerDialogWebUITest() {}

CertificateManagerDialogWebUITest.prototype = {
  __proto__: testing.Test.prototype,

  /**
   * Browse to the certification manager dialog page.
   */
  browsePreload: 'chrome://certificate-manager/',
};

// crbug.com/682497
GEN('#if defined(ADDRESS_SANITIZER)');
GEN('#define MAYBE_Basic DISABLED_Basic');
GEN('#else');
GEN('#define MAYBE_Basic Basic');
GEN('#endif');
// Sanity test of the WebUI could be opened with no errors.
TEST_F('CertificateManagerDialogWebUITest', 'MAYBE_Basic', function() {
  assertEquals(this.browsePreload, document.location.href);
});


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

namespace ConsoleApp1.BinaryHeapDataStructure
{
    public class BinaryHeap<T> : IEnumerable<T>
    {
        private List<T> heap;
        private Func<T, T, bool> compareFunc;

        public BinaryHeap(Func<T, T, bool> compareFunc)
        {
            this.heap = new List<T>();
            this.heap.Add(default(T));
            this.compareFunc = compareFunc;
        }

        public int Count => this.heap.Count - 1;

        public T Top => this.heap[1];

        public bool IsEmpty => this.heap.Count <= 1;

        public void Insert(T value)
        {
            this.heap.Add(default(T));

            int index = this.heap.Count - 1;
            while (index > 1)
            {
                if (this.compareFunc(this.heap[index / 2], value))
                {
                    this.heap[index] = heap[index / 2];
                }
                else
                {
                    break;
                }

                index /= 2;
            }

            this.heap[index] = value;
        }

        public void RemoveTop()
        {
            var value = this.heap[this.heap.Count - 1];
            this.heap.RemoveAt(this.heap.Count - 1);

            if (!this.IsEmpty)
            {
                this.HeapifyDown(1, value);
            }
        }

        public void HeapifyDown(int initialIndex,  T value)
        {
            int index = initialIndex;
            while (index * 2 + 1 < this.heap.Count)
            {
                int leftKidIndex = index * 2;
                int rightKidIndex = index * 2 + 1;

                int smallerKidIndex =
                    this.compareFunc(this.heap[leftKidIndex], this.heap[rightKidIndex]) ?
                    rightKidIndex :
                    leftKidIndex;

                if (this.compareFunc(value, this.heap[smallerKidIndex]))
                {
                    this.heap[index] = this.heap[smallerKidIndex];
                }
                else
                {
                    break;
                }

                index = smallerKidIndex;
            }

            if (index * 2 < this.heap.Count)
            {
                int smallerKidIndex = index * 2;

                if (this.compareFunc(this.heap[smallerKidIndex], value))
                {
                    this.heap[index] = this.heap[smallerKidIndex];
                    index = smallerKidIndex;
                }
            }

            this.heap[index] = value;
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public IEnumerator<T> GetEnumerator()
        {
            for (int i = 1; i < this.heap.Count; i++)
            {
                yield return this.heap[i];
            }
        }
    }
}


text:
cat "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/$PRODUCT_NAME.h" >> "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/tmp.txt"
echo "#define IPHONE 1" > "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/$PRODUCT_NAME.h"
cat "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/tmp.txt" >> "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/$PRODUCT_NAME.h"
rm -rf "$BUILT_PRODUCTS_DIR/include/$PRODUCT_NAME/tmp.txt"


text:
maintainer       "Ry4an Brase"
maintainer_email "rbrase-opscode@ry4an.org"
license          "Apache 2.0"
description      "Installs/Configures New Relic Monitoring "
long_description IO.read(File.join(File.dirname(__FILE__), 'README.md'))
version          "1.0.0"

recipe "newrelic_monitoring", "Installs and configured newrelic monitoring"

%w{ ubuntu debian redhat fedora centos }.each do |os|
  supports os
end


text:
define(
"dojo/cldr/nls/en/japanese", //begin v1.x content
{
	"field-sat-relative+0": "this Saturday",
	"field-sat-relative+1": "next Saturday",
	"field-dayperiod": "AM/PM",
	"field-sun-relative+-1": "last Sunday",
	"field-mon-relative+-1": "last Monday",
	"field-minute": "Minute",
	"field-day-relative+-1": "yesterday",
	"field-weekday": "Day of the Week",
	"field-era": "Era",
	"field-hour": "Hour",
	"field-sun-relative+0": "this Sunday",
	"field-sun-relative+1": "next Sunday",
	"field-wed-relative+-1": "last Wednesday",
	"field-day-relative+0": "today",
	"field-day-relative+1": "tomorrow",
	"dateFormat-long": "MMMM d, y G",
	"field-tue-relative+0": "this Tuesday",
	"field-zone": "Time Zone",
	"field-tue-relative+1": "next Tuesday",
	"field-week-relative+-1": "last week",
	"dateFormat-medium": "MMM d, y G",
	"field-year-relative+0": "this year",
	"field-year-relative+1": "next year",
	"field-sat-relative+-1": "last Saturday",
	"field-year-relative+-1": "last year",
	"field-year": "Year",
	"field-fri-relative+0": "this Friday",
	"field-fri-relative+1": "next Friday",
	"field-week": "Week",
	"field-week-relative+0": "this week",
	"field-week-relative+1": "next week",
	"field-month-relative+0": "this month",
	"field-month": "Month",
	"field-month-relative+1": "next month",
	"field-fri-relative+-1": "last Friday",
	"field-second": "Second",
	"field-tue-relative+-1": "last Tuesday",
	"field-day": "Day",
	"field-mon-relative+0": "this Monday",
	"field-mon-relative+1": "next Monday",
	"field-thu-relative+0": "this Thursday",
	"field-second-relative+0": "now",
	"dateFormat-short": "M/d/y GGGGG",
	"field-thu-relative+1": "next Thursday",
	"dateFormat-full": "EEEE, MMMM d, y G",
	"field-wed-relative+0": "this Wednesday",
	"field-wed-relative+1": "next Wednesday",
	"field-month-relative+-1": "last month",
	"field-thu-relative+-1": "last Thursday"
}
//end v1.x content
);


text:
// Generated by the Scala Plugin for the Protocol Buffer Compiler.
// Do not edit!
//
// Protofile syntax: PROTO3

package com.google.protobuf.any

/** `Any` contains an arbitrary serialized protocol buffer message along with a
  * URL that describes the type of the serialized message.
  *
  * Protobuf library provides support to pack/unpack Any values in the form
  * of utility functions or additional generated methods of the Any type.
  *
  * Example 1: Pack and unpack a message in C++.
  *
  *     Foo foo = ...;
  *     Any any;
  *     any.PackFrom(foo);
  *     ...
  *     if (any.UnpackTo(&foo)) {
  *       ...
  *     }
  *
  * Example 2: Pack and unpack a message in Java.
  *
  *     Foo foo = ...;
  *     Any any = Any.pack(foo);
  *     ...
  *     if (any.is(Foo.class)) {
  *       foo = any.unpack(Foo.class);
  *     }
  *
  *  Example 3: Pack and unpack a message in Python.
  *
  *     foo = Foo(...)
  *     any = Any()
  *     any.Pack(foo)
  *     ...
  *     if any.Is(Foo.DESCRIPTOR):
  *       any.Unpack(foo)
  *       ...
  *
  *  Example 4: Pack and unpack a message in Go
  *
  *      foo := &pb.Foo{...}
  *      any, err := ptypes.MarshalAny(foo)
  *      ...
  *      foo := &pb.Foo{}
  *      if err := ptypes.UnmarshalAny(any, foo); err != nil {
  *        ...
  *      }
  *
  * The pack methods provided by protobuf library will by default use
  * 'type.googleapis.com/full.type.name' as the type URL and the unpack
  * methods only use the fully qualified type name after the last '/'
  * in the type URL, for example "foo.bar.com/x/y.z" will yield type
  * name "y.z".
  *
  *
  * JSON
  *
  * The JSON representation of an `Any` value uses the regular
  * representation of the deserialized, embedded message, with an
  * additional field `@type` which contains the type URL. Example:
  *
  *     package google.profile;
  *     message Person {
  *       string first_name = 1;
  *       string last_name = 2;
  *     }
  *
  *     {
  *       "@type": "type.googleapis.com/google.profile.Person",
  *       "firstName": <string>,
  *       "lastName": <string>
  *     }
  *
  * If the embedded message type is well-known and has a custom JSON
  * representation, that representation will be embedded adding a field
  * `value` which holds the custom JSON in addition to the `@type`
  * field. Example (for message [google.protobuf.Duration][]):
  *
  *     {
  *       "@type": "type.googleapis.com/google.protobuf.Duration",
  *       "value": "1.212s"
  *     }
  *
  * @param typeUrl
  *   A URL/resource name that uniquely identifies the type of the serialized
  *   protocol buffer message. This string must contain at least
  *   one "/" character. The last segment of the URL's path must represent
  *   the fully qualified name of the type (as in
  *   `path/google.protobuf.Duration`). The name should be in a canonical form
  *   (e.g., leading "." is not accepted).
  *
  *   In practice, teams usually precompile into the binary all types that they
  *   expect it to use in the context of Any. However, for URLs which use the
  *   scheme `http`, `https`, or no scheme, one can optionally set up a type
  *   server that maps type URLs to message definitions as follows:
  *
  *   * If no scheme is provided, `https` is assumed.
  *   * An HTTP GET on the URL must yield a [google.protobuf.Type][]
  *     value in binary format, or produce an error.
  *   * Applications are allowed to cache lookup results based on the
  *     URL, or have them precompiled into a binary to avoid any
  *     lookup. Therefore, binary compatibility needs to be preserved
  *     on changes to types. (Use versioned type names to manage
  *     breaking changes.)
  *
  *   Note: this functionality is not currently available in the official
  *   protobuf release, and it is not used for type URLs beginning with
  *   type.googleapis.com.
  *
  *   Schemes other than `http`, `https` (or the empty scheme) might be
  *   used with implementation specific semantics.
  * @param value
  *   Must be a valid serialized protocol buffer of the above specified type.
  */
@SerialVersionUID(0L)
final case class Any(
    typeUrl: _root_.scala.Predef.String = "",
    value: _root_.com.google.protobuf.ByteString = _root_.com.google.protobuf.ByteString.EMPTY,
    unknownFields: _root_.scalapb.UnknownFieldSet = _root_.scalapb.UnknownFieldSet.empty
    ) extends scalapb.GeneratedMessage with scalapb.lenses.Updatable[Any] with _root_.scalapb.AnyMethods {
    @transient
    private[this] var __serializedSizeMemoized: _root_.scala.Int = 0
    private[this] def __computeSerializedSize(): _root_.scala.Int = {
      var __size = 0

      {
        val __value = typeUrl
        if (!__value.isEmpty) {
          __size += _root_.com.google.protobuf.CodedOutputStream.computeStringSize(1, __value)
        }
      };

      {
        val __value = value
        if (!__value.isEmpty) {
          __size += _root_.com.google.protobuf.CodedOutputStream.computeBytesSize(2, __value)
        }
      };
      __size += unknownFields.serializedSize
      __size
    }
    override def serializedSize: _root_.scala.Int = {
      var __size = __serializedSizeMemoized
      if (__size == 0) {
        __size = __computeSerializedSize() + 1
        __serializedSizeMemoized = __size
      }
      __size - 1

    }
    def writeTo(`_output__`: _root_.com.google.protobuf.CodedOutputStream): _root_.scala.Unit = {
      {
        val __v = typeUrl
        if (!__v.isEmpty) {
          _output__.writeString(1, __v)
        }
      };
      {
        val __v = value
        if (!__v.isEmpty) {
          _output__.writeBytes(2, __v)
        }
      };
      unknownFields.writeTo(_output__)
    }
    def withTypeUrl(__v: _root_.scala.Predef.String): Any = copy(typeUrl = __v)
    def withValue(__v: _root_.com.google.protobuf.ByteString): Any = copy(value = __v)
    def withUnknownFields(__v: _root_.scalapb.UnknownFieldSet) = copy(unknownFields = __v)
    def discardUnknownFields = copy(unknownFields = _root_.scalapb.UnknownFieldSet.empty)
    def getFieldByNumber(__fieldNumber: _root_.scala.Int): _root_.scala.Any = {
      (__fieldNumber: @_root_.scala.unchecked) match {
        case 1 => {
          val __t = typeUrl
          if (__t != "") __t else null
        }
        case 2 => {
          val __t = value
          if (__t != _root_.com.google.protobuf.ByteString.EMPTY) __t else null
        }
      }
    }
    def getField(__field: _root_.scalapb.descriptors.FieldDescriptor): _root_.scalapb.descriptors.PValue = {
      _root_.scala.Predef.require(__field.containingMessage eq companion.scalaDescriptor)
      (__field.number: @_root_.scala.unchecked) match {
        case 1 => _root_.scalapb.descriptors.PString(typeUrl)
        case 2 => _root_.scalapb.descriptors.PByteString(value)
      }
    }
    def toProtoString: _root_.scala.Predef.String = _root_.scalapb.TextFormat.printToUnicodeString(this)
    def companion: com.google.protobuf.any.Any.type = com.google.protobuf.any.Any
    // @@protoc_insertion_point(GeneratedMessage[google.protobuf.Any])
}

object Any extends scalapb.GeneratedMessageCompanion[com.google.protobuf.any.Any] with scalapb.AnyCompanionMethods {
  implicit def messageCompanion: scalapb.GeneratedMessageCompanion[com.google.protobuf.any.Any] with scalapb.AnyCompanionMethods = this
  def parseFrom(`_input__`: _root_.com.google.protobuf.CodedInputStream): com.google.protobuf.any.Any = {
    var __typeUrl: _root_.scala.Predef.String = ""
    var __value: _root_.com.google.protobuf.ByteString = _root_.com.google.protobuf.ByteString.EMPTY
    var `_unknownFields__`: _root_.scalapb.UnknownFieldSet.Builder = null
    var _done__ = false
    while (!_done__) {
      val _tag__ = _input__.readTag()
      _tag__ match {
        case 0 => _done__ = true
        case 10 =>
          __typeUrl = _input__.readStringRequireUtf8()
        case 18 =>
          __value = _input__.readBytes()
        case tag =>
          if (_unknownFields__ == null) {
            _unknownFields__ = new _root_.scalapb.UnknownFieldSet.Builder()
          }
          _unknownFields__.parseField(tag, _input__)
      }
    }
    com.google.protobuf.any.Any(
        typeUrl = __typeUrl,
        value = __value,
        unknownFields = if (_unknownFields__ == null) _root_.scalapb.UnknownFieldSet.empty else _unknownFields__.result()
    )
  }
  implicit def messageReads: _root_.scalapb.descriptors.Reads[com.google.protobuf.any.Any] = _root_.scalapb.descriptors.Reads{
    case _root_.scalapb.descriptors.PMessage(__fieldsMap) =>
      _root_.scala.Predef.require(__fieldsMap.keys.forall(_.containingMessage eq scalaDescriptor), "FieldDescriptor does not match message type.")
      com.google.protobuf.any.Any(
        typeUrl = __fieldsMap.get(scalaDescriptor.findFieldByNumber(1).get).map(_.as[_root_.scala.Predef.String]).getOrElse(""),
        value = __fieldsMap.get(scalaDescriptor.findFieldByNumber(2).get).map(_.as[_root_.com.google.protobuf.ByteString]).getOrElse(_root_.com.google.protobuf.ByteString.EMPTY)
      )
    case _ => throw new RuntimeException("Expected PMessage")
  }
  def javaDescriptor: _root_.com.google.protobuf.Descriptors.Descriptor = AnyProto.javaDescriptor.getMessageTypes().get(0)
  def scalaDescriptor: _root_.scalapb.descriptors.Descriptor = AnyProto.scalaDescriptor.messages(0)
  def messageCompanionForFieldNumber(__number: _root_.scala.Int): _root_.scalapb.GeneratedMessageCompanion[_] = throw new MatchError(__number)
  lazy val nestedMessagesCompanions: Seq[_root_.scalapb.GeneratedMessageCompanion[_ <: _root_.scalapb.GeneratedMessage]] = Seq.empty
  def enumCompanionForFieldNumber(__fieldNumber: _root_.scala.Int): _root_.scalapb.GeneratedEnumCompanion[_] = throw new MatchError(__fieldNumber)
  lazy val defaultInstance = com.google.protobuf.any.Any(
    typeUrl = "",
    value = _root_.com.google.protobuf.ByteString.EMPTY
  )
  implicit class AnyLens[UpperPB](_l: _root_.scalapb.lenses.Lens[UpperPB, com.google.protobuf.any.Any]) extends _root_.scalapb.lenses.ObjectLens[UpperPB, com.google.protobuf.any.Any](_l) {
    def typeUrl: _root_.scalapb.lenses.Lens[UpperPB, _root_.scala.Predef.String] = field(_.typeUrl)((c_, f_) => c_.copy(typeUrl = f_))
    def value: _root_.scalapb.lenses.Lens[UpperPB, _root_.com.google.protobuf.ByteString] = field(_.value)((c_, f_) => c_.copy(value = f_))
  }
  final val TYPE_URL_FIELD_NUMBER = 1
  final val VALUE_FIELD_NUMBER = 2
  def of(
    typeUrl: _root_.scala.Predef.String,
    value: _root_.com.google.protobuf.ByteString
  ): _root_.com.google.protobuf.any.Any = _root_.com.google.protobuf.any.Any(
    typeUrl,
    value
  )
  // @@protoc_insertion_point(GeneratedMessageCompanion[google.protobuf.Any])
}


text:
package org.apache.wicket.security.actions;

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

/**
 * Actions maintains the collection of {@link ActionFactory}s. There can only be one
 * Actions in each virtual machine. Having a separate instance where all the
 * ActionFactories are registered makes it easier to use them outside wicket because there
 * now is a single (non wicket) point of entry. {@link ActionFactory}s should not be
 * shared.
 *
 * @author marrink
 */
public class Actions
{
	private static final Actions INSTANCE = new Actions();

	private Map<Object, ActionFactory> factoryCollection;

	/**
	 * Private constructor for this simple class.
	 */
	private Actions()
	{
		factoryCollection = new HashMap<Object, ActionFactory>();
	}

	/**
	 * Returns the ActionFactory stored with the key.
	 *
	 * @param key
	 *            the key
	 * @return the factory or null if no factory is registered with that key
	 */
	public static ActionFactory getActionFactory(Object key)
	{
		return INSTANCE.factoryCollection.get(key);
	}

	/**
	 * Registers a new ActionFactory for anybody knowing the right key to be retrieved. It
	 * is not possible to overwrite a registration without first unregistering the
	 * previous factory.
	 *
	 * @param key
	 *            the key to store the factory with.
	 * @param factory
	 *            the ActionFactory.
	 * @throws IllegalArgumentException
	 *             if the factory is null if an attempt is made to overwrite the
	 *             registration.
	 * @see #unregisterActionFactory(Object)
	 */
	public static void registerActionFactory(Object key, ActionFactory factory)
	{
		if (factory == null)
			throw new IllegalArgumentException("Cannot register null ActionFactory.");
		synchronized (INSTANCE.factoryCollection)
		{
			if (INSTANCE.factoryCollection.containsKey(key))
				throw new IllegalArgumentException(
					"Another ActionFactory is already registered with the following key: " + key);
			INSTANCE.factoryCollection.put(key, factory);
		}
	}

	/**
	 * Removes the registration of a single ActionFactory.
	 *
	 * @param key
	 *            the key the factory is registered with
	 * @return the registered factory or null if none was registered with the key.
	 */
	public static ActionFactory unregisterActionFactory(Object key)
	{
		return INSTANCE.factoryCollection.remove(key);
	}
}


text:
import { diag } from '@opentelemetry/api';
import {
  isWrapped,
  InstrumentationBase,
  InstrumentationNodeModuleDefinition,
} from '@opentelemetry/instrumentation';
import type * as redisTypes from 'redis';
import {
  getTracedCreateClient,
  getTracedCreateStreamTrace,
  getTracedInternalSendCommand,
} from './utils';
import { RedisInstrumentationConfig } from './types';
import { VERSION } from './version';

const DEFAULT_CONFIG: RedisInstrumentationConfig = {
  requireParentSpan: false,
};

export class RedisInstrumentation extends InstrumentationBase<
  typeof redisTypes
> {
  static readonly COMPONENT = 'redis';

  constructor(protected override _config: RedisInstrumentationConfig = {}) {
    super('@opentelemetry/instrumentation-redis', VERSION, _config);
  }

  override setConfig(config: RedisInstrumentationConfig = {}) {
    this._config = Object.assign({}, DEFAULT_CONFIG, config);
  }

  protected init() {
    return [
      new InstrumentationNodeModuleDefinition<typeof redisTypes>(
        'redis',
        ['^2.6.0', '^3.0.0'],
        (moduleExports, moduleVersion) => {
          diag.debug(`Patching redis@${moduleVersion}`);
          diag.debug('Patching redis.RedisClient.internal_send_command');
          if (
            isWrapped(
              moduleExports.RedisClient.prototype['internal_send_command']
            )
          ) {
            this._unwrap(
              moduleExports.RedisClient.prototype,
              'internal_send_command'
            );
          }
          this._wrap(
            moduleExports.RedisClient.prototype,
            'internal_send_command',
            this._getPatchInternalSendCommand()
          );

          diag.debug('patching redis.RedisClient.create_stream');
          if (isWrapped(moduleExports.RedisClient.prototype['create_stream'])) {
            this._unwrap(moduleExports.RedisClient.prototype, 'create_stream');
          }
          this._wrap(
            moduleExports.RedisClient.prototype,
            'create_stream',
            this._getPatchCreateStream()
          );

          diag.debug('patching redis.createClient');
          if (isWrapped(moduleExports.createClient)) {
            this._unwrap(moduleExports, 'createClient');
          }
          this._wrap(
            moduleExports,
            'createClient',
            this._getPatchCreateClient()
          );
          return moduleExports;
        },
        moduleExports => {
          if (moduleExports === undefined) return;
          this._unwrap(
            moduleExports.RedisClient.prototype,
            'internal_send_command'
          );
          this._unwrap(moduleExports.RedisClient.prototype, 'create_stream');
          this._unwrap(moduleExports, 'createClient');
        }
      ),
    ];
  }
  /**
   * Patch internal_send_command(...) to trace requests
   */
  private _getPatchInternalSendCommand() {
    const tracer = this.tracer;
    const config = this._config;
    return function internal_send_command(original: Function) {
      return getTracedInternalSendCommand(tracer, original, config);
    };
  }

  private _getPatchCreateClient() {
    const tracer = this.tracer;
    return function createClient(original: Function) {
      return getTracedCreateClient(tracer, original);
    };
  }

  private _getPatchCreateStream() {
    const tracer = this.tracer;
    return function createReadStream(original: Function) {
      return getTracedCreateStreamTrace(tracer, original);
    };
  }
}


text:
import {Resource} from 'node-odata';
import {gallery} from '../models/gallery';
import isAdmin from '../auth/isAdmin';

export default Resource('gallery', gallery)
  .orderBy('createDate desc')
  .post().auth(isAdmin).before((entity, req) => {
    entity.author = req.user;
  })
  .put().auth(isAdmin)
  .delete().auth(isAdmin);


text:
title: "Язык Markdown - обзор редакторов для работы"
layout: post
categories: css
tags: [markdown]
share: true
---

> Начал создавать серию статей по Bootstrap, чтобы основательно изучить для себя данный вопрос. Но вот незадача - придется на время отложить его в сторону и отвлечься на пару моментов.

Первый из них - это язык Markdown, а второй - модульные сетки. И если без первого вопроса изучение Bootstrap можно продолжить без какого-либо ущерба (до этого же как-то обходился без него?), то вот со вторым вопросом посложнее будет.

Дело в том, что фреймворк Bootstrap в основе своей работы использует *модульную сетку*. А вы хорошо себе представляете (и знаете ли вообще?), что такое модульная сетка?

## Начнем с языка Markdown

Совсем недавно узнал о существовании языка Markdown. Мне стало интересно, что это за язык такой и зачем он нужен. Оказалось все просто и практично, как раз для меня, так как я довольно часто пишу статьи для своего бложика.

Язык Markdown - по мне, так его языком даже назвать нельзя. Это просто специальный синтаксис, призвание которого - облегчить и убыстрить написание HTML-документов. Это важно для людей, которые или сами ведут блоги\сайты или профессия которых называется контент-менеджер. Другими словами, это люди, которые часто пишут статьи с форматированием в виде HTML-документов.

Если вы хотя бы раз писали статьи с таким форматированием, то прекрасно знаете, что необходимо делать бесчисленное число раз в редакторе - ввод HTML-тегов для форматирования текста. Поверьте (если не знаете) - это очень неудобно и утомительно.

Конечно, для браузера HTML-теги необходимы, иначе он не сможет правильно прочитать HTML-документ. Но вот нам, человекам, эти теги, по большому счету, ни к чему.

Язык Markdown был создан именно для того, чтобы позволить человеку, набирающему текст в HTML-формате, забыть об HTML-тегах. Вместо этих тегов в Markdown применяются символы-заменители, которые гораздо легче набирать вручную. В этом заключается смысл создания и использования языка Markdown.

Конечно, как любой другой язык-надстройка (например, тот же SASS\SCSS или LESS для CSS), Markdown нуждается в компиляторе, который "переводил" бы текст в формате этого языка в стандартный формат HTML-документа.

В терминологии Markdown такой компилятор называется транслятором и их существует достаточное количество. Существуют платные или бесплатные Markdown-редакторы, в которых уже встроен такой транслятор.

Ниже я рассмотрю два варианта использования языка Markdown - один с помощью специализированных редакторов, второй - с помощью плагина под редактор Sublime Text 2, расширяющего его возможности в плане написания статей с таким синтаксисом.

## Редактор MarkdownPad2

Редактор MarkdownPad2 - это герой моего дня сегодня! Бесплатный, интуитивно понятный и простой. Под Windows XP у меня на работе он установился и запустился без проблем. А вот дома на ноутбуке HP Pavilion g6 с Windows 7 установился, но запуститься отказался. Выдал какую-то ошибку, которую мне неохота было выискивать в Google.

В версии MarkdownPad2 (бесплатная) нет многих удобных фишек, которые есть в версии MarkdownPad2 Pro (платная). Но и без них можно прожить, это не так уж "страшно".

Текст, который вы читаете в данный момент (нетрудно догадаться) набран в этом редакторе с использованием синтаксиса Markdown (как ни странно). Сам синтаксис мне описывать совсем неохота по нескольким причинам.

  1. Первая - там описывать нечего. Он настолько прост и лаконичен, что ему можно и нужно выучиться за полчаса, просто набирая текст в редакторе. Глупо было бы - ведь для цели упрощения написания статей в HTML-разметке язык Markdown и создавался.
  2. Вторая - если у вас все же есть желание почитать статью-описание этого языка, то есть прекрасный вариант - "Технический блог" Владимира Старкова, где помещен материал [Основы markdown][1]. Статья совсем свежая, написана автором 13 февраля этого года. Кроме этого, малоизвестная поисковая система Google поможет вам найти целую кучу разнообразных `cheatsheet`'ов по этому языку.

Чтобы не быть голословным, приведу небольшое изображение редактора MarkdownPad2 после первого запуска программы:

![MarkdownPad2 после первого запуска]({{site.url}}/images/uploads/2013/11/markdownpad_first-launch.jpg){:.center-image}

Левая половина окна - это пример синтаксиса Markdown. Правая половина окна - это предварительный просмотр текста, набранного в левой половине. Точно также текст будет выглядеть в окне браузера. Включить или отключить предварительный просмотр можно по клавише F5.

Если хотите точно в этом удостовериться, нажмите клавишу F6 (или самую последнюю иконку на панели инструментов редактора). Создаваемая страница откроется в окне браузера, являющегося браузером по умолчанию в системе.

Давайте быстро пробежимся, как использовать программу и создавать документы в ней:

  * создаем новый документ Ctrl+N
  * вносим в него изменения: текст, изображения и так далее
  * сохраняем файл с расширением `.md`
  * экспортируем в HTML-файл Ctrl+Shift+1

Как видим, все просто до предела. Но хочу сказать о паре моментов по работе в этой программе:

  * при форматировании текста лучше использовать панель инструментов редактора, так как синтаксис в редакторе слегка отличается от "официального";
  * опция экспорта в pdf-формат Ctrl+Shift+2 доступна только в платной версии (*а оно нам надо?*).

## Редактор MarkDown#Editor

Еще один редактор для написания текстов в синтаксисе Markdown - "MarkDown#Editor". Он также бесплатный, но на моем ноутбуке он запустился без ошибок.

Программа создана автором из Страны Восходящего Солнца по имени Mitsuhiro Hibara. Проект проживает по запоминающемуся адресу [http://www.hibara.org][2] (думаю, жители Восточной Украины и юга России меня поймут).

Редактор мне понравился как внешним видом, так и своими возможностями. В нем все просто и интуитивно понятно. Ниже представлен внешний вид программы после первого ее запуска:

![MarkdownSharpEditor - первый запуск редактора]({{site.url}}/images/uploads/2013/11/markdowneditor_first-launch.jpg){:.center-image}

Программа умеет экспортировать только в один формат - HTML. Но больше и не нужно, правда?

## Плагин MarkdownEditing

Готовые редакторы под Markdown - это прекрасная вещь, но меня не устраивает одно. Я не люблю держать на компьютере целую кучу программ, каждая из которых выполняет только одну задачу.

Я говорю это к тому, что под мой любимый редактор Sublime Text имеется плагин MarkdownEditing, который позволяет создавать документы формата Markdown в этой программе.

Давайте рассмотрим установку, настройку и работу этого плагина в ST2. Надо сказать, что вопрос с плагином под Sublime потратил у меня достаточно времени. Я не знал, как выполнять экспорт готового md-файла в html-файл. Ни Stackoverflow, ни Toster не помогли мне разобраться с данным вопросом. Только прямая свзяь с maintainer'ом плагина помогла разрешить ситуацию.

  1. Установка плагина MarkdownEditing в Sublime Text 2 стандартная - через менеджер пакетов
  2. Перезапускаем редактор Sublime Text 2
  3. Создаем новый документ и устанавливаем для него синтаксис Markdown Shift+Ctrl+P
  4. Пишем в новом документе текст
  5. Сохраняем отредактированный документ как файл с расширением `.md`

![Плагин MarkdownEditing в Sublime Text 2]({{site.url}}/images/uploads/2013/11/markdownediting_first-launch.jpg){:.center-image}

А теперь немного внимания! Для меня данный вопрос был камнем преткновения, который заставил добраться с просьбой о помощи до самого maintainer'а плагина - Ali Ayas. Я долго не мог понять простой вещи - MarkdownEditing предназначен только для редактирования файлов с синтаксисом Markdown, о чем говорит само название этого плагина.

Плагин MarkdownEditing не умеет сам конвертировать .md-файлы в файлы формата html. Поэтому, если вы пишите статьи для сайта под управлением WordPress (как в моем случае), вам необходимо поставить на эту CMS плагин для конвертации - WP-Markdown. Затем закидываете статьи в формате `.md` под эту CMS, а там уже плагин WP-Markdown автоматически превратит их в html-файлы.

Не знаю, кого как, а меня разочаровал такой подход к делу создания markdown-файлов в Sublime Text 2 с плагином MarkdownEditing.

## P.S.

Эмоции немного остыли и я пришел к выводу, что не все так плохо, как казалось с первого взгляда. Более того, имеется плагин MarkdownBuild под Sublime Text 2, который прекрасно справляется с задачей компиляции файла `markdown` в html-файл. Устанавливается этот плагин как обычно, через менеджер пакетов.

Настройки плагина минимальные и их можно привести здесь целиком:

{% highlight powershell %}
{
  "output_html" : true, // сохранить выходной файл html в ту же папку, в которой находиться входной файл markdown
  "open_html_in" : "browser",  // открыть файл html в браузере
  "use_css" : true,
  "charset" : "UTF-8"
}
{% endhighlight %}

Единственный момент заключается в том, что настройки плагина MarkdownBuild находятся в файле `MarkdownBuild.sublime-settings`, добраться до которого можно только через файловый менеджер или Проводник. В редакторе Sublime Text 2 я не нашел способа открыть настройки этого плагина.

Кроме того, компиляция в этом плагине производится через сочетание клавиш Shift+Ctrl+B, а не Ctrl+B, как описано в документации.

## Заключение

Я доволен тем, что познакомился с языком Markdown. С ним действительно создавать статьи под сайт гораздо легче, быстрее и удобнее. Писать статьи или обзоры с помощью Markdown - одно удовольствие.

Редактором-победителем для меня стала программа MarkdownPad - быстрая, удобная и надежная. Тот момент, что она отказалась установиться на моем ноуте под Windows 7 роли не играет, как мне кажется.

На этом все.

---

[1]: http://vstarkov.ru/markdown-basics/ "Markdown Basics"
[2]: http://www.hibara.org "MarkDown#Editor"