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

/**
 * @param {!Protocol.Network.ResourcePriority} priority
 * @return {string}
 */
PerfUI.uiLabelForNetworkPriority = function(priority) {
  return PerfUI._priorityUILabelMap().get(priority) || '';
};

/**
 * @param {string} priorityLabel
 * @return {string}
 */
PerfUI.uiLabelToNetworkPriority = function(priorityLabel) {
  if (!PerfUI._uiLabelToPriorityMapInstance) {
    /** @type {!Map<string, !Protocol.Network.ResourcePriority>} */
    PerfUI._uiLabelToPriorityMapInstance = new Map();
    PerfUI._priorityUILabelMap().forEach((value, key) => PerfUI._uiLabelToPriorityMapInstance.set(value, key));
  }
  return PerfUI._uiLabelToPriorityMapInstance.get(priorityLabel) || '';
};

/**
 * @return {!Map<!Protocol.Network.ResourcePriority, string>}
 */
PerfUI._priorityUILabelMap = function() {
  if (PerfUI._priorityUILabelMapInstance)
    return PerfUI._priorityUILabelMapInstance;

  /** @type {!Map<!Protocol.Network.ResourcePriority, string>} */
  const map = new Map();
  map.set(Protocol.Network.ResourcePriority.VeryLow, Common.UIString('Lowest'));
  map.set(Protocol.Network.ResourcePriority.Low, Common.UIString('Low'));
  map.set(Protocol.Network.ResourcePriority.Medium, Common.UIString('Medium'));
  map.set(Protocol.Network.ResourcePriority.High, Common.UIString('High'));
  map.set(Protocol.Network.ResourcePriority.VeryHigh, Common.UIString('Highest'));
  PerfUI._priorityUILabelMapInstance = map;
  return map;
};

/**
 * @param {!Protocol.Network.ResourcePriority} priority
 * @return {number}
 */
PerfUI.networkPriorityWeight = function(priority) {
  if (!PerfUI._networkPriorityWeights) {
    /** @type {!Map<!Protocol.Network.ResourcePriority, number>} */
    const priorityMap = new Map();
    priorityMap.set(Protocol.Network.ResourcePriority.VeryLow, 1);
    priorityMap.set(Protocol.Network.ResourcePriority.Low, 2);
    priorityMap.set(Protocol.Network.ResourcePriority.Medium, 3);
    priorityMap.set(Protocol.Network.ResourcePriority.High, 4);
    priorityMap.set(Protocol.Network.ResourcePriority.VeryHigh, 5);
    PerfUI._networkPriorityWeights = priorityMap;
  }
  return PerfUI._networkPriorityWeights.get(priority) || 0;
};


text:
//-----------------------------------------------------------------------
// <copyright file="TaskBasedScheduler_ActionScheduler_Schedule_Tests.cs" company="Akka.NET Project">
//     Copyright (C) 2009-2020 Lightbend Inc. <http://www.lightbend.com>
//     Copyright (C) 2013-2020 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.Threading;
using Akka.Actor;
using Akka.TestKit;
using Akka.Util.Internal;
using Xunit;
using Xunit.Extensions;

namespace Akka.Tests.Actor.Scheduler
{
    // ReSharper disable once InconsistentNaming
    public class DefaultScheduler_ActionScheduler_Schedule_Tests : AkkaSpec
    {
        [Theory]
        [InlineData(10, 1000)]
        public void ScheduleRepeatedly_in_milliseconds_Tests_and_verify_the_interval(int initialDelay, int interval)
        {
            // Prepare, set up actions to be fired
            IActionScheduler scheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                var cancelable = new Cancelable(Sys.Scheduler);
                var receiver = ActorOf(dsl =>
                {
                    //Receive three messages, and store the time when these were received
                    //after three messages stop the actor and send the times to TestActor
                    var messages = new List<DateTimeOffset>();
                    dsl.Receive<string>((s, context) =>
                    {
                        messages.Add(context.System.Scheduler.Now);
                        if (messages.Count == 3)
                        {
                            TestActor.Tell(messages);
                            cancelable.Cancel();
                            context.Stop(context.Self);
                        }
                    });
                });
                scheduler.ScheduleRepeatedly(initialDelay, interval, () => receiver.Tell(""), cancelable);

                //Expect to get a list from receiver after it has received three messages
                var dateTimeOffsets = ExpectMsg<List<DateTimeOffset>>();
                dateTimeOffsets.ShouldHaveCount(3);
                Action<int, int> validate = (a, b) =>
                {
                    var valA = dateTimeOffsets[a];
                    var valB = dateTimeOffsets[b];
                    var diffBetweenMessages = Math.Abs((valB - valA).TotalMilliseconds);
                    var diffInMs = Math.Abs(diffBetweenMessages - interval);
                    var deviate = (diffInMs/interval);
                    deviate.Should(val => val < 0.1,
                        string.Format(
                            "Expected the interval between message {1} and {2} to deviate maximum 10% from {0}. It was {3} ms between the messages. It deviated {4}%",
                            interval, a + 1, b + 1, diffBetweenMessages, deviate*100));
                };
                validate(0, 1);
                validate(1, 2);
            }
            finally
            {
                scheduler.AsInstanceOf<IDisposable>().Dispose();
            }

        }

        [Theory]
        [InlineData(50, 50)]
        [InlineData(00, 50)]
        public void ScheduleRepeatedly_in_milliseconds_Tests(int initialDelay, int interval)
        {
            // Prepare, set up actions to be fired
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                testScheduler.ScheduleRepeatedly(initialDelay, interval, () => TestActor.Tell("Test"));

                //Just check that we receives more than one message
                ExpectMsg("Test");
                ExpectMsg("Test");
                ExpectMsg("Test");
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Theory]
        [InlineData(50, 50)]
        [InlineData(00, 50)]
        public void ScheduleRepeatedly_in_TimeSpan_Tests(int initialDelay, int interval)
        {
            // Prepare, set up actions to be fired
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                testScheduler.ScheduleRepeatedly(TimeSpan.FromMilliseconds(initialDelay),
                    TimeSpan.FromMilliseconds(interval), () => TestActor.Tell("Test"));

                //Just check that we receives more than one message
                ExpectMsg("Test");
                ExpectMsg("Test");
                ExpectMsg("Test");
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Fact]
        public void ScheduleOnceTests()
        {
            // Prepare, set up actions to be fired
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                testScheduler.ScheduleOnce(50, () => TestActor.Tell("Test1"));
                testScheduler.ScheduleOnce(100, () => TestActor.Tell("Test2"));

                ExpectMsg("Test1");
                ExpectMsg("Test2");

                ExpectNoMsg(100);
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Theory]
        [InlineData(new int[] { 1, 1, 50, 50, 100, 100 })]
        public void When_ScheduleOnce_many_at_the_same_time_Then_all_fires(int[] times)
        {
            // Prepare, set up actions to be fired
            IActionScheduler scheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                foreach (var time in times)
                {
                    var t = time;
                    scheduler.ScheduleOnce(time, () => TestActor.Tell("Test" + t));
                }

                //Perform the test
                ExpectMsg("Test1");
                ExpectMsg("Test1");
                ExpectMsg("Test50");
                ExpectMsg("Test50");
                ExpectMsg("Test100");
                ExpectMsg("Test100");
                ExpectNoMsg(50);
            }
            finally
            {
                scheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(-4711)]
        public void When_ScheduleOnce_with_invalid_delay_Then_exception_is_thrown(int invalidTime)
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);
            try
            {
                XAssert.Throws<ArgumentOutOfRangeException>(() =>
                            testScheduler.ScheduleOnce(invalidTime, () => { })
                );
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Theory]
        [InlineData(-1)]
        [InlineData(-4711)]
        public void When_ScheduleRepeatedly_with_invalid_delay_Then_exception_is_thrown(int invalidTime)
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                XAssert.Throws<ArgumentOutOfRangeException>(() =>
                            testScheduler.ScheduleRepeatedly(invalidTime, 100, () => { })
                );
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Theory]
        [InlineData(0)]
        [InlineData(-1)]
        [InlineData(-4711)]
        public void When_ScheduleRepeatedly_with_invalid_interval_Then_exception_is_thrown(int invalidInterval)
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                XAssert.Throws<ArgumentOutOfRangeException>(() =>
                            testScheduler.ScheduleRepeatedly(42, invalidInterval, () => { })
                );
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Fact]
        public void When_ScheduleOnce_with_0_delay_Then_action_is_executed_immediately()
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                var manualResetEvent = new ManualResetEventSlim();
                manualResetEvent.IsSet.ShouldBeFalse();
                testScheduler.ScheduleOnce(0, () => manualResetEvent.Set());

                manualResetEvent.Wait(500).ShouldBeTrue();
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Fact]
        public void When_ScheduleRepeatedly_with_0_delay_Then_action_is_executed_immediately()
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                var manualResetEvent = new ManualResetEventSlim();
                manualResetEvent.IsSet.ShouldBeFalse();
                testScheduler.ScheduleRepeatedly(0, 100, () => manualResetEvent.Set());

                manualResetEvent.Wait(500).ShouldBeTrue();
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }

        [Fact]
        public void When_ScheduleRepeatedly_action_crashes_Then_no_more_calls_will_be_scheduled()
        {
            IActionScheduler testScheduler = new HashedWheelTimerScheduler(Sys.Settings.Config, Log);

            try
            {
                var timesCalled = 0;
                testScheduler.ScheduleRepeatedly(0, 10, () =>
                {
                    Interlocked.Increment(ref timesCalled);
                    throw new Exception("Crash");
                });
                AwaitCondition(() => timesCalled >= 1);
                Thread.Sleep(200); //Allow any scheduled actions to be fired.

                //We expect only one of the scheduled actions to actually fire
                timesCalled.ShouldBe(1);
            }
            finally
            {
                testScheduler.AsInstanceOf<IDisposable>().Dispose();
            }
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
/**
 * \file
 * \brief OCV image_container inteface
 */

#ifndef MAPTK_PLUGINS_OCV_IMAGE_CONTAINER_H_
#define MAPTK_PLUGINS_OCV_IMAGE_CONTAINER_H_

#include <vital/vital_config.h>
#include <maptk/plugins/ocv/maptk_ocv_export.h>

#include <opencv2/core/core.hpp>

#include <vital/types/image_container.h>

namespace kwiver {
namespace maptk {

namespace ocv
{

/// This image container wraps a cv::Mat
class MAPTK_OCV_EXPORT image_container
  : public vital::image_container
{
public:

  /// Constructor - from a cv::Mat
  explicit image_container(const cv::Mat& d)
  : data_(d) {}

  /// Constructor - convert kwiver image to cv::Mat
  explicit image_container(const vital::image& maptk_image)
  : data_(maptk_to_ocv(maptk_image)) {}

  /// Constructor - convert base image container to cv::Mat
  explicit image_container(const vital::image_container& image_cont);

  /// Copy Constructor
  image_container(const maptk::ocv::image_container& other)
  : data_(other.data_) {}

  /// The size of the image data in bytes
  /**
   * This size includes all allocated image memory,
   * which could be larger than width*height*depth.
   */
  virtual size_t size() const;

  /// The width of the image in pixels
  virtual size_t width() const { return data_.cols; }

  /// The height of the image in pixels
  virtual size_t height() const { return data_.rows; }

  /// The depth (or number of channels) of the image
  virtual size_t depth() const { return data_.channels(); }

  /// Get and in-memory image class to access the data
  virtual vital::image get_image() const { return ocv_to_maptk(data_); }

  /// Access the underlying cv::Mat data structure
  cv::Mat get_Mat() const { return data_; }

  /// Convert an OpenCV cv::Mat to a MAPTK image
  static vital::image ocv_to_maptk(const cv::Mat& img);

  /// Convert a MAPTK image to an OpenCV cv::Mat
  static cv::Mat maptk_to_ocv(const vital::image& img);

protected:
  /// image data
  cv::Mat data_;
};

/// Extract a cv::Mat from any image container
/**
 * If \a img is actually an maptk::ocv::image_container then
 * return the underlying cv::Mat.  Otherwise, convert the image data
 * to cv:Mat by shallow copy (if possible) or deep copy as a last resort.
 *
 * \param img Image container to convert to cv::mat
 */
MAPTK_OCV_EXPORT cv::Mat image_container_to_ocv_matrix(const vital::image_container& img);

} // end namespace ocv

} // end namespace maptk
} // end namespace kwiver

#endif // MAPTK_PLUGINS_OCV_IMAGE_CONTAINER_H_


text:
package database::informix::mode::tablelocks;

use base qw(centreon::plugins::mode);

use strict;
use warnings;
use centreon::plugins::misc;
use centreon::plugins::statefile;

sub new {
    my ($class, %options) = @_;
    my $self = $class->SUPER::new(package => __PACKAGE__, %options);
    bless $self, $class;

    $self->{version} = '1.0';
    $options{options}->add_options(arguments =>
                                {
                                  "warning-deadlks:s"       => { name => 'warning_deadlks', },
                                  "critical-deadlks:s"      => { name => 'critical_deadlks', },
                                  "warning-lockwts:s"       => { name => 'warning_lockwts', },
                                  "critical-lockwts:s"      => { name => 'critical_lockwts', },
                                  "warning-lockreqs:s"      => { name => 'warning_lockreqs', },
                                  "critical-lockreqs:s"     => { name => 'critical_lockreqs', },
                                  "warning-lktouts:s"       => { name => 'warning_lktouts', },
                                  "critical-lktouts:s"      => { name => 'critical_lktouts', },
                                  "name:s"                  => { name => 'name', },
                                  "regexp"                  => { name => 'use_regexp' },
                                  "filter-tables:s"         => { name => 'filter_tables' },
                                  "only-databases"          => { name => 'only_databases' },
                                });
    $self->{statefile_cache} = centreon::plugins::statefile->new(%options);

    return $self;
}

sub check_options {
    my ($self, %options) = @_;
    $self->SUPER::init(%options);

    if (($self->{perfdata}->threshold_validate(label => 'warning-deadlks', value => $self->{option_results}->{warning_deadlks})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong warning-deadlks threshold '" . $self->{option_results}->{warning_deadlks} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical-deadlks', value => $self->{option_results}->{critical_deadlks})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong critical-deadlks threshold '" . $self->{option_results}->{critical_deadlks} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'warning-lockwts', value => $self->{option_results}->{warning_lockwts})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong warning-lockwts threshold '" . $self->{option_results}->{warning_lockwts} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical-lockwts', value => $self->{option_results}->{critical_lockwts})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong critical-lockwts threshold '" . $self->{option_results}->{critical_lockwts} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'warning-lockreqs', value => $self->{option_results}->{warning_lockreqs})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong warning-lockreqs threshold '" . $self->{option_results}->{warning_lockreqs} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical-lockreqs', value => $self->{option_results}->{critical_lockreqs})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong critical-lockreqs threshold '" . $self->{option_results}->{critical_lockreqs} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'warning-lktouts', value => $self->{option_results}->{warning_block})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong warning-lktouts threshold '" . $self->{option_results}->{warning_block} . "'.");
       $self->{output}->option_exit();
    }
    if (($self->{perfdata}->threshold_validate(label => 'critical-lktouts', value => $self->{option_results}->{critical_lktouts})) == 0) {
       $self->{output}->add_option_msg(short_msg => "Wrong critical-lktouts threshold '" . $self->{option_results}->{critical_lktouts} . "'.");
       $self->{output}->option_exit();
    }

    $self->{statefile_cache}->check_options(%options);
}

sub run {
    my ($self, %options) = @_;
    # $options{sql} = sqlmode object
    $self->{sql} = $options{sql};

    $self->{sql}->connect();

    my $query = q{
SELECT dbsname, tabname, deadlks, lockwts, lockreqs, lktouts FROM sysptprof
ORDER BY dbsname, tabname
};

    $self->{sql}->query(query => $query);

    $self->{output}->output_add(severity => 'OK',
                                short_msg => 'All database/table locks are ok');

    my $new_datas = {};
    $self->{statefile_cache}->read(statefile => 'informix_' . $self->{mode} . '_' . $self->{sql}->get_unique_id4save());
    my $old_timestamp = $self->{statefile_cache}->get(name => 'last_timestamp');
    $new_datas->{last_timestamp} = time();

    my $count = 0;
    my $db_found = {};
    while ((my $row = $self->{sql}->fetchrow_hashref())) {
        my $dbname = centreon::plugins::misc::trim($row->{dbsname});
        my $tabname = centreon::plugins::misc::trim($row->{tabname});
        my $longname = $dbname . '.' . $tabname;
        next if (defined($self->{option_results}->{name}) && !defined($self->{option_results}->{use_regexp}) && $dbname ne $self->{option_results}->{name});
        next if (defined($self->{option_results}->{name}) && defined($self->{option_results}->{use_regexp}) && $dbname !~ /$self->{option_results}->{name}/);
        next if (defined($self->{option_results}->{filter_tables}) && $longname !~ /$self->{option_results}->{filter_tables}/);

        $count++;
        my $old_datas = {};
        my $get_old_value = 0;
        $db_found->{$dbname} = {deadlks => 0, lockwts => 0, lockreqs => 0, lktouts => 0, process => 0} if (!defined($db_found->{$dbname}));
        foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
            $new_datas->{$dbname . '_' . $_} = 0 if (!defined($new_datas->{$dbname . '_' . $_}));
            $new_datas->{$dbname . '_' . $_} += $row->{$_};
            $new_datas->{$longname . '_' . $_} = $row->{$_};
            $old_datas->{$longname . '_' . $_} = $self->{statefile_cache}->get(name => $longname . '_' . $_);
            # Restart or onstat -z - we set to 0
            $old_datas->{$longname . '_' . $_} = 0 if (defined($old_datas->{$longname . '_' . $_}) && $old_datas->{$longname . '_' . $_} > $new_datas->{$longname . '_' . $_});
            # If we have a buffer or not
            if (defined($old_datas->{$longname . '_' . $_})) {
                $get_old_value = 1;
                $db_found->{$dbname}->{$_} += $old_datas->{$longname . '_' . $_};
            }
        }

        # Buffer needed
        next if ($get_old_value == 0 || !defined($old_timestamp));

        $db_found->{$dbname}->{process} = 1;

        next if ($self->{option_results}->{only_databases});

        my $diff = {};
        foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
            $diff->{$_} = $new_datas->{$longname . '_' . $_} - $old_datas->{$longname . '_' . $_};
        }

        my $exit1 = $self->{perfdata}->threshold_check(value => $diff->{deadlks}, threshold => [ { label => 'critical-deadlks', 'exit_litteral' => 'critical' }, { label => 'warning-deadlks', exit_litteral => 'warning' } ]);
        my $exit2 = $self->{perfdata}->threshold_check(value => $diff->{lockwts}, threshold => [ { label => 'critical-lockwts', 'exit_litteral' => 'critical' }, { label => 'warning-lockwts', exit_litteral => 'warning' } ]);
        my $exit3 = $self->{perfdata}->threshold_check(value => $diff->{lockreqs}, threshold => [ { label => 'critical-lockreqs', 'exit_litteral' => 'critical' }, { label => 'warning-lockreqs', exit_litteral => 'warning' } ]);
        my $exit4 = $self->{perfdata}->threshold_check(value => $diff->{lktouts}, threshold => [ { label => 'critical-lktouts', 'exit_litteral' => 'critical' }, { label => 'warning-lktouts', exit_litteral => 'warning' } ]);
        my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]);

        $self->{output}->output_add(long_msg => sprintf("Table '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, Lock Timeouts %d",
                                                         $longname, $diff->{deadlks}, $diff->{lockwts}, $diff->{lockreqs}, $diff->{lktouts}));
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(severity => $exit,
                                        short_msg => sprintf("Table '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, Lock Timeouts %d",
                                                             $longname, $diff->{deadlks}, $diff->{lockwts}, $diff->{lockreqs}, $diff->{lktouts}));
        }

        foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
            $self->{output}->perfdata_add(label => 'tbl_' . $_ . '_' . $longname,
                                          value => $diff->{$_},
                                          warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $_),
                                          critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $_),
                                          min => 0);
        }
    }

    foreach my $dbname (keys %{$db_found}) {
        next if ($db_found->{$dbname}->{process} == 0);

        my $exit1 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks}, threshold => [ { label => 'critical-deadlks', 'exit_litteral' => 'critical' }, { label => 'warning-deadlks', exit_litteral => 'warning' } ]);
        my $exit2 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts}, threshold => [ { label => 'critical-lockwts', 'exit_litteral' => 'critical' }, { label => 'warning-lockwts', exit_litteral => 'warning' } ]);
        my $exit3 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs}, threshold => [ { label => 'critical-lockreqs', 'exit_litteral' => 'critical' }, { label => 'warning-lockreqs', exit_litteral => 'warning' } ]);
        my $exit4 = $self->{perfdata}->threshold_check(value => $new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}, threshold => [ { label => 'critical-lktouts', 'exit_litteral' => 'critical' }, { label => 'warning-lktouts', exit_litteral => 'warning' } ]);
        my $exit = $self->{output}->get_most_critical(status => [ $exit1, $exit2, $exit3, $exit4 ]);

        $self->{output}->output_add(long_msg => sprintf("Database '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, lock timeouts %d",
                                                         $dbname,
                                                         $new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks},
                                                         $new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts},
                                                         $new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs},
                                                         $new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}));
        if (!$self->{output}->is_status(value => $exit, compare => 'ok', litteral => 1)) {
            $self->{output}->output_add(severity => $exit,
                                        short_msg => sprintf("Database '%s': Deadlocks %d, Lock Waits %d, Lock Requests %d, lock timeouts %d",
                                                             $dbname,
                                                             $new_datas->{$dbname . '_deadlks'} - $db_found->{$dbname}->{deadlks},
                                                             $new_datas->{$dbname . '_lockwts'} - $db_found->{$dbname}->{lockwts},
                                                             $new_datas->{$dbname . '_lockreqs'} - $db_found->{$dbname}->{lockreqs},
                                                             $new_datas->{$dbname . '_lktouts'} - $db_found->{$dbname}->{lktouts}));
        }
        foreach (('deadlks', 'lockwts', 'lockreqs', 'lktouts')) {
            $self->{output}->perfdata_add(label => 'db_' . $_ . '_' . $dbname,
                                          value => $new_datas->{$dbname . '_' . $_} - $db_found->{$dbname}->{$_},
                                          warning => $self->{perfdata}->get_perfdata_for_output(label => 'warning-' . $_),
                                          critical => $self->{perfdata}->get_perfdata_for_output(label => 'critical-' . $_),
                                          min => 0);
        }
    }

    if ($count == 0) {
        $self->{output}->output_add(severity => 'UNKNOWN',
                                    short_msg => "Cannot find a table (maybe filters).");
    }

    $self->{statefile_cache}->write(data => $new_datas);
    if (!defined($old_timestamp)) {
        $self->{output}->output_add(severity => 'OK',
                                    short_msg => "Buffer creation...");
    }

    $self->{output}->display();
    $self->{output}->exit();
}

1;

__END__

=head1 MODE

Check table locks:
- deadlks: deadlocks.
- lockwts: lock waits.
- lockreqs: lock requests.
- lktouts: lock timeouts.

=over 8

=item B<--warning-deadlks>

Threshold warning 'deadlks' in absolute.

=item B<--critical-deadlks>

Threshold critical 'deadlks' in absolute.

=item B<--warning-lockwts>

Threshold warning 'lockwts' in absolute.

=item B<--critical-lockwts>

Threshold critical 'lockwts' in absolute.

=item B<--warning-lockreqs>

Threshold warning 'lockreqs' in absolute.

=item B<--critical-lockreqs>

Threshold critical 'lockreqs' in absolute.

=item B<--warning-lktouts>

Threshold warning 'lktouts' in absolute.

=item B<--critical-lktouts>

Threshold critical 'lktouts' in absolute.

=item B<--name>

Set the database (empty means 'check all databases').

=item B<--regexp>

Allows to use regexp to filter database (with option --name).

=item B<--filter-tables>

Filter tables (format of a table name: 'sysmater.dual').

=item B<--only-databases>

only check locks globally on database (no output for tables).

=back

=cut


text:
function type = getMatlabDatatype(this)
% IceImarisConnector:  getMatlabDatatype (public method)
%
% DESCRIPTION
%
%   This method returns the datatype of the dataset as a MATLAB type
%   (e.g. one of 'uint8', 'uint16', 'single').
%
% SYNOPSIS
%
%   type = conn.getMatlabDatatype()
%
% INPUT
%
%   None
%
% OUTPUT
%
%   type : datatype of the dataset as a MATLAB type: one of one of 'uint8',
%          'uint16', 'single', or '' if the type is unknown in Imaris.

% AUTHORS
%
% Author: Aaron Ponti

% LICENSE
%
% ImarisConnector is a simple commodity class that eases communication between
% Imaris and MATLAB using the Imaris XT interface.
% Copyright (C) 2011  Aaron Ponti
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License
% as published by the Free Software Foundation; either version 2
% of the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; if not, write to the Free Software
% Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

type = '';

% Is Imaris running?
if this.isAlive() == 0
    return
end

% Which datatype?
switch char(this.mImarisApplication.GetDataSet().GetType())
    case 'eTypeUInt8',
        type  = 'uint8';
    case 'eTypeUInt16',
        type  = 'uint16';
    case 'eTypeFloat',
        type  = 'single';
    case 'eTypeUnknown',
        type = '';
    otherwise,
        type = '';
end

end


text:
<!DOCTYPE html>

  <meta charset="utf-8">
<title>Jekyll theme for Programmers</title>
<meta name="description" content="Jekyll theme for Programmers">
<meta name="keywords" content="">

<meta property="og:type" content="article">
<meta property="og:title" content="strstr in c – ">
<meta property="og:description" content="Jekyll theme for Programmers">
<meta property="og:url" content="http://bgame.github.io/algorithm/2015/07/14/strstr.html">
<meta property="og:site_name" content="">

<link rel="canonical" href="http://bgame.github.io/algorithm/2015/07/14/strstr.html">
<link href="http://bgame.github.io/feed.xml" type="application/atom+xml" rel="alternate" title=" Feed">

<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="http://bgame.github.io/css/base.min.css" type="text/css" />
<link rel="stylesheet" href="http://bgame.github.io/css/github.min.css" type="text/css" />
<link rel="stylesheet" href="http://bgame.github.io/css/octicons.css" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Lato' rel='stylesheet' type='text/css'>

Kevin's blog : eating/drinking/shitting/fucking/coding.

strstr in c

14 Jul 2015

Source Code

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define NOTFOUND -1
int my_strstr(const char * s1, const char * s2) {
    const char * p = s1;
    do {
        if (*p == *s2) { /* match first char */
            const char * p1 = p;
            const char * p2 = s2;
            do
            {
                if (!*p2) /* FOUND */
                    return p - s1;
                if (!*p1)
                    return NOTFOUND;
            }
            while (*p1++ == *p2++);
        }
    }
    while(*p++);

    return NOTFOUND;
}

int
main(int argc, char ** argv)
{
    char s1[] = "skldjfwioeuwetewtsdfsdf";
    char s2[] = "sdfsdf";

    int pos = my_strstr(s1, s2);
    if (pos >= 0) {
        printf("found:%d\n", pos);
    }
    else
        printf("not found!\n");

    exit(EXIT_SUCCESS);
}


text:
package requirejs;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RequireMap {
    public Map<String, RequireMapModule> modules = new HashMap<String, RequireMapModule>();

    public void clear() {
        modules.clear();
    }

    public void addModule(RequireMapModule module) {
        this.modules.put(module.module, module);
    }

    public RequirePathAlias getAliasByModule(String moduleName, String aliasString) {
        RequirePathAlias alias = null;
        if (modules.containsKey(moduleName)) {
            alias = modules.get(moduleName).getAlias(aliasString);
        }
        if (null == alias && modules.containsKey("*")) {
            alias = modules.get("*").getAlias(aliasString);
        }

        return alias;
    }

    public List<String> getCompletionByModule(String moduleName) {
        List<String> completions = new ArrayList<String>();

        if (modules.containsKey(moduleName)) {
            completions.addAll(modules.get(moduleName).getAliases());
        }

        if (modules.containsKey("*")) {
            completions.addAll(modules.get("*").getAliases());
        }

        return completions;
    }
}


text:
package com.dream.android.sample.feature.main;

import com.dream.android.sample.R;
import com.dream.android.sample.base.DIFragment;
import com.dream.android.sample.di.component.ActivityComponent;

public class Tab3Fragment extends DIFragment {

    public static Tab3Fragment newInstance() {
        return new Tab3Fragment();
    }

    @Override
    protected void injectComponent(ActivityComponent activityComponent) {
        activityComponent.inject(this);
    }

    @Override
    protected int getRootViewId() {
        return R.layout.fragment_tab3;
    }

    @Override
    protected String getFragmentName() {
        return null;
    }
}


text:
'use strict';

//  For original reference see https://github.com/petkaantonov/cookieparser
const crypto = require('crypto');

/**
 * Max allowed Cookie string length
 * @constant
 * @type {number}
 */
const maxCookieStringLength = 4096;

/**
 * Produces sha1 hmac signature of 'val' and returns it's buffers concatenation in Base64 format
 * @param {Buffer} val stUtils.getNewSID() value (10-bytes)
 * @param {String} secret HEX secret value (16-bytes)
 * @returns {String} Base64 value (40-bytes, 10-bytes val + 20-bytes hmac + Base64 overhead (4/3))
 */
//  Returns String:      val             hmac          =>                   Base64
//                  [....10....][.........20.........] => [...................40...................]
exports.cookieSign = (val, secret) => {
    const hmac = crypto.createHmac('sha1', secret).update(val).digest(); // eslint-disable-line newline-per-chained-call

    return Buffer.concat([val, hmac], 30).toString('base64');
};

/**
 * Check SSO value for correct signature and returns it or undefined in error case
 * @param {string} val Base64 value (40-bytes, 10-bytes SSO + 20-bytes SSO's hmac + Base64 overhead (4/3))
 * @param {string} secret HEX secret value (16-bytes)
 * @returns {Buffer} SSO value (10-bytes) or undefined
 */
exports.cookieUnSign = (val, secret) => {   //  eslint-disable-line consistent-return
    const buf = new Buffer(val, 'base64');
    const SID = buf.slice(0, 10);
    const hmac = crypto.createHmac('sha1', secret).update(SID).digest(); // eslint-disable-line newline-per-chained-call

    if (buf.slice(10).equals(hmac)) return SID;
};

const encode = require('querystring').escape;
const decode = require('querystring').unescape;

/**
 * Serialize a name value pair into a cookie string suitable for http headers.
 * An optional object specifies cookie parameters
 * @param {string} name cookie's name
 * @param {string} val cookie's value
 * @param {number} maxAge maximum cookie age in seconds
 * @param {string} domain defaults to the host portion of the current document location
 * @param {string} path defaults to the current path of the current document location
 * @param {Date} expires expiration date, defaults to the end of the session
 * @param {boolean} httpOnly cookie cannot be accessed by client-side API (such as JavaScript)
 * @param {boolean} secure cookie to only be transmitted over secure protocol as https
 * @example Example usage
 * cookies.cookieSerialize('foo', 'bar', { httpOnly: true }) // returns "foo=bar; httpOnly"
 * @returns {string} Serialized string (ex.: "foo=bar; Max-Age=3600; httpOnly")
 */
exports.cookieSerialize = (name, val, { maxAge, domain, path, expires, httpOnly, secure } = {}) => {
    const pair = [`${name}=${encode(val)}`];

    if (maxAge) pair.push(`Max-Age=${maxAge}`);
    if (domain) pair.push(`Domain=${domain}`);
    if (path) pair.push(`Path=${path}`);
    if (expires) pair.push(`Expires=${expires.toUTCString()}`);
    if (httpOnly) pair.push('HttpOnly');
    if (secure) pair.push('Secure');

    return pair.join('; ');
};

/**
 * Parse cookie string into {name1: value1, name2: value2, ...} pairs object
 * @param {string} str input string to parse
 * @returns {Object} object with name-value pairs
 */
/* eslint-disable complexity, max-statements, max-depth */
exports.cookieParse = str => {
    const dictionary = {};

    if (!str || str.length > maxCookieStringLength) return dictionary;

    const len = str.length;

    let keyStart = 0,
        keyEnd = 0,
        valueStart = 0,
        valueEnd = 0,
        valueMND = false,
        isQuote = false;

    let key, value,
        i, j, k, ch;

    mainloop: for (i = 0; i < len; i++) {
        ch = str.charCodeAt(i);

        if (ch > 127) {
            return cookieSlowParse(str, dictionary);
        } else if (ch === 61) {
            keyEnd = i - 1;
            j = i + 1;
            ch = str.charCodeAt(j);
            while (ch === 32) {
                j++;
                ch = str.charCodeAt(j);
            }
            if (ch === 34) {
                j++;
                isQuote = true;
            }
            valueStart = j;
            for (; j < len; j++) {
                ch = str.charCodeAt(j);
                if (ch === 37) {
                    valueMND = true;
                } else if (ch === 59 || ch === 44) {
                    if (isQuote) {
                        k = trimBackward(str, j - 1);
                        valueEnd = k - 1;
                        if (valueEnd < valueStart) valueStart = valueEnd;
                    } else {
                        valueEnd = j - 1;
                    }

                    key = cookieExtract(str, keyStart, keyEnd);
                    value = cookieExtract(str, valueStart, valueEnd);
                    dictionary[key] = valueMND ? decode(value) : value;

                    i = j;
                    for (; j < len; j++) {
                        if (str.charCodeAt(j) !== 32) {
                            i = j - 1;
                            break;
                        }
                    }
                    keyEnd = keyStart = i + 1;
                    isQuote = false;
                    valueMND = false;
                    continue mainloop;
                }
            }

            if (isQuote) {
                k = trimBackward(str, j - 1);
                valueEnd = k - 1;
                if (valueEnd < valueStart) valueStart = valueEnd;
            } else {
                valueEnd = j - 1;
            }

            key = cookieExtract(str, keyStart, keyEnd);
            value = cookieExtract(str, valueStart, valueEnd);
            dictionary[key] = valueMND ? decode(value) : value;

            i = j;
        } else if (ch === 59 || ch === 44) {
            keyStart = i + 1;
        }
    }

    return dictionary;
}; /* eslint-enable complexity, max-statements, max-depth */

/**
 * Parse the given cookie header string into an object (less robust version than .cookieParse)
 * @param {string} str input string to parse
 * @param {Object} obj dictionary object
 * @returns {Object} object with name-value pairs
 */
function cookieSlowParse (str, obj) {
    const pairs = str.split(/[;,] */);
    let idx, key, val;

    pairs.forEach(pair => {
        idx = pair.indexOf('=');
        if (idx < 0) return;

        key = pair.substr(0, idx).trim();
        val = pair.substr(++idx, pair.length).trim();

        // quoted values
        if (val[0] === '"') val = val.slice(1, -1);

        // only assign once
        if (typeof obj[key] === 'undefined') obj[key] = decode(val);
    });

    return obj;
}

/**
 * Extracts trimmed key / value from string
 * @param {string} str provided string
 * @param {number} start slice op index from
 * @param {number} end slice op index to
 * @returns {string} trimmed key or value
 */
function cookieExtract (str, start, end) {
    if (start === end + 1) return '';

    return str.slice(trimForward(str, start), trimBackward(str, end) + 1);
}

/**
 * Skip leading spaces from indexed string
 * @param {string} str provided string
 * @param {number} i index to begin operation from
 * @returns {number} new index (to the first non-space char)
 */
function trimForward (str, i) {
    let ch = str.charCodeAt(i);

    while (ch < 33) ch = str.charCodeAt(++i);

    return i;
}

/**
 * Skip trailing spaces from indexed string
 * @param {string} str provided string
 * @param {number} i index to begin operation from
 * @returns {number} new index (to the first non-space char)
 */
function trimBackward (str, i) {
    let ch = str.charCodeAt(i);

    while (ch < 33) ch = str.charCodeAt(--i);

    return i;
}


text:
using System;
using ProtoBuf;

namespace MumbleDj.Packets
{
    [ProtoContract]
    public sealed class Acl
    {
        public override String ToString()
        {
            return string.Format("ChannelId:{0}\nInheritAcls:{1}\nGroups:{2}\nAcls:{3}\nQuery:{4}",
                ChannelId, InheritAcls, Groups != null ? string.Join(",", Groups.ToString()) : "null",
                Acls != null ? string.Join(",", Acls.ToString()) : "null", Query);
        }

        // ReSharper disable UnassignedField.Global
        [ProtoMember(1)] public UInt32 ChannelId;
        [ProtoMember(2, IsRequired = false)] public bool? InheritAcls = true;
        [ProtoMember(3)] public ChanGroup[] Groups;
        [ProtoMember(4)] public ChanAcl[] Acls;
        [ProtoMember(5, IsRequired = false)] public bool? Query = false;
        // ReSharper restore UnassignedField.Global
    }

    [ProtoContract]
    public sealed class ChanAcl
    {
        public override String ToString()
        {
            return
                string.Format("ApplyHere:{0}\nApplySubs:{1}\nInherited:{2}\nUserId:{3}\nGroup:{4}\nGrant:{5}\nDeny:{6}",
                    ApplyHere, ApplySubs, Inherited, UserId, Group, Grant, Deny);
        }

        // ReSharper disable UnassignedField.Global
        [ProtoMember(1, IsRequired = false)] public bool? ApplyHere = true;
        [ProtoMember(2, IsRequired = false)] public bool? ApplySubs = true;
        [ProtoMember(3, IsRequired = false)] public bool? Inherited = true;
        [ProtoMember(4, IsRequired = false)] public UInt32? UserId;
        [ProtoMember(5, IsRequired = false)] public string Group;
        [ProtoMember(6, IsRequired = false)] public UInt32? Grant;
        [ProtoMember(7, IsRequired = false)] public UInt32? Deny;
        // ReSharper restore UnassignedField.Global
    }

    public sealed class ChanGroup
    {
        public override string ToString()
        {
            return
                string.Format(
                    "Name:{0}\nInherited:{1}\nInherit:{2}\nInheritable:{3}\nAdd:{4}\nRemove:{5}\nInheritedMembers:{6}",
                    Name, Inherited, Inherit, Inheritable, Add != null ? string.Join(",", Add) : "null",
                    Remove != null ? string.Join(",", Remove) : null,
                    InheritedMembers != null ? string.Join(",", InheritedMembers) : "null");
        }

        // ReSharper disable UnassignedField.Global
        [ProtoMember(1)] public string Name;
        [ProtoMember(2, IsRequired = false)] public bool? Inherited = true;
        [ProtoMember(3, IsRequired = false)] public bool? Inherit = true;
        [ProtoMember(4, IsRequired = false)] public bool? Inheritable = true;
        [ProtoMember(5)] public UInt32[] Add;
        [ProtoMember(6)] public UInt32[] Remove;
        [ProtoMember(7)] public UInt32[] InheritedMembers;
        // ReSharper restore UnassignedField.Global
    }
}


text:
Examples of the cron-like scheduler introduced in OOZIE-1306. The following
examples have been tested on Hartonworks HDP 2.1 Sandbox

## Usage

Copy files to local filesystem on your Hadoop cluster or sandbox.

### Place the files into HDFS.
* hadoop fs -put oozie

### Every 15 minutes example:
* oozie job -oozie http://localhost:11000/oozie -config oozie/every-fifteen-minutes/job.properties -run

### First day of every month example:
* oozie job -oozie http://localhost:11000/oozie -config oozie/first-day-of-the-month/job.properties -run

### Weekdays at 2 am example.
* oozie job -oozie http://localhost:11000/oozie -config oozie/weekdays-at-two-am/job.properties -run

### Kill a job
* oozie job -oozie http://localhost:11000/oozie -kill 0000310-150206075957529-oozie-oozi-C

### Note
If you are not running on Hortonworks Sandbox (2.0+) you will need to edit job properties to specify your name node, job tracker and username.

Apache Oozie is a workflow scheduling engine for the Hadoop platform. The
framework facilitates coordination among interdependent, recurring jobs using
the Oozie coordinator, which you can trigger by either a prescheduled time or
data availability.

## Workflow.xml
Workflow control nodes
The start control node, as shown in Listing 1, is the entry point for a workflow job. When a workflow starts, it automatically transitions to the node specified in the start.
Listing 1. Start control node
<workflow-app xmlns="uri:oozie:workflow:0.2" name="ooziedemo-wf">
    <start to="timeCheck"/>
</workflow-app>
The end control node, as shown in Listing 2, is the end of the workflow job. It indicates the workflow actions have completed successfully. A workflow definition must have an end node.
Listing 2. End control node
<workflow-app xmlns="uri:oozie:workflow:0.2" name="ooziedemo-wf">
    <end name="end"/>
</workflow-app>
The kill control node , as shown in Listing 3, enables the workflow job to stop itself. When one or more actions started by the workflow job are running when the kill node is reached, all the actions that are currently running are stopped. A workflow definition can have zero or more kill nodes.
Listing 3. Kill control code
<workflow-app xmlns="uri:oozie:workflow:0.2" name="ooziedemo-wf">
    <kill name="fail">
        <message>Sqoop failed, error message[${wf:errorMessage(wf:lastErrorNode())}]</message>
   </kill>
</workflow-app>
The decision control node, as shown in Listing 4, enables a workflow to decide on the execution path to follow. The decision node works similar to a switch-case block that has a set of predicates-transition pairs and a default transition. Predicates are evaluated in order, until one of them evaluates to true, and the corresponding transition is taken. If none of the predicates evaluates to true, the default transition is taken.
Listing 4. Decision control node
<workflow-app xmlns="uri:oozie:workflow:0.2" name="ooziedemo-wf">
    <decision name="master-decision">
       <switch>
         <case to="sqoopMerge1">
                 ${wf:actionData('hiveSwitch')['paramNum'] eq 1}
         </case>
         <default to="sqoopMerge2"/>
       </switch>
   </decision>
</workflow-app>
The fork node splits one execution path into multiple concurrent paths. The join node waits until all concurrent execution paths of the precursory fork node arrive at the join node. You must use the fork and join nodes, as shown in Listing 5, in pairs.
Listing 5. Fork-join control node
<workflow-app xmlns="uri:oozie:workflow:0.2" name="ooziedemo-wf">
    <fork name="forking">
        <path start="sqoopMerge1"/>
        <path start="sqoopMerge2"/>
    </fork>
    <join name="joining" to="hiveSwitch"/>
</workflow-app>


text:
define([
    "knockout",
    "../options",
    "../CriteriaGroup",
    "../CriteriaTypes",
    "../CohortExpression",
    "../InclusionRule",
    "text!./CensoringCriteriaEditor.html",
    "../const",
    "less!./CensoringCriteriaEditor.less",
], function (
    ko,
    options,
    CriteriaGroup,
    criteriaTypes,
    CohortExpression,
    InclusionRule,
    template,
    constants
) {
    function CensoringCriteriaViewModel(params) {
        var self = this;

        self.expression = params.expression;

        self.censorCriteriaOptions = [
            {
                ...constants.censoringEventList.addConditionEra,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        ConditionEra: new criteriaTypes.ConditionEra(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addConditionOccurrence,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        ConditionOccurrence: new criteriaTypes.ConditionOccurrence(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addDeath,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        Death: new criteriaTypes.Death(
                            null,
                            unwrappedExpression.ConceptSets),
                    });
                },
            },
            {
                ...constants.censoringEventList.addDeviceExposure,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        DeviceExposure: new criteriaTypes.DeviceExposure(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addDoseEra,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        DoseEra: new criteriaTypes.DoseEra(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addDrugEra,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        DrugEra: new criteriaTypes.DrugEra(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addDrugExposure,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        DrugExposure: new criteriaTypes.DrugExposure(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addMeasurement,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        Measurement: new criteriaTypes.Measurement(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addObservation,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        Observation: new criteriaTypes.Observation(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addPayerPlanPeriod,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        PayerPlanPeriod: new criteriaTypes.PayerPlanPeriod(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addProcedureOccurrence,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        ProcedureOccurrence: new criteriaTypes.ProcedureOccurrence(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addSpecimen,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        Specimen: new criteriaTypes.Specimen(
                            null,
                            unwrappedExpression.ConceptSets
                        )
                    });
                }
            },
            {
                ...constants.censoringEventList.addVisit,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        VisitOccurrence: new criteriaTypes.VisitOccurrence(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.addVisitDetail,
                selected: false,
                action: function () {
                    var unwrappedExpression = ko.utils.unwrapObservable(self.expression);
                    unwrappedExpression.CensoringCriteria.push({
                        VisitDetail: new criteriaTypes.VisitDetail(
                            null,
                            unwrappedExpression.ConceptSets
                        ),
                    });
                },
            },
            {
                ...constants.censoringEventList.fromReusable,
                selected: false,
                action: function () {
                    self.showReusablesModal(true);
                }
            },
        ];

        self.removeCensoringCriteria = function (criteria) {
            ko.utils.unwrapObservable(self.expression).CensoringCriteria.remove(criteria);
        };

        self.getCriteriaIndexComponent = function (data) {
            data = ko.utils.unwrapObservable(data);

            if (data.hasOwnProperty("ConditionOccurrence"))
                return "condition-occurrence-criteria";
            else if (data.hasOwnProperty("ConditionEra"))
                return "condition-era-criteria";
            else if (data.hasOwnProperty("DrugExposure"))
                return "drug-exposure-criteria";
            else if (data.hasOwnProperty("DrugEra")) return "drug-era-criteria";
            else if (data.hasOwnProperty("DoseEra")) return "dose-era-criteria";
            else if (data.hasOwnProperty("ProcedureOccurrence"))
                return "procedure-occurrence-criteria";
            else if (data.hasOwnProperty("Observation"))
                return "observation-criteria";
            else if (data.hasOwnProperty("VisitOccurrence"))
                return "visit-occurrence-criteria";
            else if (data.hasOwnProperty("VisitDetail"))
                return "visit-detail-criteria";
            else if (data.hasOwnProperty("DeviceExposure"))
                return "device-exposure-criteria";
            else if (data.hasOwnProperty("Measurement"))
                return "measurement-criteria";
            else if (data.hasOwnProperty("Specimen")) return "specimen-criteria";
            else if (data.hasOwnProperty("ObservationPeriod"))
                return "observation-period-criteria";
            else if (data.hasOwnProperty("PayerPlanPeriod"))
                return "payer-plan-period-criteria";
            else if (data.hasOwnProperty("Death")) return "death-criteria";
            else if (data.hasOwnProperty("LocationRegion"))
                return "location-region-criteria";
            else return "unknownCriteriaType";
        };

        self.showReusablesModal = ko.observable(false);
        self.insertFromReusable = (expression, conceptSets) => {
            const unwrappedExpression = ko.utils.unwrapObservable(self.expression);
            if (conceptSets.length > 0) {
                unwrappedExpression.ConceptSets(unwrappedExpression.ConceptSets().concat(conceptSets));
            }
            ko.utils.arrayForEach(expression.CriteriaList(), c => {
                unwrappedExpression.CensoringCriteria.push(c);
            });
        };
    }

    return {
        viewModel: CensoringCriteriaViewModel,
        template: template
    };
});


text:
<?php

namespace Oro\Bundle\EntityConfigBundle\Tests\Unit\Stub;

class TestEntity2
{
}


text:
<?php
class testNPathComplexityForTryCatchStatementWithNestedIfStatements
{
    function testNPathComplexityForTryCatchStatementWithNestedIfStatements()
    {
        try {
            if (true) {}
        } catch (E1 $e) {
            if (false) {
            } else {
                if (true) {}
            }
        }
    }
}


text:
import React from 'react';
import ReactDOM from 'react-dom';
import {Paper, List, ListItem, Subheader} from 'material-ui';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import ContentSend from 'material-ui/svg-icons/content/send';
import ContentDrafts from 'material-ui/svg-icons/content/drafts';
import Divider from 'material-ui/Divider';
import ActionInfo from 'material-ui/svg-icons/action/info';

export default class Results extends React.Component {
  render() {
    const paper = {
      height: '25%',
      width: '60%',
      marginLeft: '20%',
      marginRight: '20%',
      textAlign: 'center',
      display: 'inline-block',
    };
    console.log("props",this.props.results);
    return (
      <List>
        <Subheader>Here's what we found:</Subheader>
        {this.props.results
          ? this.props.results.map(item => (
            <a key={item.name} href={item.link} target="_blank" style={{ linkStyle: 'none' }}>
              <ListItem primaryText={item.title} /><Divider/>
            </a>
          ))
          : null
        }
      </List>
    );
  }
}


text:
Charicharts.PercentageBar = CClass.extend({

  modules: [
    p_svg,
    p_percentage_bar
  ],

  getInstanceProperties: function() {
    return _.pick(this.$scope, 'bar');
  },

  defaults: {
    margin: '0 0 0 0',
    orientation: 'horizontal',
    hoverFade: 1,
    gridTicks: 0
  },

  parseOptions: function(options) {
    var o = _.extend({}, this.defaults, options);

    o.margin = _.object(['top', 'right', 'bottom', 'left'],
      o.margin.split(' ').map(Number));

    var responsive = !o.margin.left && !o.margin.right;

    o.fullWidth = responsive ? '100%' : o.target.offsetWidth;
    o.fullHeight = o.target.offsetHeight;

    if (!responsive) {
      o.width = o.fullWidth - o.margin.left - o.margin.right;
    }

    o.height = o.fullHeight - o.margin.top - o.margin.bottom;
    o.gmainTranslate = h_getTranslate(o.margin.left, o.margin.top);
    return o;
  }

});


text:
require 'desk/api/modules/listable'
require 'desk/facebook_user'

module Desk
  module Api
    class FacebookUsers

      include Desk::Api::Listable

      attr_reader :connection, :endpoint, :return_class

      def initialize(connection)
        @connection = connection
        @endpoint = "facebook_users"
        @return_class = Desk::FacebookUser
      end
    end
  end
end


text:
package org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * @author ilyas
 */
public interface GrBinaryExpression extends GrOperatorExpression {

  /**
   * @return left operand of binary expression
   */
  @NotNull
  GrExpression getLeftOperand();

  /**
   * @return right operand of binary expression
   */
  @Nullable
  GrExpression getRightOperand();
}


text:
define(['jquery', 'alertify', 'socketio', 'domReady!'], function($, alertify, io, doc) {

    console.log('notification.js called');

    var socket = io.connect('http://localhost:3000');

    $('.click-me-button').on('click', function() {
        socket.emit('message', { name: 'Bobby', message: ' has clicked on the button !' });
    });

    socket.on( 'message', function(data) {
        alertify.success('<strong>' + data.name + '</strong>' + data.message);
    });
});


text:
namespace Google.Cloud.Metastore.V1Alpha.Snippets
{
    // [START metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_sync]
    using Google.Cloud.Metastore.V1Alpha;
    using Google.LongRunning;

    public sealed partial class GeneratedDataprocMetastoreClientSnippets
    {
        /// <summary>Snippet for ExportMetadata</summary>
        /// <remarks>
        /// This snippet has been automatically generated and should be regarded as a code template only.
        /// It will require modifications to work:
        /// - It may require correct/in-range values for request initialization.
        /// - It may require specifying regional endpoints when creating the service client as shown in
        ///   https://cloud.google.com/dotnet/docs/reference/help/client-configuration#endpoint.
        /// </remarks>
        public void ExportMetadataRequestObject()
        {
            // Create client
            DataprocMetastoreClient dataprocMetastoreClient = DataprocMetastoreClient.Create();
            // Initialize request argument(s)
            ExportMetadataRequest request = new ExportMetadataRequest
            {
                ServiceAsServiceName = ServiceName.FromProjectLocationService("[PROJECT]", "[LOCATION]", "[SERVICE]"),
                DestinationGcsFolder = "",
                RequestId = "",
                DatabaseDumpType = DatabaseDumpSpec.Types.Type.Unspecified,
            };
            // Make the request
            Operation<MetadataExport, OperationMetadata> response = dataprocMetastoreClient.ExportMetadata(request);

            // Poll until the returned long-running operation is complete
            Operation<MetadataExport, OperationMetadata> completedResponse = response.PollUntilCompleted();
            // Retrieve the operation result
            MetadataExport result = completedResponse.Result;

            // Or get the name of the operation
            string operationName = response.Name;
            // This name can be stored, then the long-running operation retrieved later by name
            Operation<MetadataExport, OperationMetadata> retrievedResponse = dataprocMetastoreClient.PollOnceExportMetadata(operationName);
            // Check if the retrieved long-running operation has completed
            if (retrievedResponse.IsCompleted)
            {
                // If it has completed, then access the result
                MetadataExport retrievedResult = retrievedResponse.Result;
            }
        }
    }
    // [END metastore_v1alpha_generated_DataprocMetastore_ExportMetadata_sync]
}


text:
#ifndef INSTRGRAB_H
#define INSTRGRAB_H

#define MAX_LABELS 1000
#define MAX_IMMS 64

#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>

#include "Checker.h"

using namespace std;

class InstructionGrab {
	public:
		ifstream filestream;
		Checker chkr;

		string LabelTable[MAX_LABELS][2];
		int ImmTable[MAX_IMMS];

		string line;
		string opcode;
		string immAddr;
		string temp;

		int CurrLine;
		int InstrAddr;

		InstructionGrab(string);
		string getLine();
		bool getOpcode();
};

#endif


text:
from __future__ import unicode_literals

import os

INSTALLED_APPS = [
    'wagtailvideos',
    'tests.app',

    'taggit',
    'modelcluster',

    'wagtail.core',
    'wagtail.admin',
    'wagtail.users',
    'wagtail.sites',
    'wagtail.snippets',
    'wagtail.images',
    'wagtail.documents',

    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.staticfiles',
]

SECRET_KEY = 'not a secret'

ROOT_URLCONF = 'tests.app.urls'

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': ':memory:',
    },
}

WAGTAIL_SITE_NAME = 'Wagtail Videos'

DEBUG = True

USE_TZ = True
TIME_ZONE = 'Australia/Hobart'

MIDDLEWARE = [
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

    'wagtail.core.middleware.SiteMiddleware',
]

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.contrib.auth.context_processors.auth',
                'django.template.context_processors.debug',
                'django.template.context_processors.i18n',
                'django.template.context_processors.media',
                'django.template.context_processors.static',
                'django.template.context_processors.tz',
                'django.template.context_processors.request',
                'django.contrib.messages.context_processors.messages'
            ],
        },
    },
]

DEFAULT_FILE_STORAGE = 'tests.storage.RemoteStorage'

STATIC_ROOT = os.path.join(os.path.dirname(__file__), 'static')
STATIC_URL = '/static/'

MEDIA_ROOT = os.path.join(os.path.dirname(__file__), 'media')
MEDIA_URL = '/media/'


text:
/*
 * optitrack.cpp
 *
 *  Created on: Aug 19, 2014
 *      Author: Bjorn Blissing
 */

#include "optitrack.h"
#include <iostream>

int OptiTrack::initialize()
{
	if (m_projectFile.empty()) {
		std::cerr << "Error: OptiTrack Project filename cannot be empty." << std::endl;
		return 1;
	}

	int errorCode = 0;
	// Try to initialize the OptiTrack system
	errorCode = checkResult(TT_Initialize());
	// Do an update to pick up any recently-arrived cameras.
	errorCode = checkResult(TT_Update());
	// Load project definition file
	errorCode = checkResult(TT_LoadProject(m_projectFile.c_str()));

	if (errorCode == NPRESULT_SUCCESS) {
		m_initialized = true;
		return 0;
	}

	return errorCode;
}

int OptiTrack::terminate()
{
	int errorCode = checkResult(TT_Shutdown());
	m_initialized = false;
	return errorCode;
}

size_t OptiTrack::getNumberOfCameras() const
{
	if (m_initialized) {
		return TT_CameraCount();
	}

	return 0;
}

size_t OptiTrack::getNumberOfRigidBodies() const
{
	if (m_initialized) {
		return TT_RigidBodyCount();
	}

	return 0;
}

std::string OptiTrack::getNameOfCamera(int id) const
{
	if (m_initialized) {
		if (id <= TT_CameraCount()) {
			return std::string(TT_CameraName(id));
		}
	}

	return std::string("");
}

std::string OptiTrack::getNameOfRigidBody(int id) const
{
	if (m_initialized) {
		if (id <= TT_RigidBodyCount()) {
			return std::string(TT_RigidBodyName(id));
		}
	}

	return std::string("");
}

bool OptiTrack::getPosition(int rigidBodyId, float& x, float& y, float& z)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx, qy, qz, qw, yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& yaw, float& pitch, float& roll)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, qx, qy, qz, qw;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getOrientation(int rigidBodyId, float& qx, float& qy, float& qz, float& qw)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float x, y, z, yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& yaw, float& pitch, float& roll)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float qx,qy,qz,qw;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

bool OptiTrack::getPositionAndOrientation(int rigidBodyId, float& x, float& y, float& z, float& qx, float& qy, float& qz, float& qw)
{
	if (m_initialized &&  TT_Update() == NPRESULT_SUCCESS ) {
		float yaw, pitch, roll;
		TT_RigidBodyLocation( rigidBodyId, &x, &y, &z, &qx, &qy, &qz, &qw, &yaw, &pitch, &roll);

		if ( TT_IsRigidBodyTracked(rigidBodyId)) {
			return true;
		}
	}

	return false;
}

int OptiTrack::checkResult(int result)
{
	if (result != NPRESULT_SUCCESS) {
		std::cerr << "Error: " << TT_GetResultString(result) << std::endl;
	}

	return result;
}


text:
class Go < Formula
  desc "Go programming environment"
  homepage "https://golang.org"
  # Version 1.5 is going to require version 1.4 present to bootstrap 1.4
  # Perhaps we can use our previous bottles, ala the discussion around PyPy?
  # https://docs.google.com/document/d/1OaatvGhEAq7VseQ9kkavxKNAfepWy2yhPUBs96FGV28
  url "https://storage.googleapis.com/golang/go1.4.2.src.tar.gz"
  sha1 "460caac03379f746c473814a65223397e9c9a2f6"
  version "1.4.2"

  head "https://github.com/golang/go.git"

  devel do
    url "https://storage.googleapis.com/golang/go1.5beta1.src.tar.gz"
    sha256 "e02be87011421dc08ae6d03a3dc07492cad03faf83cb4f8ba8d39a403d38d3a1"
    version "1.5beta1"
  end

  bottle do
    revision 2
    sha256 "bb8b8e79201d93eb69e77763535b201ea812d426e259f106e18f62ddf80f86dd" => :yosemite
    sha256 "46fbe85b2c75e45686ee463eeaa975ce1604f04ee611815d7c163f5feee90e03" => :mavericks
    sha256 "7913ecbc952e22f9d6e5df114b857ed23ad97adcbc88419fa3b6425b856ee38e" => :mountain_lion
  end

  option "with-cc-all", "Build with cross-compilers and runtime support for all supported platforms"
  option "with-cc-common", "Build with cross-compilers and runtime support for darwin, linux and windows"
  option "without-cgo", "Build without cgo"
  option "without-godoc", "godoc will not be installed for you"
  option "without-vet", "vet will not be installed for you"

  deprecated_option "cross-compile-all" => "with-cc-all"
  deprecated_option "cross-compile-common" => "with-cc-common"

  resource "gotools" do
    url "https://go.googlesource.com/tools.git",
    :revision => "69db398fe0e69396984e3967724820c1f631e971"
  end

  resource "gobootstrap" do
    if MacOS.version > :lion
      url "https://storage.googleapis.com/golang/go1.4.2.darwin-amd64-osx10.8.tar.gz"
      sha1 "58a04b3eb9853c75319d9076df6f3ac8b7430f7f"
    else
      url "https://storage.googleapis.com/golang/go1.4.2.darwin-amd64-osx10.6.tar.gz"
      sha1 "00c3f9a03daff818b2132ac31d57f054925c60e7"
    end
  end

  def install
    # host platform (darwin) must come last in the targets list
    if build.with? "cc-all"
      targets = [
        ["linux",   ["386", "amd64", "arm"]],
        ["freebsd", ["386", "amd64", "arm"]],
        ["netbsd",  ["386", "amd64", "arm"]],
        ["openbsd", ["386", "amd64"]],
        ["windows", ["386", "amd64"]],
        ["dragonfly", ["386", "amd64"]],
        ["plan9",   ["386", "amd64"]],
        ["solaris", ["amd64"]],
        ["darwin",  ["386", "amd64"]],
      ]
    elsif build.with? "cc-common"
      targets = [
        ["linux",   ["386", "amd64", "arm"]],
        ["windows", ["386", "amd64"]],
        ["darwin",  ["386", "amd64"]],
      ]
    else
      targets = [[`uname`.strip.downcase, [""]]]
    end

    if build.head? || build.devel?
      # GOROOT_FINAL must be overidden later on real Go install
      ENV["GOROOT_FINAL"] = buildpath/"gobootstrap"

      # build the gobootstrap toolchain Go >=1.4
      (buildpath/"gobootstrap").install resource("gobootstrap")
      cd "#{buildpath}/gobootstrap/src" do
        system "./make.bash", "--no-clean"
      end
      # This should happen after we build the test Go, just in case
      # the bootstrap toolchain is aware of this variable too.
      ENV["GOROOT_BOOTSTRAP"] = ENV["GOROOT_FINAL"]
    end

    cd "src" do
      targets.each do |os, archs|
        cgo_enabled = os == "darwin" && build.with?("cgo") ? "1" : "0"
        archs.each do |arch|
          ENV["GOROOT_FINAL"] = libexec
          ENV["GOOS"]         = os
          ENV["GOARCH"]       = arch
          ENV["CGO_ENABLED"]  = cgo_enabled
          ohai "Building go for #{arch}-#{os}"
          system "./make.bash", "--no-clean"
        end
      end
    end

    (buildpath/"pkg/obj").rmtree
    libexec.install Dir["*"]
    bin.install_symlink Dir["#{libexec}/bin/go*"]

    if build.with?("godoc") || build.with?("vet")
      ENV.prepend_path "PATH", bin
      ENV["GOPATH"] = buildpath
      (buildpath/"src/golang.org/x/tools").install resource("gotools")

      if build.with? "godoc"
        cd "src/golang.org/x/tools/cmd/godoc/" do
          system "go", "build"
          (libexec/"bin").install "godoc"
        end
        bin.install_symlink libexec/"bin/godoc"
      end

      if build.with? "vet"
        cd "src/golang.org/x/tools/cmd/vet/" do
          system "go", "build"
          # This is where Go puts vet natively; not in the bin.
          (libexec/"pkg/tool/darwin_amd64/").install "vet"
        end
      end
    end
  end

  def caveats; <<-EOS.undent
    As of go 1.2, a valid GOPATH is required to use the `go get` command:
      https://golang.org/doc/code.html#GOPATH

    You may wish to add the GOROOT-based install location to your PATH:
      export PATH=$PATH:#{opt_libexec}/bin
    EOS
  end

  test do
    (testpath/"hello.go").write <<-EOS.undent
    package main

    import "fmt"

    func main() {
        fmt.Println("Hello World")
    }
    EOS
    # Run go fmt check for no errors then run the program.
    # This is a a bare minimum of go working as it uses fmt, build, and run.
    system "#{bin}/go", "fmt", "hello.go"
    assert_equal "Hello World\n", `#{bin}/go run hello.go`

    if build.with? "godoc"
      assert File.exist?(libexec/"bin/godoc")
      assert File.executable?(libexec/"bin/godoc")
    end
    if build.with? "vet"
      assert File.exist?(libexec/"pkg/tool/darwin_amd64/vet")
      assert File.executable?(libexec/"pkg/tool/darwin_amd64/vet")
    end
  end
end


text:
const render_more_topics = require('../templates/more_topics.hbs');
const render_more_topics_spinner = require('../templates/more_topics_spinner.hbs');
const render_topic_list_item = require('../templates/topic_list_item.hbs');
const topic_list_data = require('./topic_list_data');

/*
    Track all active widgets with a Map.

    (We have at max one for now, but we may
    eventually allow multiple streams to be
    expanded.)
*/

const active_widgets = new Map();

// We know whether we're zoomed or not.
let zoomed = false;

exports.update = function () {
    for (const widget of active_widgets.values()) {
        widget.build();
    }
};

exports.clear = function () {
    stream_popover.hide_topic_popover();

    for (const widget of active_widgets.values()) {
        widget.remove();
    }

    active_widgets.clear();
};

exports.close = function () {
    zoomed = false;
    exports.clear();
};

exports.zoom_out = function () {
    zoomed = false;

    const stream_ids = Array.from(active_widgets.keys());

    if (stream_ids.length !== 1) {
        blueslip.error('Unexpected number of topic lists to zoom out.');
        return;
    }

    const stream_id = stream_ids[0];
    const widget = active_widgets.get(stream_id);
    const parent_widget = widget.get_parent();

    exports.rebuild(parent_widget, stream_id);
};

exports.keyed_topic_li = (convo) => {
    const render = () => {
        return render_topic_list_item(convo);
    };

    const eq = (other) => {
        return _.isEqual(convo, other.convo);
    };

    const key = 't:' + convo.topic_name;

    return {
        key: key,
        render: render,
        convo: convo,
        eq: eq,
    };
};

exports.more_li = (more_topics_unreads) => {
    const render = () => {
        return render_more_topics({
            more_topics_unreads: more_topics_unreads,
        });
    };

    const eq = (other) => {
        return other.more_items &&
            more_topics_unreads === other.more_topics_unreads;
    };

    const key = 'more';

    return {
        key: key,
        more_items: true,
        more_topics_unreads: more_topics_unreads,
        render: render,
        eq: eq,
    };
};

exports.spinner_li = () => {
    const render = () => {
        return render_more_topics_spinner();
    };

    const eq = (other) => {
        return other.spinner;
    };

    const key = 'more';

    return {
        key: key,
        spinner: true,
        render: render,
        eq: eq,
    };
};

exports.widget = function (parent_elem, my_stream_id) {
    const self = {};

    self.prior_dom = undefined;

    self.build_list = function (spinner) {
        const list_info = topic_list_data.get_list_info(
            my_stream_id, zoomed);

        const num_possible_topics = list_info.num_possible_topics;
        const more_topics_unreads = list_info.more_topics_unreads;

        const is_showing_all_possible_topics =
            list_info.items.length === num_possible_topics &&
            stream_topic_history.is_complete_for_stream_id(my_stream_id);

        const attrs = [
            ['class', 'topic-list'],
        ];

        const nodes = list_info.items.map(exports.keyed_topic_li);

        if (spinner) {
            nodes.push(exports.spinner_li());
        } else if (!is_showing_all_possible_topics) {
            nodes.push(exports.more_li(more_topics_unreads));
        }

        const dom = vdom.ul({
            attrs: attrs,
            keyed_nodes: nodes,
        });

        return dom;
    };

    self.get_parent = function () {
        return parent_elem;
    };

    self.get_stream_id = function () {
        return my_stream_id;
    };

    self.remove = function () {
        parent_elem.find('.topic-list').remove();
        self.prior_dom = undefined;
    };

    self.build = function (spinner) {
        const new_dom = self.build_list(spinner);

        function replace_content(html) {
            self.remove();
            parent_elem.append(html);
        }

        function find() {
            return parent_elem.find('.topic-list');
        }

        vdom.update(replace_content, find, new_dom, self.prior_dom);

        self.prior_dom = new_dom;
    };

    return self;
};

exports.active_stream_id = function () {
    const stream_ids = Array.from(active_widgets.keys());

    if (stream_ids.length !== 1) {
        return;
    }

    return stream_ids[0];
};

exports.get_stream_li = function () {
    const widgets = Array.from(active_widgets.values());

    if (widgets.length !== 1) {
        return;
    }

    const stream_li = widgets[0].get_parent();
    return stream_li;
};

exports.rebuild = function (stream_li, stream_id) {
    const active_widget = active_widgets.get(stream_id);

    if (active_widget) {
        active_widget.build();
        return;
    }

    exports.clear();
    const widget = exports.widget(stream_li, stream_id);
    widget.build();

    active_widgets.set(stream_id, widget);
};

// For zooming, we only do topic-list stuff here...let stream_list
// handle hiding/showing the non-narrowed streams
exports.zoom_in = function () {
    zoomed = true;

    const stream_id = exports.active_stream_id();
    if (!stream_id) {
        blueslip.error('Cannot find widget for topic history zooming.');
        return;
    }

    const active_widget = active_widgets.get(stream_id);

    function on_success() {
        if (!active_widgets.has(stream_id)) {
            blueslip.warn('User re-narrowed before topic history was returned.');
            return;
        }

        if (!zoomed) {
            blueslip.warn('User zoomed out before topic history was returned.');
            // Note that we could attempt to re-draw the zoomed out topic list
            // here, given that we have more history, but that might be more
            // confusing than helpful to a user who is likely trying to browse
            // other streams.
            return;
        }

        active_widget.build();
    }

    ui.get_scroll_element($('#stream-filters-container')).scrollTop(0);

    const spinner = true;
    active_widget.build(spinner);

    stream_topic_history.get_server_history(stream_id, on_success);
};

exports.initialize = function () {
    $('#stream_filters').on('click', '.topic-box', function (e) {
        if (e.metaKey || e.ctrlKey) {
            return;
        }
        if ($(e.target).closest('.show-more-topics').length > 0) {
            return;
        }

        // In a more componentized world, we would delegate some
        // of this stuff back up to our parents.

        const stream_row = $(e.target).parents('.narrow-filter');
        const stream_id = parseInt(stream_row.attr('data-stream-id'), 10);
        const sub = stream_data.get_sub_by_id(stream_id);
        const topic = $(e.target).parents('li').attr('data-topic-name');

        narrow.activate([
            {operator: 'stream', operand: sub.name},
            {operator: 'topic', operand: topic}],
                        {trigger: 'sidebar'});

        e.preventDefault();
    });
};

window.topic_list = exports;


text:
import * as gulp from 'gulp';
import * as gulpLoadPlugins from 'gulp-load-plugins';
import * as merge from 'merge-stream';
import { join } from 'path';

import { TMP_DIR, TOOLS_DIR, BOOTSTRAP_MODULE, ENV } from '../../config';
import { makeTsProject, templateLocals } from '../../utils';

const plugins = <any>gulpLoadPlugins();

const INLINE_OPTIONS = {
  base: TMP_DIR,
  useRelativePaths: false,
  removeLineBreaks: true
};

const isDev = ENV === 'dev';

export = () => {
  let tsProject = makeTsProject();

  let typings = gulp.src([
    'typings/browser.d.ts',
    TOOLS_DIR + '/manual_typings/**/*.d.ts'
  ]);

  let baseSrc = [
    join(TMP_DIR, '**/*.ts'),
    '!' + join(TMP_DIR, '**/node_modules/**/*.ts')
  ];

  let src = baseSrc.concat(getGlobBasedOnEnv(ENV));

  let projectFiles = gulp.src(src)
   .pipe(plugins.cached());

  let result = merge(typings, projectFiles)
    .pipe(plugins.plumber())
    .pipe(plugins.sourcemaps.init())
    // TODO css must be created prior to running this in order to merge it into the javascript
    .pipe(isDev ? plugins.util.noop() : plugins.inlineNg2Template(INLINE_OPTIONS))
    .pipe(plugins.typescript(tsProject));

  return result.js
    .pipe(plugins.sourcemaps.write('.'))
    .pipe(plugins.template(templateLocals()))
    .pipe(gulp.dest(TMP_DIR));
};

function getGlobBasedOnEnv(env: string): string[] {
  switch (env) {
    case 'dev':
      return ['!' + join(TMP_DIR, '**/*.spec.ts'),
              '!' + join(TMP_DIR, '**/*.e2e-spec.ts')];
    case 'test':
      return ['!' + join(TMP_DIR, '**/*.e2e-spec.ts'),
              '!' + join(TMP_DIR, `${BOOTSTRAP_MODULE}.ts`)];
    case 'e2e':
      return ['!' + join(TMP_DIR, '**/*.spec.ts')];
    case 'prod':
    default:
      return [];

  }
}