text:
import typing

import numpy as np

import measurement_stats as mstats
from tracksim import limb
from tracksim import trackway

def time_steps_from_data(
        steps_per_cycle: int,
        trackway_definition: trackway.TrackwayDefinition
) -> np.ndarray:
    """
    Creates an array of time steps based on the number of steps per cycle and
    the information stored in the trackway_definition. This works like the
    time_steps method, but the minimum and maximum times are determined
    automatically based on the trackway_definition.

    :param steps_per_cycle:
        The number of time steps in each cycle, where a cycle is defined as a
        unit amount of time (1.0, 2.0, 3.0, ...).
    :param trackway_definition:
        The positional information for the trackway
    """

    max_time = 0
    for key in limb.KEYS:
        track_count = trackway_definition.limb_positions.get(key)
        max_time = max(max_time, len(track_count))

    return time_steps(steps_per_cycle, -1.0, max_time)

def time_steps(
        steps_per_cycle: int,
        min_time: float,
        max_time: float
) -> np.ndarray:
    """
    Creates an evenly spaced Numpy array of time steps between the min and max
    times inclusively where the spacing is determined by the steps_per_cycle.

    :param steps_per_cycle:
        The number of time steps in each cycle, where a cycle is defined as a
        unit amount of time (1.0, 2.0, 3.0, ...).
    :param min_time:
        The time at which to start the time step array
    :param max_time:
        The time at which to end the time step array
    """

    return np.linspace(
        start=min_time,
        stop=max_time,
        num=steps_per_cycle * (max_time - min_time) + 1
    )

def trackway_data(
        cycle_count: int,
        step_size: float,
        activity_phases: limb.Property,
        track_offsets: limb.Property,
        lateral_displacement: typing.Union[float, list, tuple],
        positional_uncertainty: float = None
) -> trackway.TrackwayDefinition:
    """
    Creates a simulated trackway definition with trackway positions calculated
    based on the arguments

    :param cycle_count:
        The number cycles to include in the simulation data
    :param step_size:
        The length (in meters) between successive steps for each limb in the
        trackway
    :param activity_phases:
        The phases for each limb, which is the standard phases object used by
        both
    :param track_offsets:
        The spatial offsets for each limb in the trackway.
    :param lateral_displacement:
        The lateral distance from the mid-line for each limb
    :param positional_uncertainty:
        The amount of uncertainty in the x and y positions for each track
        in the trackway
    """

    return trackway.TrackwayDefinition(
        activity_phases=activity_phases,
        limb_positions=trackway_positions(
            cycle_count=cycle_count,
            step_size=step_size,
            track_offsets=track_offsets,
            lateral_displacement=lateral_displacement,
            positional_uncertainty=positional_uncertainty
        ))

def trackway_positions(
        cycle_count: int,
        step_size: float,
        track_offsets: limb.Property,
        lateral_displacement: typing.Union[float, list, tuple],
        positional_uncertainty: float = None,
) -> limb.Property:
    """
    Creates a limb Property with trackway positions for each limb based on the
    specified arguments

    :param cycle_count:
        The number cycles to include in the simulation data
    :param step_size:
        The length (in meters) between successive steps for each limb in the
        trackway
    :param track_offsets:
        The spatial offsets for each limb in the trackway.
    :param lateral_displacement:
        The lateral distance from the mid-line for each limb
    :param positional_uncertainty:
        The amount of uncertainty in the x and y positions for each track
        in the trackway
    """

    assert isinstance(track_offsets, limb.Property), \
        'Phases must be a limb property'

    if isinstance(lateral_displacement, (list, tuple)):
        pes_lateral_displacement = lateral_displacement[0]
        manus_lateral_displacement = lateral_displacement[1]
    else:
        pes_lateral_displacement = lateral_displacement
        manus_lateral_displacement = lateral_displacement

    return limb.Property(
        left_pes=track_positions(
            cycle_count=cycle_count,
            step_size=step_size,
            track_offset=track_offsets.left_pes,
            lateral_displacement=pes_lateral_displacement,
            positional_uncertainty=positional_uncertainty
        ),
        right_pes=track_positions(
            cycle_count=cycle_count,
            step_size=step_size,
            track_offset=track_offsets.right_pes,
            lateral_displacement=-pes_lateral_displacement,
            positional_uncertainty=positional_uncertainty
        ),
        left_manus=track_positions(
            cycle_count=cycle_count,
            step_size=step_size,
            track_offset=track_offsets.left_manus,
            lateral_displacement=manus_lateral_displacement,
            positional_uncertainty=positional_uncertainty
        ),
        right_manus=track_positions(
            cycle_count=cycle_count,
            step_size=step_size,
            track_offset=track_offsets.right_manus,
            lateral_displacement=-manus_lateral_displacement,
            positional_uncertainty=positional_uncertainty
        )
    )

def track_positions(
        cycle_count: int,
        step_size: float,
        track_offset: float,
        lateral_displacement: float,
        positional_uncertainty: float = None
) -> list:
    """
    Creates a list of trackway positions for a limb based on the
    specified arguments

    :param cycle_count:
        The number cycles to include in the simulation data
    :param step_size:
        The length (in meters) between successive steps for each limb in the
        trackway
    :param track_offset:
        The spatial offsets for each limb in the trackway.
    :param lateral_displacement:
        The lateral distance from the mid-line for each limb
    :param positional_uncertainty:
        The amount of uncertainty in the x and y positions for each track
        in the trackway
    """

    out = []

    if positional_uncertainty is None:
        positional_uncertainty = 0.01

    for i in range(cycle_count):
        out.append(trackway.TrackPosition(
            x=mstats.value.ValueUncertainty(
                value=(track_offset + i) * step_size,
                uncertainty=positional_uncertainty
            ),
            y=mstats.value.ValueUncertainty(
                value=lateral_displacement,
                uncertainty=positional_uncertainty
            )
        ))

    return out


text:
export from SRS, may not be updated, please follow upstream

## 导出`srs-librtmp`项目源码与编译
* `./configure --export-librtmp-project=srs-librtmp`
* `cd srs-librtmp && make`
* 成果物: `objs/include/srs_librtmp.h` `objs/lib/srs_librtmp.a`
* examples: `research/librtmp` <https://github.com/winlinvip/simple-rtmp-server/wiki/v2_CN_SrsLibrtmp#srs-librtmp-examples>
* 源码: `src`

redpajama_set_name: RedPajamaGithub


text:
@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>
{
    __weak IBOutlet UITableView *table;
    NSMutableArray* tableData;
}

@end


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

using System;
using UnityEngine;

namespace HoloToolkit.Unity.InputModule
{
    /// <summary>
    /// Very simple class that implements basic logic for a trigger button.
    /// </summary>
    public class TriggerButton : MonoBehaviour, IInputClickHandler
    {
        /// <summary>
        /// Indicates whether the button is clickable or not.
        /// </summary>
        [Tooltip("Indicates whether the button is clickable or not.")]
        public bool IsEnabled = true;

        public event Action ButtonPressed;

        /// <summary>
        /// Press the button programatically.
        /// </summary>
        public void Press()
        {
            if (IsEnabled)
            {
                ButtonPressed.RaiseEvent();
            }
        }

        public void OnInputClicked(InputClickedEventData eventData)
        {
            if (IsEnabled)
            {
                ButtonPressed.RaiseEvent();
            }
        }
    }
}


text:
<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

define('POSTAGEAPP_VERSION', '1.0.0');

/**
 * PostageApp Class
 *
 * Permits email to be sent via PostageApp service
 *
 * @package PostageApp
 * @author Oleg Khabarov, The Working Group Inc.
 * @Modified by Crankeye 10-22-2012
 * @link http://postageapp.com
 */
class PostageApp {

  var $api_key            = '';
  var $secure             = TRUE;
  var $host               = 'api.postageapp.com';
  var $recipient_override = '';
  var $template           = '';
  var $variables          = array();
  var $_arguments         = array();

  /**
   * Constructor - Sets PostageApp Preferences
   *
   * The constructor can be passed an array of config values
   */
  function PostageApp($config = array()){
    $this->initialize($config);
    log_message('debug', 'PostageApp Class Initialized');
  }

  /**
   * Initialize preferences
   *
   * @access  public
   * @param   array
   * @return  void
   */
  function initialize($config = array()){
    $this->clear();
    if(count($config) > 0){
      foreach($config as $key => $val){
        if(isset($this->$key)){
          $this->$key = $val;
        }
      }
    }
  }

  /**
   * Setting Defaults
   *
   * @access  public
   * @return  void
   */
  function clear(){
    $this->api_key            = '';
    $this->secure             = TRUE;
    $this->host               = 'api.postageapp.com';
    $this->recipient_override = '';
    $this->template           = '';
    $this->variables          = array();
    $this->_arguments         = array();
  }

  /**
   * Setting arbitrary message headers. You may set from, subject, etc here
   *
   * @access  public
   * @return  void
   */
  function headers($headers = array()){
    $this->_arguments['headers'] = $headers;
  }

  /**
   * Setting Subject Header
   *
   * @access  public
   * @return  void
   */
  function subject($subject){
    $this->_arguments['headers']['subject'] = $subject;
  }

  /**
   * Setting From header
   *
   * @access  public
   * @return  void
   */
  function from($from){
    $this->_arguments['headers']['from'] = $from;
  }

  /**
   * Setting Recipients. Accepted formats for $to are (see API docs):
   *   -> 'recipient@example.com'
   *   -> 'John Doe <recipient@example.com>'
   *   -> 'recipient1@example.com, recipient2@example.com'
   *   -> array('recipient1@example.com', 'recipient2@example.com')
   *   -> array('recipient1@example.com' => array('variable1' => 'value',
   *                                              'variable2' => 'value'),
   *            'recipient2@example.com' => array('variable1' => 'value',
   *                                              'variable2' => 'value'))
   * @access  public
   * @return  void
   */
  function to($to){
    $this->_arguments['recipients'] = $to;
  }

  /**
   * Setting message body. If you need to send both html and text set $content to:
   *   array(
   *    'text/html'   => 'HTML Content,
   *    'text/plain'  => 'Plain Text Content
   *   )
   *
   * @access  public
   * @return  void
   */
  function message($content){
    $this->_arguments['content'] = $content;
  }

  /**
   * Appending attachments to the message
   *
   * @access  public
   * @return  void
   */
  function attach($filename){
    $handle = fopen($filename, 'rb');
    $file_content = fread($handle, filesize($filename));
    fclose($handle);

    $this->_arguments['attachments'][basename($filename)] = array(
      'content_type'  => mime_content_type($filename),
      'content'       => chunk_split(base64_encode($file_content), 60, "\n")
    );
  }

  /**
   * Setting PostageApp project template
   *
   * @access  public
   * @return  void
   */
  function template($template){
    $this->_arguments['template'] = $template;
  }

  /**
   * Setting  message variables
   *
   * @access  public
   * @return  void
   */
  function variables($variables = array()){
    $this->_arguments['variables'] = $variables;
  }

  /**
   * Content that gets sent in the API call
   *
   * @access  public
   * @return  array
   */
  function payload(){
    $message = array(
      'api_key'   => $this->api_key,
      'uid'       => sha1(time() . json_encode($this->_arguments)),
      'arguments' => $this->_arguments
    );

    // applying recipient override
    if($this->recipient_override != ''){
      $message['arguments']['recipient_override'] = $this->recipient_override;
    }

    return $message;
  }

  /**
   * Send Email message via PostageApp
   *
   * @url: http://help.postageapp.com/kb/api/send_message
   * @access:  public
   * @return  object
   */
  function send(){
	$function = 'send_message.json';

	return $this->_request($function,$this->payload());
  }

   /**
   * Get Account Info
   * @desc: Provides information about the account.
   * @url: http://help.postageapp.com/kb/api/get_account_info
   * @access:  public
   * @return:  object
   */
  function get_account_info(){
	$function 	= 'get_account_info.json';
	$payload 	= array('api_key' => $this->api_key);

	return $this->_request($function,$payload);
  }

  /**
   * Get Message Receipt
   * @desc: Confirm that message with a particular UID exists
   * @params:  $uid - unique email identifier of the message
   * @url: http://help.postageapp.com/kb/api/get_message_receipt
   * @access:  public
   * @return:  object
   */
  function get_message_receipt($uid){
	$function 	= 'get_message_receipt.json';
	$payload 	= array('api_key' => $this->api_key,'uid' => $uid);

	return $this->_request($function,$payload);
  }

  /**
   * Get Message Transmissions
   * @desc: To get data on individual recipients' delivery and open status,
   * 		you can pass a particular message UID and receive a JSON encoded
   * 		set of data for each recipient within that message.
   * @params:  $uid - unique email identifier of the message
   * @url: http://help.postageapp.com/kb/api/get_message_transmissions
   * @access:  public
   * @return:  object
   */
  function get_message_transmissions($uid){
	$function 	= 'get_message_transmissions.json';
	$payload 	= array('api_key' => $this->api_key,'uid' => $uid);

	return $this->_request($function,$payload);
  }

  /**
   * Get Messages
   * @desc: Gets a list of all message UIDs within your project, for subsequent
   * use in collection statistics or open rates.
   * @url: http://help.postageapp.com/kb/api/get_messages
   * @access:  public
   * @return:  object
   */
  function get_messages(){
	$function 	= 'get_messages.json';
	$payload 	= array('api_key' => $this->api_key);

	return $this->_request($function,$payload);
  }

  /**
   * Get Method List
   * @desc: Get a list of all available api methods.
   * @url: http://help.postageapp.com/kb/api/get_method_list
   * @access:  public
   * @return:  object
   */
  function get_method_list(){
	$function 	= 'get_method_list.json';
	$payload 	= array('api_key' => $this->api_key);

	return $this->_request($function,$payload);
  }

  /**
   * Get Metrics
   * @desc: Gets data on aggregate delivery and open status for a project,
   * 		broken down by current hour, current day, current week, current
   * 		month with the previous of each as a comparable.
   * @url: http://help.postageapp.com/kb/api/get_metrics
   * @access:  public
   * @return:  object
   */
  function get_metrics(){
	$function 	= 'get_metrics.json';
	$payload 	= array('api_key' => $this->api_key);

	return $this->_request($function,$payload);
  }

  /**
   * Get Project Info
   * @desc: Provides information about the project. e.g. urls, transmissions, users.
   * @url: http://help.postageapp.com/kb/api/get_project_info
   * @access:  public
   * @return:  object
   */
  function get_project_info(){
	$function 	= 'get_project_info.json';
	$payload 	= array('api_key' => $this->api_key);

	return $this->_request($function,$payload);
  }

   /**
   * Request
   * @desc: Make a request to the Code Igniter JSON API
   * @access:  private
   * @return:  object
   */
  function _request($function,$payload)
  {
	$protocol = $this->secure ? 'https' : 'http';
    $ch = curl_init($protocol.'://'.$this->host.'/v.1.0/'.$function);
    curl_setopt($ch, CURLOPT_POSTFIELDS,  json_encode($payload));
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
      'Content-Type: application/json',
      'User-Agent: PostageApp CodeIgniter '.POSTAGEAPP_VERSION . ' (CI '.CI_VERSION.', PHP '.phpversion().')'
    ));
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    $output = curl_exec($ch);
    curl_close($ch);
    return json_decode($output);
  }

}

/* End of file PostageApp.php */
/* Location: ./system/application/libraries/PostageApp.php */


text:
angular.module('tilesArrangement', [
    'tilesArrangement.arrangementGenerator',
    'tilesArrangement.arrangementPicture',
    'tilesArrangement.tilesSwapper',
    'bathroomShape'
])

    .controller('TilesArrangementController', function ($scope, ArrangementGenerator, TilesSwapper) {

        $scope.shouldShowTilesLabels = false;
        const rows = 20;
        const columns = 11;

        $scope.generateNextArrangement = function (tileWidth, tileHeight, groutWidth) {
            $scope.isSwappingTilesInProgress = false;
            $scope.arrangement =
                ArrangementGenerator.newArrangementFor(rows, columns, tileWidth, tileHeight, groutWidth);
        };

        TilesSwapper.attachTo($scope);
    })

    .directive('tilesArrangement', function (ArrangementPictureCreator, TilesSwapper) {

        var scope;
        var canvas;
        var arrangement;
        var arrangementPicture;

        function link(_scope_, _element_) {
            scope = _scope_;
            TilesSwapper.onSwapBegin(highlightTileIn);
            TilesSwapper.onSwapFinish(swapTilesBetween);
            _element_.on("click", toggleSwappingTiles);
            canvas = _element_[0];
            scope.$watch('arrangement', updateCanvas);
            scope.$watch('shouldShowTilesLabels', updateCanvas);
        }

        function toggleSwappingTiles(event) {
            var cell = arrangementPicture.cellAt(event.offsetX, event.offsetY);
            TilesSwapper.clickedTileIn(cell);
        }

        function updateCanvas() {
            arrangement = scope.arrangement;
            arrangementPicture = ArrangementPictureCreator.newPictureOf(arrangement);
            if (!!arrangementPicture) {
                resetCanvas();
                drawArrangementAsynchronously();
            }
        }

        function resetCanvas() {
            canvas.width = arrangementPicture.width();
            canvas.height = arrangementPicture.height();
            context2d().fillStyle = "#FFFFFF";
            context2d().fillRect(0, 0, canvas.width, canvas.height);
        }

        function drawArrangementAsynchronously() {
            arrangementPicture.loadImagesAndThen(function (images) {
                drawTilesUsing(images);
                drawBathroomShape();
                TilesSwapper.ifSwapIsInProgressThen(highlightTileIn);
            });
        }

        function drawTilesUsing(images) {
            arrangementPicture.forEachTile(function (tileName, x, y, width, height, rotation) {
                var tileImage = images[tileName];
                context2d().save();
                context2d().translate(x + width / 2, y + height / 2);
                context2d().rotate(rotation);
                context2d().drawImage(tileImage, -width / 2, -height / 2, width, height);
                context2d().restore();
                if (shouldShowTilesLabels()) {
                    drawTileLabel(tileName, x + 2, y + 2);
                }
            });
        }

        function drawTileLabel(labelText, x, y) {
            context2d().save();
            context2d().font = "16px Arial";
            context2d().textBaseline = "top";
            const textXOffset = 2;
            const width = context2d().measureText(labelText).width + textXOffset;
            const height = 16;
            context2d().fillStyle = "#FFFFFF";
            context2d().fillRect(x, y, width, height);
            context2d().fillStyle = "#000000";
            context2d().fillText(labelText, x + textXOffset, y);
            context2d().restore();
        }

        function drawBathroomShape() {
            context2d().save();
            context2d().globalAlpha = 0.6;
            context2d().beginPath();
            context2d().strokeStyle = "#FF0000";
            context2d().lineWidth = 5;
            arrangementPicture.forEachLineInBathroomShape(drawLine);
            context2d().closePath();
            context2d().stroke();
            context2d().restore();
        }

        function drawLine(line) {
            context2d().moveTo(line.x1, line.y1);
            context2d().lineTo(line.x2, line.y2);
        }

        function highlightTileIn(cell) {
            var rectangle = arrangementPicture.rectangleIn(cell);
            context2d().save();
            context2d().globalAlpha = 0.4;
            context2d().fillStyle = "#999900";
            context2d().fillRect(rectangle.x, rectangle.y, rectangle.width, rectangle.height);
            context2d().restore();
        }

        function swapTilesBetween(sourceCell, targetCell) {
            arrangement
                .swapTileAt(sourceCell.row, sourceCell.column)
                .withTileAt(targetCell.row, targetCell.column);
            updateCanvas();
        }

        function context2d() {
            return canvas.getContext("2d");
        }

        function shouldShowTilesLabels() {
            return scope.shouldShowTilesLabels;
        }

        return {
            restrict: 'E',
            replace: true,
            template: '<canvas id="arrangement"></canvas>',
            link: link
        }
    });


text:
require 'spec_helper'

describe 'nexus3_test::user' do
  context 'linux' do
    let(:chef_run) do
      ChefSpec::SoloRunner.new(platform: 'centos', version: CENTOS_VERSION, step_into: 'nexus3_user',
                               file_cache_path: CACHE).converge(described_recipe)
    end

    before do
      stub_request(:post, 'http://localhost:8081/service/rest/v1/script/get_user/run')
        .with(basic_auth: %w[admin admin123])
        .with(body: 'uploader-bot', headers: { 'Content-Type' => 'application/json' })
        .to_return(api_response(404),
                   user_response('uploader-bot'),
                   user_response('uploader-bot'))

      stub_request(:post, 'http://localhost:8081/service/rest/v1/script/get_user/run')
        .with(basic_auth: %w[admin admin123])
        .with(body: 'uploader2-bot', headers: { 'Content-Type' => 'application/json' })
        .to_return(api_response(404),
                   user_response('uploader2-bot'),
                   user_response('uploader2-bot'))

      stub_request(:post, 'http://localhost:8081/service/rest/v1/script/get_user/run')
        .with(basic_auth: %w[admin admin123])
        .with(body: 'test-with-pass', headers: { 'Content-Type' => 'application/json' })
        .to_return(api_response(404),
                   user_response('test-with-pass'),
                   user_response('test-with-pass'))

      stub_request(:post, 'http://localhost:8081/service/rest/v1/script/get_user/run')
        .with(basic_auth: %w[admin admin123])
        .with(body: 'doesnotexist', headers: { 'Content-Type' => 'application/json' })
        .to_return(api_response(404),
                   user_response('doesnotexist'),
                   user_response('doesnotexist'))

      stub_request(:post, 'http://localhost:8081/service/rest/v1/script/get_user/run')
        .with(basic_auth: %w[admin admin123])
        .with(body: 'user_with_role', headers: { 'Content-Type' => 'application/json' })
        .to_return(api_response(404),
                   user_response('user_with_role'),
                   user_response('user_with_role'))

      stub_request(:get, 'http://localhost:8081/service/metrics/ping')
        .to_return(api_response(200))
    end

    it 'creates a user' do
      expect(chef_run).to create_nexus3_user('uploader')
      expect(chef_run).to create_nexus3_api('get_user uploader-bot')
      expect(chef_run).to create_nexus3_api('upsert_user uploader-bot')
      expect(chef_run).to run_nexus3_api('upsert_user uploader-bot').with(
        args: { username: 'uploader-bot', password: 'test-1', first_name: '', last_name: '', email: '', roles: [] }
      )
    end

    it 'updates a user' do
      expect(chef_run).to create_nexus3_user('uploader2 update')
      expect(chef_run).to create_nexus3_api('get_user uploader2-bot')
      expect(chef_run).to create_nexus3_api('upsert_user uploader2-bot')
      expect(chef_run).to run_nexus3_api('upsert_user uploader2-bot').with(
        args: { username: 'uploader2-bot', password: 'test-2', first_name: 'uploader2', last_name: 'bot',
                email: 'uploader2@example.com', roles: [] }
      )
    end

    it 'changes a password' do
      expect(chef_run).to create_nexus3_user('test-with-pass')
      expect(chef_run).to create_nexus3_api('get_user test-with-pass')
      expect(chef_run).to create_nexus3_api('upsert_user test-with-pass')
      expect(chef_run).to run_nexus3_api('upsert_user test-with-pass').with(
        args: { username: 'test-with-pass', password: 'newpassword', first_name: '', last_name: '',
                email: '', roles: [] }
      )
    end

    it 'deletes a user' do
      expect(chef_run).to create_nexus3_user('doesnotexist')
      expect(chef_run).to create_nexus3_api('get_user doesnotexist')
      expect(chef_run).to create_nexus3_api('upsert_user doesnotexist')
      expect(chef_run).to delete_nexus3_user('doesnotexist')
      expect(chef_run).to create_nexus3_api('delete_user doesnotexist')
      expect(chef_run).to run_nexus3_api('delete_user doesnotexist').with(
        args: 'doesnotexist'
      )
    end
  end
end


text:
class URLCtrl : public Window
{
public:
    URLCtrl():_hfUnderlined(0),_hCursor(0), _msgDest(NULL), _cmdID(0), _oldproc(NULL), \
		_linkColor(), _visitedColor(), _clicking(false), _URL(TEXT("")){};

    void create(HWND itemHandle, TCHAR * link, COLORREF linkColor = RGB(0,0,255));
	void create(HWND itemHandle, int cmd, HWND msgDest = NULL);
    void destroy();

protected :
    TString _URL;
    HFONT	_hfUnderlined;
    HCURSOR	_hCursor;

	HWND _msgDest;
	unsigned long _cmdID;

    WNDPROC  _oldproc;
    COLORREF _linkColor;
    COLORREF _visitedColor;
    bool  _clicking;

    static LRESULT CALLBACK URLCtrlProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam){
        return ((URLCtrl *)(::GetWindowLongPtr(hwnd, GWL_USERDATA)))->runProc(hwnd, Message, wParam, lParam);
    };
    LRESULT runProc(HWND hwnd, UINT Message, WPARAM wParam, LPARAM lParam);
};

#endif //URLCTRL_INCLUDED


text:
<head>
  <link href="http://gmpg.org/xfn/11" rel="profile">
  <meta http-equiv="content-type" content="text/html; charset=utf-8">

  <!-- Enable responsiveness on mobile devices-->
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1">

  <title>
    {% if page.title == "Home" %}
      {{ site.title }} · {{ site.tagline }}
    {% else %}
      {{ page.title }} · {{ site.title }}
    {% endif %}
  </title>

  <!-- CSS -->
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/poole.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/syntax.css">
  <link rel="stylesheet" href="{{ site.baseurl }}public/css/lanyon.css">

  <!-- Icons -->
  <link rel="apple-touch-icon-precomposed" sizes="144x144" href="{{ site.baseurl }}public/apple-touch-icon-144-precomposed.png">
  <link rel="shortcut icon" href="{{ site.baseurl }}public/favicon.ico">

  <!-- RSS -->
  <link rel="alternate" type="application/rss+xml" title="RSS" href="/atom.xml">
</head>


text:
"""Test Henson-Sentry."""

import asyncio

from henson_sentry import Sentry

def test_capture_exception(sentry, test_app, event_loop, cancelled_future,
                           queue):
    """Test capture_exception."""
    @asyncio.coroutine
    def callback(app, message):
        try:
            1 / 0
        except:
            yield from sentry.capture_exception()
    test_app.callback = callback

    event_loop.run_until_complete(
        test_app._process(cancelled_future, queue, event_loop))

    assert sentry._client._events

def test_capture_message(sentry, test_app, event_loop, cancelled_future,
                         queue):
    """Test capture_message."""
    @asyncio.coroutine
    def callback(app, message):
        yield from sentry.capture_message(message)
    test_app.callback = callback

    event_loop.run_until_complete(
        test_app._process(cancelled_future, queue, event_loop))

    assert sentry._client._events

def test_handle_exception(sentry, test_app, event_loop, cancelled_future,
                          queue):
    """Test that exceptions are handled."""
    event_loop.run_until_complete(
        test_app._process(cancelled_future, queue, event_loop))

    assert sentry._client._events

def test_handle_exception_with_ignored_error(sentry, test_app, event_loop,
                                             cancelled_future, queue):
    """Test that ignored exceptions aren't handled."""
    test_app.settings['RAVEN_IGNORE_EXCEPTIONS'] = Exception

    event_loop.run_until_complete(
        test_app._process(cancelled_future, queue, event_loop))

    assert not sentry._client._events

def test_no_dsn(test_app):
    """Test that Sentry is disabled when there's no DSN."""
    # Ensure that there's no DSN set for test_app.
    del test_app.settings['SENTRY_DSN']

    sentry = Sentry(test_app)

    assert sentry._client is None


text:
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="App.xaml.cs" company="None">
//   None
// </copyright>
// <summary>
//   Interaction logic for App.xaml
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace TfsWorkbench.WpfUI
{
    using System;
    using System.Globalization;
    using System.IO;
    using System.Text;
    using System.Windows;
    using System.Windows.Markup;
    using System.Windows.Threading;

    using Microsoft.Win32;

    using Properties;

    using TfsWorkbench.WpfUI.Controllers;

    using UIElements;

    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        /// <summary>
        /// The application controller intance.
        /// </summary>
        private ApplicationController applicationController;

        /// <summary>
        /// The activation status flag.
        /// </summary>
        private bool isActivated;

        /// <summary>
        /// The is showing error message flag.
        /// </summary>
        private bool isShowingErrorMessage;

        /// <summary>
        /// Initializes a new instance of the <see cref="App"/> class.
        /// </summary>
        /// <exception cref="T:System.InvalidOperationException">More than one instance of the <see cref="T:System.Windows.Application"/> class is created per <see cref="T:System.AppDomain"/>.</exception>
        public App()
        {
            FrameworkElement.LanguageProperty.OverrideMetadata(
                typeof(FrameworkElement),
                new FrameworkPropertyMetadata(XmlLanguage.GetLanguage(CultureInfo.CurrentCulture.IetfLanguageTag)));
        }

        /// <summary>
        /// Gets a value indicating whether this instance has unhandled exception.
        /// </summary>
        /// <value>
        /// <c>true</c> if this instance has unhandled exception; otherwise, <c>false</c>.
        /// </value>
        internal bool HasUnhandledException { get; private set; }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Activated"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.EventArgs"/> that contains the event data.</param>
        protected override void OnActivated(EventArgs e)
        {
            if (this.isActivated)
            {
                return;
            }

            this.isActivated = true;

            this.InitialiseApp();
        }

        /// <summary>
        /// Raises the <see cref="E:System.Windows.Application.Exit"/> event.
        /// </summary>
        /// <param name="e">An <see cref="T:System.Windows.ExitEventArgs"/> that contains the event data.</param>
        protected override void OnExit(ExitEventArgs e)
        {
            if (this.applicationController == null)
            {
                return;
            }

            this.applicationController.SaveProjectLayout();
        }

        /// <summary>
        /// Initialises the app.
        /// </summary>
        private void InitialiseApp()
        {
            EventManager.RegisterClassHandler(typeof(UIElement), UIElement.PreviewMouseWheelEvent, new RoutedEventHandler(MouseWheelScrollBubbler.HandleMouseWheel), true);

            this.applicationController = new ApplicationController(Current.MainWindow as MainAppWindow);
        }

        /// <summary>
        /// Handles the DispatcherUnhandledException event of the Application.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Threading.DispatcherUnhandledExceptionEventArgs"/> instance containing the event data.</param>
        private void OnAppDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            if (this.isShowingErrorMessage)
            {
                return;
            }

            this.isShowingErrorMessage = true;

            var sb = new StringBuilder();
            var ex = e.Exception;

            sb.AppendLine("An unhandled exception has occured and the application needs to close. Exception details:");
            sb.AppendLine();

            while (ex != null)
            {
                sb.AppendLine(ex.Message);
                ex = ex.InnerException;
            }

            sb.AppendLine();
            sb.AppendLine("Save exception details to file?");

            if (MessageBox.Show(
                sb.ToString(), Settings.Default.ApplicationTitle, MessageBoxButton.YesNo, MessageBoxImage.Error) == MessageBoxResult.Yes)
            {
                if (!string.IsNullOrEmpty(e.Exception.StackTrace))
                {
                    sb.AppendLine();
                    sb.AppendLine(e.Exception.StackTrace);
                }

                var fileSaveDialog = new SaveFileDialog
                    {
                        Filter = "Text File|*.txt",
                        Title = "Save exception to file:"
                    };

                if ((bool)fileSaveDialog.ShowDialog(Current.MainWindow))
                {
                    using (var sr = new StreamWriter(fileSaveDialog.FileName, false))
                    {
                        sr.Write(sb.ToString());
                        sr.Flush();
                        sr.Close();
                    }
                }
            }

            e.Handled = true;

            this.HasUnhandledException = true;

            this.Shutdown();
        }
    }
}


text:
package dagger.producers.internal;

import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Maps.newLinkedHashMapWithExpectedSize;

import com.google.common.collect.ImmutableMap;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import dagger.internal.Beta;
import dagger.producers.Producer;
import java.util.Map;

/**
 * A {@link Producer} implementation used to implement {@link Map} bindings. This factory returns an
 * immediate future of {@code Map<K, Producer<V>>} when calling {@link #get}.
 *
 * @author Jesse Beder
 */
@Beta
public final class MapOfProducerProducer<K, V> extends AbstractProducer<Map<K, Producer<V>>> {
  private static final MapOfProducerProducer<Object, Object> EMPTY =
      new MapOfProducerProducer<Object, Object>(ImmutableMap.<Object, Producer<Object>>of());

  private final ImmutableMap<K, Producer<V>> contributingMap;

  /** Returns a new {@link Builder}. */
  public static <K, V> Builder<K, V> builder(int size) {
    return new Builder<K, V>(size);
  }

  /** Returns a producer of an empty map. */
  @SuppressWarnings("unchecked") // safe contravariant cast
  public static <K, V> MapOfProducerProducer<K, V> empty() {
    return (MapOfProducerProducer<K, V>) EMPTY;
  }

  private MapOfProducerProducer(ImmutableMap<K, Producer<V>> contributingMap) {
    this.contributingMap = contributingMap;
  }

  @Override
  public ListenableFuture<Map<K, Producer<V>>> compute() {
    return Futures.<Map<K, Producer<V>>>immediateFuture(contributingMap);
  }

  /**
   * A builder to help build the {@link MapOfProducerProducer}
   */
  public static final class Builder<K, V> {
    private final Map<K, Producer<V>> mapBuilder;

    private Builder(int size) {
      this.mapBuilder = newLinkedHashMapWithExpectedSize(size);
    }

    /** Returns a new {@link MapOfProducerProducer}. */
    public MapOfProducerProducer<K, V> build() {
      return new MapOfProducerProducer<K, V>(ImmutableMap.copyOf(mapBuilder));
    }

    /** Associates k with producerOfValue in {@code Builder}. */
    public Builder<K, V> put(K key, Producer<V> producerOfValue) {
      checkNotNull(key, "key");
      checkNotNull(producerOfValue, "producer of value");
      mapBuilder.put(key, producerOfValue);
      return this;
    }
  }
}


text:
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { replaceState } from 'redux-router';
import Joi from 'joi';

import notify from '../actions/notification/notify';
import resetNotifications from '../actions/notification/reset';
import sendResetPasswordLink from '../actions/users/send_reset_password_link';
import validate from '../actions/form/validate_schema';

import Content from './Content';

import TopBar from '../components/TopBar';
import Notification from '../components/Notification';
import Input from '../components/Input';
import SubmitButton from '../components/SubmitButton';

class ForgotPassword extends Component {
  constructor(props) {
    super(props);
    this.state = {
      inProgress: false,
      form: {
        email: ''
      }
    };
    this.schema = Joi.object().keys({
      email: Joi.string().email().required()
    });
  }

  render() {
    return (

        <TopBar title='Forgot your password' />
        <Content>
          <Notification {...this.props} />

            We will send you an email with a link to reset your password.

          <form
            name='forgot'
            onSubmit={this.handleSubmit.bind(this)}
            className='ForgotPassword-form'>
            <Input
              type='email'
              placeholder='email@example.com'
              value={this.state.form.email}
              hasError={this.props.error.email}
              handleChange={this.handleChange.bind(this)} />
            <SubmitButton
              inProgress={this.state.inProgress}>
              Send email
            </SubmitButton>
          </form>
        </Content>

    );
  }

  handleChange(email) {
    this.setState({form: {email} });
  }

  handleSubmit(event) {
    const {
      sendResetPasswordLink,
      notify,
      validate
    } = this.props;

    event.preventDefault();

    this.setState({ inProgress: true });

    validate(this.state.form, this.schema)
      .then(() => sendResetPasswordLink(this.state.form.email))
      .then(() => notify('success', 'Email sent'))
      .catch(({message}) => notify('error', message))
      .then(() => this.setState({ inProgress: false }));
  }

}

export default connect(mapStateToProps, {
  replaceState,
  notify,
  resetNotifications,
  sendResetPasswordLink,
  validate
})(ForgotPassword);

function mapStateToProps({notification, form}) {
  return {
    notification,
    error: form.schema.error
  };
}


text:
<?php

namespace Google\Service\Transcoder;

class PubsubDestination extends \Google\Model
{
  /**
   * @var string
   */
  public $topic;

  /**
   * @param string
   */
  public function setTopic($topic)
  {
    $this->topic = $topic;
  }
  /**
   * @return string
   */
  public function getTopic()
  {
    return $this->topic;
  }
}

// Adding a class alias for backwards compatibility with the previous class name.
class_alias(PubsubDestination::class, 'Google_Service_Transcoder_PubsubDestination');


text:
var mensaje = "Hola Mundo! \nQué fácil es incluir \'comillas simples\'\ny \"comillas dobles\"";
alert(mensaje + "\nAlert");
document.write(mensaje + "<br> write");
console.log(mensaje + "\nEn la consola");


text:
#include "pbcontroller.h"

#include <cinttypes>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <getopt.h>
#include <iostream>
#include <pwd.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <thread>
#include <unistd.h>

#include "config.h"
#include "configcontainer.h"
#include "configexception.h"
#include "configparser.h"
#include "logger.h"
#include "matcherexception.h"
#include "nullconfigactionhandler.h"
#include "pbview.h"
#include "poddlthread.h"
#include "queueloader.h"
#include "strprintf.h"
#include "utils.h"

using namespace newsboat;

static void ctrl_c_action(int sig)
{
	LOG(Level::DEBUG, "caugh signal %d", sig);
	Stfl::reset();
	::exit(EXIT_FAILURE);
}

namespace podboat {

/**
 * \brief Try to setup XDG style dirs.
 *
 * returns false, if that fails
 */
bool PbController::setup_dirs_xdg(const char* env_home)
{
	const char* env_xdg_config;
	const char* env_xdg_data;
	std::string xdg_config_dir;
	std::string xdg_data_dir;

	env_xdg_config = ::getenv("XDG_CONFIG_HOME");
	if (env_xdg_config) {
		xdg_config_dir = env_xdg_config;
	} else {
		xdg_config_dir = env_home;
		xdg_config_dir.push_back(NEWSBEUTER_PATH_SEP);
		xdg_config_dir.append(".config");
	}

	env_xdg_data = ::getenv("XDG_DATA_HOME");
	if (env_xdg_data) {
		xdg_data_dir = env_xdg_data;
	} else {
		xdg_data_dir = env_home;
		xdg_data_dir.push_back(NEWSBEUTER_PATH_SEP);
		xdg_data_dir.append(".local");
		xdg_data_dir.push_back(NEWSBEUTER_PATH_SEP);
		xdg_data_dir.append("share");
	}

	xdg_config_dir.push_back(NEWSBEUTER_PATH_SEP);
	xdg_config_dir.append(NEWSBOAT_SUBDIR_XDG);

	xdg_data_dir.push_back(NEWSBEUTER_PATH_SEP);
	xdg_data_dir.append(NEWSBOAT_SUBDIR_XDG);

	bool config_dir_exists =
		0 == access(xdg_config_dir.c_str(), R_OK | X_OK);

	if (!config_dir_exists) {
		std::cerr << strprintf::fmt(
				_("XDG: configuration directory '%s' not "
					"accessible, "
					"using '%s' instead."),
				xdg_config_dir,
				config_dir)
			<< std::endl;

		return false;
	}

	/* Invariant: config dir exists.
	 *
	 * At this point, we're confident we'll be using XDG. We don't check if
	 * data dir exists, because if it doesn't we'll create it. */

	config_dir = xdg_config_dir;

	// create data directory if it doesn't exist
	int ret = utils::mkdir_parents(xdg_data_dir, 0700);
	if (ret == -1) {
		LOG(Level::CRITICAL,
			"Couldn't create `%s'",
			xdg_data_dir);
		::exit(EXIT_FAILURE);
	}

	/* in config */
	config_file =
		config_dir + NEWSBEUTER_PATH_SEP + config_file;

	/* in data */
	const std::string LOCK_SUFFIX(".lock");
	lock_file = xdg_data_dir + NEWSBEUTER_PATH_SEP + LOCK_SUFFIX;
	queue_file =
		xdg_data_dir + NEWSBEUTER_PATH_SEP + queue_file;

	return true;
}

PbController::PbController()
	: config_file("config")
	, queue_file("queue")
	, max_dls(1)
	, lock_file("pb-lock.pid")
	, keys(KM_PODBOAT)
{
	char* cfgdir;
	if (!(cfgdir = ::getenv("HOME"))) {
		struct passwd* spw = ::getpwuid(::getuid());
		if (spw) {
			cfgdir = spw->pw_dir;
		} else {
			std::cout << _("Fatal error: couldn't determine home "
					"directory!")
				<< std::endl;
			std::cout << strprintf::fmt(
					_("Please set the HOME "
						"environment variable or add a "
						"valid user for UID %u!"),
					::getuid())
				<< std::endl;
			::exit(EXIT_FAILURE);
		}
	}
	config_dir = cfgdir;

	if (setup_dirs_xdg(cfgdir)) {
		return;
	}

	config_dir.push_back(NEWSBEUTER_PATH_SEP);
	config_dir.append(NEWSBOAT_CONFIG_SUBDIR);

	// create configuration directory if it doesn't exist
	int ret = ::mkdir(config_dir.c_str(), 0700);
	if (ret && errno != EEXIST) {
		std::cerr << strprintf::fmt(
				_("Fatal error: couldn't create "
					"configuration directory `%s': (%i) %s"),
				config_dir,
				errno,
				std::strerror(errno))
			<< std::endl;
		::exit(EXIT_FAILURE);
	}

	config_file = config_dir + NEWSBEUTER_PATH_SEP + config_file;
	queue_file = config_dir + NEWSBEUTER_PATH_SEP + queue_file;
	lock_file = config_dir + NEWSBEUTER_PATH_SEP + lock_file;
}

void PbController::initialize(int argc, char* argv[])
{
	int c;

	::signal(SIGINT, ctrl_c_action);

	static const char getopt_str[] = "C:q:d:l:havV";
	static const struct option longopts[] = {
		{"config-file", required_argument, 0, 'C'},
		{"queue-file", required_argument, 0, 'q'},
		{"log-file", required_argument, 0, 'd'},
		{"log-level", required_argument, 0, 'l'},
		{"help", no_argument, 0, 'h'},
		{"autodownload", no_argument, 0, 'a'},
		{"version", no_argument, 0, 'v'},
		{0, 0, 0, 0}
	};

	while ((c = ::getopt_long(argc, argv, getopt_str, longopts, nullptr)) !=
		-1) {
		switch (c) {
		case ':':
		case '?':
			print_usage(argv[0]);
			exit(EXIT_FAILURE);
		case 'C':
			config_file = optarg;
			break;
		case 'q':
			queue_file = optarg;
			break;
		case 'a':
			automatic_dl = true;
			break;
		case 'd':
			Logger::set_logfile(optarg);
			break;
		case 'l': {
			Level l = static_cast<Level>(atoi(optarg));
			if (l >= Level::USERERROR && l <= Level::DEBUG) {
				Logger::set_loglevel(l);
			} else {
				std::cerr << strprintf::fmt(_("%s: %d: invalid "
							"loglevel value"),
						argv[0],
						static_cast<int>(l))
					<< std::endl;
				exit(EXIT_FAILURE);
			}
		}
		break;
		case 'h':
			print_usage(argv[0]);
			exit(EXIT_SUCCESS);
		}
	};

	std::cout << strprintf::fmt(
			_("Starting %s %s..."), "Podboat", utils::program_version())
		<< std::endl;

	fslock = std::unique_ptr<FsLock>(new FsLock());
	pid_t pid;
	std::string error_message;
	if (!fslock->try_lock(lock_file, pid, error_message)) {
		if (pid != 0) {
			std::cout << strprintf::fmt(
					_("Error: an instance of %s is already "
						"running (PID: %s)"),
					"Podboat",
					std::to_string(pid))
				<< std::endl;
		} else {
			std::cout << _("Error: ") << error_message << std::endl;
		}
		exit(EXIT_FAILURE);
	}

	std::cout << _("Loading configuration...");
	std::cout.flush();

	ConfigParser cfgparser;
	cfg.register_commands(cfgparser);
	colorman.register_commands(cfgparser);

	cfgparser.register_handler("bind-key", keys);
	cfgparser.register_handler("unbind-key", keys);

	NullConfigActionHandler null_cah;
	cfgparser.register_handler("macro", null_cah);
	cfgparser.register_handler("ignore-article", null_cah);
	cfgparser.register_handler("always-download", null_cah);
	cfgparser.register_handler("define-filter", null_cah);
	cfgparser.register_handler("highlight", null_cah);
	cfgparser.register_handler("highlight-article", null_cah);
	cfgparser.register_handler("highlight-feed", null_cah);
	cfgparser.register_handler("reset-unread-on-update", null_cah);
	cfgparser.register_handler("run-on-startup", null_cah);

	try {
		cfgparser.parse_file("/etc/newsboat/config");
		cfgparser.parse_file(config_file);
	} catch (const ConfigException& ex) {
		std::cout << ex.what() << std::endl;
		exit(EXIT_FAILURE);
	}
}

int PbController::run(PbView& v)
{
	v.apply_colors_to_all_forms();

	max_dls = cfg.get_configvalue_as_int("max-downloads");

	std::cout << _("done.") << std::endl;

	ql.reset(new QueueLoader(queue_file, cfg, [&]() {
		v.set_view_update_necessary();
	}));
	ql->reload(downloads_);

	v.set_keymap(&keys);

	v.run(automatic_dl, cfg.get_configvalue_as_bool("wrap-scroll"));

	Stfl::reset();

	std::cout << _("Cleaning up queue...");
	std::cout.flush();

	ql->reload(downloads_);

	std::cout << _("done.") << std::endl;

	return EXIT_SUCCESS;
}

void PbController::print_usage(const char* argv0)
{
	auto msg = strprintf::fmt(
			_("%s %s\nusage %s [-C <file>] [-q <file>] [-h]\n"),
			"Podboat",
			utils::program_version(),
			argv0);
	std::cout << msg;

	struct Arg {
		const char name;
		const std::string longname;
		const std::string params;
		const std::string desc;
	};

	static const std::vector<Arg> args = {
		{
			'C',
			"config-file",
			_s("<configfile>"),
			_s("read configuration from <configfile>")
		},
		{
			'q',
			"queue-file",
			_s("<queuefile>"),
			_s("use <queuefile> as queue file")
		},
		{'a', "autodownload", "", _s("start download on startup")},
		{
			'l',
			"log-level",
			_s("<loglevel>"),
			_s("write a log with a certain loglevel (valid values: "
				"1 to "
				"6)")
		},
		{
			'd',
			"log-file",
			_s("<logfile>"),
			_s("use <logfile> as output log file")
		},
		{'h', "help", "", _s("this help")}
	};

	for (const auto& a : args) {
		std::string longcolumn("-");
		longcolumn += a.name;
		longcolumn += ", --" + a.longname;
		longcolumn += a.params.size() > 0 ? "=" + a.params : "";
		std::cout << "\t" << longcolumn;
		for (unsigned int j = 0; j < utils::gentabs(longcolumn); j++) {
			std::cout << "\t";
		}
		std::cout << a.desc << std::endl;
	}

	std::cout << std::endl
		<< _("Support at #newsboat at https://libera.chat or on our mailing "
			"list https://groups.google.com/g/newsboat")
		<< std::endl
		<< _("For more information, check out https://newsboat.org/")
		<< std::endl;
}

unsigned int PbController::downloads_in_progress()
{
	unsigned int count = 0;
	for (const auto& dl : downloads_) {
		if (dl.status() == DlStatus::DOWNLOADING) {
			++count;
		}
	}
	return count;
}

unsigned int PbController::get_maxdownloads()
{
	return max_dls;
}

void PbController::purge_queue()
{
	if (ql != nullptr) {
		ql->reload(downloads_, true);
	}
}

double PbController::get_total_kbps()
{
	double result = 0.0;
	for (const auto& dl : downloads_) {
		if (dl.status() == DlStatus::DOWNLOADING) {
			result += dl.kbps();
		}
	}
	return result;
}

void PbController::start_downloads()
{
	int dl2start = get_maxdownloads() - downloads_in_progress();
	for (auto& download : downloads_) {
		if (dl2start == 0) {
			break;
		}

		if (download.status() == DlStatus::QUEUED) {
			start_download(download);
			--dl2start;
		}
	}
}

void PbController::start_download(Download& item)
{
	std::thread t{PodDlThread(&item, &cfg)};
	t.detach();
}

void PbController::increase_parallel_downloads()
{
	++max_dls;
}

void PbController::decrease_parallel_downloads()
{
	if (max_dls > 1) {
		--max_dls;
	}
}

void PbController::play_file(const std::string& file)
{
	std::string cmdline;
	std::string player = cfg.get_configvalue("player");
	if (player == "") {
		return;
	}
	cmdline.append(player);
	cmdline.append(" '");
	cmdline.append(utils::replace_all(file, "'", "'\\''"));
	cmdline.append("'");
	Stfl::reset();
	utils::run_interactively(cmdline, "PbController::play_file");
}

} // namespace podboat


text:
function zpadDateOrTimeField(val) {
    val = val || 0;

    return val > 9  ? val.toString() : "0" + val;
}

function renderDate(iso8601Utc) {
    var date = new Date(iso8601Utc);

    var year = date.getFullYear();
    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hours = date.getHours();
    var minutes = date.getMinutes();

    var dateStr = zpadDateOrTimeField(month) + "/"
                + zpadDateOrTimeField(day) + "/"
                + year + " "
                + zpadDateOrTimeField(hours) + ":"
                + zpadDateOrTimeField(minutes);

    document.write(dateStr);
}


text:
    #{{index + 1}}
    <input type="checkbox" formControlName="isMutated" id="mutated" />

    {{labelSiteMutation(siteGroup.controls.isMutated)}}
    <button type="button" class="btn btn-xs btn-danger gene-button" (click)="removeSite()">X</button>
    <select class="form-control auto-width display-inline" formControlName="site">
        <option *ngFor="let item of siteItems" [ngValue]="item">{{getSiteName(item)}}</option>
    </select>


text:
from __future__ import (nested_scopes, generators, division, absolute_import, with_statement,
                        print_function, unicode_literals)

from pants.backend.core.tasks.task import Task
from pants.backend.android.distribution.android_distribution import AndroidDistribution

class AndroidTask(Task):
  # The flag for release/debug will eventually go here (as we build out the ops in other tasks)
  @classmethod
  def register_options(cls, register):
    super(AndroidTask, cls).register_options(register)
    register('--sdk-path',
             help='Use the Android SDK at this path.')

  def __init__(self, *args, **kwargs):
    super(AndroidTask, self).__init__(*args, **kwargs)
    self.forced_sdk = self.get_options().sdk_path or None
    self._android_sdk = None

  @property
  def android_sdk(self):
    if self._android_sdk is None:
      self._android_sdk = AndroidDistribution.cached(self.forced_sdk)
    return self._android_sdk


text:
<mat-form-field appearance="outline" class="w100">
  <mat-label>Artifact</mat-label>
  <input
    #input
    name="artifactName"
    matInput
    [formControl]="controls.artifactName"
    [matAutocomplete]="auto"
    placeholder="Search for artifacts by name, filename, registry key, …"
  />
  <mat-autocomplete
    #auto="matAutocomplete"
    (optionSelected)="selectArtifact($event.option.value)"
  >
    <mat-option
      *ngFor="let artifact of filteredArtifactDescriptors$ | async; trackBy: trackArtifactDescriptor"
      [value]="artifact.name"
      class="artifact-option"
      [class.unavailable]="!artifact.availableOnClient"
    >

{{ artifact.name }}

        {{artifact.doc}}

        Only available on {{printOs(artifact)}}.

          {{artifact.sampleSource.name}}
          {{artifact.sampleSource.value}}
           1">
            and {{artifact.totalSources - 1}} more

    </mat-option>
  </mat-autocomplete>
</mat-form-field>

  <mat-tree
    [dataSource]="dataSource"
    [treeControl]="treeControl"
    class="sources-tree"
  >

    <mat-tree-node *matTreeNodeDef="let node" matTreeNodeToggle>

          <button mat-icon-button disabled [attr.aria-hidden]="true"></button>
          {{node.name}}

            <ng-container *ngIf="node.type === SourceType.FILE; else fallback">
              <glob-expression-explanation
                [globExpression]="source"
                [clientId]="clientId$ | async"
              ></glob-expression-explanation>
            </ng-container>
            <ng-template #fallback>{{source}}</ng-template>

    </mat-tree-node>

    <mat-nested-tree-node *matTreeNodeDef="let node; when: hasChild">

          <button
            mat-icon-button
            matTreeNodeToggle
            disabled
            [attr.aria-label]="'Toggle ' + node.name"
          >
            <mat-icon class="mat-icon-rtl-mirror chevron"
              >arrow_drop_down</mat-icon
            >
          </button>
          {{node.name}}: {{node.values.join(" ")}}

          <ng-container matTreeNodeOutlet></ng-container>

    </mat-nested-tree-node>
  </mat-tree>

 0" class="links">
    See:
    {{url}}


text:
namespace cc {
class TaskGraphRunner;
}  // namespace cc

namespace content {

class CompositorImpl;

class CompositorDependenciesAndroid {
 public:
  static CompositorDependenciesAndroid& Get();

  CompositorDependenciesAndroid(const CompositorDependenciesAndroid&) = delete;
  CompositorDependenciesAndroid& operator=(
      const CompositorDependenciesAndroid&) = delete;

  cc::TaskGraphRunner* GetTaskGraphRunner();

  viz::HostFrameSinkManager* host_frame_sink_manager() {
    return &host_frame_sink_manager_;
  }

  viz::FrameSinkId AllocateFrameSinkId();
  void TryEstablishVizConnectionIfNeeded();
  void OnCompositorVisible(CompositorImpl* compositor);
  void OnCompositorHidden(CompositorImpl* compositor);

 private:
  friend class base::NoDestructor<CompositorDependenciesAndroid>;

  static void ConnectVizFrameSinkManagerOnMainThread(
      mojo::PendingReceiver<viz::mojom::FrameSinkManager> receiver,
      mojo::PendingRemote<viz::mojom::FrameSinkManagerClient> client,
      const viz::DebugRendererSettings& debug_renderer_settings);

  CompositorDependenciesAndroid();
  ~CompositorDependenciesAndroid();

  void CreateVizFrameSinkManager();
  void EnqueueLowEndBackgroundCleanup();
  void DoLowEndBackgroundCleanup();
  void OnVisibilityChanged();

  viz::HostFrameSinkManager host_frame_sink_manager_;
  viz::FrameSinkIdAllocator frame_sink_id_allocator_;

  // A task which runs cleanup tasks on low-end Android after a delay. Enqueued
  // when we hide, canceled when we're shown.
  base::CancelableOnceClosure low_end_background_cleanup_task_;

  // A callback which connects to the viz service on the main thread.
  base::OnceClosure pending_connect_viz_on_main_thread_;

  // The set of visible CompositorImpls.
  base::flat_set<CompositorImpl*> visible_compositors_;

  std::unique_ptr<cc::TaskGraphRunner> task_graph_runner_;
};

}  // namespace content

#endif  // CONTENT_BROWSER_RENDERER_HOST_COMPOSITOR_DEPENDENCIES_ANDROID_H_


text:
class LogFile < ActiveRecord::Base
end


text:
package com.jcodeshare.webtemplate.service.email;

import com.jcodeshare.webtemplate.service.email.EmailService;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

/**
 * @author YP Leung
 */
public class EmailServiceImpl implements EmailService {

    public void sendMessage(MimeMessage message) {
        try{
            Transport.send(message);
            System.out.println("Sent message successfully....");
         }catch (MessagingException me) {
            me.printStackTrace();
         }
    }
}


text:
package com.nikhaldimann.viewselector.robolectric;

import android.app.Activity;
import android.os.Bundle;

/**
 * Robolectric 1.2 can't see resources from an Android library, so we
 * need to create a separate activity here with a layout defined in
 * this project rather than the shared test library.
 */
public class RobolectricTestHelloWorldActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hello_world);
    }

}


text:
package org.deeplearning4j.spark.models.sequencevectors.functions;

import lombok.NonNull;
import org.apache.spark.api.java.function.VoidFunction;
import org.apache.spark.broadcast.Broadcast;
import org.deeplearning4j.models.embeddings.learning.ElementsLearningAlgorithm;
import org.deeplearning4j.models.embeddings.learning.SequenceLearningAlgorithm;
import org.deeplearning4j.models.embeddings.loader.VectorsConfiguration;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.sequencevectors.sequence.SequenceElement;
import org.deeplearning4j.models.sequencevectors.sequence.ShallowSequenceElement;
import org.deeplearning4j.models.word2vec.wordstore.VocabCache;
import org.deeplearning4j.spark.models.sequencevectors.learning.SparkElementsLearningAlgorithm;
import org.deeplearning4j.spark.models.sequencevectors.learning.SparkSequenceLearningAlgorithm;
import org.nd4j.linalg.exception.ND4JIllegalStateException;
import org.nd4j.parameterserver.distributed.VoidParameterServer;
import org.nd4j.parameterserver.distributed.conf.VoidConfiguration;
import org.nd4j.parameterserver.distributed.logic.sequence.BasicSequenceProvider;
import org.nd4j.parameterserver.distributed.messages.Frame;
import org.nd4j.parameterserver.distributed.messages.TrainingMessage;
import org.nd4j.parameterserver.distributed.training.TrainingDriver;
import org.nd4j.parameterserver.distributed.transport.RoutedTransport;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

/**
 * @author raver119@gmail.com
 */
public class PartitionTrainingFunction<T extends SequenceElement> implements VoidFunction<Iterator<Sequence<T>>> {
    protected Broadcast<VocabCache<ShallowSequenceElement>> vocabCacheBroadcast;
    protected Broadcast<VectorsConfiguration> configurationBroadcast;
    protected Broadcast<VoidConfiguration> paramServerConfigurationBroadcast;

    protected transient VoidParameterServer paramServer;
    protected transient VectorsConfiguration vectorsConfiguration;

    protected transient SparkElementsLearningAlgorithm elementsLearningAlgorithm;
    protected transient SparkSequenceLearningAlgorithm sequenceLearningAlgorithm;
    protected transient VocabCache<ShallowSequenceElement> shallowVocabCache;

    protected transient TrainingDriver<? extends TrainingMessage> driver;

    public PartitionTrainingFunction(@NonNull Broadcast<VocabCache<ShallowSequenceElement>> vocabCacheBroadcast,
                    @NonNull Broadcast<VectorsConfiguration> vectorsConfigurationBroadcast,
                    @NonNull Broadcast<VoidConfiguration> paramServerConfigurationBroadcast) {
        this.vocabCacheBroadcast = vocabCacheBroadcast;
        this.configurationBroadcast = vectorsConfigurationBroadcast;
        this.paramServerConfigurationBroadcast = paramServerConfigurationBroadcast;
    }

    @SuppressWarnings("unchecked")
    @Override
    public void call(Iterator<Sequence<T>> sequenceIterator) throws Exception {
        /**
         * first we initialize
         */
        if (vectorsConfiguration == null)
            vectorsConfiguration = configurationBroadcast.getValue();

        if (paramServer == null) {
            paramServer = VoidParameterServer.getInstance();

            if (elementsLearningAlgorithm == null) {
                try {
                    elementsLearningAlgorithm = (SparkElementsLearningAlgorithm) Class
                                    .forName(vectorsConfiguration.getElementsLearningAlgorithm()).newInstance();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            driver = elementsLearningAlgorithm.getTrainingDriver();

            // FIXME: init line should probably be removed, basically init happens in VocabRddFunction
            paramServer.init(paramServerConfigurationBroadcast.getValue(), new RoutedTransport(), driver);
        }

        if (shallowVocabCache == null)
            shallowVocabCache = vocabCacheBroadcast.getValue();

        if (elementsLearningAlgorithm == null && vectorsConfiguration.getElementsLearningAlgorithm() != null) {
            // TODO: do ELA initialization
            try {
                elementsLearningAlgorithm = (SparkElementsLearningAlgorithm) Class
                                .forName(vectorsConfiguration.getElementsLearningAlgorithm()).newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        if (elementsLearningAlgorithm != null)
            elementsLearningAlgorithm.configure(shallowVocabCache, null, vectorsConfiguration);

        if (sequenceLearningAlgorithm == null && vectorsConfiguration.getSequenceLearningAlgorithm() != null) {
            // TODO: do SLA initialization
            try {
                sequenceLearningAlgorithm = (SparkSequenceLearningAlgorithm) Class
                                .forName(vectorsConfiguration.getSequenceLearningAlgorithm()).newInstance();
                sequenceLearningAlgorithm.configure(shallowVocabCache, null, vectorsConfiguration);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        if (sequenceLearningAlgorithm != null)
            sequenceLearningAlgorithm.configure(shallowVocabCache, null, vectorsConfiguration);

        if (elementsLearningAlgorithm == null && sequenceLearningAlgorithm == null) {
            throw new ND4JIllegalStateException("No LearningAlgorithms specified!");
        }

        List<Sequence<ShallowSequenceElement>> sequences = new ArrayList<>();

        // now we roll throw Sequences and prepare/convert/"learn" them
        while (sequenceIterator.hasNext()) {
            Sequence<T> sequence = sequenceIterator.next();

            Sequence<ShallowSequenceElement> mergedSequence = new Sequence<>();
            for (T element : sequence.getElements()) {
                // it's possible to get null here, i.e. if frequency for this element is below minWordFrequency threshold
                ShallowSequenceElement reduced = shallowVocabCache.tokenFor(element.getStorageId());

                if (reduced != null)
                    mergedSequence.addElement(reduced);
            }

            // do the same with labels, transfer them, if any
            if (sequenceLearningAlgorithm != null && vectorsConfiguration.isTrainSequenceVectors()) {
                for (T label : sequence.getSequenceLabels()) {
                    ShallowSequenceElement reduced = shallowVocabCache.tokenFor(label.getStorageId());

                    if (reduced != null)
                        mergedSequence.addSequenceLabel(reduced);
                }
            }

            sequences.add(mergedSequence);
            if (sequences.size() >= 8) {
                trainAllAtOnce(sequences);
                sequences.clear();
            }
        }

        if (sequences.size() > 0) {
            // finishing training round, to make sure we don't have trails
            trainAllAtOnce(sequences);
            sequences.clear();
        }
    }

    protected void trainAllAtOnce(List<Sequence<ShallowSequenceElement>> sequences) {
        Frame bigFrame = new Frame(BasicSequenceProvider.getInstance().getNextValue());

        for (Sequence<ShallowSequenceElement> sequence : sequences) {
            Frame frame = elementsLearningAlgorithm.frameSequence(sequence, new AtomicLong(119L), 25e-3f);
            bigFrame.stackMessages(frame.getMessages());
        }

        if (bigFrame.size() > 0)
            paramServer.execDistributed(bigFrame);
    }
}


text:
require 'spec_helper'

RSpec.describe RubyPlayingCards::Deck do

  describe 'when building a deck of cards' do

    it 'should have 52 cards' do
      deck = RubyPlayingCards::Deck.new
      expect(deck.size).to eq(52)
    end

  end
end


text:
layout: post
title: Omniauth-Facebook With Devise
modified:
categories:
description:
tags: []
image:
feature:
credit:
creditlink:
comments:
share:
date: 2016-02-21T19:25:01-05:00
---
Instead of putting the burden on yourself and your team for implementing an authentication feature for your app, many programmers are deflecting the responsibility to tech giants such as Facebook, Google, and Twitter to securely log in their users. Besides saving your team from writing code, the major benefit of using another authentication provider is that your app becomes considerably more robust against security vulnerabilities.

Omniauth is the miraculous gem that allows you to use alternative authentication providers in your app. For the purpose of this blog I'm going to demonstrate how you can use [Omniauth-Facebook](https://github.com/mkdynamic/omniauth-facebook) with [Devise](https://github.com/plataformatec/devise), a popular gem used for user authentication.

First, you'll need to include the following gems in your Gemfile:

{% highlight ruby linenos %}
gem 'devise'
gem 'omniauth-facebook'
{% endhighlight %}

Now run bundle install

Next, create your User model with Devise by entering the following two commands in your terminal:

{% highlight ruby linenos %}
rails generate devise:install
rails g devise User
{% endhighlight %}

This will create a migration file for your User model with all the predefined fields that ship with Devise. You can view all of these attributes by going to db/migrate/20160215180931_devise_create_users.rb (your file name will have different numbers).

Before you run rake db:migrate you'll need to add two more fields to the User table so you'll be able to create users with data returned to you from Facebook.

{% highlight ruby linenos %}
rails g migration AddOmniauthToUsers provider:string uid:string
{% endhighlight %}

Now you can run rake db:migrate

Earlier when you installed Devise you created several files for your rails application, and one of those files happens to be config/initializers/devise.rb. Go to that file to declare Facebook as your authentication provider and fill in your Facebook APP_ID and APP_SECRET:

{% highlight ruby linenos %}
config.omniauth :facebook, "APP_ID", "APP_SECRET"
{% endhighlight %}

To get an APP_ID and APP_SECRET you'll have to create an app at the [Facebook Developers website](https://developers.facebook.com/). If this is your first time creating a Facebook app then follow this [guide](https://developers.facebook.com/docs/apps/register).

In order for Devise to be aware that Omniauth exists in your application you'll need to let your User model know. Include the following code in app/models/user.rb:

{% highlight ruby linenos %}
devise :omniauthable, :omniauth providers => [:facebook]
{% endhighlight %}

The above code creates these two routes or url methods:
user_omniauth_authorize_path(proivider)
user_omniauth_callback_path(proivider)

To activate the user_omniauth_authrorize_path you'll need to display a link in your application. Input the following link in the view where you would like your user to have the option to sign in through Facebook:

{% highlight erb linenos %}
<%= link_to "Sign in with Facebook", user_omniauth_authorize_path(:facebook) %>
{% endhighlight %}

Although you won't be explicitly calling user_omniauth_callback_path in your views, it's essential to have in your app. After a user signs in through Facebook they are redirected to this callback url within your application where you'll have access to the data you received from Facebook. To declare this callback url update your config/routes.rb file:

{% highlight ruby linenos %}
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }
{% endhighlight %}

Now we'll need to create a controller so we can create users with Facebook's authentication and sign them in to our app. Label the controller file app/controllers/users/omniauth_callbacks_controller.rb and set up the file like so:

{% highlight ruby linenos %}
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.from_omniauth(request.env["omniauth.auth"])

    @user.save if !@user
    sign_in_and_redirect @user, :event => :authentication
    set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
  end

  def failure
    redirect_to root_path
  end
end
{% endhighlight %}

On line 3 inside the facebook method you'll notice we're calling the from_omniauth method on the User class. To utilize this method we'll have to define it, so head over to app/models/user.rb and update your file with the following code:

{% highlight ruby linenos %}
def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
    user.name = auth.info.name
    user.password = Devise.friendly_token[0,20]
  end
end
{% endhighlight %}

Inside this method we use the data that is provided by Facebook to either find a user or create one. The first_or_create method is pretty self-explanatory: it returns the user if they exist in the database or it creates a new user. It's important to note that when initializing a new user the first_or_create method automatically sets the uid and provider fields with their appropriate data.

To create a new user for your app you will need to include at minimum the password field inside the first_or_create loop (remember the uid is provided for you by default). However, the programmer is free to use whatever data Facebook provides to incorporate into their user class. For instance, you can extract the users Facebook's profile picture to use in your application by adding user.image = auth.info.image inside the first_or_create loop.

In a nutshell, that's how to use Omniauth-Facebook in conjunction with Devise to allow your users to sign in securely to your website.


text:
class BuildsAddOwner < ActiveRecord::Migration
  def change
    change_table :builds do |t|
      t.references :owner, :polymorphic => true
    end
  end
end


text:
	<title>Append to a File Example </title>
	<link rel ="stylesheet" type="text/css" href="sample.css"  />

<?php
	$messageFile =fopen("message.txt", "a");

	fputs($messageFile, "This is being appended to message.txt\n");

	fclose($messageFile);

	print("
A message has been added to the message.txt file.
");
?>


text:
/**
 * unit tests for storage.Storage
 */

var storage = require(__dirname + "/../../").storage;
var errors = require(__dirname + "/../../").errors;

/**
 * constructorTest
 *
 * assert interface
 * @param test
 */
var interfaceTest = function(test) {
  test.expect(13);

  var s = new storage.Storage();
  test.equal(typeof s.length, "number");
  test.equal(typeof s.key, "function");
  test.equal(typeof s.keySync, "function");
  test.equal(typeof s.getItem, "function");
  test.equal(typeof s.getItemSync, "function");
  test.equal(typeof s.setItem, "function");
  test.equal(typeof s.setItemSync, "function");
  test.equal(typeof s.removeItem, "function");
  test.equal(typeof s.removeItemSync, "function");
  test.equal(typeof s.expire,  "function");
  test.equal(typeof s.expireSync, "function");
  test.equal(typeof s.clear, "function");
  test.equal(typeof s.clearSync, "function");
  test.done();
};

// export module
module.exports = {
  interfaceTest: interfaceTest
};


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

#include "chrome/browser/ui/views/javascript_tab_modal_dialog_view_views.h"

#include "base/callback.h"
#include "chrome/browser/ui/javascript_dialogs/javascript_tab_modal_dialog_manager_delegate_desktop.h"
#include "chrome/browser/ui/views/title_origin_label.h"
#include "components/constrained_window/constrained_window_views.h"
#include "content/public/browser/javascript_dialog_manager.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/strings/grit/ui_strings.h"
#include "ui/views/accessibility/view_accessibility.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/label.h"
#include "ui/views/controls/message_box_view.h"
#include "ui/views/controls/textfield/textfield.h"
#include "ui/views/layout/fill_layout.h"

JavaScriptTabModalDialogViewViews::~JavaScriptTabModalDialogViewViews() =
    default;

void JavaScriptTabModalDialogViewViews::CloseDialogWithoutCallback() {
  dialog_callback_.Reset();
  dialog_force_closed_callback_.Reset();
  GetWidget()->Close();
}

std::u16string JavaScriptTabModalDialogViewViews::GetUserInput() {
  return message_box_view_->GetInputText();
}

std::u16string JavaScriptTabModalDialogViewViews::GetWindowTitle() const {
  return title_;
}

bool JavaScriptTabModalDialogViewViews::ShouldShowCloseButton() const {
  return false;
}

views::View* JavaScriptTabModalDialogViewViews::GetInitiallyFocusedView() {
  auto* text_box = message_box_view_->GetVisiblePromptField();
  return text_box ? text_box : views::DialogDelegate::GetInitiallyFocusedView();
}

void JavaScriptTabModalDialogViewViews::AddedToWidget() {
  auto* bubble_frame_view = static_cast<views::BubbleFrameView*>(
      GetWidget()->non_client_view()->frame_view());
  bubble_frame_view->SetTitleView(CreateTitleOriginLabel(GetWindowTitle()));
  if (!message_text_.empty()) {
    GetWidget()->GetRootView()->GetViewAccessibility().OverrideDescription(
        message_text_);
  }
  // On some platforms, the platform accessibility API automatically
  // calculates the name of the native window based on the child RootView.
  // We override that calculation here so that we can present both the
  // title (e.g. "url.com says") and the message text on platforms where
  // the accessible description is ignored.
  GetViewAccessibility().OverrideNativeWindowTitle(l10n_util::GetStringFUTF16(
      IDS_CONCAT_TWO_STRINGS_WITH_COMMA, GetWindowTitle(), message_text_));
}

JavaScriptTabModalDialogViewViews::JavaScriptTabModalDialogViewViews(
    content::WebContents* parent_web_contents,
    content::WebContents* alerting_web_contents,
    const std::u16string& title,
    content::JavaScriptDialogType dialog_type,
    const std::u16string& message_text,
    const std::u16string& default_prompt_text,
    content::JavaScriptDialogManager::DialogClosedCallback dialog_callback,
    base::OnceClosure dialog_force_closed_callback)
    : title_(title),
      message_text_(message_text),
      default_prompt_text_(default_prompt_text),
      dialog_callback_(std::move(dialog_callback)),
      dialog_force_closed_callback_(std::move(dialog_force_closed_callback)) {
  SetModalType(ui::MODAL_TYPE_CHILD);
  SetDefaultButton(ui::DIALOG_BUTTON_OK);
  const bool is_alert = dialog_type == content::JAVASCRIPT_DIALOG_TYPE_ALERT;
  SetButtons(
      // Alerts only have an OK button, no Cancel, because there is no choice
      // being made.
      is_alert ? ui::DIALOG_BUTTON_OK
               : (ui::DIALOG_BUTTON_OK | ui::DIALOG_BUTTON_CANCEL));

  SetAcceptCallback(base::BindOnce(
      [](JavaScriptTabModalDialogViewViews* dialog) {
        // Remove the force-close callback to indicate that we were closed as a
        // result of user action.
        dialog->dialog_force_closed_callback_ = base::OnceClosure();
        if (dialog->dialog_callback_)
          std::move(dialog->dialog_callback_)
              .Run(true, dialog->message_box_view_->GetInputText());
      },
      base::Unretained(this)));
  SetCancelCallback(base::BindOnce(
      [](JavaScriptTabModalDialogViewViews* dialog) {
        // Remove the force-close callback to indicate that we were closed as a
        // result of user action.
        dialog->dialog_force_closed_callback_ = base::OnceClosure();
        if (dialog->dialog_callback_)
          std::move(dialog->dialog_callback_).Run(false, std::u16string());
      },
      base::Unretained(this)));
  RegisterWindowWillCloseCallback(base::BindOnce(
      [](JavaScriptTabModalDialogViewViews* dialog) {
        // If the force-close callback still exists at this point we're not
        // closed due to a user action (would've been caught in Accept/Cancel).
        if (dialog->dialog_force_closed_callback_)
          std::move(dialog->dialog_force_closed_callback_).Run();
      },
      base::Unretained(this)));

  message_box_view_ = new views::MessageBoxView(
      message_text, /* detect_directionality = */ true);
  if (dialog_type == content::JAVASCRIPT_DIALOG_TYPE_PROMPT)
    message_box_view_->SetPromptField(default_prompt_text);

  SetLayoutManager(std::make_unique<views::FillLayout>());
  AddChildView(message_box_view_.get());

  constrained_window::ShowWebModalDialogViews(this, parent_web_contents);
}

// static
JavaScriptTabModalDialogViewViews*
JavaScriptTabModalDialogViewViews::CreateAlertDialogForTesting(
    Browser* browser,
    std::u16string title,
    std::u16string message) {
  return new JavaScriptTabModalDialogViewViews(
      browser->tab_strip_model()->GetActiveWebContents(),
      browser->tab_strip_model()->GetActiveWebContents(), title,
      content::JAVASCRIPT_DIALOG_TYPE_ALERT, message, std::u16string(),
      base::NullCallback(), base::NullCallback());
}

BEGIN_METADATA(JavaScriptTabModalDialogViewViews, views::DialogDelegateView)
END_METADATA

// Creates a new JS dialog. Note the two callbacks; |dialog_callback| is for
// user responses, while |dialog_force_closed_callback| is for when Views
// forces the dialog closed without a user reply.
base::WeakPtr<javascript_dialogs::TabModalDialogView>
JavaScriptTabModalDialogManagerDelegateDesktop::CreateNewDialog(
    content::WebContents* alerting_web_contents,
    const std::u16string& title,
    content::JavaScriptDialogType dialog_type,
    const std::u16string& message_text,
    const std::u16string& default_prompt_text,
    content::JavaScriptDialogManager::DialogClosedCallback dialog_callback,
    base::OnceClosure dialog_force_closed_callback) {
  return (new JavaScriptTabModalDialogViewViews(
              web_contents_, alerting_web_contents, title, dialog_type,
              message_text, default_prompt_text, std::move(dialog_callback),
              std::move(dialog_force_closed_callback)))
      ->weak_factory_.GetWeakPtr();
}


text:
package com.litesuits.bluetooth.sample;

import android.app.Activity;
import android.app.AlertDialog;
import android.bluetooth.*;
import android.os.Bundle;
import android.widget.Toast;
import com.litesuits.bluetooth.LiteBleGattCallback;
import com.litesuits.bluetooth.LiteBluetooth;
import com.litesuits.bluetooth.conn.BleCharactCallback;
import com.litesuits.bluetooth.conn.BleDescriptorCallback;
import com.litesuits.bluetooth.conn.BleRssiCallback;
import com.litesuits.bluetooth.conn.LiteBleConnector;
import com.litesuits.bluetooth.exception.BleException;
import com.litesuits.bluetooth.exception.hanlder.DefaultBleExceptionHandler;
import com.litesuits.bluetooth.log.BleLog;
import com.litesuits.bluetooth.scan.PeriodMacScanCallback;
import com.litesuits.bluetooth.scan.PeriodScanCallback;
import com.litesuits.bluetooth.utils.BluetoothUtil;

import java.util.Arrays;

public class SampleActivity extends Activity {

    private static final String TAG = SampleActivity.class.getSimpleName();

    /**
     * mac和服务uuid纯属测试,测试时请替换真实参数。
     */
    public String UUID_SERVICE = "6e400000-0000-0000-0000-000011112222";

    public String UUID_CHAR_WRITE = "6e400001-0000-0000-0000-000011112222";
    public String UUID_CHAR_READ = "6e400002-0000-0000-0000-000011112222";

    public String UUID_DESCRIPTOR = "00002902-0000-1000-8000-00805f9b34fb";
    public String UUID_DESCRIPTOR_WRITE = "00002902-0000-1000-8000-00805f9b34fb";
    public String UUID_DESCRIPTOR_READ = "00002902-0000-1000-8000-00805f9b34fb";

    private static int TIME_OUT_SCAN = 10000;
    private static int TIME_OUT_OPERATION = 5000;
    private Activity activity;
    /**
     * 蓝牙主要操作对象,建议单例。
     */
    private static LiteBluetooth liteBluetooth;
    /**
     * 默认异常处理器
     */
    private DefaultBleExceptionHandler bleExceptionHandler;
    /**
     * mac和服务uuid纯属测试,测试时请替换真实参数。
     */
    private static String MAC = "00:00:00:AA:AA:AA";

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        activity = this;
        if (liteBluetooth == null) {
            liteBluetooth = new LiteBluetooth(activity);
        }
        liteBluetooth.enableBluetoothIfDisabled(activity, 1);
        bleExceptionHandler = new DefaultBleExceptionHandler(this);
    }

    /**
     * scan devices for a while
     */
    private void scanDevicesPeriod() {
        liteBluetooth.startLeScan(new PeriodScanCallback(TIME_OUT_SCAN) {
            @Override
            public void onScanTimeout() {
                dialogShow(TIME_OUT_SCAN + " Millis Scan Timeout! ");
            }

            @Override
            public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
                BleLog.i(TAG, "device: " + device.getName() + "  mac: " + device.getAddress()
                              + "  rssi: " + rssi + "  scanRecord: " + Arrays.toString(scanRecord));
            }
        });
    }

    /**
     * scan a specified device for a while
     */
    private void scanSpecifiedDevicePeriod() {
        liteBluetooth.startLeScan(new PeriodMacScanCallback(MAC, TIME_OUT_SCAN) {

            @Override
            public void onScanTimeout() {
                dialogShow(TIME_OUT_SCAN + " Millis Scan Timeout!  Device Not Found! ");
            }

            @Override
            public void onDeviceFound(BluetoothDevice device, int rssi, byte[] scanRecord) {
                dialogShow(" Device Found " + device.getName() + " MAC: " + device.getAddress()
                           + " \n RSSI: " + rssi + " records:" + Arrays.toString(scanRecord));
            }
        });
    }

    /**
     * scan and connect to device
     */
    private void scanAndConnect() {
        liteBluetooth.scanAndConnect(MAC, false, new LiteBleGattCallback() {

            @Override
            public void onConnectSuccess(BluetoothGatt gatt, int status) {
                // discover services !
                gatt.discoverServices();
            }

            @Override
            public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                BluetoothUtil.printServices(gatt);
                dialogShow(MAC + " Services Discovered SUCCESS !");
            }

            @Override
            public void onConnectFailure(BleException exception) {
                bleExceptionHandler.handleException(exception);
                dialogShow(MAC + " Services Discovered FAILURE !");
            }
        });
    }

    /**
     * scan first, then connect
     */
    private void scanThenConnect() {
        liteBluetooth.startLeScan(new PeriodMacScanCallback(MAC, TIME_OUT_SCAN) {

            @Override
            public void onScanTimeout() {
                dialogShow(TIME_OUT_SCAN + "毫秒扫描结束,未发现设备");
            }

            @Override
            public void onDeviceFound(final BluetoothDevice device, int rssi, byte[] scanRecord) {
                Toast.makeText(activity, "发现 " + device.getAddress() + " 正在连接...", Toast.LENGTH_LONG).show();
                liteBluetooth.connect(device, false, new LiteBleGattCallback() {

                    @Override
                    public void onConnectSuccess(BluetoothGatt gatt, int status) {
                        gatt.discoverServices();
                    }

                    @Override
                    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
                        BluetoothUtil.printServices(gatt);
                    }

                    @Override
                    public void onConnectFailure(BleException exception) {
                        bleExceptionHandler.handleException(exception);
                        dialogShow(device.getAddress() + " 设备连接失败");
                    }
                });

            }
        });
    }

    /**
     * get state
     */
    private void getBluetoothState() {
        BleLog.i(TAG, "liteBluetooth.getConnectionState: " + liteBluetooth.getConnectionState());
        BleLog.i(TAG, "liteBluetooth isInScanning: " + liteBluetooth.isInScanning());
        BleLog.i(TAG, "liteBluetooth isConnected: " + liteBluetooth.isConnected());
        BleLog.i(TAG, "liteBluetooth isServiceDiscoered: " + liteBluetooth.isServiceDiscoered());
        if (liteBluetooth.getConnectionState() >= LiteBluetooth.STATE_CONNECTING) {
            BleLog.i(TAG, "lite bluetooth is in connecting or connected");
        }
        if (liteBluetooth.getConnectionState() == LiteBluetooth.STATE_SERVICES_DISCOVERED) {
            BleLog.i(TAG, "lite bluetooth is in connected, services have been found");
        }
    }

    /**
     * add(remove) new callback to an existing connection.
     * One Device, One {@link LiteBluetooth}.
     * But one device( {@link LiteBluetooth}) can add many callback {@link BluetoothGattCallback}
     *
     * {@link LiteBleGattCallback} is a extension of {@link BluetoothGattCallback}
     */
    private void addNewCallbackToOneConnection() {
        BluetoothGattCallback liteCallback = new BluetoothGattCallback() {
            @Override
            public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {}

            @Override
            public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            }

            @Override
            public void onCharacteristicWrite(BluetoothGatt gatt,
                                              BluetoothGattCharacteristic characteristic, int status) {
            }

            @Override
            public void onReadRemoteRssi(BluetoothGatt gatt, int rssi, int status) {}
        };

        if (liteBluetooth.isConnectingOrConnected()) {
            liteBluetooth.addGattCallback(liteCallback);
            liteBluetooth.removeGattCallback(liteCallback);
        }
    }

    /**
     * refresh bluetooth device cache
     */
    private void refreshDeviceCache() {
        liteBluetooth.refreshDeviceCache();
    }

    /**
     * close connection
     */
    private void closeBluetoothGatt() {
        if (liteBluetooth.isConnectingOrConnected()) {
            liteBluetooth.closeBluetoothGatt();
        }
    }

    /**
     * write data to characteristic
     */
    private void writeDataToCharacteristic() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_WRITE, null)
                 .writeCharacteristic(new byte[]{1, 2, 3}, new BleCharactCallback() {
                     @Override
                     public void onSuccess(BluetoothGattCharacteristic characteristic) {
                         BleLog.i(TAG, "Write Success, DATA: " + Arrays.toString(characteristic.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Write failure: " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * write data to descriptor
     */
    private void writeDataToDescriptor() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_WRITE, UUID_DESCRIPTOR_WRITE)
                 .writeDescriptor(new byte[]{1, 2, 3}, new BleDescriptorCallback() {
                     @Override
                     public void onSuccess(BluetoothGattDescriptor descriptor) {
                         BleLog.i(TAG, "Write Success, DATA: " + Arrays.toString(descriptor.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Write failure: " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * read data from characteristic
     */
    private void readDataFromCharacteristic() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, null)
                 .readCharacteristic(new BleCharactCallback() {
                     @Override
                     public void onSuccess(BluetoothGattCharacteristic characteristic) {
                         BleLog.i(TAG, "Read Success, DATA: " + Arrays.toString(characteristic.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Read failure: " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * read data from descriptor
     */
    private void readDataFromDescriptor() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, UUID_DESCRIPTOR_READ)
                 .readDescriptor(new BleDescriptorCallback() {
                     @Override
                     public void onSuccess(BluetoothGattDescriptor descriptor) {
                         BleLog.i(TAG, "Read Success, DATA: " + Arrays.toString(descriptor.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Read failure : " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * enble notification of characteristic
     */
    private void enableNotificationOfCharacteristic() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, null)
                 .enableCharacteristicNotification(new BleCharactCallback() {
                     @Override
                     public void onSuccess(BluetoothGattCharacteristic characteristic) {
                         BleLog.i(TAG, "Notification characteristic Success, DATA: " + Arrays
                                 .toString(characteristic.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Notification characteristic failure: " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * enable notification of descriptor
     */
    private void enableNotificationOfDescriptor() {
        LiteBleConnector connector = liteBluetooth.newBleConnector();
        connector.withUUIDString(UUID_SERVICE, UUID_CHAR_READ, UUID_DESCRIPTOR_READ)
                 .enableDescriptorNotification(new BleDescriptorCallback() {
                     @Override
                     public void onSuccess(BluetoothGattDescriptor descriptor) {
                         BleLog.i(TAG,
                                 "Notification descriptor Success, DATA: " + Arrays.toString(descriptor.getValue()));
                     }

                     @Override
                     public void onFailure(BleException exception) {
                         BleLog.i(TAG, "Notification descriptor failure : " + exception);
                         bleExceptionHandler.handleException(exception);
                     }
                 });
    }

    /**
     * read RSSI of device
     */
    public void readRssiOfDevice() {
        liteBluetooth.newBleConnector()
                     .readRemoteRssi(new BleRssiCallback() {
                         @Override
                         public void onSuccess(int rssi) {
                             BleLog.i(TAG, "Read Success, rssi: " + rssi);
                         }

                         @Override
                         public void onFailure(BleException exception) {
                             BleLog.i(TAG, "Read failure : " + exception);
                             bleExceptionHandler.handleException(exception);
                         }
                     });
    }

    public void dialogShow(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(activity);
        builder.setTitle("Lite BLE");
        builder.setMessage(msg);
        builder.setPositiveButton("OK", null);
        builder.show();
    }
}


text:
package io.astefanutti.metrics.cdi.ee;

import com.codahale.metrics.Meter;
import com.codahale.metrics.MetricRegistry;
import io.astefanutti.metrics.cdi.ee.categories.Integration;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.shrinkwrap.api.Archive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.EnterpriseArchive;
import org.jboss.shrinkwrap.api.spec.JavaArchive;
import org.jboss.shrinkwrap.resolver.api.maven.Maven;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;

import javax.inject.Inject;

import static org.hamcrest.Matchers.greaterThan;
import static org.hamcrest.Matchers.hasKey;
import static org.junit.Assert.assertThat;

@RunWith(Arquillian.class)
@Category(Integration.class)
public class MeteredMethodScheduledBeanTest {

    private final static String METER_NAME = MetricRegistry.name(MeteredMethodScheduledBean.class, "meter");

    @Deployment
    public static Archive<?> createTestArchive() {
        return ShrinkWrap.create(EnterpriseArchive.class)
            .addAsLibraries(
                Maven.configureResolver()
                    .workOffline()
                    .loadPomFromFile("pom.xml")
                    .resolve("io.astefanutti.metrics.cdi:metrics-cdi")
                    .withTransitivity()
                    .as(JavaArchive.class))
            .addAsModule(
                ShrinkWrap.create(JavaArchive.class)
                    .addClass(MeteredMethodScheduledBean.class)
                    .addClass(CallCounter.class)
                    // FIXME: Test class must be added until ARQ-659 is fixed
                    .addClass(MeteredMethodScheduledBeanTest.class)
                    .addAsManifestResource(EmptyAsset.INSTANCE, "beans.xml"));
    }

    @Inject
    private MetricRegistry registry;

    @Inject
    private CallCounter counter;

    @Before
    public void init() {
        counter.reset();
    }

    @Test
    public void testAScheduleMethodCanBeTimed() throws InterruptedException {
        // let's wait a few seconds, so that the scheduled method has been fired
        Thread.sleep(3000l);

        assertThat("Scheduled meter is not registered correctly", registry.getMeters(), hasKey(METER_NAME));
        Meter meter = registry.getMeters().get(METER_NAME);

        // Make sure that the timer has been called
        assertThat("Scheduled method of EJB has not been called", counter.value(), greaterThan(0l));

        // Make sure that the interception occurred
        assertThat("Schedule timer count is incorrect", meter.getCount(), greaterThan(0l));
    }
}


text:
/* eslint-disable no-console */
"use strict";

const colors = require("colors/safe");

module.exports.info = (message) => {
    console.log(message);
};

module.exports.warning = (message) => {
    console.warn(message);
};

module.exports.error = (message) => {
    console.error(colors.red(message));
};