text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using Microsoft.AspNet.WebHooks.Payloads;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Xunit;

namespace Microsoft.AspNet.WebHooks
{
    public class WorkItemCommentedOnPayloadTests
    {
        [Fact]
        public void WorkItemCommentedOnPayload_Roundtrips()
        {
            // Arrange
            JObject data = EmbeddedResource.ReadAsJObject("Microsoft.AspNet.WebHooks.Messages.workitem.commented.json");
            var expected = new WorkItemCommentedOnPayload
            {
                SubscriptionId = "00000000-0000-0000-0000-000000000000",
                NotificationId = 4,
                Id = "fb2617ed-60df-4518-81fa-749faa6c5cd6",
                EventType = "workitem.commented",
                PublisherId = "tfs",
                Message = new PayloadMessage
                {
                    Text = "Bug #5 (Some great new idea!) commented on by Jamal Hartnett.\r\n(http://good-company.some.ssl.host/web/wi.aspx?id=74e918bf-3376-436d-bd20-8e8c1287f465&id=5)",
                    Html = "Bug #5 (Some great new idea!) commented on by Jamal Hartnett.",
                    Markdown = "[Bug #5](http://good-company.some.ssl.host/web/wi.aspx?id=74e918bf-3376-436d-bd20-8e8c1287f465&id=5) (Some great new idea!) commented on by Jamal Hartnett."
                },
                DetailedMessage = new PayloadMessage
                {
                    Text = "Bug #5 (Some great new idea!) commented on by Jamal Hartnett.\r\n(http://good-company.some.ssl.host/web/wi.aspx?id=74e918bf-3376-436d-bd20-8e8c1287f465&id=5)\r\nThis is a great new idea",
                    Html = "Bug #5 (Some great new idea!) commented on by Jamal Hartnett.
This is a great new idea",
                    Markdown = "[Bug #5](http://good-company.some.ssl.host/web/wi.aspx?id=74e918bf-3376-436d-bd20-8e8c1287f465&id=5) (Some great new idea!) commented on by Jamal Hartnett.\r\nThis is a great new idea"
                },
                Resource = new WorkItemCommentedOnResource
                {
                    Id = 5,
                    RevisionNumber = 4,
                    Fields = new WorkItemFields
                    {
                        SystemAreaPath = "GoodCompanyCloud",
                        SystemTeamProject = "GoodCompanyCloud",
                        SystemIterationPath = "GoodCompanyCloud\\Release 1\\Sprint 1",
                        SystemWorkItemType = "Bug",
                        SystemState = "New",
                        SystemReason = "New defect reported",
                        SystemCreatedDate = "2014-07-15T17:42:44.663Z".ToDateTime(),
                        SystemCreatedBy = "Jamal Hartnett",
                        SystemChangedDate = "2014-07-15T17:42:44.663Z".ToDateTime(),
                        SystemChangedBy = "Jamal Hartnett",
                        SystemTitle = "Some great new idea!",
                        MicrosoftCommonSeverity = "3 - Medium",
                        KanbanColumn = "New",
                        SystemHistory = "This is a great new idea"
                    },
                    Links = new WorkItemLinks
                    {
                        Self = new WorkItemLink { Href = "http://good-company.some.ssl.host/DefaultCollection/_apis/wit/workItems/5" },
                        WorkItemUpdates = new WorkItemLink { Href = "http://good-company.some.ssl.host/DefaultCollection/_apis/wit/workItems/5/updates" },
                        WorkItemRevisions = new WorkItemLink { Href = "http://good-company.some.ssl.host/DefaultCollection/_apis/wit/workItems/5/revisions" },
                        WorkItemType = new WorkItemLink { Href = "http://good-company.some.ssl.host/DefaultCollection/_apis/wit/ea830882-2a3c-4095-a53f-972f9a376f6e/workItemTypes/Bug" },
                        Fields = new WorkItemLink { Href = "http://good-company.some.ssl.host/DefaultCollection/_apis/wit/fields" }
                    },
                    Url = new Uri("http://good-company.some.ssl.host/DefaultCollection/_apis/wit/workItems/5")
                },
                ResourceVersion = "1.0",
                ResourceContainers = new PayloadResourceContainers
                {
                    Collection = new PayloadResourceContainer { Id = "c12d0eb8-e382-443b-9f9c-c52cba5014c2" },
                    Account = new PayloadResourceContainer { Id = "f844ec47-a9db-4511-8281-8b63f4eaf94e" },
                    Project = new PayloadResourceContainer { Id = "be9b3917-87e6-42a4-a549-2bc06a7a878f" }
                },
                CreatedDate = "2016-05-02T19:15:37.4638247Z".ToDateTime()
            };

            // Act
            var actual = data.ToObject<WorkItemCommentedOnPayload>();

            // Assert
            string expectedJson = JsonConvert.SerializeObject(expected);
            string actualJson = JsonConvert.SerializeObject(actual);
            Assert.Equal(expectedJson, actualJson);
        }
    }
}


text:
function Controller() {
    require("alloy/controllers/BaseController").apply(this, Array.prototype.slice.call(arguments));
    this.__controllerPath = "location";
    arguments[0] ? arguments[0]["__parentSymbol"] : null;
    arguments[0] ? arguments[0]["$model"] : null;
    arguments[0] ? arguments[0]["__itemTemplate"] : null;
    var $ = this;
    var exports = {};
    $.__views.location = Ti.UI.createWindow({
        id: "location"
    });
    $.__views.location && $.addTopLevelView($.__views.location);
    $.__views.header = Ti.UI.createView({
        id: "header"
    });
    $.__views.location.add($.__views.header);
    $.__views.title = Ti.UI.createLabel({
        text: "Locations",
        id: "title"
    });
    $.__views.header.add($.__views.title);
    exports.destroy = function() {};
    _.extend($, $.__views);
    arguments[0] || {};
    _.extend($, exports);
}

var Alloy = require("alloy"), Backbone = Alloy.Backbone, _ = Alloy._;

module.exports = Controller;

redpajama_set_name: RedPajamaGithub


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

/**
 * Namespace for test related things.
 */
var test = test || {};

/**
 * Namespace for test utility functions.
 *
 * Public functions in the test.util.sync and the test.util.async namespaces are
 * published to test cases and can be called by using callRemoteTestUtil. The
 * arguments are serialized as JSON internally. If application ID is passed to
 * callRemoteTestUtil, the content window of the application is added as the
 * first argument. The functions in the test.util.async namespace are passed the
 * callback function as the last argument.
 */
test.util = {};

/**
 * Namespace for synchronous utility functions.
 */
test.util.sync = {};

/**
 * Namespace for asynchronous utility functions.
 */
test.util.async = {};

/**
 * Extension ID of the testing extension.
 * @type {string}
 * @const
 */
test.util.TESTING_EXTENSION_ID = 'oobinhbdbiehknkpbpejbbpdbkdjmoco';

/**
 * Opens the main Files.app's window and waits until it is ready.
 *
 * @param {Object} appState App state.
 * @param {function(string)} callback Completion callback with the new window's
 *     App ID.
 */
test.util.async.openMainWindow = function(appState, callback) {
  launchFileManager(appState,
                    undefined,  // opt_type
                    undefined,  // opt_id
                    callback);
};

/**
 * Obtains window information.
 *
 * @return {Object.<string, {innerWidth:number, innerHeight:number}>} Map window
 *     ID and window information.
 */
test.util.sync.getWindows = function() {
  var windows = {};
  for (var id in background.appWindows) {
    var windowWrapper = background.appWindows[id];
    windows[id] = {
      outerWidth: windowWrapper.contentWindow.outerWidth,
      outerHeight: windowWrapper.contentWindow.outerHeight
    };
  }
  for (var id in background.dialogs) {
    windows[id] = {
      outerWidth: background.dialogs[id].outerWidth,
      outerHeight: background.dialogs[id].outerHeight
    };
  }
  return windows;
};

/**
 * Closes the specified window.
 *
 * @param {string} appId AppId of window to be closed.
 * @return {boolean} Result: True if success, false otherwise.
 */
test.util.sync.closeWindow = function(appId) {
  if (appId in background.appWindows &&
      background.appWindows[appId].contentWindow) {
    background.appWindows[appId].close();
    return true;
  }
  return false;
};

/**
 * Gets a document in the Files.app's window, including iframes.
 *
 * @param {Window} contentWindow Window to be used.
 * @param {string=} opt_iframeQuery Query for the iframe.
 * @return {Document=} Returns the found document or undefined if not found.
 * @private
 */
test.util.sync.getDocument_ = function(contentWindow, opt_iframeQuery) {
  if (opt_iframeQuery) {
    var iframe = contentWindow.document.querySelector(opt_iframeQuery);
    return iframe && iframe.contentWindow && iframe.contentWindow.document;
  }

  return contentWindow.document;
};

/**
 * Gets total Javascript error count from background page and each app window.
 * @return {number} Error count.
 */
test.util.sync.getErrorCount = function() {
  var totalCount = JSErrorCount;
  for (var appId in background.appWindows) {
    var contentWindow = background.appWindows[appId].contentWindow;
    if (contentWindow.JSErrorCount)
      totalCount += contentWindow.JSErrorCount;
  }
  return totalCount;
};

/**
 * Resizes the window to the specified dimensions.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {number} width Window width.
 * @param {number} height Window height.
 * @return {boolean} True for success.
 */
test.util.sync.resizeWindow = function(contentWindow, width, height) {
  background.appWindows[contentWindow.appID].resizeTo(width, height);
  return true;
};

/**
 * Returns an array with the files currently selected in the file manager.
 * TODO(hirono): Integrate the method into getFileList method.
 *
 * @param {Window} contentWindow Window to be tested.
 * @return {Array.<string>} Array of selected files.
 */
test.util.sync.getSelectedFiles = function(contentWindow) {
  var table = contentWindow.document.querySelector('#detail-table');
  var rows = table.querySelectorAll('li');
  var selected = [];
  for (var i = 0; i < rows.length; ++i) {
    if (rows[i].hasAttribute('selected')) {
      selected.push(
          rows[i].querySelector('.filename-label').textContent);
    }
  }
  return selected;
};

/**
 * Returns an array with the files on the file manager's file list.
 *
 * @param {Window} contentWindow Window to be tested.
 * @return {Array.<Array.<string>>} Array of rows.
 */
test.util.sync.getFileList = function(contentWindow) {
  var table = contentWindow.document.querySelector('#detail-table');
  var rows = table.querySelectorAll('li');
  var fileList = [];
  for (var j = 0; j < rows.length; ++j) {
    var row = rows[j];
    fileList.push([
      row.querySelector('.filename-label').textContent,
      row.querySelector('.size').textContent,
      row.querySelector('.type').textContent,
      row.querySelector('.date').textContent
    ]);
  }
  return fileList;
};

/**
 * Queries all elements.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {?string} iframeQuery Iframe selector or null if no iframe.
 * @param {Array.<string>=} opt_styleNames List of CSS property name to be
 *     obtained.
 * @return {Array.<{attributes:Object.<string, string>, text:string,
 *                  styles:Object.<string, string>, hidden:boolean}>} Element
 *     information that contains contentText, attribute names and
 *     values, hidden attribute, and style names and values.
 */
test.util.sync.queryAllElements = function(
    contentWindow, targetQuery, iframeQuery, opt_styleNames) {
  var doc = test.util.sync.getDocument_(contentWindow, iframeQuery);
  if (!doc)
    return [];
  // The return value of querySelectorAll is not an array.
  return Array.prototype.map.call(
      doc.querySelectorAll(targetQuery),
      function(element) {
        var attributes = {};
        for (var i = 0; i < element.attributes.length; i++) {
          attributes[element.attributes[i].nodeName] =
              element.attributes[i].nodeValue;
        }
        var styles = {};
        var styleNames = opt_styleNames || [];
        var computedStyles = contentWindow.getComputedStyle(element);
        for (var i = 0; i < styleNames.length; i++) {
          styles[styleNames[i]] = computedStyles[styleNames[i]];
        }
        var text = element.textContent;
        return {
          attributes: attributes,
          text: text,
          styles: styles,
          // The hidden attribute is not in the element.attributes even if
          // element.hasAttribute('hidden') is true.
          hidden: !!element.hidden
        };
      });
};

/**
 * Assigns the text to the input element.
 * @param {Window} contentWindow Window to be tested.
 * @param {string} query Query for the input element.
 * @param {string} text Text to be assigned.
 */
test.util.sync.inputText = function(contentWindow, query, text) {
  var input = contentWindow.document.querySelector(query);
  input.value = text;
};

/**
 * Fakes pressing the down arrow until the given |filename| is selected.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} filename Name of the file to be selected.
 * @return {boolean} True if file got selected, false otherwise.
 */
test.util.sync.selectFile = function(contentWindow, filename) {
  var rows = contentWindow.document.querySelectorAll('#detail-table li');
  test.util.sync.fakeKeyDown(contentWindow, '#file-list', 'Home', false);
  for (var index = 0; index < rows.length; ++index) {
    var selection = test.util.sync.getSelectedFiles(contentWindow);
    if (selection.length === 1 && selection[0] === filename)
      return true;
    test.util.sync.fakeKeyDown(contentWindow, '#file-list', 'Down', false);
  }
  console.error('Failed to select file "' + filename + '"');
  return false;
};

/**
 * Open the file by selectFile and fakeMouseDoubleClick.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} filename Name of the file to be opened.
 * @return {boolean} True if file got selected and a double click message is
 *     sent, false otherwise.
 */
test.util.sync.openFile = function(contentWindow, filename) {
  var query = '#file-list li.table-row[selected] .filename-label span';
  return test.util.sync.selectFile(contentWindow, filename) &&
         test.util.sync.fakeMouseDoubleClick(contentWindow, query);
};

/**
 * Selects a volume specified by its icon name
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} iconName Name of the volume icon.
 * @param {function(boolean)} callback Callback function to notify the caller
 *     whether the target is found and mousedown and click events are sent.
 */
test.util.async.selectVolume = function(contentWindow, iconName, callback) {
  var query = '[volume-type-icon=' + iconName + ']';
  var driveQuery = '[volume-type-icon=drive]';
  var isDriveSubVolume = iconName == 'drive_recent' ||
                         iconName == 'drive_shared_with_me' ||
                         iconName == 'drive_offline';
  var preSelection = false;
  var steps = {
    checkQuery: function() {
      if (contentWindow.document.querySelector(query)) {
        steps.sendEvents();
        return;
      }
      // If the target volume is sub-volume of drive, we must click 'drive'
      // before clicking the sub-item.
      if (!preSelection) {
        if (!isDriveSubVolume) {
          callback(false);
          return;
        }
        if (!(test.util.sync.fakeMouseDown(contentWindow, driveQuery) &&
              test.util.sync.fakeMouseClick(contentWindow, driveQuery))) {
          callback(false);
          return;
        }
        preSelection = true;
      }
      setTimeout(steps.checkQuery, 50);
    },
    sendEvents: function() {
      // To change the selected volume, we have to send both events 'mousedown'
      // and 'click' to the navigation list.
      callback(test.util.sync.fakeMouseDown(contentWindow, query) &&
               test.util.sync.fakeMouseClick(contentWindow, query));
    }
  };
  steps.checkQuery();
};

/**
 * Executes Javascript code on a webview and returns the result.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} webViewQuery Selector for the web view.
 * @param {string} code Javascript code to be executed within the web view.
 * @param {function(*)} callback Callback function with results returned by the
 *     script.
 */
test.util.async.executeScriptInWebView = function(
    contentWindow, webViewQuery, code, callback) {
  var webView = contentWindow.document.querySelector(webViewQuery);
  webView.executeScript({code: code}, callback);
};

/**
 * Sends an event to the element specified by |targetQuery|.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {Event} event Event to be sent.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.sendEvent = function(
    contentWindow, targetQuery, event, opt_iframeQuery) {
  var doc = test.util.sync.getDocument_(contentWindow, opt_iframeQuery);
  if (doc) {
    var target = doc.querySelector(targetQuery);
    if (target) {
      target.dispatchEvent(event);
      return true;
    }
  }
  console.error('Target element for ' + targetQuery + ' not found.');
  return false;
};

/**
 * Sends an fake event having the specified type to the target query.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string} eventType Type of event.
 * @param {Object=} opt_additionalProperties Object contaning additional
 *     properties.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.fakeEvent = function(contentWindow,
                                    targetQuery,
                                    eventType,
                                    opt_additionalProperties) {
  var event = new Event(eventType, opt_additionalProperties || {});
  if (opt_additionalProperties) {
    for (var name in opt_additionalProperties) {
      event[name] = opt_additionalProperties[name];
    }
  }
  return test.util.sync.sendEvent(contentWindow, targetQuery, event);
};

/**
 * Sends a fake key event to the element specified by |targetQuery| with the
 * given |keyIdentifier| and optional |ctrl| modifier to the file manager.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string} keyIdentifier Identifier of the emulated key.
 * @param {boolean} ctrl Whether CTRL should be pressed, or not.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.fakeKeyDown = function(
    contentWindow, targetQuery, keyIdentifier, ctrl, opt_iframeQuery) {
  var event = new KeyboardEvent(
      'keydown',
      { bubbles: true, keyIdentifier: keyIdentifier, ctrlKey: ctrl });
  return test.util.sync.sendEvent(
      contentWindow, targetQuery, event, opt_iframeQuery);
};

/**
 * Simulates a fake mouse click (left button, single click) on the element
 * specified by |targetQuery|. If the element has the click method, just calls
 * it. Otherwise, this sends 'mouseover', 'mousedown', 'mouseup' and 'click'
 * events in turns.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the all events are sent to the target, false
 *     otherwise.
 */
test.util.sync.fakeMouseClick = function(
    contentWindow, targetQuery, opt_iframeQuery) {
  var mouseOverEvent = new MouseEvent('mouseover', {bubbles: true, detail: 1});
  var resultMouseOver = test.util.sync.sendEvent(
      contentWindow, targetQuery, mouseOverEvent, opt_iframeQuery);
  var mouseDownEvent = new MouseEvent('mousedown', {bubbles: true, detail: 1});
  var resultMouseDown = test.util.sync.sendEvent(
      contentWindow, targetQuery, mouseDownEvent, opt_iframeQuery);
  var mouseUpEvent = new MouseEvent('mouseup', {bubbles: true, detail: 1});
  var resultMouseUp = test.util.sync.sendEvent(
      contentWindow, targetQuery, mouseUpEvent, opt_iframeQuery);
  var clickEvent = new MouseEvent('click', {bubbles: true, detail: 1});
  var resultClick = test.util.sync.sendEvent(
      contentWindow, targetQuery, clickEvent, opt_iframeQuery);
  return resultMouseOver && resultMouseDown && resultMouseUp && resultClick;
};

/**
 * Simulates a fake mouse click (right button, single click) on the element
 * specified by |targetQuery|.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false
 *     otherwise.
 */
test.util.sync.fakeMouseRightClick = function(
    contentWindow, targetQuery, opt_iframeQuery) {
  var contextMenuEvent = new MouseEvent('contextmenu', {bubbles: true});
  var result = test.util.sync.sendEvent(
      contentWindow, targetQuery, contextMenuEvent, opt_iframeQuery);
  return result;
};

/**
 * Simulates a fake double click event (left button) to the element specified by
 * |targetQuery|.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.fakeMouseDoubleClick = function(
    contentWindow, targetQuery, opt_iframeQuery) {
  // Double click is always preceded with a single click.
  if (!test.util.sync.fakeMouseClick(
      contentWindow, targetQuery, opt_iframeQuery)) {
    return false;
  }

  // Send the second click event, but with detail equal to 2 (number of clicks)
  // in a row.
  var event = new MouseEvent('click', { bubbles: true, detail: 2 });
  if (!test.util.sync.sendEvent(
      contentWindow, targetQuery, event, opt_iframeQuery)) {
    return false;
  }

  // Send the double click event.
  var event = new MouseEvent('dblclick', { bubbles: true });
  if (!test.util.sync.sendEvent(
      contentWindow, targetQuery, event, opt_iframeQuery)) {
    return false;
  }

  return true;
};

/**
 * Sends a fake mouse down event to the element specified by |targetQuery|.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.fakeMouseDown = function(
    contentWindow, targetQuery, opt_iframeQuery) {
  var event = new MouseEvent('mousedown', { bubbles: true });
  return test.util.sync.sendEvent(
      contentWindow, targetQuery, event, opt_iframeQuery);
};

/**
 * Sends a fake mouse up event to the element specified by |targetQuery|.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} targetQuery Query to specify the element.
 * @param {string=} opt_iframeQuery Optional iframe selector.
 * @return {boolean} True if the event is sent to the target, false otherwise.
 */
test.util.sync.fakeMouseUp = function(
    contentWindow, targetQuery, opt_iframeQuery) {
  var event = new MouseEvent('mouseup', { bubbles: true });
  return test.util.sync.sendEvent(
      contentWindow, targetQuery, event, opt_iframeQuery);
};

/**
 * Selects |filename| and fakes pressing Ctrl+C, Ctrl+V (copy, paste).
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} filename Name of the file to be copied.
 * @return {boolean} True if copying got simulated successfully. It does not
 *     say if the file got copied, or not.
 */
test.util.sync.copyFile = function(contentWindow, filename) {
  if (!test.util.sync.selectFile(contentWindow, filename))
    return false;
  // Ctrl+C and Ctrl+V
  test.util.sync.fakeKeyDown(contentWindow, '#file-list', 'U+0043', true);
  test.util.sync.fakeKeyDown(contentWindow, '#file-list', 'U+0056', true);
  return true;
};

/**
 * Selects |filename| and fakes pressing the Delete key.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} filename Name of the file to be deleted.
 * @return {boolean} True if deleting got simulated successfully. It does not
 *     say if the file got deleted, or not.
 */
test.util.sync.deleteFile = function(contentWindow, filename) {
  if (!test.util.sync.selectFile(contentWindow, filename))
    return false;
  // Delete
  test.util.sync.fakeKeyDown(contentWindow, '#file-list', 'U+007F', false);
  return true;
};

/**
 * Execute a command on the document in the specified window.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} command Command name.
 * @return {boolean} True if the command is executed successfully.
 */
test.util.sync.execCommand = function(contentWindow, command) {
  return contentWindow.document.execCommand(command);
};

/**
 * Override the installWebstoreItem method in private api for test.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} expectedItemId Item ID to be called this method with.
 * @param {?string} intendedError Error message to be returned when the item id
 *     matches. 'null' represents no error.
 * @return {boolean} Always return true.
 */
test.util.sync.overrideInstallWebstoreItemApi =
    function(contentWindow, expectedItemId, intendedError) {
  var setLastError = function(message) {
    contentWindow.chrome.runtime.lastError =
        message ? {message: message} : null;
  };

  var installWebstoreItem = function(itemId, silentInstallation, callback) {
    setTimeout(function() {
      if (itemId !== expectedItemId) {
        setLastError('Invalid Chrome Web Store item ID');
        callback();
        return;
      }

      setLastError(intendedError);
      callback();
    });
  };

  test.util.executedTasks_ = [];
  contentWindow.chrome.fileBrowserPrivate.installWebstoreItem =
      installWebstoreItem;
  return true;
};

/**
 * Override the task-related methods in private api for test.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {Array.<Object>} taskList List of tasks to be returned in
 *     fileBrowserPrivate.getFileTasks().
 * @return {boolean} Always return true.
 */
test.util.sync.overrideTasks = function(contentWindow, taskList) {
  var getFileTasks = function(urls, onTasks) {
    // Call onTask asynchronously (same with original getFileTasks).
    setTimeout(function() {
      onTasks(taskList);
    });
  };

  var executeTask = function(taskId, url) {
    test.util.executedTasks_.push(taskId);
  };

  var setDefaultTask = function(taskId) {
    for (var i = 0; i < taskList.length; i++) {
      taskList[i].isDefault = taskList[i].taskId === taskId;
    }
  };

  test.util.executedTasks_ = [];
  contentWindow.chrome.fileBrowserPrivate.getFileTasks = getFileTasks;
  contentWindow.chrome.fileBrowserPrivate.executeTask = executeTask;
  contentWindow.chrome.fileBrowserPrivate.setDefaultTask = setDefaultTask;
  return true;
};

/**
 * Obtains the list of executed tasks.
 * @param {Window} contentWindow Window to be tested.
 * @return {Array.<string>} List of executed task ID.
 */
test.util.sync.getExecutedTasks = function(contentWindow) {
  if (!test.util.executedTasks_) {
    console.error('Please call overrideTasks() first.');
    return null;
  }
  return test.util.executedTasks_;
};

/**
 * Invoke chrome.fileBrowserPrivate.visitDesktop(profileId) to cause window
 * teleportation.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} profileId Destination profile's ID.
 * @return {boolean} Always return true.
 */
test.util.sync.visitDesktop = function(contentWindow, profileId) {
  contentWindow.chrome.fileBrowserPrivate.visitDesktop(profileId);
  return true;
};

/**
 * Runs the 'Move to profileId' menu.
 *
 * @param {Window} contentWindow Window to be tested.
 * @param {string} profileId Destination profile's ID.
 * @return {boolean} True if the menu is found and run.
 */
test.util.sync.runVisitDesktopMenu = function(contentWindow, profileId) {
  var list = contentWindow.document.querySelectorAll('.visit-desktop');
  for (var i = 0; i < list.length; ++i) {
    if (list[i].label.indexOf(profileId) != -1) {
      var activateEvent = contentWindow.document.createEvent('Event');
      activateEvent.initEvent('activate');
      list[i].dispatchEvent(activateEvent);
      return true;
    }
  }
  return false;
};

/**
 * Registers message listener, which runs test utility functions.
 */
test.util.registerRemoteTestUtils = function() {
  // Register the message listener.
  var onMessage = chrome.runtime ? chrome.runtime.onMessageExternal :
      chrome.extension.onMessageExternal;
  // Return true for asynchronous functions and false for synchronous.
  onMessage.addListener(function(request, sender, sendResponse) {
    // Check the sender.
    if (sender.id != test.util.TESTING_EXTENSION_ID) {
      console.error('The testing extension must be white-listed.');
      return false;
    }
    // Set a global flag that we are in tests, so other components are aware
    // of it.
    window.IN_TEST = true;
    // Check the function name.
    if (!request.func || request.func[request.func.length - 1] == '_') {
      request.func = '';
    }
    // Prepare arguments.
    var args = request.args.slice();  // shallow copy
    if (request.appId) {
      if (background.appWindows[request.appId]) {
        args.unshift(background.appWindows[request.appId].contentWindow);
      } else if (background.dialogs[request.appId]) {
        args.unshift(background.dialogs[request.appId]);
      } else {
        console.error('Specified window not found: ' + request.appId);
        return false;
      }
    }
    // Call the test utility function and respond the result.
    if (test.util.async[request.func]) {
      args[test.util.async[request.func].length - 1] = function() {
        console.debug('Received the result of ' + request.func);
        sendResponse.apply(null, arguments);
      };
      console.debug('Waiting for the result of ' + request.func);
      test.util.async[request.func].apply(null, args);
      return true;
    } else if (test.util.sync[request.func]) {
      sendResponse(test.util.sync[request.func].apply(null, args));
      return false;
    } else {
      console.error('Invalid function name.');
      return false;
    }
  });
};

// Register the test utils.
test.util.registerRemoteTestUtils();


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<TITLE>
org.springframework.security.adapters.resin (Spring Security 2.0.4 API)
</TITLE>

<META NAME="keywords" CONTENT="org.springframework.security.adapters.resin package">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

org.springframework.security.adapters.resin

Classes

ResinAcegiAuthenticator


text:
SQLGitHub — Managing GitHub organization made easier

## Introduction

SQLGitHub features a SQL-like syntax that allows you to:
**Query information about an organization as a whole.**

You may also think of it as a better, enhanced frontend layer built on top of GitHub's RESTful API.

- [Presentation](assets/slides.pdf)
- [Poster](assets/poster.pdf)

![ScreenshotIntro](https://i.imgur.com/Ii355Ds.png)

## Installation

1. Install prerequisites
```bash
pip install requests prompt_toolkit pygments regex
```

2. Install my patched PyGithub
```bash
git clone https://github.com/lnishan/PyGithub.git
cd PyGithub
./setup.py build
sudo ./setup.py install
```

3. Configure SQLGitHub (optional)
In root directory (same directory as `SQLGitHub.py`),
Create and edit `config.py`:
```python
token = "your token here"  # can be obtained from https://github.com/settings/tokens
output = "str"  # or "csv", "html"
```

4. Start SQLGitHub
```bash
./SQLGitHub.py
```

## Sample Usage

### → Get name and description from all the repos in [abseil](https://github.com/abseil).

```sql
select name, description from abseil.repos
```

![Screenshot1](https://i.imgur.com/OG5c2GS.png)

---

### → Get last-updated time and title of the issues closed in the past 3 days in [servo](https://github.com/servo) listed in descending order of last-updated time.

```sql
select updated_at, title from servo.issues.closed.3 order by updated_at desc
```

![Screenshot2](https://i.imgur.com/nyXdiEh.png)

---

### → Get top 10 most-starred repositories in [servo](https://github.com/servo).

```sql
select concat(concat("(", stargazers_count, ") ", name), ": ", description) from servo.repos order by stargazers_count desc, name limit 10
```

![Screenshot3](https://i.imgur.com/sl2Ztrp.png)

---

### → Get top 10 contributors in [servo](https://github.com/servo) for the past 7 days based on number of commits.

```sql
select login, count(login) from servo.commits.7 group by login order by count(login) desc, login limit 10
```

![Screenshot4](https://i.imgur.com/2ISHbPJ.png)

## SQL Language Support

### Supported Schema

```
SELECT
    select_expr [, select_expr ...]
    FROM {org_name | org_name.{repos | issues | pulls | commits}}
    [WHERE where_condition]
    [GROUP BY {col_name | expr}
      [ASC | DESC], ...]
    [HAVING where_condition]
    [ORDER BY {col_name | expr}
      [ASC | DESC], ...]
    [LIMIT row_count]
```

### Supported Fields

Most of the fields listed in [GitHub API v3](https://developer.github.com/v3/) are available for query.
For example, for `org_name.repos` queries, you can specify `id`, `name`, `full_name`, `description` ... etc. in expr's.
You may also use `select *` for the full list of fields.

### Supported Functions

**String Functions:**
"concat", "concat_ws", "find_in_set", "insert", "instr", "length", "locate", "lcase", "lower", "left", "mid", "repeat", "right", "replace", "strcmp", "substr", "substring", "ucase", "upper"

**Numeric Functions:**
"avg", "count", "max", "min", "sum", "abs", "ceil", "ceiling", "exp", "floor", "greatest", "least", "ln", "log", "pow", "power", "sign", "sqrt"

**Date & Advanced Functions:**
"curdate", "current_date", "current_time", "current_timestamp", "curtime", "localtime", "localtimestamp", "now", "bin"


text:
<?php

namespace Cit\TestBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Cit\TestBundle\Entity\City
 *
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="Cit\TestBundle\Entity\CityRepository")
 */
class City
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $frenchname
     *
     * @ORM\Column(name="frenchname", type="string", length=255)
     */
    private $frenchname;

    /**
     * @var string $englishname
     *
     * @ORM\Column(name="englishname", type="string", length=255)
     */
    private $englishname;

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

    /**
     * Set frenchname
     *
     * @param string $name
     */
    public function setNameFrench($name)
    {
        $this->frenchname = $name;
    }

    /**
     * Get frenchname
     *
     * @return string
     */
    public function getNameFrench()
    {
        return $this->frenchname;
    }

    /**
     * Set englishname
     *
     * @param string $name
     */
    public function setNameEnglish($name)
    {
        $this->englishname = $name;
    }

    /**
     * Get englishname
     *
     * @return string
     */
    public function getNameEnglish()
    {
        return $this->englishname;
    }

    public function __toString()
    {
        //$locale = $this->get('session')->getLocale();
        return $this->frenchname;
    }
}


text:
service ssh restart

# Setup password less ssh
sshpass -p screencast ssh-copy-id root@localhost

export HOSTNAME=`hostname`
sed -i "s#localhost#$HOSTNAME#g" /opt/hadoop-2.6.0/etc/hadoop/core-site.xml

# Format the NameNode data directory
hdfs namenode -format -force

# Start HDFS services
start-dfs.sh

# Wait for HDFS services to be up and running
sleep 5

# Create a tmp directory and make it accessible to everyone
hadoop fs -mkdir -p /tmp
hadoop fs -chmod -R 777 /tmp

# Run in daemon mode, don't exit
while true; do
  sleep 100;
done


text:
package org.osgi.test.cases.log.tb1;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class LogBundle1 implements BundleActivator {

	@Override
	public void start(BundleContext context) throws Exception {
	}

	@Override
	public void stop(BundleContext context) throws Exception {
	}

}


text:
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
//
using HUX.Collections;
using HUX.Interaction;
using HUX.Receivers;
using UnityEngine;

namespace HUX
{
    /// <summary>
    /// Receives button input and sets object collection display mode
    /// </summary>
    public class ObjectCollectionMode : InteractionReceiver
    {
        public Vector3 HomeOffset = Vector3.zero;
        public Vector3 PlaneOffset = Vector3.zero;
        public Vector3 SphereOffset = Vector3.zero;
        public Vector3 CylinderOffset = Vector3.zero;
        public float HomeRadius = 1f;
        public float PlaneRadius = 1f;
        public float SphereRadius = 1f;
        public float CylinderRadius = 1f;

        public ObjectCollection TargetCollection;

        protected override void OnTapped(GameObject obj, InteractionManager.InteractionEventArgs eventArgs)
        {
            Debug.Log(obj.name);
            switch (obj.name)
            {
                case "SurfaceTypeButtonDefault":
                    TargetCollection.GetComponent<ObjectCollectionDynamic>().RestoreArrangement();
                    TargetCollection.Radius = HomeRadius;
                    TargetCollection.transform.localPosition = HomeOffset;
                    break;
                case "SurfaceTypeButtonPlane":
                    TargetCollection.SurfaceType = ObjectCollection.SurfaceTypeEnum.Plane;
                    TargetCollection.transform.localPosition = PlaneOffset;
                    TargetCollection.Radius = PlaneRadius;
                    TargetCollection.UpdateCollection();
                    break;

                case "SurfaceTypeButtonSphere":
                    TargetCollection.SurfaceType = ObjectCollection.SurfaceTypeEnum.Sphere;
                    TargetCollection.transform.localPosition = SphereOffset;
                    TargetCollection.Radius = SphereRadius;
                    TargetCollection.UpdateCollection();
                    break;

                case "SurfaceTypeButtonCylinder":
                    TargetCollection.SurfaceType = ObjectCollection.SurfaceTypeEnum.Cylinder;
                    TargetCollection.transform.localPosition = CylinderOffset;
                    TargetCollection.Radius = CylinderRadius;
                    TargetCollection.UpdateCollection();
                    break;
            }
            base.OnTapped(obj, eventArgs);
        }
    }
}


text:
class Spree::EnquiriesController < Spree::StoreController
  def new
    @enquiry = Spree::Enquiry.new
  end

  def create
    @enquiry = Spree::Enquiry.new(params[:enquiry])
    unless params[:details][:full_name].blank?
      redirect_to root_path, :notice => t('spree_enquiry.successfully_submitted')
    else
      @enquiry.ip = request.ip
      if @enquiry.save
        redirect_to root_path, :notice => t('spree_enquiry.successfully_submitted')
      else
        render :action => "new"
      end
    end
  end
end


text:
from __future__ import print_function

import argparse
import os
import codecs
import re
import colorsys
import json

parser = argparse.ArgumentParser(
    description='Generate uORB pub/sub dependency graph from source code')

parser.add_argument('-s', '--src-path', action='append',
                    help='Source path(s) (default=src, can be specified multiple times)',
                    default=[])
parser.add_argument('-e', '--exclude-path', action='append',
                    help='Excluded path(s), can be specified multiple times',
                    default=[])
parser.add_argument('-f', '--file', metavar='file', action='store',
                    help='output file name prefix',
                    default='graph')
parser.add_argument('-o', '--output', metavar='output', action='store',
                    help='output format (json or graphviz)',
                    default='json')
parser.add_argument('--use-topic-union', action='store_true',
                    help='''
Use the union of all publication and subscription topics (useful for complete
graphs or only few/single module(s)). The default is to use the intersection
(remove topics that have no subscriber or no publisher)''')
parser.add_argument('-m', '--modules', action='store',
                    help='Comma-separated whitelist of modules (the module\'s '+
                    'MAIN, e.g. from a startup script)',
                    default='')

args = parser.parse_args()

g_debug = False
def dbg_print(string):
    if g_debug:
        print(string)

def get_N_colors(N, s=0.8, v=0.9):
    """ get N distinct colors as a list of hex strings """
    HSV_tuples = [(x*1.0/N, s, v) for x in range(N)]
    hex_out = []
    for rgb in HSV_tuples:
        rgb = map(lambda x: int(x*255), colorsys.hsv_to_rgb(*rgb))
        hex_out.append("#"+"".join(map(lambda x: format(x, '02x'), rgb)))
    return hex_out

class PubSub(object):
    """ Collects either publication or subscription information for nodes
    (modules and topics) & edges """

    def __init__(self, is_publication, topic_blacklist, orb_pub_sub_regexes, special_cases):
        """
            :param is_publication: if True, publications, False for
            subscriptions
            :param topic_blacklist: list of topics to blacklist
            :param orb_pub_sub_regexes: list of regexes to extract orb calls
                (e.g. orb_subscribe). They need to have 2 captures, the second
                one is the one capturing ORB_ID(<topic>
        """
        self._module_pubsubs = {} # key = module name, value = set of topic names
        self._special_cases = special_cases
        self._special_cases_matched = None
        self._topic_blacklist = topic_blacklist
        self._orb_pub_sub_regexes = orb_pub_sub_regexes
        if is_publication:
            self._method = 'Publication'
        else:
            self._method = 'Subscription'

    def reset(self):
        self._special_cases_matched = [False]*len(self._special_cases)

    def filter_modules(self, module_whitelist):
        remove = [k for k in self._module_pubsubs if k not in module_whitelist]
        for k in remove: del self._module_pubsubs[k]

    def check_if_match_found(self, modules):
        """ check if all special cases got a match (if not, it means the source
            code got changed)
        """
        for i, (module_match, file_match_re, src_match_re, _) in enumerate(self._special_cases):
            if module_match in modules and src_match_re is not None:
                if not self._special_cases_matched[i]:
                    raise Exception('Module '+module_match+
                            ': no match for '+self._method+' special case'+
                            src_match_re.pattern+'. The case needs to be updated')

    def extract(self, file_name, src_str, module, orb_id_vehicle_attitude_controls_topic):
        """ Extract subscribed/published topics from a source string
        :param src_str: string of C/C++ code with comments and whitespace removed
        """

        orb_pubsub_matches = []
        for regex in self._orb_pub_sub_regexes:
            orb_pubsub_matches += re.findall(regex, src_str)

        orb_id = 'ORB_ID('

        for _, match in orb_pubsub_matches:
            if match == 'ORB_ID_VEHICLE_ATTITUDE_CONTROLS': # special case
                match = orb_id+orb_id_vehicle_attitude_controls_topic

            # match has the form: '[ORB_ID(]<topic_name>'
            if match.startswith(orb_id):
                topic_name = match[len(orb_id):]
                self._add_topic(topic_name, file_name, module)
            else:
                ignore_found = False
                for module_match, file_match_re, _, ignore_re in self._special_cases:
                    if module == module_match:
                        if file_match_re.search(file_name):
                            if ignore_re.search(match):
                                ignore_found = True
                if not ignore_found:
                    # If we land here, we need to add another special case
                    raise Exception(self._method+' w/o ORB_ID(): '+match+' in '
                            +file_name+' ('+module+'). You need to add another special case.')

        # handle special cases
        for i, (module_match, file_match_re, src_match_re, _) in enumerate(self._special_cases):
            if src_match_re is None:
                continue
            if module == module_match:
                if file_match_re.search(file_name):
                    matches = src_match_re.findall(src_str)
                    for match in matches:
                        # match has the form: '[ORB_ID(]<topic_name>'
                        if match.startswith(orb_id):
                            topic_name = match[len(orb_id):]
                            dbg_print('Found '+self._method+' for special case in '
                                      +module+': '+topic_name)
                            self._add_topic(topic_name, file_name, module)
                            self._special_cases_matched[i] = True
                        else:
                            # this is not fatal, as it could be a method delaration/definition
                            dbg_print('Special case '+self._method+' w/o ORB_ID(): '
                                      +match+' in '+file_name+' ('+module+')')

    def _add_topic(self, topic_name, file_name, module):
        """ add a subscription/publication for a module
        """
        if topic_name in self._topic_blacklist:
            dbg_print('ignoring blacklisted topic '+topic_name)
            return

        if module is None:
            if not file_name.endswith('hott/messages.cpp'): # hott has a special module structure. just ignore it
                print('Warning: found '+self._method+' without associated module: '
                      +topic_name+' in '+file_name)
            return

        if not module in self._module_pubsubs:
            self._module_pubsubs[module] = set()
        self._module_pubsubs[module].add(topic_name)

    def get_topics(self, modules):
        """ get the set of topics
            :param modules: list of modules to take into account
        """
        topics = set()
        for module in modules:
            if module in self._module_pubsubs:
                topics |= self._module_pubsubs[module]
        return topics

    @property
    def pubsubs(self):
        """ get dict of all publication/subscriptions (key=modules, value=set of
            topic names"""
        return self._module_pubsubs

class Graph(object):
    """ Collects Node and Edge information by parsing the source tree """
    def __init__(self, module_whitelist=[], topic_blacklist=[]):
        self._current_module = [] # stack with current module (they can be nested)
        self._all_modules = set() # set of all found modules

        self._comment_remove_pattern = re.compile(
            r'//.*?$|/\*.*?\*/|\'(?:\\.|[^\\\'])*\'|"(?:\\.|[^\\"])*"',
            re.DOTALL | re.MULTILINE)
        self._whitespace_pattern = re.compile(r'\s+')
        self._module_whitelist = module_whitelist
        self._excluded_paths = []

        self._orb_id_vehicle_attitude_controls_topic = 'actuator_controls_0'
        self._orb_id_vehicle_attitude_controls_re = \
            re.compile(r'\#define\s+ORB_ID_VEHICLE_ATTITUDE_CONTROLS\s+([^,)]+)')

        self._module_subscriptions = {} # key = module name, value = set of topic names
        self._module_publications = {} # key = module name, value = set of topic names

        self._modules = set() # all modules
        self._topics = set() # all topics
        self._topic_colors = {} # key = topic, value = color (html string)

    # handle special cases
    # format: list of tuples with 4 entries:
    # - module name to match (module MAIN)
    # - regex for file name(s) to match within the module (matched against the full path)
    # - regex to extract the topic name: the match must be ORB_ID(<topic_name>
    #   Note: whitespace is removed from source code, so it does not need to be
    #   accounted for in the regex.
    #   If this is None, it will just be ignored
    # - regex to ignore matches in the form orb_[subscribe|advertise](<match>
    #   (the expectation is that the previous matching ORB_ID() will be passed
    #   to this, so that we can ignore it)
        special_cases_sub = [
    ('sensors', r'voted_sensors_update\.cpp$', r'\binit_sensor_class\b\(([^,)]+)', r'^meta$'),
    ('mavlink', r'.*', r'\badd_orb_subscription\b\(([^,)]+)', r'^_topic$'),
    ('listener', r'.*', None, r'^(id)$'),
    ('logger', r'.*', None, r'^(topic|sub\.metadata|_polling_topic_meta)$'),

    ('uavcan', r'uavcan_main\.cpp$', r'\b_control_topics\[[0-9]\]=([^,)]+)', r'^_control_topics\[i\]$'),
    ('tap_esc', r'.*', r'\b_control_topics\[[0-9]\]=([^,)]+)', r'^_control_topics\[i\]$'),
    ('pwm_out_sim', r'.*', r'\b_control_topics\[[0-9]\]=([^,)]+)', r'^_control_topics\[i\]$'),
    ('snapdragon_pwm_out', r'.*', r'\b_controls_topics\[[0-9]\]=([^,)]+)', r'^_controls_topics\[i\]$'),
    ('fmu', r'.*', r'\b_control_topics\[[0-9]\]=([^,)]+)', r'^_control_topics\[i\]$'),
    ('linux_pwm_out', r'.*', r'\b_controls_topics\[[0-9]\]=([^,)]+)', r'^_controls_topics\[i\]$'),
    ]
        special_cases_sub = [(a, re.compile(b), re.compile(c) if c is not None else None, re.compile(d))
                                   for a,b,c,d in special_cases_sub]

        self._subscriptions = PubSub(False, topic_blacklist,
                [r"\borb_subscribe(_multi|)\b\(([^,)]+)"],
                special_cases_sub)

        special_cases_pub = [
    ('replay', r'replay_main\.cpp$', None, r'^sub\.orb_meta$'),
    ('fw_pos_control_l1', r'FixedwingPositionControl\.cpp$', r'\b_attitude_setpoint_id=([^,)]+)', r'^_attitude_setpoint_id$'),

    ('mc_pos_control', r'mc_pos_control_main\.cpp$', r'\b_attitude_setpoint_id=([^,)]+)', r'^_attitude_setpoint_id$'),

    ('mc_att_control', r'mc_att_control_main\.cpp$', r'\b_actuators_id=([^,)]+)', r'^_actuators_id$'),
    ('mc_att_control', r'mc_att_control_main\.cpp$', r'\_attitude_sp_id=([^,)]+)', r'^_attitude_sp_id$'),

    ('fw_att_control', r'FixedwingAttitudeControl\.cpp$', r'\b_actuators_id=([^,)]+)', r'^_actuators_id$'),
    ('fw_att_control', r'FixedwingAttitudeControl\.cpp$', r'\b_attitude_setpoint_id=([^,)]+)', r'^_attitude_setpoint_id$'),

    ('uavcan', r'sensors/.*\.cpp$', r'\bUavcanCDevSensorBridgeBase\([^{]*DEVICE_PATH,([^,)]+)', r'^_orb_topic$'),
    ]
        special_cases_pub = [(a, re.compile(b), re.compile(c) if c is not None else None, re.compile(d))
                                   for a,b,c,d in special_cases_pub]
        self._publications = PubSub(True, topic_blacklist,
                [r"\borb_advertise(_multi|_queue|_multi_queue|)\b\(([^,)]+)",
                 r"\borb_publish_auto()\b\(([^,)]+)"],
                special_cases_pub)

    def _get_current_module(self):
        if len(self._current_module) == 0:
            return None
        return self._current_module[-1]

    def build(self, src_path_list, excluded_paths=[], use_topic_pubsub_union=True):
        """ parse the source tree & extract pub/sub information.
            :param use_topic_pubsub_union: if true, use all topics that have a
            publisher or subscriber. If false, use only topics with at least one
            publisher and subscriber.

            fill in self._module_subsciptions & self._module_publications
        """

        self._subscriptions.reset()
        self._publications.reset()

        self._excluded_paths = [os.path.normpath(p) for p in excluded_paths]
        for path in src_path_list:
            self._build_recursive(path)

        # filter by whitelist
        if len(self._module_whitelist) > 0:
            self._subscriptions.filter_modules(self._module_whitelist)
            self._publications.filter_modules(self._module_whitelist)

        # modules & topics sets
        self._modules = set(self._publications.pubsubs.keys() +
                self._subscriptions.pubsubs.keys())
        print('number of modules: '+str(len(self._modules)))
        self._topics = self._get_topics(use_topic_pubsub_union=use_topic_pubsub_union)
        print('number of topics: '+str(len(self._topics)))

        # initialize colors
        color_list = get_N_colors(len(self._topics), 0.7, 0.85)
        self._topic_colors = {}
        for i, topic in enumerate(self._topics):
            self._topic_colors[topic] = color_list[i]

        # validate that all special rules got used
        self._subscriptions.check_if_match_found(self._all_modules)
        self._publications.check_if_match_found(self._all_modules)

    def _get_topics(self, use_topic_pubsub_union=True):
        """ get the set of topics
        """
        subscribed_topics = self._subscriptions.get_topics(self._modules)
        published_topics = self._publications.get_topics(self._modules)
        if use_topic_pubsub_union:
            return subscribed_topics | published_topics
        return subscribed_topics & published_topics

    def _build_recursive(self, path):

        if os.path.normpath(path) in self._excluded_paths:
            dbg_print('ignoring excluded path '+path)
            return

        entries = os.listdir(path)

        # check if entering a new module
        cmake_file = 'CMakeLists.txt'
        new_module = False
        if cmake_file in entries:
            new_module = self._extract_module_name(os.path.join(path, cmake_file))

        # iterate directories recursively
        for entry in entries:
            file_name = os.path.join(path, entry)
            if os.path.isdir(file_name):
                self._build_recursive(file_name)

        # iterate source files
        # Note: we could skip the entries if we're not in a module, but we don't
        # so that we get appropriate error messages to know where we miss subs
        # or pubs
        for entry in entries:
            file_name = os.path.join(path, entry)
            if os.path.isfile(file_name):
                _, ext = os.path.splitext(file_name)
                if ext in ['.cpp', '.c', '.h', '.hpp']:
                    self._process_source_file(file_name)

        if new_module:
            self._current_module.pop()

    def _extract_module_name(self, file_name):
        """ extract the module name from a CMakeLists.txt file and store
            in self._current_module if there is any """
        datafile = file(file_name)
        found_module_def = False
        for line in datafile:
            if 'px4_add_module' in line: # must contain 'px4_add_module'
                found_module_def = True

            words = line.split()
            # get the definition of MAIN
            if found_module_def and 'MAIN' in words and len(words) >= 2:
                self._current_module.append(words[1])
                self._all_modules.add(words[1])
                dbg_print('Found module name: '+words[1])
                return True
        return False

    def _process_source_file(self, file_name):
        """ extract information from a single source file """

        with codecs.open(file_name, 'r', 'utf-8') as f:
            try:
                content = f.read()
            except:
                print('Failed reading file: %s, skipping content.' % path)
                return

            current_module = self._get_current_module()
            if current_module == 'uorb_tests': # skip this
                return
            if current_module == 'uorb':

                # search and validate the ORB_ID_VEHICLE_ATTITUDE_CONTROLS define
                matches = self._orb_id_vehicle_attitude_controls_re.findall(content)
                for match in matches:
                    if match != 'ORB_ID('+self._orb_id_vehicle_attitude_controls_topic:
                        # if we land here, you need to change _orb_id_vehicle_attitude_controls_topic
                        raise Exception(
                            'The extracted define for ORB_ID_VEHICLE_ATTITUDE_CONTROLS '
                            'is '+match+' but expected ORB_ID('+
                            self._orb_id_vehicle_attitude_controls_topic)

                return # skip uorb module for the rest

            if content.lower().find('orb_') != -1: # approximative filter to quickly
                                           # discard files we're not interested in
                                           # (speedup the parsing)
                src = self._comment_remover(content)
                src = re.sub(self._whitespace_pattern, '', src) # remove all whitespace

                # subscriptions
                self._subscriptions.extract(file_name, src, current_module,
                        self._orb_id_vehicle_attitude_controls_topic)

                # publications
                self._publications.extract(file_name, src, current_module,
                        self._orb_id_vehicle_attitude_controls_topic)

                # TODO: handle Publication & Subscription template classes

    def _comment_remover(self, text):
        """ remove C++ & C style comments.
            Source: https://stackoverflow.com/a/241506 """
        def replacer(match):
            s = match.group(0)
            if s.startswith('/'):
                return " " # note: a space and not an empty string
            else:
                return s
        return re.sub(self._comment_remove_pattern, replacer, text)

    @property
    def modules(self):
        """ get the set of all modules """
        return self._modules

    @property
    def topics(self):
        """ get set set of all topics """
        return self._topics

    @property
    def topic_colors(self):
        """ get a dict of all topic colors with key=topic, value=color """
        return self._topic_colors

    @property
    def module_subscriptions(self):
        """ get a dict of all subscriptions with key=module name, value=set(topic names) """
        return self._subscriptions.pubsubs

    @property
    def module_publications(self):
        """ get a dict of all publications with key=module name, value=set(topic names) """
        return self._publications.pubsubs

class OutputGraphviz(object):
    """ write graph using Graphviz """

    def __init__(self, graph):
        self._graph = graph

    def write(self, file_name, engine='fdp',
              show_publications=True, show_subscriptions=True):
        """ write the graph to a file
            :param engine: graphviz engine
                - fdp works for large graphs
                - neato works better for smaller graphs
                - circo works for single modules
                CLI: fdp graph.fv -Tpdf -o test.pdf
        """

        print('Writing to '+file_name)

        ratio = 1 # aspect ratio

        modules = self._graph.modules
        topics = self._graph.topics
        topic_colors = self._graph.topic_colors
        module_publications = self._graph.module_publications
        module_subscriptions = self._graph.module_subscriptions

        graph_attr={'splines': 'true', 'ratio': str(ratio), 'overlap': 'false'}
        graph_attr['sep'] = '"+15,15"' # increase spacing between nodes
        graph = Digraph(comment='autogenerated graph with graphviz using uorb_graph.py',
                engine=engine, graph_attr=graph_attr)

        # nodes
        for module in modules:
            graph.node('m_'+module, module, shape='box', fontcolor='#ffffff',
                    style='filled', color='#666666', fontsize='16')

        for topic in topics:
            graph.node('t_'+topic, topic, shape='ellipse', fontcolor='#ffffff',
                    style='filled', color=topic_colors[topic])

        # edges
        if show_publications:
            for module in modules:
                if module in module_publications:
                    for topic in module_publications[module]:
                        if topic in topics:
                            graph.edge('m_'+module, 't_'+topic,
                                    color=topic_colors[topic], style='dashed')

        if show_subscriptions:
            for module in modules:
                if module in module_subscriptions:
                    for topic in module_subscriptions[module]:
                        if topic in topics:
                            graph.edge('t_'+topic, 'm_'+module,
                                    color=topic_colors[topic])

	graph.render(file_name, view=False)

class OutputJSON(object):
    """ write graph to a JSON file (that can be used with D3.js) """

    def __init__(self, graph):
        self._graph = graph

    def write(self, file_name):

        print('Writing to '+file_name)

        modules = self._graph.modules
        topics = self._graph.topics
        topic_colors = self._graph.topic_colors
        module_publications = self._graph.module_publications
        module_subscriptions = self._graph.module_subscriptions

        data = {}
        nodes = []

        # nodes
        # (sort by length, such that short names are last. The rendering order
        # will be the same, so that in case of an overlap, the shorter label
        # will be on top)
        for module in sorted(modules, key=len, reverse=True):
            node = {}
            node['id'] = 'm_'+module
            node['name'] = module
            node['type'] = 'module'
            node['color'] = '#666666'
            # TODO: add url to open module documentation?
            nodes.append(node)

        for topic in sorted(topics, key=len, reverse=True):
            node = {}
            node['id'] = 't_'+topic
            node['name'] = topic
            node['type'] = 'topic'
            node['color'] = topic_colors[topic]
            # url is opened when double-clicking on the node
            # TODO: does not work for multi-topics
            node['url'] = 'https://github.com/PX4/Firmware/blob/master/msg/'+topic+'.msg'
            nodes.append(node)

        data['nodes'] = nodes

        edges = []

        # edges
        for module in modules:
            if module in module_publications:
                for topic in module_publications[module]:
                    if topic in topics:
                        edge = {}
                        edge['source'] = 'm_'+module
                        edge['target'] = 't_'+topic
                        edge['color'] = topic_colors[topic]
                        edge['style'] = 'dashed'
                        edges.append(edge)

        for module in modules:
            if module in module_subscriptions:
                for topic in module_subscriptions[module]:
                    if topic in topics:
                        edge = {}
                        edge['source'] = 't_'+topic
                        edge['target'] = 'm_'+module
                        edge['color'] = topic_colors[topic]
                        edge['style'] = 'normal'
                        edges.append(edge)

        data['links'] = edges

        with open(file_name, 'w') as outfile:
            json.dump(data, outfile) # add indent=2 for readable formatting

# ignore topics that are subscribed/published by many topics, but are not really
# useful to show in the graph
topic_blacklist = [ 'parameter_update', 'mavlink_log', 'log_message' ]
print('Excluded topics: '+str(topic_blacklist))

if len(args.modules) == 0:
    module_whitelist = []
else:
    module_whitelist = [ m.strip() for m in args.modules.split(',')]

graph = Graph(module_whitelist=module_whitelist, topic_blacklist=topic_blacklist)
if len(args.src_path) == 0:
    args.src_path = ['src']
graph.build(args.src_path, args.exclude_path, use_topic_pubsub_union=args.use_topic_union)

if args.output == 'json':
    output_json = OutputJSON(graph)
    output_json.write(args.file+'.json')

elif args.output == 'graphviz':
    try:
        from graphviz import Digraph
    except:
        print("Failed to import graphviz.")
        print("You may need to install it with 'pip install graphviz'")
        print("")
        raise
    output_graphviz = OutputGraphviz(graph)
    engine='fdp' # use neato or fdp
    output_graphviz.write(args.file+'.fv', engine=engine)
    output_graphviz.write(args.file+'_subs.fv', show_publications=False, engine=engine)
    output_graphviz.write(args.file+'_pubs.fv', show_subscriptions=False, engine=engine)
else:
    print('Error: unknown output format '+args.output)


text:
<!DOCTYPE html>

	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
	<title>Selectores de atributos</title>
	<link rel="stylesheet" href="css/estilos.css">

	<input type="text" placeholder="Nombre">

	<input type="date" placeholder="Fecha">

	<input type="time" placeholder="Hora">

	<input type="color" placeholder="Color">

		Lorem ipsum dolor sit amet, consectetur adipisicing elit.

		Lorem ipsum dolor sit amet, consectetur adipisicing elit.

Español de España

Español de El Salvador

Español de Mexico


text:
package de.egore911.appframework.persistence.model;

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

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

/**
 * @author Christoph Brill <egore911@gmail.com>
 */
@Entity(name = "Role")
@Table(name = "role")
public class RoleEntity extends IntegerDbObject {

	private static final long serialVersionUID = 1353587049705666524L;

	private String name;
	private List<String> permissions = new ArrayList<>(0);
	private List<UserEntity> users = new ArrayList<>(0);

	@Column(nullable = false)
	@NotNull
	@Size(min = 1, max = 255)
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	@ElementCollection
	@CollectionTable(name = "role_permissions", joinColumns = @JoinColumn(name = "role_id"))
	@Column(name = "permission")
	public List<String> getPermissions() {
		return permissions;
	}

	public void setPermissions(List<String> permissions) {
		this.permissions = permissions;
	}

	@ManyToMany(mappedBy = "roles")
	@OrderBy("name")
	public List<UserEntity> getUsers() {
		return users;
	}

	public void setUsers(List<UserEntity> users) {
		this.users = users;
	}

}


text:
package isis.nest.math;

import java.util.Random;

/**
 * RandomSingleton makes possible singleton access to the random number
 * generator .
 */
public class RandomSingleton
{
    private static java.util.Random rand = new Random();

    /**
     * Gives back the isntance of the Random number generator.
     * @return The instance of the Random number generator.
     */
    static public Random instance()
    {
        return rand;
    }
}


text:
SpecBegin(BuildStatusNotifierSpec)

describe(@"BuildStatusNotifier", ^{
  __block id notifier ;

  beforeEach(^{
    notifier = [OCMockObject niceMockForClass:[BuildStatusNotifier class]] ;
  }) ;
}) ;
SpecEnd


text:
using System;
using System.Threading.Tasks;
using System.Web.Http;
using SFA.DAS.PAS.Account.Api.Attributes;
using SFA.DAS.PAS.Account.Api.Orchestrator;
using SFA.DAS.PAS.Account.Api.Types;
using SFA.DAS.ProviderApprenticeshipsService.Domain.Interfaces;

namespace SFA.DAS.PAS.Account.Api.Controllers
{
    [RoutePrefix("api/email")]
    public class EmailController : ApiController
    {
        private readonly EmailOrchestrator _emailOrchestrator;

        private readonly IProviderCommitmentsLogger _logger;

        public EmailController(EmailOrchestrator emailOrchestrator, IProviderCommitmentsLogger logger)
        {
            _emailOrchestrator = emailOrchestrator;
            _logger = logger;
        }

        [Route("{ukprn}/send")]
        [HttpPost]
        [ApiAuthorize(Roles = "ReadAccountUsers")]
        public async Task<IHttpActionResult> SendEmailToAllProviderRecipients(long ukprn, ProviderEmailRequest request)
        {
            try
            {
                await _emailOrchestrator.SendEmailToAllProviderRecipients(ukprn, request);
                _logger.Info($"Email template '{request?.TemplateId}' sent to Provider recipients successfully", ukprn);
                return Ok();
            }
            catch (Exception e)
            {
                _logger.Error(e, $"Error sending email template '{request?.TemplateId}' to Provider recipients", ukprn);
                throw;
            }
        }
    }
}


text:
module LLT
  module Review::Treebank::Difference
    class Word < Review::Common::Difference::Word
      attr_reader :lemma, :head, :relation, :postag
    end
  end
end


text:
export TRAVIS_PULL_REQUEST=false
export FORCE_LOCAL_BUILD=true
if [ "${FORCE_BRANCH}" != "" ]; then
  export TRAVIS_BRANCH=$FORCE_BRANCH
else
  export TRAVIS_BRANCH=`git branch 2>/dev/null | sed -e '/^[^\*]/d' -e 's/* \(.*\)/\1/'`
fi
export GH_REF="git@github.com:ractivejs/ractive"

set -e

echo "This will build your local branch ($TRAVIS_BRANCH) and attempt to publish it. If you want to bail now, you have 5 seconds..."
sleep 1
echo "4..."
sleep 1
echo "3..."
sleep 1
echo "2..."
sleep 1
echo "1..."
sleep 1
echo "Hold on to your butts...  "

sh scripts/build-ci-dev.sh

sh scripts/release-ci.sh


text:
require 'net/http'
require 'json'

class Psei::Parser
  attr_reader :url

  def initialize url, headers
    @url = url
    @headers = headers
  end

  def process(response=nil)
    resp = response || get_response
    JSON.parse(resp)
  end

  private

  def get_response
    uri = URI.parse(@url)
    http = Net::HTTP.new(uri.host, uri.port)
    http.use_ssl = true

    request = Net::HTTP::Get.new(uri.request_uri)
    @headers.keys.each do |k|
      request[k.to_s] = @headers[k]
    end

    @response ||= http.request(request).body
  end

end