text:
package org.apache.spark.deploy.worker

import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.Supplier

import org.mockito.{Mock, MockitoAnnotations}
import org.mockito.Answers.RETURNS_SMART_NULLS
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito._
import org.mockito.invocation.InvocationOnMock
import org.mockito.stubbing.Answer
import org.scalatest.{BeforeAndAfter, Matchers}

import org.apache.spark.{SecurityManager, SparkConf, SparkFunSuite}
import org.apache.spark.deploy.{Command, ExecutorState, ExternalShuffleService}
import org.apache.spark.deploy.DeployMessages.{DriverStateChanged, ExecutorStateChanged}
import org.apache.spark.deploy.master.DriverState
import org.apache.spark.rpc.{RpcAddress, RpcEnv}

class WorkerSuite extends SparkFunSuite with Matchers with BeforeAndAfter {

  import org.apache.spark.deploy.DeployTestUtils._

  @Mock(answer = RETURNS_SMART_NULLS) private var shuffleService: ExternalShuffleService = _

  def cmd(javaOpts: String*): Command = {
    Command("", Seq.empty, Map.empty, Seq.empty, Seq.empty, Seq(javaOpts : _*))
  }
  def conf(opts: (String, String)*): SparkConf = new SparkConf(loadDefaults = false).setAll(opts)

  private var _worker: Worker = _

  private def makeWorker(
      conf: SparkConf,
      shuffleServiceSupplier: Supplier[ExternalShuffleService] = null): Worker = {
    assert(_worker === null, "Some Worker's RpcEnv is leaked in tests")
    val securityMgr = new SecurityManager(conf)
    val rpcEnv = RpcEnv.create("test", "localhost", 12345, conf, securityMgr)
    _worker = new Worker(rpcEnv, 50000, 20, 1234 * 5, Array.fill(1)(RpcAddress("1.2.3.4", 1234)),
      "Worker", "/tmp", conf, securityMgr, shuffleServiceSupplier)
    _worker
  }

  before {
    MockitoAnnotations.initMocks(this)
  }

  after {
    if (_worker != null) {
      _worker.rpcEnv.shutdown()
      _worker.rpcEnv.awaitTermination()
      _worker = null
    }
  }

  test("test isUseLocalNodeSSLConfig") {
    Worker.isUseLocalNodeSSLConfig(cmd("-Dasdf=dfgh")) shouldBe false
    Worker.isUseLocalNodeSSLConfig(cmd("-Dspark.ssl.useNodeLocalConf=true")) shouldBe true
    Worker.isUseLocalNodeSSLConfig(cmd("-Dspark.ssl.useNodeLocalConf=false")) shouldBe false
    Worker.isUseLocalNodeSSLConfig(cmd("-Dspark.ssl.useNodeLocalConf=")) shouldBe false
  }

  test("test maybeUpdateSSLSettings") {
    Worker.maybeUpdateSSLSettings(
      cmd("-Dasdf=dfgh", "-Dspark.ssl.opt1=x"),
      conf("spark.ssl.opt1" -> "y", "spark.ssl.opt2" -> "z"))
        .javaOpts should contain theSameElementsInOrderAs Seq(
          "-Dasdf=dfgh", "-Dspark.ssl.opt1=x")

    Worker.maybeUpdateSSLSettings(
      cmd("-Dspark.ssl.useNodeLocalConf=false", "-Dspark.ssl.opt1=x"),
      conf("spark.ssl.opt1" -> "y", "spark.ssl.opt2" -> "z"))
        .javaOpts should contain theSameElementsInOrderAs Seq(
          "-Dspark.ssl.useNodeLocalConf=false", "-Dspark.ssl.opt1=x")

    Worker.maybeUpdateSSLSettings(
      cmd("-Dspark.ssl.useNodeLocalConf=true", "-Dspark.ssl.opt1=x"),
      conf("spark.ssl.opt1" -> "y", "spark.ssl.opt2" -> "z"))
        .javaOpts should contain theSameElementsAs Seq(
          "-Dspark.ssl.useNodeLocalConf=true", "-Dspark.ssl.opt1=y", "-Dspark.ssl.opt2=z")

  }

  test("test clearing of finishedExecutors (small number of executors)") {
    val conf = new SparkConf()
    conf.set("spark.worker.ui.retainedExecutors", 2.toString)
    val worker = makeWorker(conf)
    // initialize workers
    for (i <- 0 until 5) {
      worker.executors += s"app1/$i" -> createExecutorRunner(i)
    }
    // initialize ExecutorStateChanged Message
    worker.handleExecutorStateChanged(
      ExecutorStateChanged("app1", 0, ExecutorState.EXITED, None, None))
    assert(worker.finishedExecutors.size === 1)
    assert(worker.executors.size === 4)
    for (i <- 1 until 5) {
      worker.handleExecutorStateChanged(
        ExecutorStateChanged("app1", i, ExecutorState.EXITED, None, None))
      assert(worker.finishedExecutors.size === 2)
      if (i > 1) {
        assert(!worker.finishedExecutors.contains(s"app1/${i - 2}"))
      }
      assert(worker.executors.size === 4 - i)
    }
  }

  test("test clearing of finishedExecutors (more executors)") {
    val conf = new SparkConf()
    conf.set("spark.worker.ui.retainedExecutors", 30.toString)
    val worker = makeWorker(conf)
    // initialize workers
    for (i <- 0 until 50) {
      worker.executors += s"app1/$i" -> createExecutorRunner(i)
    }
    // initialize ExecutorStateChanged Message
    worker.handleExecutorStateChanged(
      ExecutorStateChanged("app1", 0, ExecutorState.EXITED, None, None))
    assert(worker.finishedExecutors.size === 1)
    assert(worker.executors.size === 49)
    for (i <- 1 until 50) {
      val expectedValue = {
        if (worker.finishedExecutors.size < 30) {
          worker.finishedExecutors.size + 1
        } else {
          28
        }
      }
      worker.handleExecutorStateChanged(
        ExecutorStateChanged("app1", i, ExecutorState.EXITED, None, None))
      if (expectedValue == 28) {
        for (j <- i - 30 until i - 27) {
          assert(!worker.finishedExecutors.contains(s"app1/$j"))
        }
      }
      assert(worker.executors.size === 49 - i)
      assert(worker.finishedExecutors.size === expectedValue)
    }
  }

  test("test clearing of finishedDrivers (small number of drivers)") {
    val conf = new SparkConf()
    conf.set("spark.worker.ui.retainedDrivers", 2.toString)
    val worker = makeWorker(conf)
    // initialize workers
    for (i <- 0 until 5) {
      val driverId = s"driverId-$i"
      worker.drivers += driverId -> createDriverRunner(driverId)
    }
    // initialize DriverStateChanged Message
    worker.handleDriverStateChanged(DriverStateChanged("driverId-0", DriverState.FINISHED, None))
    assert(worker.drivers.size === 4)
    assert(worker.finishedDrivers.size === 1)
    for (i <- 1 until 5) {
      val driverId = s"driverId-$i"
      worker.handleDriverStateChanged(DriverStateChanged(driverId, DriverState.FINISHED, None))
      if (i > 1) {
        assert(!worker.finishedDrivers.contains(s"driverId-${i - 2}"))
      }
      assert(worker.drivers.size === 4 - i)
      assert(worker.finishedDrivers.size === 2)
    }
  }

  test("test clearing of finishedDrivers (more drivers)") {
    val conf = new SparkConf()
    conf.set("spark.worker.ui.retainedDrivers", 30.toString)
    val worker = makeWorker(conf)
    // initialize workers
    for (i <- 0 until 50) {
      val driverId = s"driverId-$i"
      worker.drivers += driverId -> createDriverRunner(driverId)
    }
    // initialize DriverStateChanged Message
    worker.handleDriverStateChanged(DriverStateChanged("driverId-0", DriverState.FINISHED, None))
    assert(worker.finishedDrivers.size === 1)
    assert(worker.drivers.size === 49)
    for (i <- 1 until 50) {
      val expectedValue = {
        if (worker.finishedDrivers.size < 30) {
          worker.finishedDrivers.size + 1
        } else {
          28
        }
      }
      val driverId = s"driverId-$i"
      worker.handleDriverStateChanged(DriverStateChanged(driverId, DriverState.FINISHED, None))
      if (expectedValue == 28) {
        for (j <- i - 30 until i - 27) {
          assert(!worker.finishedDrivers.contains(s"driverId-$j"))
        }
      }
      assert(worker.drivers.size === 49 - i)
      assert(worker.finishedDrivers.size === expectedValue)
    }
  }

  test("cleanup non-shuffle files after executor exits when config " +
      "spark.storage.cleanupFilesAfterExecutorExit=true") {
    testCleanupFilesWithConfig(true)
  }

  test("don't cleanup non-shuffle files after executor exits when config " +
      "spark.storage.cleanupFilesAfterExecutorExit=false") {
    testCleanupFilesWithConfig(false)
  }

  private def testCleanupFilesWithConfig(value: Boolean) = {
    val conf = new SparkConf().set("spark.storage.cleanupFilesAfterExecutorExit", value.toString)

    val cleanupCalled = new AtomicBoolean(false)
    when(shuffleService.executorRemoved(any[String], any[String])).thenAnswer(new Answer[Unit] {
      override def answer(invocations: InvocationOnMock): Unit = {
        cleanupCalled.set(true)
      }
    })
    val externalShuffleServiceSupplier = new Supplier[ExternalShuffleService] {
      override def get: ExternalShuffleService = shuffleService
    }
    val worker = makeWorker(conf, externalShuffleServiceSupplier)
    // initialize workers
    for (i <- 0 until 10) {
      worker.executors += s"app1/$i" -> createExecutorRunner(i)
    }
    worker.handleExecutorStateChanged(
      ExecutorStateChanged("app1", 0, ExecutorState.EXITED, None, None))
    assert(cleanupCalled.get() == value)
  }
}


text:
#include <pcap.h>
#include <stdbool.h>

pcap_if_t* GetDevices();
void FreeDevices(pcap_if_t* devices);
pcap_if_t* FindDeviceByIndex(pcap_if_t* devices, int deviceIndex);
pcap_t* OpenTcpIpDevice(pcap_if_t* device, int timeoutMs);
void CloseTcpIpDevice(pcap_t* session);
bool WaitNextEthernetPacket(pcap_t* session, long* timestamp, const unsigned char** buffer, size_t* size);

#endif

redpajama_set_name: RedPajamaGithub


text:
/* jshint onevar: false, devel: true, smarttabs: true */
/* global GrunionFB_i18n: true, FB, ajax_nonce_shortcode, ajax_nonce_json, ajaxurl, postId */

if ( ! window.FB ) {
	window.FB = {};
}

GrunionFB_i18n = jQuery.extend( {
	nameLabel: 'Name',
	emailLabel: 'Email',
	urlLabel: 'Website',
	commentLabel: 'Comment',
	newLabel: 'New Field',
	optionsLabel: 'Options',
	optionLabel: 'Option',
	firstOptionLabel: 'First option',
	problemGeneratingForm: 'Oops, there was a problem generating your form.  You\'ll likely need to try again.',
	moveInstructions: 'Drag up or down\nto re-arrange',
	moveLabel: 'move',
	editLabel: 'edit',
	savedMessage: 'Saved successfully',
	requiredLabel: '(required)',
	exitConfirmMessage: 'Are you sure you want to exit the form editor without saving?  Any changes you have made will be lost.',
	maxNewFields: 5
}, GrunionFB_i18n );

GrunionFB_i18n.moveInstructions = GrunionFB_i18n.moveInstructions.replace( '\n', '
' );

FB.span = jQuery( '' );
FB.esc_html = function( string ) {
	return FB.span.text( string ).html();
};

FB.esc_attr = function( string ) {
	string = FB.esc_html( string );
	return string.replace( '"', '"' ).replace( '\'', ''' );
};

FB.ContactForm = (function() {
	var fbForm = { // Main object that generated shortcode via AJAX call
	'action' : 'grunion_shortcode',
	'_ajax_nonce' : ajax_nonce_shortcode,
	'to' : '',
	'subject' : '',
	'fields' : {}
	};
	var defaultFields = {
		'name': {
			'label' : GrunionFB_i18n.nameLabel,
			'type' : 'name',
			'required' : true,
			'options' : [],
			'order' : '1'
		},
		'email': {
			'label' : GrunionFB_i18n.emailLabel,
			'type' : 'email',
			'required' : true,
			'options' : [],
			'order' : '2'
		},
		'url': {
			'label' : GrunionFB_i18n.urlLabel,
			'type' : 'url',
			'required' : false,
			'options' : [],
			'order' : '3'
		},
		'comment': {
			'label' : GrunionFB_i18n.commentLabel,
			'type' : 'textarea',
			'required' : true,
			'options' : [],
			'order' : '4'
		}
	};
	var debug = false; // will print errors to log if true
	var grunionNewCount = 0; // increment for new fields
	var maxNewFields = GrunionFB_i18n.maxNewFields;  // See filter in ../grunion-form-view.php
	var optionsCache = {};
	var optionsCount = 0; // increment for options
	var shortcode;

	function addField () {
		try {
			grunionNewCount++;
			if (grunionNewCount <= maxNewFields) {
				// Add to preview
				jQuery('#fb-extra-fields').append('

' + GrunionFB_i18n.newLabel + ' <input type="text" id="fb-field' + grunionNewCount + '" disabled="disabled" />

');
				// Add to form object
				fbForm.fields[grunionNewCount] = {
					'label' : GrunionFB_i18n.newLabel,
					'type' : 'text',
					'required' : false,
					'options' : [],
					'order' : '5'
				};
				if (grunionNewCount === maxNewFields) {
					jQuery('#fb-new-field').hide();
				}
				// Reset form for this new field
				optionsCount = 0;
				optionsCache = {};
				jQuery('#fb-new-options').html('' + GrunionFB_i18n.optionsLabel + '<input type="text" id="fb-option0" optionid="0" value="' + GrunionFB_i18n.firstOptionLabel + '" class="fb-options" />');
				jQuery('#fb-options').hide();
				jQuery('#fb-new-label').val( GrunionFB_i18n.newLabel );
				jQuery('#fb-new-type').val('text');
				jQuery('#fb-field-id').val(grunionNewCount);
				setTimeout(function () { jQuery('#fb-new-label').focus().select(); }, 100);
			} else {
				jQuery('#fb-new-field').hide();
			}
		} catch(e) {
			if (debug) {
				console.log('addField(): ' + e);
			}
		}
	}
	function addOption () {
		try {
			optionsCount = jQuery( '#fb-new-options .fb-options' ).length;
			var thisId = jQuery('#fb-field-id').val();
			var thisType = jQuery('#fb-new-type').val();
			if (thisType === 'radio') {
				// Add to right col
				jQuery('#fb-new-options').append('
<input type="text" id="fb-option' + optionsCount + '" optionid="' + optionsCount + '" value="' + GrunionFB_i18n.optionLabel + '" class="fb-options" />
');
				// Add to preview
				jQuery('#fb-new-field' + thisId + ' .fb-fields').append('
<input type="radio" disabled="disabled" id="fb-field' + thisId + '" name="radio-' + thisId + '" />' + GrunionFB_i18n.optionLabel + '

');
			} else {
				// Add to right col
				jQuery('#fb-new-options').append('
<input type="text" id="fb-option' + optionsCount + '" optionid="' + optionsCount + '" value="" class="fb-options" />
');
				// Add to preview
				jQuery('#fb-field'+ thisId).append('<option id="fb-' + thisId + '-' + optionsCount + '" value="' + thisId + '-' + optionsCount + '"></option>');
			}
			// Add to fbForm object
			fbForm.fields[thisId].options[optionsCount] = '';
			// Add focus to new field
			jQuery('#fb-option' + optionsCount).focus().select();
		} catch(e) {
			if (debug) {
				console.log('addOption(): ' + e);
			}
		}
	}
	function buildPreview () {
		try {
			if (fbForm.to) { jQuery('#fb-field-my-email').val(fbForm.to); }
			if (fbForm.subject) { jQuery('#fb-field-subject').val(fbForm.subject); }
			// Loop over and add fields
			jQuery.each(fbForm.fields, function(index, value) {
				jQuery('#fb-extra-fields').before('

');
				jQuery('#fb-field-id').val(index);
				optionsCache[index] = {};
				optionsCache[index].options = [];
				if (value.type === 'radio' || value.type === 'select') {
					jQuery.each(value.options, function(i, value) {
						optionsCache[index].options[i] = value;
					});
				}
				updateType(value.type, value.label, value.required);
			});
		} catch(e) {
			if (debug) {
				console.log('buildPreview(): ' + e);
			}
		}
	}
	function customOptions (id, thisType) {
		try {
			var thisOptions = '';
			for (var i=0; i<optionsCache[id].options.length; i++) {
				if (optionsCache[id].options[i] !== undefined) {
					if (thisType === 'radio') {
						thisOptions = thisOptions + '
<input type="radio" id="fb-field' + id + '" name="radio-' + id + '" />' + FB.esc_html( optionsCache[id].options[i] ) + '

';
					} else {
						thisOptions = thisOptions + '<option id="fb-' + id + '-' + i + '" value="' + id + '-' + i + '">' + FB.esc_html( optionsCache[id].options[i] ) + '</option>';
					}
				}
			}
			return thisOptions;
		} catch(e) {
			if (debug) {
				console.log('customOptions(): ' + e);
			}
		}
	}
	function deleteField (that) {
		try {
			grunionNewCount--;
			var thisId = that.attr('id');
			delete fbForm.fields[thisId];
			jQuery('#' + thisId).parent().parent().remove();
			if (grunionNewCount <= maxNewFields) {
				jQuery('#fb-new-field').show();
			}
		} catch(e) {
			if (debug) {
				console.log('deleteField(): ' + e);
			}
		}
	}
	function editField (that) {
		try {
			scroll(0,0);
			setTimeout(function () { jQuery('#fb-new-label').focus().select(); }, 100);
			var thisId = that.parent().attr('fieldid');
			loadFieldEditor(thisId);
		} catch(e) {
			if (debug) {
				console.log('editField(): ' + e);
			}
		}
	}
	function grabShortcode () {
		try {
			// Takes fbForm object and returns shortcode syntax
			jQuery.post(ajaxurl, fbForm, function(response) {
				shortcode = response;
			});
		} catch(e) {
			alert( GrunionFB_i18n.problemGeneratingForm );
			if (debug) {
				console.log('grabShortcode(): ' + e);
			}
		}
	}
	function hideDesc () {
		jQuery('#fb-desc').hide();
		jQuery('#fb-add-field').show();
	}
	function hidePopup () {
		try {
			// copied from wp-includes/js/thickbox/thickbox.js
			jQuery('#TB_imageOff', window.parent.document).unbind('click');
			jQuery('#TB_closeWindowButton', window.parent.document).unbind('click');
			jQuery('#TB_window', window.parent.document).fadeOut('fast');
			jQuery('body', window.parent.document).removeClass('modal-open');
			jQuery('#TB_window,#TB_overlay,#TB_HideSelect', window.parent.document).trigger('unload').unbind().remove();
			jQuery('#TB_load', window.parent.document).remove();
			if (typeof window.parent.document.body.style.maxHeight === 'undefined') {//if IE 6
				jQuery('body', 'html', window.parent.document).css({height: 'auto', width: 'auto'});
				jQuery('html', window.parent.document).css('overflow', '');
			}
			window.parent.document.onkeydown = '';
			window.parent.document.onkeyup = '';
			return false;
		} catch(e) {
			if (debug) {
				console.log('hidePopup(): ' + e);
			}
		}
	}
	function hideShowEditLink (whichType, that) {
		try {
			if (whichType === 'show') {
				// Prevents showing links twice
				if (jQuery('.fb-edit-field').is(':visible')) {
					jQuery('.fb-edit-field').remove();
				}
				that.find('label').prepend('
' + GrunionFB_i18n.moveInstructions + '
' + GrunionFB_i18n.moveLabel + '  |  ' + GrunionFB_i18n.editLabel + '');
			} else {
				jQuery('.fb-edit-field').remove();
			}
		} catch(e) {
			if (debug) {
				console.log('hideShowEditLink(): ' + e);
			}
		}
	}
	function loadFieldEditor (id) {
		try {
			var thisType = fbForm.fields[id].type;
			jQuery('#fb-options').hide();
			// Reset hidden field ID
			jQuery('#fb-field-id').val(id);
			// Load label
			jQuery('#fb-new-label').val(fbForm.fields[id].label);
			// Load type
			jQuery('#fb-new-type').val(fbForm.fields[id].type);
			// Load required
			if (fbForm.fields[id].required) {
				jQuery('#fb-new-required').prop('checked', true);
			} else {
				jQuery('#fb-new-required').prop('checked', false);
			}
			// Load options if there are any
			if (thisType === 'select' || thisType === 'radio') {
				var thisOptions = fbForm.fields[id].options;
				jQuery('#fb-options').show();
				jQuery('#fb-new-options').html(''); // Clear it all out
				for (var i=0; i<thisOptions.length; i++) {
					if (thisOptions[i] !== undefined) {
						if (thisType === 'radio') {
							jQuery('#fb-new-options').append('
<input type="text" id="fb-option' + i + '" optionid="' + i + '" value="' + FB.esc_attr( fbForm.fields[id].options[i] ) + '" class="fb-options" />
');
						} else {
							jQuery('#fb-new-options').append('
<input type="text" id="fb-option' + i + '" optionid="' + i + '" value="' + FB.esc_attr( fbForm.fields[id].options[i] ) + '" class="fb-options" />
');
						}
					}
				}
			}
			// Load editor & hide description
			hideDesc();
		} catch(e) {
			if (debug) {
				console.log('loadFieldEditor(): ' + e);
			}
		}
	}
	function parseShortcode (data) {
		try {
			// Clean up fields by resetting them
			fbForm.fields = {};
			// Add new fields
			if (!data) {
				fbForm.fields = defaultFields;
			} else {
				jQuery.each(data.fields, function(index, value) {
					if ( 1 === parseInt(value.required, 10) ) {
						value.required = 'true';
					}
					fbForm.fields[index] = value;
				});
				fbForm.to = data.to;
				fbForm.subject = data.subject;
			}
		} catch(e) {
			if (debug) {
				console.log('parseShortcode(): ' + e);
			}
		}
	}
	function removeOption (optionId) {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisVal = jQuery('#fb-option' + optionId).val();
			var thisType = jQuery('#fb-new-type').val();
			// Remove from right
			jQuery('#fb-option-box-' + optionId).remove();
			// Remove from preview
			if (thisType === 'radio') {
				jQuery('#fb-radio-' + thisId + '-' + optionId).remove();
			} else {
				jQuery('#fb-' + thisId + '-' + optionId).remove();
			}
			// Remove from fbForm object
			var idx = fbForm.fields[thisId].options.indexOf(thisVal);
			if (idx !== -1) { fbForm.fields[thisId].options.splice(idx, 1); }
		} catch(e) {
			if (debug) {
				console.log('removeOption(): ' + e);
			}
		}
	}
	function removeOptions () {
		try {
			var thisId = jQuery('#fb-field-id').val();
			jQuery('#fb-options').hide();
			if (optionsCache[thisId] === undefined) { optionsCache[thisId] = {}; }
			optionsCache[thisId].options = fbForm.fields[thisId].options; // Save options in case they change their mind
			fbForm.fields[thisId].options = []; // Removes all options
		} catch(e) {
			if (debug) {
				console.log('removeOptions(): ' + e);
			}
		}
	}
	function sendShortcodeToEditor () {
		try {
			// Serialize fields
			jQuery('div#sortable div.fb-new-fields').each(function(index) {
				var thisId = jQuery(this).attr('fieldid');
				fbForm.fields[thisId].order = index;
			});
			// Export to WYSIWYG editor
			jQuery.post(ajaxurl, fbForm, function(response) {
				var isVisual = jQuery('#edButtonPreview', window.parent.document).hasClass('active');
				/* WP 3.3+ */
				if ( !isVisual ) {
					isVisual = jQuery( '#wp-content-wrap', window.parent.document ).hasClass( 'tmce-active' );
				}

				var win = window.dialogArguments || opener || parent || top;
				var currentCode;
				if (isVisual) {
					currentCode = win.tinyMCE.activeEditor.getContent();
				} else {
					currentCode = jQuery('#editorcontainer textarea', window.parent.document).val();
					/* WP 3.3+ */
					if ( typeof currentCode !== 'string' ) {
						currentCode = jQuery( '.wp-editor-area', window.parent.document ).val();
					}
				}
				var regexp = new RegExp('\\[contact-form\\b.*?\\/?\\](?:[\\s\\S]+?\\[\\/contact-form\\])?');

				// Remove new lines that cause BR tags to show up
				response = response.replace(/\n/g,' ');

				// Add new shortcode
				if (currentCode.match(regexp)) {
					if (isVisual) {
						win.tinyMCE.activeEditor.execCommand('mceSetContent', false, currentCode.replace(regexp, response));
					} else {
						// looks like the visual editor is disabled,
						// update the contents of the post directly
						jQuery( '#content', window.parent.document ).val( currentCode.replace( regexp, response ) );
					}
				} else {
					try {
						win.send_to_editor( response );
					} catch ( e ) {
						if (isVisual) {
							win.tinyMCE.activeEditor.execCommand('mceInsertContent', false, response);
						} else {
							// looks like the visual editor is disabled,
							// update the contents of the post directly
							jQuery( '#content', window.parent.document ).val( currentCode + response );
						}
					}
				}
				hidePopup();
			});
		} catch(e) {
			if (debug) {
				console.log('sendShortcodeToEditor(): ' + e);
			}
		}
	}
	function showDesc () {
		jQuery('#fb-desc').show();
		jQuery('#fb-add-field').hide();
	}
	function showAndHideMessage (message) {
		try {
			var newMessage = (!message) ? GrunionFB_i18n.savedMessage : message;
			jQuery('#fb-success').text(newMessage);
			jQuery('#fb-success').slideDown('fast');
			setTimeout(function () {
				 jQuery('#fb-success').slideUp('fast');
			}, 2500);
		} catch(e) {
			if (debug) {
				console.log('showAndHideMessage(): ' + e);
			}
		}
	}
	function switchTabs (whichType) {
		try {
			if (whichType === 'preview') {
				jQuery('#tab-preview a').addClass('current');
				jQuery('#tab-settings a').removeClass('current');
				jQuery('#fb-preview-form, #fb-desc').show();
				jQuery('#fb-email-settings, #fb-email-desc').hide();
			} else {
				jQuery('#tab-preview a').removeClass('current');
				jQuery('#tab-settings a').addClass('current');
				jQuery('#fb-preview-form, #fb-desc, #fb-add-field').hide();
				jQuery('#fb-email-settings, #fb-email-desc').show();
				jQuery('#fb-field-my-email').focus().select();
			}
		} catch(e) {
			if (debug) {
				console.log('switchTabs(): ' + e);
			}
		}
	}
	function updateLabel () {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisLabel = jQuery('#fb-new-label').val();
			// Update preview
			if (thisLabel.length === 0) {
				jQuery('#fb-new-field' + thisId + ' label .label-text').text( GrunionFB_i18n.newLabel );
			} else {
				jQuery('#fb-new-field' + thisId + ' label .label-text').text( thisLabel );
			}
			// Update fbForm object
			fbForm.fields[thisId].label = thisLabel;
		} catch(e) {
			if (debug) {
				console.log('updateLabel(): ' + e);
			}
		}
	}
	function updateMyEmail () {
		try {
			var thisEmail = jQuery('#fb-field-my-email').val();
			fbForm.to = thisEmail;
		} catch(e) {
			if (debug) {
				console.log('updateMyEmail(): ' + e);
			}
		}
	}
	function updateOption (that) {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisOptionid = that.attr('optionid');
			var thisOptionValue = that.val();
			var thisType = jQuery('#fb-new-type').val();
			// Update preview
			if (thisType === 'radio') {
				jQuery('#fb-radio-' + thisId + '-' + thisOptionid + ' span').text(thisOptionValue);
			} else {
				jQuery('#fb-' + thisId + '-' + thisOptionid).text(thisOptionValue);
			}
			// Update fbForm object
			fbForm.fields[thisId].options[thisOptionid] = thisOptionValue;
		} catch(e) {
			if (debug) {
				console.log('updateOption(): ' + e);
			}
		}
	}
	function updateRequired () {
		try {
			var thisId = jQuery('#fb-field-id').val();
			var thisChecked = jQuery('#fb-new-required').is(':checked');
			// Update object and preview
			if (thisChecked) {
				fbForm.fields[thisId].required = true;
				jQuery('#fb-new-field' + thisId + ' label').append('' + GrunionFB_i18n.requiredLabel + '');
			} else {
				fbForm.fields[thisId].required = false;
				jQuery('#fb-new-field' + thisId + ' label .label-required').remove();
			}
		} catch(e) {
			if (debug) {
				console.log('updateRequired(): ' + e);
			}
		}
	}
	function updateSubject () {
		try {
			var thisSubject = jQuery('#fb-field-subject').val();
			fbForm.subject = thisSubject;
		} catch(e) {
			if (debug) {
				console.log('updateSubject(): ' + e);
			}
		}
	}
	function updateType(thisType, thisLabelText, thisRequired) {
		try {
			var thisId = jQuery('#fb-field-id').val();
			if (!thisType) { thisType = jQuery('#fb-new-type').val(); }
			if (!thisLabelText) { thisLabelText = jQuery('#fb-new-field' + thisId + ' .label-text').text(); }
			var isRequired = (thisRequired) ? '' + GrunionFB_i18n.requiredLabel + '' : '';
			var thisLabel = '' + FB.esc_html( thisLabelText ) + '' + isRequired + '';
			var thisRadio = '<input type="radio" name="radio-' + thisId + '" id="fb-field' + thisId + ' "disabled="disabled" />';
			var thisRadioLabel = '' + FB.esc_html( thisLabelText ) + '' + isRequired + '';
			var thisRadioRemove = '

';
			var thisRemove = '

';
			var thisCheckbox = '<input type="checkbox" id="fb-field' + thisId + '" "disabled="disabled" />';
			var thisText = '<input type="text" id="fb-field' + thisId + '" "disabled="disabled" />';
			var thisTextarea = '<textarea id="fb-field' + thisId + '" "disabled="disabled"></textarea>';
			var thisClear = '

';
			var thisSelect = '<select id="fb-field' + thisId + '" fieldid="' + thisId + '"><option id="fb-' + thisId + '-' + optionsCount + '" value="' + thisId + '-' + optionsCount + '">' + GrunionFB_i18n.firstOptionLabel + '</option></select>';
			switch (thisType) {
				case 'checkbox':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRadioRemove + thisCheckbox + thisRadioLabel + thisClear);
					break;
				case 'email':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisText);
					break;
				case 'name':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisText);
					break;
				case 'radio':
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisLabel + thisRadioRemove + '

');
					if (optionsCache[thisId] !== undefined && optionsCache[thisId].options.length !== 0) {
						fbForm.fields[thisId].options = optionsCache[thisId].options;
						jQuery('#fb-custom-radio' + thisId).append(customOptions(thisId, thisType));
					} else {
						jQuery('#fb-new-options').html('' + GrunionFB_i18n.optionsLabel + '<input type="text" id="fb-option0" optionid="0" value="' + GrunionFB_i18n.firstOptionLabel + '" class="fb-options" />');
						jQuery('#fb-custom-radio' + thisId).append('
' + thisRadio + '' + GrunionFB_i18n.firstOptionLabel + '' + thisClear + '
');
						fbForm.fields[thisId].options[optionsCount] = GrunionFB_i18n.firstOptionLabel;
					}
					jQuery('#fb-options').show();
					setTimeout(function () { jQuery('#fb-option0').focus().select(); }, 100);
					break;
				case 'select':
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisSelect);
					if (optionsCache[thisId] !== undefined && optionsCache[thisId].options.length !== 0) {
						fbForm.fields[thisId].options = optionsCache[thisId].options;
						jQuery('#fb-field' + thisId).html(customOptions(thisId, thisType));
					} else {
						jQuery('#fb-new-options').html('' + GrunionFB_i18n.optionsLabel + '<input type="text" id="fb-option0" optionid="0" value="' + GrunionFB_i18n.firstOptionLabel + '" class="fb-options" />');
						fbForm.fields[thisId].options[optionsCount] = GrunionFB_i18n.firstOptionLabel;
					}
					jQuery('#fb-options').show();
					setTimeout(function () { jQuery('#fb-option0').focus().select(); }, 100);
					break;
				case 'text':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisText);
					break;
				case 'textarea':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisTextarea);
					break;
				case 'url':
					removeOptions();
					jQuery('#fb-new-field' + thisId + ' .fb-fields').html(thisRemove + thisLabel + thisText);
					break;
			}
			// update object
			fbForm.fields[thisId].type = thisType;
		} catch(e) {
			if (debug) {
				console.log('updateType(): ' + e);
			}
		}
	}
	return {
		resizePop: function () {
			try {
				//Thickbox won't resize for some reason, we are manually doing it here
				var totalWidth = jQuery('body', window.parent.document).width();
				var totalHeight = jQuery('body', window.parent.document).height();
				var isIE6 = typeof document.body.style.maxHeight === 'undefined';

				jQuery('#TB_window, #TB_iframeContent', window.parent.document).css('width', '768px');
				jQuery('#TB_window', window.parent.document).css({ left: (totalWidth-768)/2 + 'px', top: '23px', position: 'absolute', marginLeft: '0' });
				if ( ! isIE6 ) { // take away IE6
					jQuery('#TB_window, #TB_iframeContent', window.parent.document).css('height', (totalHeight-73) + 'px');
				}
			} catch(e) {
				if (debug) {
					console.log('resizePop(): ' + e);
				}
			}
		},
		init: function () {
			// Scroll to top of page
			window.parent.scroll(0,0);
			//Check for existing form data
			var contentSource;
			if (jQuery('#edButtonPreview', window.parent.document).hasClass('active') || jQuery( '#wp-content-wrap', window.parent.document ).hasClass( 'tmce-active' ) ) {
				var win = window.dialogArguments || opener || parent || top;
				contentSource = win.tinyMCE.activeEditor.getContent();
			} else {
				contentSource = jQuery('#content', window.parent.document).val();
			}
			var data = {
				action: 'grunion_shortcode_to_json',
				'_ajax_nonce' : ajax_nonce_json,
				post_id: postId,
				content: contentSource
			};

			var $doc = jQuery(document);

			jQuery.post(ajaxurl, data, function(response) {
				// Setup fbForm
				parseShortcode(jQuery.parseJSON(response));
				// Now build out the preview form
				buildPreview();
			});
			// actions
			jQuery('.fb-add-field').click(function () {
				addField();
				hideDesc();
				return false;
			});
			jQuery('#fb-new-label').keyup(function () {
				updateLabel();
			});
			jQuery('#fb-new-type').change(function () {
				updateType();
			});
			jQuery('#fb-new-required').click(function () {
				updateRequired();
			});
			$doc.on('click', '.fb-remove', function () {
				showDesc();
				deleteField(jQuery(this));
				grabShortcode();
			});
			jQuery('#fb-preview').submit(function () {
				sendShortcodeToEditor();
				return false;
			});
			jQuery('#TB_overlay, #TB_closeWindowButton', window.parent.document).mousedown(function () {
				if(confirm( GrunionFB_i18n.exitConfirmMessage )) {
					hidePopup();
				}
			});
			$doc.on('click', '#fb-another-option', function () {
				addOption();
			});
			$doc.on('keyup', '.fb-options', function () {
				updateOption(jQuery(this));
			});
			$doc.on('click', '.fb-remove-option', function () {
				removeOption(jQuery(this).attr('optionid'));
			});
			jQuery('#tab-preview a').click(function () {
				switchTabs('preview');
				return false;
			});
			jQuery('#fb-prev-form').click(function () {
				switchTabs('preview');
				showAndHideMessage( GrunionFB_i18n.savedMessage );
				return false;
			});
			jQuery('#tab-settings a').click(function () {
				switchTabs();
				return false;
			});
			jQuery('#fb-field-my-email').blur(function () {
				updateMyEmail();
			});
			jQuery('#fb-field-subject').blur(function () {
				updateSubject();
			});
			$doc.on('mouseenter', '.fb-form-case .fb-new-fields', function () {
				hideShowEditLink('show', jQuery(this));
			});
			$doc.on('mouseleave', '.fb-form-case .fb-new-fields', function () {
				hideShowEditLink('hide');
				return false;
			});
			$doc.on('click', '.fb-edit-field', function () {
				editField(jQuery(this));
				return false;
			});
			$doc.on('click', '.fb-edit-field .fb-reorder', function () {
				return false;
			});
			$doc.on('click', '#fb-save-field', function () {
				showDesc();
				showAndHideMessage();
				return false;
			});
			jQuery('#fb-feedback').click(function () {
				var thisHref = jQuery(this).attr('href');
				window.parent.location = thisHref;
				return false;
			});
			jQuery('#sortable').sortable({
				axis: 'y',
				handle: '.fb-reorder',
				revert: true,
				start: function() { jQuery('.fb-edit-field').hide(); }
			});
			jQuery('#draggable').draggable({
				axis: 'y',
				handle: '.fb-reorder',
				connectToSortable: '#sortable',
				helper: 'clone',
				revert: 'invalid'
			});
		}
	};
})();


text:
<?php

namespace by\infrastructure\base;

use by\infrastructure\helper\Object2DataArrayHelper;
use by\infrastructure\interfaces\ToJsonStringInterfaces;

class BaseJsonObject extends BaseObject implements ToJsonStringInterfaces
{

    // member function
    public function __toString()
    {
        return $this->toJsonString();
    }

    // override function __toString()

    function toJsonString()
    {
        $data = Object2DataArrayHelper::getDataArrayFrom($this);
        return json_encode($data);
    }

    // member variables

    // getter setter

}


text:
set :application, 'anidesu'
set :repo_url, 'git@bitbucket.org:JiLiZART/anidesu.app.git'

ask :branch, proc { `git rev-parse --abbrev-ref HEAD`.chomp }

role :app, %w{anidesu.ru}
role :web, %w{anidesu.ru}
role :db,  %w{anidesu.ru}

set :scm, :git
set :scm_username, "JiLiZART"
set :branch, "master"
set :git_enable_submodules, 1

set :format, :pretty
#set :log_level, :debug
set :use_sudo, false
set :pty, true

set :user, 'anidesu'
set :cli, ->{ fetch(:yiic) }
server 'anidesu.ru', user: 'anidesu', roles: %w{web app}

set :linked_files, %w{app/config/db.php app/config/redis.php}
set :linked_dirs, %w{vendor app/runtime public/assets public/vendor node_modules}

set :keep_releases, 5

set :file_permissions_paths, ["app/runtime", "public/assets"]

set :npm_flags, ' --no-spin' # default --production

set :composer_install_flags, '--no-dev --no-interaction --optimize-autoloader'

namespace :deploy do
    desc 'composer install'
    task :composer_install do
        on roles(:web) do
            within release_path do
                execute 'composer', 'install', '--no-dev', '--no-interaction', '--optimize-autoloader'
            end
        end
    end
    #after :updated, 'deploy:composer_install'
    #after :starting, 'composer:install_executable'

    desc 'bower_install'
    task :bower_install do
        on roles(:web) do
            within release_path do
                execute 'bower', 'cache', 'clean'
                execute 'bower', 'install', '--force'
            end
        end
    end
    after :updated, 'deploy:bower_install'

    desc 'assets_build'
    task :assets_build do
        on roles(:web) do
            within release_path do
                execute 'gulp', 'build'
            end
        end
    end
    after :updated, 'deploy:assets_build'

    desc 'migrations'
    task :migrate do
        on roles(:web) do
            within release_path do
                execute 'php', fetch(:cli, nil), 'migrate', '--interactive=0'
            end
        end
    end
    after :updated, 'deploy:migrate'
end


text:
<!--
Copyright 2017 The Closure Library Authors. All Rights Reserved.

Use of this source code is governed by the Apache License, Version 2.0.
See the COPYING file for details.
-->
<script>
  // We use a different base to reproduce the conditions of crbug.com/66987
  var href = window.location.href;
  var newHref = href.replace(/net.*/, '');
  document.write('<base href="' + newHref + '">');

  var baseScript = 'base.js';
  document.write('<script src="' + baseScript + '"><\/script>');
</script>


text:
var gulp        = require('gulp');
var plumber     = require('gulp-plumber');
var spritesmith = require('gulp.spritesmith');
var buffer      = require('vinyl-buffer');
var imagemin    = require('gulp-imagemin');
var config      = require('../../config');

gulp.task('sprite:png', function() {
    var spriteData = gulp.src(config.src.iconsPng + '/*.png')
    .pipe(plumber({
        errorHandler: config.errorHandler
    }))
    .pipe(spritesmith({
        imgName: 'sprite.png',
        cssName: '_sprite-png.sass',
        imgPath: '../img/sprite.png',
        // retinaSrcFilter: config.src.iconsPng + '/*@2x.png',
        // retinaImgName: 'sprite@2x.png',
        // retinaImgPath: '../img/sprite@2x.png',
        padding: 10,
        algorithm: 'binary-tree',
        cssTemplate: __dirname + '/sprite.template.mustache'
        // ,
        // cssVarMap: function(sprite) {
        //     sprite.name = 'icon-' + sprite.name;
        // }
    }));
    spriteData.img
        .pipe(buffer())
        .pipe(imagemin({
            optimizationLevel: 3
        }))
        .pipe(gulp.dest(config.dest.img));
    spriteData.css
        .pipe(gulp.dest(config.src.sassGen));
});

gulp.task('sprite:png:watch', function() {
    gulp.watch(config.src.iconsPng + '/*.png', ['sprite:png']);
});


text:
/* Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.flowable.cmmn.engine.impl.cmd;

import java.io.Serializable;

import org.flowable.cmmn.api.runtime.PlanItemInstance;
import org.flowable.cmmn.engine.impl.persistence.entity.PlanItemInstanceEntity;
import org.flowable.cmmn.engine.impl.util.CommandContextUtil;
import org.flowable.common.engine.api.FlowableIllegalArgumentException;
import org.flowable.common.engine.api.FlowableObjectNotFoundException;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.variable.api.persistence.entity.VariableInstance;

public class GetPlanItemVariableInstanceCmd implements Command<VariableInstance>, Serializable {

    private static final long serialVersionUID = 1L;

    protected String planItemInstanceId;
    protected String variableName;

    public GetPlanItemVariableInstanceCmd(String planItemInstanceId, String variableName) {
        this.planItemInstanceId = planItemInstanceId;
        this.variableName = variableName;
    }

    @Override
    public VariableInstance execute(CommandContext commandContext) {
        if (planItemInstanceId == null) {
            throw new FlowableIllegalArgumentException("planItemInstanceId is null");
        }
        if (variableName == null) {
            throw new FlowableIllegalArgumentException("variableName is null");
        }

        PlanItemInstanceEntity planItemInstance = CommandContextUtil.getPlanItemInstanceEntityManager(commandContext).findById(planItemInstanceId);

        if (planItemInstance == null) {
            throw new FlowableObjectNotFoundException("plan item instance " + planItemInstanceId + " doesn't exist", PlanItemInstance.class);
        }

        return planItemInstance.getVariableInstance(variableName, false);
    }
}


text:
namespace LinAlgFunctions {

using namespace SCIRun;
using namespace SCIRun::Core::Datatypes;

//--------------------------------------------------------------------------
// Source functions

// Field data to buffer
bool get_input_matrix_mi(SCIRun::LinAlgProgramCode& pc, std::string& err)
{
  err = "";
  MatrixHandle* data0 = pc.get_handle(0);
  MatrixHandle* data1 = pc.get_handle(1);

  if (!(*data1)) return (false);

  (*data0) = (*data1);
  return (true);
}

bool set_output_matrix_m(SCIRun::LinAlgProgramCode& pc, std::string& err)
{
  err = "";
  MatrixHandle* data0 = pc.get_handle(0);
  MatrixHandle* data1 = pc.get_handle(1);

  if (!(*data1)) return (false);

  (*data0) = (*data1);
  return (true);
}

} //end namespace

namespace SCIRun {

void
InsertSourceSinkLinAlgFunctionCatalog(LinAlgFunctionCatalogHandle& catalog)
{
  // Source functions
  catalog->add_function(LinAlgFunctions::get_input_matrix_mi,"get_input_matrix$MI","S");
  catalog->add_function(LinAlgFunctions::set_output_matrix_m,"set_output_matrix$S","MO");
}

} // end namespace


text:
import { Tooltip } from 'antd';

export default Tooltip;


text:
import * as React from 'react';
import { shallow } from 'enzyme';

import { DropdownDivider } from './../../../../src/components/Dropdown/Menu/DropdownDivider';

describe('Dropdown', () => {
    it('should rendern hr with .dropdown-divider', () => {
        const component = shallow(<DropdownDivider>My DropdownDivider</DropdownDivider>);
        expect(component.is('hr')).toBe(true);
        expect(component.hasClass('dropdown-divider')).toBe(true);
    });

    it('should rendern an img with .dropdown-divider', () => {
        const component = shallow(<DropdownDivider tag="img">My DropdownDivider</DropdownDivider>);
        expect(component.is('img')).toBe(true);
        expect(component.hasClass('dropdown-divider')).toBe(true);
    });
});


text:
module Azure::Compute::Mgmt::V2020_06_30
  module Models
    #
    # Defines values for DiskStorageAccountTypes
    #
    module DiskStorageAccountTypes
      StandardLRS = "Standard_LRS"
      PremiumLRS = "Premium_LRS"
      StandardSSDLRS = "StandardSSD_LRS"
      UltraSSDLRS = "UltraSSD_LRS"
    end
  end
end


text:
<?php
error_reporting(-1);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
date_default_timezone_set('UTC');

try {
    // Initialize Composer autoloader
    if (!file_exists($autoload = __DIR__ . '/vendor/autoload.php')) {
        throw new \Exception('Composer dependencies not installed.');
    }
    require_once $autoload;
    // Initialize Slim Framework
    if (!class_exists('\\Slim\\Slim')) {
        throw new \Exception(
            'Missing Slim from Composer dependencies.  Ensure slim/slim is in composer.json'
        );
    }

    // Create a config object
    $usfConfigObject = new \USF\IdM\UsfConfig($_ENV['VISOR_CONFIG_DIR']);

    // Run application
    $app = new \USF\IdM\Visor\Visor($usfConfigObject);
    $app->run();
} catch (\Exception $e) {
    if (isset($app)) {
        $app->handleException($e);
    } else {
        http_response_code(500);
        header('Content-Type: application/json');
        echo json_encode(
            [
                'status' => 'error',
                'data' => [
                    'status' => 500,
                    'statusText' => 'Internal Server Error',
                    'description' => $e->getMessage()
                ]
            ]
        );
    }
}


text:
#include "config.h"
#include "learn_cache.h"
#include "rspamd.h"
#include "stat_api.h"
#include "stat_internal.h"
#include "cryptobox.h"
#include "ucl.h"
#include "hiredis.h"
#include "adapters/libevent.h"

#define REDIS_DEFAULT_TIMEOUT 0.5
#define REDIS_STAT_TIMEOUT 30
#define REDIS_DEFAULT_PORT 6379
#define DEFAULT_REDIS_KEY "learned_ids"

struct rspamd_redis_cache_ctx {
	struct rspamd_statfile_config *stcf;
	struct upstream_list *read_servers;
	struct upstream_list *write_servers;
	const gchar *password;
	const gchar *dbname;
	const gchar *redis_object;
	gdouble timeout;
};

struct rspamd_redis_cache_runtime {
	struct rspamd_redis_cache_ctx *ctx;
	struct rspamd_task *task;
	struct upstream *selected;
	struct event timeout_event;
	redisAsyncContext *redis;
	gboolean has_event;
};

static GQuark
rspamd_stat_cache_redis_quark (void)
{
	return g_quark_from_static_string ("redis-statistics");
}

static void
rspamd_redis_cache_maybe_auth (struct rspamd_redis_cache_ctx *ctx,
		redisAsyncContext *redis)
{
	if (ctx->password) {
		redisAsyncCommand (redis, NULL, NULL, "AUTH %s", ctx->password);
	}
	if (ctx->dbname) {
		redisAsyncCommand (redis, NULL, NULL, "SELECT %s", ctx->dbname);
	}
}

/* Called on connection termination */
static void
rspamd_redis_cache_fin (gpointer data)
{
	struct rspamd_redis_cache_runtime *rt = data;
	redisAsyncContext *redis;

	rt->has_event = FALSE;
	if (event_get_base (&rt->timeout_event)) {
		event_del (&rt->timeout_event);
	}

	if (rt->redis) {
		redis = rt->redis;
		rt->redis = NULL;
		/* This calls for all callbacks pending */
		redisAsyncFree (redis);
	}
}

static void
rspamd_redis_cache_timeout (gint fd, short what, gpointer d)
{
	struct rspamd_redis_cache_runtime *rt = d;
	struct rspamd_task *task;

	task = rt->task;

	msg_err_task ("connection to redis server %s timed out",
			rspamd_upstream_name (rt->selected));
	rspamd_upstream_fail (rt->selected);

	if (rt->has_event) {
		rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, d);
	}
}

/* Called when we have checked the specified message id */
static void
rspamd_stat_cache_redis_get (redisAsyncContext *c, gpointer r, gpointer priv)
{
	struct rspamd_redis_cache_runtime *rt = priv;
	redisReply *reply = r;
	struct rspamd_task *task;
	glong val = 0;

	task = rt->task;

	if (c->err == 0) {
		if (reply) {
			if (G_LIKELY (reply->type == REDIS_REPLY_INTEGER)) {
				val = reply->integer;
			}
			else if (reply->type == REDIS_REPLY_STRING) {
				rspamd_strtol (reply->str, reply->len, &val);
			}
			else {
				if (reply->type != REDIS_REPLY_NIL) {
					msg_err_task ("bad learned type for %s: %d",
							rt->ctx->stcf->symbol, reply->type);
				}

				val = 0;
			}
		}

		if ((val > 0 && (task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM)) ||
				(val < 0 && (task->flags & RSPAMD_TASK_FLAG_LEARN_HAM))) {
			/* Already learned */
			msg_info_task ("<%s> has been already "
					"learned as %s, ignore it", task->message_id,
					(task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM) ? "spam" : "ham");
			task->flags |= RSPAMD_TASK_FLAG_ALREADY_LEARNED;
		}
		else if (val != 0) {
			/* Unlearn flag */
			task->flags |= RSPAMD_TASK_FLAG_UNLEARN;
		}

		rspamd_upstream_ok (rt->selected);
	}
	else {
		rspamd_upstream_fail (rt->selected);
	}

	if (rt->has_event) {
		rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, rt);
	}
}

/* Called when we have learned the specified message id */
static void
rspamd_stat_cache_redis_set (redisAsyncContext *c, gpointer r, gpointer priv)
{
	struct rspamd_redis_cache_runtime *rt = priv;
	struct rspamd_task *task;

	task = rt->task;

	if (c->err == 0) {
		/* XXX: we ignore results here */
		rspamd_upstream_ok (rt->selected);
	}
	else {
		rspamd_upstream_fail (rt->selected);
	}

	if (rt->has_event) {
		rspamd_session_remove_event (task->s, rspamd_redis_cache_fin, rt);
	}
}

static void
rspamd_stat_cache_redis_generate_id (struct rspamd_task *task)
{
	rspamd_cryptobox_hash_state_t st;
	rspamd_token_t *tok;
	guint i;
	guchar out[rspamd_cryptobox_HASHBYTES];
	gchar *b32out;
	gchar *user = NULL;

	rspamd_cryptobox_hash_init (&st, NULL, 0);

	user = rspamd_mempool_get_variable (task->task_pool, "stat_user");
	/* Use dedicated hash space for per users cache */
	if (user != NULL) {
		rspamd_cryptobox_hash_update (&st, user, strlen (user));
	}

	for (i = 0; i < task->tokens->len; i ++) {
		tok = g_ptr_array_index (task->tokens, i);
		rspamd_cryptobox_hash_update (&st, (guchar *)&tok->data,
				sizeof (tok->data));
	}

	rspamd_cryptobox_hash_final (&st, out);

	b32out = rspamd_encode_base32 (out, sizeof (out));
	g_assert (b32out != NULL);
	rspamd_mempool_set_variable (task->task_pool, "words_hash", b32out, g_free);
}

static gboolean
rspamd_redis_cache_try_ucl (struct rspamd_redis_cache_ctx *cache_ctx,
		const ucl_object_t *obj,
		struct rspamd_config *cfg,
		const gchar *symbol)
{
	const ucl_object_t *elt, *relt;

	elt = ucl_object_lookup_any (obj, "read_servers", "servers", NULL);

	if (elt == NULL) {
		return FALSE;
	}

	cache_ctx->read_servers = rspamd_upstreams_create (cfg->ups_ctx);
	if (!rspamd_upstreams_from_ucl (cache_ctx->read_servers, elt,
			REDIS_DEFAULT_PORT, NULL)) {
		msg_err ("statfile %s cannot get read servers configuration",
				symbol);
		return FALSE;
	}

	relt = elt;

	elt = ucl_object_lookup (obj, "write_servers");
	if (elt == NULL) {
		/* Use read servers as write ones */
		g_assert (relt != NULL);
		cache_ctx->write_servers = rspamd_upstreams_create (cfg->ups_ctx);
		if (!rspamd_upstreams_from_ucl (cache_ctx->write_servers, relt,
				REDIS_DEFAULT_PORT, NULL)) {
			msg_err ("statfile %s cannot get write servers configuration",
					symbol);
			return FALSE;
		}
	}
	else {
		cache_ctx->write_servers = rspamd_upstreams_create (cfg->ups_ctx);
		if (!rspamd_upstreams_from_ucl (cache_ctx->write_servers, elt,
				REDIS_DEFAULT_PORT, NULL)) {
			msg_err ("statfile %s cannot get write servers configuration",
					symbol);
			rspamd_upstreams_destroy (cache_ctx->write_servers);
			cache_ctx->write_servers = NULL;
		}
	}

	elt = ucl_object_lookup (obj, "timeout");
	if (elt) {
		cache_ctx->timeout = ucl_object_todouble (elt);
	}
	else {
		cache_ctx->timeout = REDIS_DEFAULT_TIMEOUT;
	}

	elt = ucl_object_lookup (obj, "password");
	if (elt) {
		cache_ctx->password = ucl_object_tostring (elt);
	}
	else {
		cache_ctx->password = NULL;
	}

	elt = ucl_object_lookup_any (obj, "db", "database", "dbname", NULL);
	if (elt) {
		cache_ctx->dbname = ucl_object_tostring (elt);
	}
	else {
		cache_ctx->dbname = NULL;
	}

	elt = ucl_object_lookup_any (obj, "cache_key", "key", NULL);
	if (elt == NULL || ucl_object_type (elt) != UCL_STRING) {
		cache_ctx->redis_object = DEFAULT_REDIS_KEY;
	}
	else {
		cache_ctx->redis_object = ucl_object_tostring (elt);
	}

	return TRUE;
}

gpointer
rspamd_stat_cache_redis_init (struct rspamd_stat_ctx *ctx,
		struct rspamd_config *cfg,
		struct rspamd_statfile *st,
		const ucl_object_t *cf)
{
	struct rspamd_redis_cache_ctx *cache_ctx;
	struct rspamd_statfile_config *stf = st->stcf;
	const ucl_object_t *obj;
	gboolean ret = FALSE;

	cache_ctx = g_malloc0 (sizeof (*cache_ctx));

	/* First search in backend configuration */
	obj = ucl_object_lookup (st->classifier->cfg->opts, "backend");
	if (obj != NULL && ucl_object_type (obj) == UCL_OBJECT) {
		ret = rspamd_redis_cache_try_ucl (cache_ctx, obj, cfg, stf->symbol);
	}

	/* Now try statfiles config */
	if (!ret) {
		ret = rspamd_redis_cache_try_ucl (cache_ctx, stf->opts, cfg, stf->symbol);
	}

	/* Now try classifier config */
	if (!ret) {
		ret = rspamd_redis_cache_try_ucl (cache_ctx, st->classifier->cfg->opts, cfg,
				stf->symbol);
	}

	/* Now try global redis settings */
	if (!ret) {
		obj = ucl_object_lookup (cfg->rcl_obj, "redis");

		if (obj) {
			const ucl_object_t *specific_obj;

			specific_obj = ucl_object_lookup (obj, "statistics");

			if (specific_obj) {
				ret = rspamd_redis_cache_try_ucl (cache_ctx, specific_obj, cfg,
						stf->symbol);
			}
			else {
				ret = rspamd_redis_cache_try_ucl (cache_ctx, obj, cfg,
						stf->symbol);
			}
		}
	}

	if (!ret) {
		msg_err_config ("cannot init redis cache for %s", stf->symbol);
		g_free (cache_ctx);
		return NULL;
	}

	cache_ctx->stcf = stf;

	return (gpointer)cache_ctx;
}

gpointer
rspamd_stat_cache_redis_runtime (struct rspamd_task *task,
		gpointer c, gboolean learn)
{
	struct rspamd_redis_cache_ctx *ctx = c;
	struct rspamd_redis_cache_runtime *rt;
	struct upstream *up;
	rspamd_inet_addr_t *addr;

	g_assert (ctx != NULL);

	if (learn && ctx->write_servers == NULL) {
		msg_err_task ("no write servers defined for %s, cannot learn",
				ctx->stcf->symbol);
		return NULL;
	}

	if (task->tokens == NULL || task->tokens->len == 0) {
		return NULL;
	}

	if (learn) {
		up = rspamd_upstream_get (ctx->write_servers,
				RSPAMD_UPSTREAM_MASTER_SLAVE,
				NULL,
				0);
	}
	else {
		up = rspamd_upstream_get (ctx->read_servers,
				RSPAMD_UPSTREAM_ROUND_ROBIN,
				NULL,
				0);
	}

	if (up == NULL) {
		msg_err_task ("no upstreams reachable");
		return NULL;
	}

	rt = rspamd_mempool_alloc0 (task->task_pool, sizeof (*rt));
	rt->selected = up;
	rt->task = task;
	rt->ctx = ctx;

	addr = rspamd_upstream_addr (up);
	g_assert (addr != NULL);

	if (rspamd_inet_address_get_af (addr) == AF_UNIX) {
		rt->redis = redisAsyncConnectUnix (rspamd_inet_address_to_string (addr));
	}
	else {
		rt->redis = redisAsyncConnect (rspamd_inet_address_to_string (addr),
				rspamd_inet_address_get_port (addr));
	}

	g_assert (rt->redis != NULL);

	redisLibeventAttach (rt->redis, task->ev_base);

	/* Now check stats */
	event_set (&rt->timeout_event, -1, EV_TIMEOUT, rspamd_redis_cache_timeout, rt);
	event_base_set (task->ev_base, &rt->timeout_event);
	rspamd_redis_cache_maybe_auth (ctx, rt->redis);

	if (!learn) {
		rspamd_stat_cache_redis_generate_id (task);
	}

	return rt;
}

gint
rspamd_stat_cache_redis_check (struct rspamd_task *task,
		gboolean is_spam,
		gpointer runtime)
{
	struct rspamd_redis_cache_runtime *rt = runtime;
	struct timeval tv;
	gchar *h;

	h = rspamd_mempool_get_variable (task->task_pool, "words_hash");

	if (h == NULL) {
		return RSPAMD_LEARN_INGORE;
	}

	double_to_tv (rt->ctx->timeout, &tv);

	if (redisAsyncCommand (rt->redis, rspamd_stat_cache_redis_get, rt,
			"HGET %s %s",
			rt->ctx->redis_object, h) == REDIS_OK) {
		rspamd_session_add_event (task->s, rspamd_redis_cache_fin, rt,
				rspamd_stat_cache_redis_quark ());
		event_add (&rt->timeout_event, &tv);
		rt->has_event = TRUE;
	}

	/* We need to return OK every time */
	return RSPAMD_LEARN_OK;
}

gint
rspamd_stat_cache_redis_learn (struct rspamd_task *task,
		gboolean is_spam,
		gpointer runtime)
{
	struct rspamd_redis_cache_runtime *rt = runtime;
	struct timeval tv;
	gchar *h;
	gint flag;

	h = rspamd_mempool_get_variable (task->task_pool, "words_hash");
	g_assert (h != NULL);

	double_to_tv (rt->ctx->timeout, &tv);
	flag = (task->flags & RSPAMD_TASK_FLAG_LEARN_SPAM) ? 1 : -1;

	if (redisAsyncCommand (rt->redis, rspamd_stat_cache_redis_set, rt,
			"HSET %s %s %d",
			rt->ctx->redis_object, h, flag) == REDIS_OK) {
		rspamd_session_add_event (task->s, rspamd_redis_cache_fin, rt,
				rspamd_stat_cache_redis_quark ());
		event_add (&rt->timeout_event, &tv);
		rt->has_event = TRUE;
	}

	/* We need to return OK every time */
	return RSPAMD_LEARN_OK;
}

void
rspamd_stat_cache_redis_close (gpointer c)
{

}


text:
Find your password

{{ error }}

          <form action="" class="form-horizontal" name="frm">

Enter your email to reset your password

                  <input type="email" class="form-control" placeholder="Email Address" ng-model="user.email" required="required" ng-return="onSend()" />

          </form>

            Back to Login
            <button class="btn btn-primary pull-right" ng-click="onSend()" ng-disabled="frm.$invalid">Send now</button>

Find your password

          We have sent verification email to your email address.

            Login


text:
var exec = require("cordova/exec");

/**
    attribute SpeechGrammarList grammars;
    attribute DOMString lang;
    attribute boolean continuous;
    attribute boolean interimResults;
    attribute unsigned long maxAlternatives;
    attribute DOMString serviceURI;
 */
var speechRecognitionAndroid = function () {
    this.grammars = null;
    this.lang = "en";
    this.continuous = false;
    this.interimResults = false;
    this.maxAlternatives = 1;
    this.serviceURI = "";

    // event methods
    this.onaudiostart = null;
    this.onsoundstart = null;
    this.onspeechstart = null;
    this.onspeechend = null;
    this.onsoundend = null;
    this.onaudioend = null;
    this.onresult = null;
    this.onnomatch = null;
    this.onerror = null;
    this.onstart = null;
    this.onend = null;
	this.onpartialResults = null;
	this.onreadyForSpeech = null;

    exec(function() {
        console.log("initialized");
    }, function(e) {
        console.log("error: " + e);
    }, "speechRecognitionAndroid", "init", []);
};

speechRecognitionAndroid.prototype.start = function() {
    var that = this;
    var successCallback = function(event) {
        if (event.type === "audiostart")
		{
			console.log("audiostart")
			if (typeof that.onaudiostart === "function") {
			console.log("audiostart")
            that.onaudiostart(event);}
        } else if (event.type === "soundstart" && typeof that.onsoundstart === "function") {
            that.onsoundstart(event);
        } else if (event.type === "speechstart" && typeof that.onspeechstart === "function") {
            that.onspeechstart(event);
        } else if (event.type === "speechend" && typeof that.onspeechend === "function") {
            that.onspeechend(event);
        } else if (event.type === "soundend" && typeof that.onsoundend === "function") {
            that.onsoundend(event);
        } else if (event.type === "audioend" && typeof that.onaudioend === "function") {
            that.onaudioend(event);
        } else if (event.type === "result" && typeof that.onresult === "function") {
			console.log("Gauri:result");
            that.onresult(event);
        } else if (event.type === "nomatch" && typeof that.onnomatch === "function") {
            that.onnomatch(event);
        } else if (event.type === "start" && typeof that.onstart === "function") {
            that.onstart(event);
        } else if (event.type === "end" && typeof that.onend === "function") {
            that.onend(event);
        }else if (event.type === "partialResult" && typeof that.onpartialResults === "function") {
            that.onpartialResults(event);
        }else if (event.type === "readyForSpeech" && typeof that.onreadyForSpeech === "function") {
            that.onreadyForSpeech(event);
		}
    };
    var errorCallback = function(err) {
        if (typeof that.onerror === "function") {
            that.onerror(err.errorNumber);
        }
    };

    exec(successCallback, errorCallback, "speechRecognitionAndroid", "start", [this.lang]);
};

speechRecognitionAndroid.prototype.stop = function() {
    exec(null, null, "speechRecognitionAndroid", "stop", []);
};

speechRecognitionAndroid.prototype.abort = function() {
    exec(null, null, "speechRecognitionAndroid", "abort", []);
};

module.exports = speechRecognitionAndroid;


text:
package com.springsource.greenhouse.activity.action;

import org.joda.time.DateTime;

import com.springsource.greenhouse.account.Account;
import com.springsource.greenhouse.utils.Location;

/**
 * Models an action a member performed in the application system.
 * Used to record member activity.
 * Actions also serve as input into the badge system (performing an Action may result in a badge being awarded).
 * Actions may be explicitly performed e.g. "Keith tweeted from SpringOne2gx", or implicitly triggered on behalf of a member
 * e.g. "10 minutes before the SpringOne event ended, the event organizer awarded the top speaker badges (triggered by a timer)."
 * @author Keith Donald
 */
public abstract class Action {

	private final Long id;

	private final DateTime time;

	private final Account account;

	private final Location location;

	public Action(Long id, DateTime time, Account account, Location location) {
		this.id = id;
		this.time = time;
		this.account = account;
		this.location = location;
	}

	/**
	 * The internal identifier of this Action.
	 */
	public Long getId() {
		return id;
	}

	/**
	 * The date and time the Action was performed.
	 */
	public DateTime getTime() {
		return time;
	}

	/**
	 * The member Account that performed the Action.
	 */
	public Account getAccount() {
		return account;
	}

	/**
	 * The Location where the Action was performed.
	 * May be null if geo-tagging was disabled.
	 */
	public Location getLocation() {
		return location;
	}

}


text:
A short description of your package.

![A screenshot of your package](https://f.cloud.github.com/assets/69169/2290250/c35d867a-a017-11e3-86be-cd7c5bf3ff9b.gif)


text:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#if defined(__APPLE__) && defined(__MACH__)
#include <machine/endian.h>
#include <libkern/OSByteOrder.h>
#define le16toh(x) OSSwapLittleToHostInt16(x)
#else
#include <endian.h>
#endif
#include "usbscale.h"

const char* unitAbbrev[] = {"unknown", "mg", "g", "kg", "cd", "taels", "gr", "dwt", "tonnes", "tons", "ozt", "oz", "lbs"};

struct data {
  enum report report;
  enum status status;
  enum unit unit;
  signed char exponent;
  unsigned short raw_weight; // 16 bit, little endian
  float weight;
};

int main(int argc, char** argv)
{
  if (argc < 2) {
    fprintf(stderr, "Usage: %s /dev/hidrawX\n", argv[0]);
    return 1;
  }

  FILE* fp = fopen(argv[1], "rb");
  if (fp == NULL) {
    fprintf(stderr, "Unable to open %s\n", argv[1]);
    return 1;
  }

  unsigned char buffer[6] = {0};
  fread(buffer, 1, sizeof(buffer), fp);
  fclose(fp);

  #ifdef DEBUG
  for (int i = 0; i < sizeof(buffer); i += 1) {
    printf("byte %i = %x\n", i, buffer[i]);
  }
  #endif

  struct data result;
  result.report = buffer[0];
  result.status = buffer[1];
  result.unit = buffer[2];
  result.exponent = buffer[3];
  // shall be little endian
  result.raw_weight =  le16toh(buffer[5] << 8 | buffer[4]);

  #ifdef DEBUG
  printf("report = %i\n", result.report);
  printf("status = %i\n", result.status);
  printf("unit = %i\n", result.unit);
  printf("exponent = %i\n", result.exponent);
  printf("raw weight = %i\n", result.raw_weight);
  #endif

  // Scale Data Report and Positive Weight Status
  if (result.report == DATA && result.status == POSITIVE) {
    // ...the scaling applied to the data as a base ten exponent
    result.weight = result.raw_weight * pow(10, result.exponent);
    if (result.unit == OUNCE) {
      // convert ounces to grams
      result.weight *= 28.349523125;
      // and change unit to grams
      result.unit = GRAM;
    }

    printf("%.2f %s\n", result.weight, unitAbbrev[result.unit]);
  }

  return 0;
}


text:
#include <ossimGui/OverlayBase.h>
#include <ossimGui/Export.h>
#include <ossimGui/MarkPoint.h>
#include <ossim/base/ossimObject.h>
#include <ossim/base/ossimRefPtr.h>
#include <ossim/base/ossimDpt.h>
#include <ossim/base/ossimString.h>
#include <ossim/base/ossimDpt.h>
#include <map>

namespace ossimGui {

	class IvtGeomTransform;

	class OSSIMGUI_DLL MetricOverlay : public OverlayBase
	{
		Q_OBJECT

	public:
		MetricOverlay(const ossimString& overlayId, QGraphicsScene* scene);
		virtual void reset();

		virtual void addPoint(const ossimDpt& scenePt, const ossimDpt& imagePt, const ossimString& id);
		virtual void addPoint(const ossimDpt& scenePt, const ossimDpt& imagePt);
		virtual void removePoint(const ossimString& id);
		virtual void togglePointActive(const ossimString& id);

    	virtual bool getImgPoint(const ossimString& id, ossimDpt& imgPt, bool& isActive);
    	virtual ossimGui::MarkPoint* getMarkPoint(const ossimString& id);
    	virtual ossimString getCurrentId()const {return m_currentId;}
    	virtual ossim_uint32 getNumPoints()const;

    	virtual void setVisible(const bool& visible);
    	virtual void setCurrentId(const ossimString& id) {m_currentId = id;}
      virtual void setView(ossimRefPtr<IvtGeomTransform> ivtg);

   signals:
   	void pointActivated(const ossimString&);
   	void pointDeactivated(const ossimString&);
   	void pointRemoved(const ossimString&);

	protected:
      ossimString m_currentId;

	};

}

#endif // ossimGuiMetricOverlay_HEADER


text:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_vertical"
        android:orientation="vertical" >
        <ImageView
            android:id="@+id/nfc_payment_tap_image"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:visibility="gone"
            android:src="@drawable/nfc_payment_empty_state"/>
        <TextView
            android:id="@+id/nfc_payment_empty_text"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:textSize="24sp"
            android:visibility="gone"
            android:paddingTop="16dp"
            android:text="@string/nfc_payment_no_apps"/>
        <TextView
            android:id="@+id/nfc_payment_learn_more"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:clickable="true"
            android:textSize="20sp"
            android:textStyle="italic"
            android:visibility="gone"
            android:textColor="@color/text_color_holo_blue_light"
            android:paddingTop="16dp"
            android:text="@string/nfc_payment_learn_more"/>
    </LinearLayout>
    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="5dp" />

</FrameLayout>


text:
struct GPUCreateCommandBufferConfig;

namespace IPC {
struct ChannelHandle;
}

namespace gpu {
struct SyncToken;
}

namespace content {
class BrowserChildProcessHostImpl;
class GpuMainThread;
class InProcessChildThreadParams;
class MojoApplicationHost;
class RenderWidgetHostViewFrameSubscriber;
class ShaderDiskCache;

typedef base::Thread* (*GpuMainThreadFactoryFunction)(
    const InProcessChildThreadParams&);

class GpuProcessHost : public BrowserChildProcessHostDelegate,
                       public IPC::Sender,
                       public base::NonThreadSafe {
 public:
  enum GpuProcessKind {
    GPU_PROCESS_KIND_UNSANDBOXED,
    GPU_PROCESS_KIND_SANDBOXED,
    GPU_PROCESS_KIND_COUNT
  };

  typedef base::Callback<void(const IPC::ChannelHandle&, const gpu::GPUInfo&)>
      EstablishChannelCallback;

  struct EstablishChannelRequest {
    EstablishChannelRequest();
    ~EstablishChannelRequest();
    int32_t client_id;
    EstablishChannelCallback callback;
  };

  typedef base::Callback<void(const gfx::GpuMemoryBufferHandle& handle)>
      CreateGpuMemoryBufferCallback;

  static bool gpu_enabled() { return gpu_enabled_; }
  static int gpu_crash_count() { return gpu_crash_count_; }

  // Creates a new GpuProcessHost or gets an existing one, resulting in the
  // launching of a GPU process if required.  Returns null on failure. It
  // is not safe to store the pointer once control has returned to the message
  // loop as it can be destroyed. Instead store the associated GPU host ID.
  // This could return NULL if GPU access is not allowed (blacklisted).
  CONTENT_EXPORT static GpuProcessHost* Get(GpuProcessKind kind,
                                            CauseForGpuLaunch cause);

  // Retrieves a list of process handles for all gpu processes.
  static void GetProcessHandles(
      const GpuDataManager::GetGpuProcessHandlesCallback& callback);

  // Helper function to send the given message to the GPU process on the IO
  // thread.  Calls Get and if a host is returned, sends it.  Can be called from
  // any thread.  Deletes the message if it cannot be sent.
  CONTENT_EXPORT static void SendOnIO(GpuProcessKind kind,
                                      CauseForGpuLaunch cause,
                                      IPC::Message* message);

  CONTENT_EXPORT static void RegisterGpuMainThreadFactory(
      GpuMainThreadFactoryFunction create);

  // BrowserChildProcessHostDelegate implementation.
  ServiceRegistry* GetServiceRegistry() override;

  // Get the GPU process host for the GPU process with the given ID. Returns
  // null if the process no longer exists.
  static GpuProcessHost* FromID(int host_id);
  int host_id() const { return host_id_; }

  // IPC::Sender implementation.
  bool Send(IPC::Message* msg) override;

  // Adds a message filter to the GpuProcessHost's channel.
  void AddFilter(IPC::MessageFilter* filter);

  // Tells the GPU process to create a new channel for communication with a
  // client. Once the GPU process responds asynchronously with the IPC handle
  // and GPUInfo, we call the callback.
  void EstablishGpuChannel(int client_id,
                           uint64_t client_tracing_id,
                           bool preempts,
                           bool allow_view_command_buffers,
                           bool allow_real_time_streams,
                           const EstablishChannelCallback& callback);

  // Tells the GPU process to create a new GPU memory buffer.
  void CreateGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                             const gfx::Size& size,
                             gfx::BufferFormat format,
                             gfx::BufferUsage usage,
                             int client_id,
                             int32_t surface_id,
                             const CreateGpuMemoryBufferCallback& callback);

  // Tells the GPU process to create a new GPU memory buffer from an existing
  // handle.
  void CreateGpuMemoryBufferFromHandle(
      const gfx::GpuMemoryBufferHandle& handle,
      gfx::GpuMemoryBufferId id,
      const gfx::Size& size,
      gfx::BufferFormat format,
      int client_id,
      const CreateGpuMemoryBufferCallback& callback);

  // Tells the GPU process to destroy GPU memory buffer.
  void DestroyGpuMemoryBuffer(gfx::GpuMemoryBufferId id,
                              int client_id,
                              const gpu::SyncToken& sync_token);

  // What kind of GPU process, e.g. sandboxed or unsandboxed.
  GpuProcessKind kind();

  // Forcefully terminates the GPU process.
  void ForceShutdown();

  // Asks the GPU process to stop by itself.
  void StopGpuProcess();

  void LoadedShader(const std::string& key, const std::string& data);

 private:
  static bool ValidateHost(GpuProcessHost* host);

  GpuProcessHost(int host_id, GpuProcessKind kind);
  ~GpuProcessHost() override;

  bool Init();

  // Sets up mojo support in GPU process. Returns false upon failure.
  bool SetupMojo();

  // Post an IPC message to the UI shim's message handler on the UI thread.
  void RouteOnUIThread(const IPC::Message& message);

  // BrowserChildProcessHostDelegate implementation.
  bool OnMessageReceived(const IPC::Message& message) override;
  void OnChannelConnected(int32_t peer_pid) override;
  void OnProcessLaunched() override;
  void OnProcessLaunchFailed() override;
  void OnProcessCrashed(int exit_code) override;

  // Message handlers.
  void OnInitialized(bool result, const gpu::GPUInfo& gpu_info);
  void OnChannelEstablished(const IPC::ChannelHandle& channel_handle);
  void OnGpuMemoryBufferCreated(const gfx::GpuMemoryBufferHandle& handle);
  void OnDidCreateOffscreenContext(const GURL& url);
  void OnDidLoseContext(bool offscreen,
                        gpu::error::ContextLostReason reason,
                        const GURL& url);
  void OnDidDestroyOffscreenContext(const GURL& url);
  void OnGpuMemoryUmaStatsReceived(const GPUMemoryUmaStats& stats);
#if defined(OS_MACOSX)
  void OnAcceleratedSurfaceBuffersSwapped(const IPC::Message& message);
#endif

#if defined(OS_WIN)
  void OnAcceleratedSurfaceCreatedChildWindow(
      const gfx::PluginWindowHandle& parent_handle,
      const gfx::PluginWindowHandle& window_handle);
#endif

  void CreateChannelCache(int32_t client_id);
  void OnDestroyChannel(int32_t client_id);
  void OnCacheShader(int32_t client_id,
                     const std::string& key,
                     const std::string& shader);

  bool LaunchGpuProcess(const std::string& channel_id);

  void SendOutstandingReplies();

  void BlockLiveOffscreenContexts();

  // Update GPU crash counters.  Disable GPU if crash limit is reached.
  void RecordProcessCrash();

  std::string GetShaderPrefixKey();

  // The serial number of the GpuProcessHost / GpuProcessHostUIShim pair.
  int host_id_;

  // These are the channel requests that we have already sent to
  // the GPU process, but haven't heard back about yet.
  std::queue<EstablishChannelRequest> channel_requests_;

  // The pending create gpu memory buffer requests we need to reply to.
  std::queue<CreateGpuMemoryBufferCallback> create_gpu_memory_buffer_requests_;

  // Qeueud messages to send when the process launches.
  std::queue<IPC::Message*> queued_messages_;

  // Whether the GPU process is valid, set to false after Send() failed.
  bool valid_;

  // Whether we are running a GPU thread inside the browser process instead
  // of a separate GPU process.
  bool in_process_;

  bool swiftshader_rendering_;
  GpuProcessKind kind_;

  // The GPUInfo for the connected process. Only valid after initialized_ is
  // true.
  gpu::GPUInfo gpu_info_;

  scoped_ptr<base::Thread> in_process_gpu_thread_;

  // Whether we actually launched a GPU process.
  bool process_launched_;

  // Whether the GPU process successfully initialized.
  bool initialized_;

  // Time Init started.  Used to log total GPU process startup time to UMA.
  base::TimeTicks init_start_time_;

  // Master switch for enabling/disabling GPU acceleration for the current
  // browser session. It does not change the acceleration settings for
  // existing tabs, just the future ones.
  static bool gpu_enabled_;

  static bool hardware_gpu_enabled_;

  static int gpu_crash_count_;
  static int gpu_recent_crash_count_;
  static bool crashed_before_;
  static int swiftshader_crash_count_;

  scoped_ptr<BrowserChildProcessHostImpl> process_;

  // Track the URLs of the pages which have live offscreen contexts,
  // assumed to be associated with untrusted content such as WebGL.
  // For best robustness, when any context lost notification is
  // received, assume all of these URLs are guilty, and block
  // automatic execution of 3D content from those domains.
  std::multiset<GURL> urls_with_live_offscreen_contexts_;

  // Statics kept around to send to UMA histograms on GPU process lost.
  bool uma_memory_stats_received_;
  GPUMemoryUmaStats uma_memory_stats_;

  typedef std::map<int32_t, scoped_refptr<ShaderDiskCache>>
      ClientIdToShaderCacheMap;
  ClientIdToShaderCacheMap client_id_to_shader_cache_;

  std::string shader_prefix_key_;

  // Browser-side Mojo endpoint which sets up a Mojo channel with the child
  // process and contains the browser's ServiceRegistry.
  scoped_ptr<MojoApplicationHost> mojo_application_host_;

  DISALLOW_COPY_AND_ASSIGN(GpuProcessHost);
};

}  // namespace content

#endif  // CONTENT_BROWSER_GPU_GPU_PROCESS_HOST_H_


text:
import { ChartConfiguration } from './ChartConfiguration.class';

export class GaugeSimpleChartConfiguration extends ChartConfiguration {
  readonly type: string = 'gaugeSimpleChart';

  color: Array<string> = ['#88ac67', '#f78f20', '#db4e4e'];
  title: string = '';
  showMinMaxLabels: boolean = false;
  min: number = 0;
  max: number = 100;
  zoneLimit1: number = 0.6;
  zoneLimit2: number = 0.8;
  duration: number = 500;
}


text:
package io.github.mzmine.modules.dataprocessing.id_ion_identity_networking.relations;

import io.github.mzmine.parameters.Parameter;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.parameters.parametertypes.BooleanParameter;
import io.github.mzmine.parameters.parametertypes.ionidentity.IonModificationParameter;
import io.github.mzmine.parameters.parametertypes.selectors.FeatureListsParameter;
import io.github.mzmine.parameters.parametertypes.tolerances.MZToleranceParameter;

public class IonNetRelationsParameters extends SimpleParameterSet {

  public static final FeatureListsParameter featureLists = new FeatureListsParameter();

  public static final MZToleranceParameter mzTol = new MZToleranceParameter();

  public static final IonModificationParameter adducts = new IonModificationParameter("Adducts",
      "List of modifications");

  public static final BooleanParameter searchCondensedMultimer = new BooleanParameter(
      "Search condensed multimer",
      "Searches for condensed structures (loss of water) with regards to possible structure modifications",
      true);
  public static final BooleanParameter searchCondensedHeteroMultimer = new BooleanParameter(
      "Search condensed hetero",
      "Searches for condensed structures (loss of water) of two different neutral modifications",
      true);

  public IonNetRelationsParameters() {
    super(
        new Parameter[]{featureLists, mzTol, searchCondensedMultimer, searchCondensedHeteroMultimer,
            adducts});
  }

}


text:
class AddOwnerIdToTriggers < ActiveRecord::Migration
  include Gitlab::Database::MigrationHelpers

  DOWNTIME = false

  def change
    add_column :ci_triggers, :owner_id, :integer
  end
end


text:
import bs4
import sys, os
import json, copy, re
import ExprParser, ExprSemantics
from cgi import escape

from tatl import IR

def run_file(f):
    return run_string(open(f).read())

def compile(s, source, out='py', warn=None, parser='html.parser'):
    """Return Python that implements the template"""
    dom = _ensure_html_root(bs4.BeautifulSoup(s, parser))
    c = Compiler(source, warn)
    c.root(dom)
    c.module.done()
    if out == 'ir':
        return c.module.view()
    assert out in ('py', 'js')
    code = c.module.code(out, IR.CodeState())
    if out == 'js':
        # detect unicode literals in JS
        assert not re.search("""u(['"]).*?\\1""", out)
    return code

def _ensure_html_root(dom):
    """Return a DOM that is guaranteed to have a root-level <html> tag"""
    nontag = 0; tags = []; comments = []
    for c in dom.contents:
        if type(c) is bs4.NavigableString:
            if c.strip():
                nontag = True
            tags.append(c)
        elif type(c) is bs4.Tag:
            tags.append(c)
        elif type(c) is bs4.Comment:
            comments.append(c)
        else:
            print "Extra stuff at front", c
    if nontag or len(tags) != 1 or tags[0].name != 'html':
        new_root_tag = bs4.Tag(name='html')
        new_root_tag.contents = tags
        dom.contents = comments + [new_root_tag]
    return dom

def main():
    args = sys.argv[1:]

    opts = {
        t: '-'+t in args and not args.remove('-'+t)
        for t in ('py', 'js')
    }
    if not (opts['py'] or opts['js']):
        opts['py'] = opts['js'] = True

    for inp in args:
        if inp == '-':
            html = sys.stdin.read()
        elif not inp.endswith(('.html', '.tatl')):
            print "Expected .html or .tatl file:", inp
            continue
        else:
            with open(inp) as f:
                html = f.read()
            base = inp[:-4]

        for target in 'py', 'js':
            if opts[target]:
                try:
                    code = compile(html, inp, target)
                except:
                    import traceback, pdb
                    traceback.print_exc()
                    pdb.post_mortem()
                if inp == '-':
                    sys.stdout.write(code)
                else:
                    with open(base + target, 'w') as f:
                        f.write(code)

class Compiler:
    def __init__(self, source, warn=None):
        modname = os.path.splitext(os.path.basename(source))[0]
        self.module = IR.Module(source, modname, IR.Modformat())
        self.parser = ExprParser.ExprParser(
            parseinfo=True,
            semantics=ExprSemantics.ExprSemantics()
        )
        self.tags = []
        self.lastfn = []
        self.fn = None
        if warn:
            self.warn = warn

    def root(self, dom):
        self.firsttag = 1
        self._children(self._Tagstate('[root]', None, None), dom)

    def startdef(self, funcdef):
        self.lastfn.append(self.fn)
        self.fn = self.module.startdef(funcdef)

    def enddef(self):
        self.fn = self.lastfn.pop()

    def tag(self, tag):
        if tag.name == 'else':
            return self._else(tag)

        ts = self._Tagstate(tag.name, tag.get('id'), self.fn and self.fn.block())
        if tag.name in ('script', 'style'):
            # just output it
            ts.EmitQText(unicode(tag))
            return
        self.tags.append(ts)
        self._process_attrs(tag.attrs, ts)
        self.firsttag = 0
        self._children(ts, tag)
        self._finalize(ts)
        self.tags.pop()

    def _default(self, attr, ts, v):
        if v: return v
        method = getattr(self, '_default_'+attr, lambda ts: v)
        return method(ts)

    def _default_for(self, ts):
        return '.'

    def _default_def(self, ts):
        return ts.name+'(*)'

    def _default_param(self, ts):
        return 'inner' if ts.name == 'do' else ts.name

    def _default_set(self, ts):
        return 'inner' if ts.name == 'do' else ts.name + '|contents'

    def _check_attrs(self, attrs, ts):
        if self.firsttag:
            attrs.setdefault('def', "html(*)")
            for attr in 'if', 'for':
                if attr in attrs:
                    self.warn("Attr not allowed on root tag: "+attr)
                    del attrs[attr]

    _attrs = 'def', 'param', 'set', 'use', 'for', 'if', 'process'
    def _process_attrs(self, attrs, ts):
        attrs = attrs.copy()
        self._check_attrs(attrs, ts)
        for attr in self._attrs:
            if attr not in attrs: continue
            v = self._default(attr, ts, attrs.pop(attr))
            if attr == 'if' and not v:
                    self._process_elide(ts, '')
            elif attr == 'process':
                if v in ['raw']:
                    ts.process = v
                else:
                    # ignored silently
                    raise SyntaxError("Invalid value for process= attribute (%r)" % v)
            else:
                    try:
                        result = self.parser.parse(v, rule_name=attr+'Attr')
                    except:
                        raise SyntaxError("Syntax error on <%s %s='%s'>" % (ts.name, attr, v))
                    getattr(self, '_process_'+attr)(ts, result)

        if ts.emit_tag:
            ts.EmitQText('<'+ts.name)
            for attr, val in attrs.items():
                self._emit_attr(ts.for_attr(attr), attr, val)
            ts.EmitQText('>')
        else:
            if attrs:
                self.warn("Leftover attrs on <do>")

    _boolable = re.compile('\s*\{[^{].*\}\s*$').match
    def _emit_attr(self, ts, attr, val):
        #import pdb
        #pdb.set_trace()
        # bool attributes have speical handling when the entire attribute is
        # a substitution.
        if isinstance(val, list):
            val = ' '.join(val)
        if ts.bool_attr:
            #print 'bool:', ts.name, attr, val
            if not val:
                ts.EmitQText(' '+attr)
                return
            elif self._boolable(val):
                Top = self.parser.parse(val, rule_name='top')
                if Top.boolable():
                    ts.BoolAttr(attr, Top)
                    return
        ts.EmitQText(' '+attr+'="')
        self.parse_text(ts, val)
        ts.EmitQText('"')

    class _Tagstate:
        ret = None
        if_pending = 0
        elide_pending = 0
        end_if = False
        bool_attr = False
        process = "html"
        def __init__(self, name, id, block):
            self.emit_tag = name != 'do'
            self.name = name
            self.id = id
            self.block = block
        def __getattr__(self, name):
            if name[:1] == '_': raise AttributeError
            cls = getattr(IR, name)
            fn = lambda *args: cls(*args).addto(self.block)
            setattr(self, name, fn)
            return fn
        def copy(self, **kw):
            new = copy.copy(self)
            new.__dict__.update(kw)
            return new
        def for_attr(self, attr):
            # If the attribute needs special handling,
            # return a new Tagstate. Otherwise return self
            if attr in ('selected', 'checked', 'disabled'):
                return self.copy(bool_attr=True)
            return self
    def _finalize(self, ts):
        if ts.emit_tag:
            ts.EmitQText('</%s>' % ts.name)
        self._finish_elide(ts)
        ts.block.done()
        if ts.ret:
            self.enddef()

    def _finish_elide(self, ts):
        if ts.elide_pending:
            ts.ElideEnd()
            ts.elide_pending = False

    def _process_elide(self, ts, result):
        ts.ElideStart()
        ts.elide_pending = True

    def _process_def(self, ts, funcdef):
        self.startdef(funcdef)
        ts.block = self.fn.block()
        ts.ret = True

    def _process_set(self, ts, obj):
        obj.addto(ts.block)

    def _process_if(self, ts, test):
        test.addto(ts.block)
        ts.if_pending = 1

    def _process_param(self, ts, v):
        self.fn.add_params(v)
        if len(v) == 1:
            ts.Asgn('dot', v[0].lvar)

    def _process_for(self, ts, obj):
        obj.addto(ts.block)

    def _process_use(self, ts, ast):
        #import pdb
        #pdb.set_trace()
        ast.addto(ts.block)

    def _else(self, tag):

        tags = []
        for ts in self.tags[::-1]:
            if ts.emit_tag:
                tags.append(ts.name)
            if ts.if_pending or ts.elide_pending:
                break
        else:
            self.warn("No if found for <else>")
            return self._children(ts, tag)
        if ts.end_if:
            self.warn("<else> after <else> ignored")
            return self._children(ts, tag)

        if tags:
            self.warn("<else> synthesized tags: "+str(tags))

        endtags = ''.join(['</%s>' % t for t in tags])
        starttags = ''.join(['<%s>' % t for t in tags])

        ts.EmitQText(endtags)
        self._finish_elide(ts)

        attrs = tag.attrs
        if 'if' in attrs:
            test = self.parser.parse(attrs.pop('if'), rule_name='test')
            ts.Elif(test)
        else:
            ts.Else()
            ts.end_if = True

        if attrs:
            self.warn("Extraneous attributes on <else/>")

        ts.EmitQText(starttags)

        self._children(ts, tag)

    def _children(self, ts, tag):
        for c in tag.children:
            typ = c.__class__
            if ts.process == 'raw':
                ts.EmitQText(unicode(c))
            elif typ is bs4.Tag:
                self.tag(c)
            elif typ is bs4.NavigableString:
                if ts.block is None:
                    if c.strip():
                        self.warn("Top-level content ignored: %r" % c.strip())
                else:
                    self.parse_text(ts, c)
            elif typ is bs4.Comment and c[:1] == '{':
                self._front_matter(ts, c)
            elif typ is bs4.Comment and c[:1] != '[':
                # comments ignored
                pass
            elif self.fn is None:
                # before first tag, we can't emit
                self.warn("Can't emit %s: %s" % (c.__class__.__name__, c))
            else:
                self.emit_other(ts, c)

    def _front_matter(self, ts, c):
        # update current fn/module... ideas for keys:
        # package, doc, param docs / required, sample data
        try:
            d = json.loads(c)
        except:
            self.warn("Front matter cannot be loaded in <%s>" % ts.name)
            d = None

    def emit_other(self, ts, c):
        # Emit other kind of node (CData, PI, )
        print "emit_other!", c
        text = bs4.BeautifulSoup('')
        text.contents.append(c)
        text = unicode(text)
        ts.EmitQText(text)

    def parse_text(self, ts, text):
        result = []
        ix = text.find('{')
        emit = lambda t: ts.EmitQText(escape(t.replace('}}', '}')))
        while ix > -1 and ix < len(text) - 2:
            if text[ix+1] == '{':
                emit(text[:ix+1])
                text = text[ix+2:]
                ix = text.find('{')
                continue
            if ix > 0:
                emit(text[:ix])
                text = text[ix:]
            Top = self.parser.parse(text, rule_name='top')
            Top.addto(ts.block)
            text = Top.rest
            ix = text.find('{')
        emit(text)

    def warn(self, s):
        #TODO pass line number
        print>>sys.stderr, "*Warning:", s


text:
///<reference path='../references.ts' />

module Shumway.AVM1.Lib {
  import flash = Shumway.AVMX.AS.flash;

  export class AVM1Color extends AVM1Object {
    static createAVM1Class(context: AVM1Context): AVM1Object {
      return wrapAVM1NativeClass(context, true, AVM1Color,
        [],
        ['getRGB', 'getTransform', 'setRGB', 'setTransform'],
        null, AVM1Color.prototype.avm1Constructor);
    }

    private _target: IAVM1SymbolBase;

    public avm1Constructor(target_mc) {
      this._target = AVM1Utils.resolveTarget(this.context, target_mc);
    }

    public getRGB(): number {
      var transform = AVM1Color.prototype.getTransform.call(this);
      return transform.alGet('rgb');
    }

    public getTransform(): AVM1ColorTransform {
      return AVM1ColorTransform.fromAS3ColorTransform(this.context,
        this._target.as3Object.transform.colorTransform);
    }

    public setRGB(offset): void {
      var transform = AVM1Color.prototype.getTransform.call(this);
      transform.alPut('rgb', offset);
      AVM1Color.prototype.setTransform.call(this, transform);
    }

    public setTransform(transform: AVM1Object): void {
      this._target.as3Object.transform.colorTransform = toAS3ColorTransform(transform);
    }
  }
}