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

import os
import sys
from collections import defaultdict
from contextlib import contextmanager

from twitter.common.collections import OrderedSet

from pants.base.build_environment import get_buildroot, get_scm
from pants.base.worker_pool import SubprocPool
from pants.base.workunit import WorkUnitLabel
from pants.build_graph.target import Target
from pants.engine.isolated_process import ExecuteProcessResult
from pants.goal.products import Products
from pants.goal.workspace import ScmWorkspace
from pants.process.lock import OwnerPrintingInterProcessFileLock
from pants.reporting.report import Report
from pants.source.source_root import SourceRootConfig

class Context(object):
  """Contains the context for a single run of pants.

  Task implementations can access configuration data from pants.ini and any flags they have exposed
  here as well as information about the targets involved in the run.

  Advanced uses of the context include adding new targets to it for upstream or downstream goals to
  operate on and mapping of products a goal creates to the targets the products are associated with.

  :API: public
  """

  class Log(object):
    """A logger facade that logs into the pants reporting framework."""

    def __init__(self, run_tracker):
      self._run_tracker = run_tracker

    def debug(self, *msg_elements):
      self._run_tracker.log(Report.DEBUG, *msg_elements)

    def info(self, *msg_elements):
      self._run_tracker.log(Report.INFO, *msg_elements)

    def warn(self, *msg_elements):
      self._run_tracker.log(Report.WARN, *msg_elements)

    def error(self, *msg_elements):
      self._run_tracker.log(Report.ERROR, *msg_elements)

    def fatal(self, *msg_elements):
      self._run_tracker.log(Report.FATAL, *msg_elements)

  # TODO: Figure out a more structured way to construct and use context than this big flat
  # repository of attributes?
  def __init__(self, options, run_tracker, target_roots,
               requested_goals=None, target_base=None, build_graph=None,
               build_file_parser=None, address_mapper=None, console_outstream=None, scm=None,
               workspace=None, invalidation_report=None, scheduler=None):
    self._options = options
    self.build_graph = build_graph
    self.build_file_parser = build_file_parser
    self.address_mapper = address_mapper
    self.run_tracker = run_tracker
    self._log = self.Log(run_tracker)
    self._target_base = target_base or Target
    self._products = Products()
    self._buildroot = get_buildroot()
    self._source_roots = SourceRootConfig.global_instance().get_source_roots()
    self._lock = OwnerPrintingInterProcessFileLock(os.path.join(self._buildroot, '.pants.workdir.file_lock'))
    self._java_sysprops = None  # Computed lazily.
    self.requested_goals = requested_goals or []
    self._console_outstream = console_outstream or sys.stdout
    self._scm = scm or get_scm()
    self._workspace = workspace or (ScmWorkspace(self._scm) if self._scm else None)
    self._replace_targets(target_roots)
    self._invalidation_report = invalidation_report
    self._scheduler = scheduler

  @property
  def options(self):
    """Returns the new-style options.

    :API: public
    """
    return self._options

  @property
  def log(self):
    """Returns the preferred logger for goals to use.

    :API: public
    """
    return self._log

  @property
  def products(self):
    """Returns the Products manager for the current run.

    :API: public
    """
    return self._products

  @property
  def source_roots(self):
    """Returns the :class:`pants.source.source_root.SourceRoots` instance for the current run.

    :API: public
    """
    return self._source_roots

  @property
  def target_roots(self):
    """Returns the targets specified on the command line.

    This set is strictly a subset of all targets in play for the run as returned by self.targets().
    Note that for a command line invocation that uses wildcard selectors : or ::, the targets
    globbed by the wildcards are considered to be target roots.

    :API: public
    """
    return self._target_roots

  @property
  def console_outstream(self):
    """Returns the output stream to write console messages to.

    :API: public
    """
    return self._console_outstream

  @property
  def scm(self):
    """Returns the current workspace's scm, if any.

    :API: public
    """
    return self._scm

  @property
  def workspace(self):
    """Returns the current workspace, if any."""
    return self._workspace

  @property
  def invalidation_report(self):
    return self._invalidation_report

  def __str__(self):
    ident = Target.identify(self.targets())
    return 'Context(id:{}, targets:{})'.format(ident, self.targets())

  @contextmanager
  def executing(self):
    """A contextmanager that sets metrics in the context of a (v1) engine execution."""
    self._set_target_root_count_in_runtracker()
    yield
    self.run_tracker.pantsd_stats.set_scheduler_metrics(self._scheduler.metrics())
    self._set_affected_target_count_in_runtracker()

  def _set_target_root_count_in_runtracker(self):
    """Sets the target root count in the run tracker's daemon stats object."""
    # N.B. `self._target_roots` is always an expanded list of `Target` objects as
    # provided by `GoalRunner`.
    target_count = len(self._target_roots)
    self.run_tracker.pantsd_stats.set_target_root_size(target_count)
    return target_count

  def _set_affected_target_count_in_runtracker(self):
    """Sets the realized target count in the run tracker's daemon stats object."""
    target_count = len(self.build_graph)
    self.run_tracker.pantsd_stats.set_affected_targets_size(target_count)
    return target_count

  def submit_background_work_chain(self, work_chain, parent_workunit_name=None):
    """
    :API: public
    """
    background_root_workunit = self.run_tracker.get_background_root_workunit()
    if parent_workunit_name:
      # We have to keep this workunit alive until all its child work is done, so
      # we manipulate the context manually instead of using it as a contextmanager.
      # This is slightly funky, but the with-context usage is so pervasive and
      # useful elsewhere that it's worth the funkiness in this one place.
      workunit_parent_ctx = self.run_tracker.new_workunit_under_parent(
        name=parent_workunit_name, labels=[WorkUnitLabel.MULTITOOL], parent=background_root_workunit)
      workunit_parent = workunit_parent_ctx.__enter__()
      done_hook = lambda: workunit_parent_ctx.__exit__(None, None, None)
    else:
      workunit_parent = background_root_workunit  # Run directly under the root.
      done_hook = None
    self.run_tracker.background_worker_pool().submit_async_work_chain(
      work_chain, workunit_parent=workunit_parent, done_hook=done_hook)

  def background_worker_pool(self):
    """Returns the pool to which tasks can submit background work.

    :API: public
    """
    return self.run_tracker.background_worker_pool()

  def subproc_map(self, f, items):
    """Map function `f` over `items` in subprocesses and return the result.

      :API: public

      :param f: A multiproc-friendly (importable) work function.
      :param items: A iterable of pickleable arguments to f.
    """
    try:
      # Pool.map (and async_map().get() w/o timeout) can miss SIGINT.
      # See: http://stackoverflow.com/a/1408476, http://bugs.python.org/issue8844
      # Instead, we map_async(...), wait *with a timeout* until ready, then .get()
      # NB: in 2.x, wait() with timeout wakes up often to check, burning CPU. Oh well.
      res = SubprocPool.foreground().map_async(f, items)
      while not res.ready():
        res.wait(60)  # Repeatedly wait for up to a minute.
        if not res.ready():
          self.log.debug('subproc_map result still not ready...')
      return res.get()
    except KeyboardInterrupt:
      SubprocPool.shutdown(True)
      raise

  @contextmanager
  def new_workunit(self, name, labels=None, cmd='', log_config=None):
    """Create a new workunit under the calling thread's current workunit.

    :API: public
    """
    with self.run_tracker.new_workunit(name=name, labels=labels, cmd=cmd, log_config=log_config) as workunit:
      yield workunit

  def acquire_lock(self):
    """ Acquire the global lock for the root directory associated with this context. When
    a goal requires serialization, it will call this to acquire the lock.

    :API: public
    """
    if self.options.for_global_scope().lock:
      if not self._lock.acquired:
        self._lock.acquire()

  def release_lock(self):
    """Release the global lock if it's held.
    Returns True if the lock was held before this call.

    :API: public
    """
    if not self._lock.acquired:
      return False
    else:
      self._lock.release()
      return True

  def is_unlocked(self):
    """Whether the global lock object is actively holding the lock.

    :API: public
    """
    return not self._lock.acquired

  def _replace_targets(self, target_roots):
    # Replaces all targets in the context with the given roots and their transitive dependencies.
    #
    # If another task has already retrieved the current targets, mutable state may have been
    # initialized somewhere, making it now unsafe to replace targets. Thus callers of this method
    # must know what they're doing!
    #
    # TODO(John Sirois): This currently has only 1 use (outside ContextTest) in pantsbuild/pants and
    # only 1 remaining known use case in the Foursquare codebase that will be able to go away with
    # the post RoundEngine engine - kill the method at that time.
    self._target_roots = list(target_roots)

  def add_new_target(self, address, target_type, target_base=None, dependencies=None,
                     derived_from=None, **kwargs):
    """Creates a new target, adds it to the context and returns it.

    This method ensures the target resolves files against the given target_base, creating the
    directory if needed and registering a source root.

    :API: public
    """
    rel_target_base = target_base or address.spec_path
    abs_target_base = os.path.join(get_buildroot(), rel_target_base)
    if not os.path.exists(abs_target_base):
      os.makedirs(abs_target_base)
      # TODO: Adding source roots on the fly like this is yucky, but hopefully this
      # method will go away entirely under the new engine. It's primarily used for injecting
      # synthetic codegen targets, and that isn't how codegen will work in the future.
    if not self.source_roots.find_by_path(rel_target_base):
      # TODO: Set the lang and root category (source/test/thirdparty) based on the target type?
      self.source_roots.add_source_root(rel_target_base)
    if dependencies:
      dependencies = [dep.address for dep in dependencies]

    self.build_graph.inject_synthetic_target(address=address,
                                             target_type=target_type,
                                             dependencies=dependencies,
                                             derived_from=derived_from,
                                             **kwargs)
    new_target = self.build_graph.get_target(address)

    return new_target

  def targets(self, predicate=None, **kwargs):
    """Selects targets in-play in this run from the target roots and their transitive dependencies.

    Also includes any new synthetic targets created from the target roots or their transitive
    dependencies during the course of the run.

    See Target.closure_for_targets for remaining parameters.

    :API: public

    :param predicate: If specified, the predicate will be used to narrow the scope of targets
                      returned.
    :param bool postorder: `True` to gather transitive dependencies with a postorder traversal;
                          `False` or preorder by default.
    :returns: A list of matching targets.
    """
    target_set = self._collect_targets(self.target_roots, **kwargs)

    synthetics = OrderedSet()
    for synthetic_address in self.build_graph.synthetic_addresses:
      if self.build_graph.get_concrete_derived_from(synthetic_address) in target_set:
        synthetics.add(self.build_graph.get_target(synthetic_address))
    target_set.update(self._collect_targets(synthetics, **kwargs))

    return filter(predicate, target_set)

  def _collect_targets(self, root_targets, **kwargs):
    return Target.closure_for_targets(
      target_roots=root_targets,
      **kwargs
    )

  def dependents(self, on_predicate=None, from_predicate=None):
    """Returns  a map from targets that satisfy the from_predicate to targets they depend on that
      satisfy the on_predicate.

    :API: public
    """
    core = set(self.targets(on_predicate))
    dependees = defaultdict(set)
    for target in self.targets(from_predicate):
      for dependency in target.dependencies:
        if dependency in core:
          dependees[target].add(dependency)
    return dependees

  def resolve(self, spec):
    """Returns an iterator over the target(s) the given address points to.

    :API: public
    """
    return self.build_graph.resolve(spec)

  def scan(self, root=None):
    """Scans and parses all BUILD files found under ``root``.

    Only BUILD files found under ``root`` are parsed as roots in the graph, but any dependencies of
    targets parsed in the root tree's BUILD files will be followed and this may lead to BUILD files
    outside of ``root`` being parsed and included in the returned build graph.

    :API: public

    :param string root: The path to scan; by default, the build root.
    :returns: A new build graph encapsulating the targets found.
    """
    build_graph = self.build_graph.clone_new()
    for address in self.address_mapper.scan_addresses(root):
      build_graph.inject_address_closure(address)
    return build_graph

  def execute_process_synchronously(self, execute_process_request, name, labels):
    """Executes a process (possibly remotely), and returns information about its output.

    :param execute_process_request: The ExecuteProcessRequest to run.
    :param name: A descriptive name representing the process being executed.
    :param labels: A tuple of WorkUnitLabels.
    :return: An ExecuteProcessResult with information about the execution.

    Note that this is an unstable, experimental API, which is subject to change with no notice.
    """
    with self.new_workunit(
      name=name,
      labels=labels,
      cmd=' '.join(execute_process_request.argv),
    ) as workunit:
      result = self._scheduler.product_request(ExecuteProcessResult, [execute_process_request])[0]
      workunit.output("stdout").write(result.stdout)
      workunit.output("stderr").write(result.stderr)
      return result


text:
package core.aws.task.elb.v2;

import core.aws.env.Context;
import core.aws.resource.elb.v2.TargetGroup;
import core.aws.workflow.Action;
import core.aws.workflow.Task;

@Action("describe-tg")
public class DescribeTargetGroupTask extends Task<TargetGroup> {
    public DescribeTargetGroupTask(TargetGroup resource) {
        super(resource);
    }

    @Override
    public void execute(Context context) throws Exception {
        String key = "tg/" + resource.id;
        context.output(key, String.format("name=%s, health-check=%s", resource.name, resource.healthCheckURL));

        if (resource.remoteTG != null) {
            context.output(key, String.format("arn=%s", resource.remoteTG.getTargetGroupArn()));
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
import { TextManipulator } from "./TextManipulator";

export class FullReplacementTextManipulator implements TextManipulator {
    constructor(private readonly newText: string) {
    }

    getNewText(inputText: string) {
        return this.newText;
    }

    getTextForError(newText: string) {
        return newText;
    }
}


text:
package io.github.mzmine.modules.tools.clear_project;

import io.github.mzmine.datamodel.MZmineProject;
import io.github.mzmine.modules.MZmineModuleCategory;
import io.github.mzmine.modules.MZmineProcessingModule;
import io.github.mzmine.parameters.ParameterSet;
import io.github.mzmine.parameters.impl.SimpleParameterSet;
import io.github.mzmine.taskcontrol.Task;
import io.github.mzmine.util.ExitCode;
import java.time.Instant;
import java.util.Collection;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

public class ClearProjectModule implements MZmineProcessingModule {

  @Override
  public @NotNull String getName() {
    return "Clear project";
  }

  @Override
  public @Nullable Class<? extends ParameterSet> getParameterSetClass() {
    return SimpleParameterSet.class;
  }

  @Override
  public @NotNull String getDescription() {
    return "Clearing all project files and feature lists";
  }

  @Override
  public @NotNull ExitCode runModule(@NotNull MZmineProject project,
      @NotNull ParameterSet parameters, @NotNull Collection<Task> tasks,
      @NotNull Instant moduleCallDate) {
    tasks.add(new ClearProjectTask(moduleCallDate));
    return ExitCode.OK;
  }

  @Override
  public @NotNull MZmineModuleCategory getModuleCategory() {
    return MZmineModuleCategory.PROJECT;
  }
}


text:
package jetbrains.exodus.tree.btree;

import org.jetbrains.annotations.Nullable;

/**
 * Result of binary search
 */
public class SearchRes {

    public static final SearchRes NOT_FOUND = new SearchRes(-1);

    public final int index;
    public final ILeafNode key;

    public SearchRes(int index, @Nullable ILeafNode key) {
        this.index = index;
        this.key = key;
    }

    public SearchRes(int index) {
        this(index, null);
    }

}


text:
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <geometry_msgs/Transform.h>
#include <nav_msgs/Odometry.h>
#include <sensor_msgs/Imu.h>
#include <iostream>

#include <std_srvs/Empty.h>
#include <naoqi_msgs/SetTransform.h>

#include <tf/transform_broadcaster.h>
#include <tf/transform_datatypes.h>

// Aldebaran includes
#include <alproxies/almemoryproxy.h>
#include <alproxies/almotionproxy.h>
#include <alvision/alvisiondefinitions.h>
#include <alerror/alerror.h>
#include <alvalue/alvalue.h>
#include <alcommon/altoolsmain.h>
#include <alproxies/alvideodeviceproxy.h>
#include <alcommon/albroker.h>
#include <alcommon/albrokermanager.h>
#include <alcommon/alproxy.h>
#include <alproxies/alproxies.h>
#include <alproxies/almotionproxy.h>
#include <alproxies/almemoryproxy.h>
#include <alcommon/almodule.h>
#include <alcommon/albroker.h>
#include <alcommon/albrokermanager.h>

#include <naoqi_driver/naoqi_node.h>

// Other includes
#include <boost/program_options.hpp>

using namespace std;

class NaoqiJointStates : public NaoqiNode
{
public:

    NaoqiJointStates(int argc, char ** argv);
    ~NaoqiJointStates();

    bool connectProxy();
    void run();

    bool pauseOdomCallback(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res);
    bool resumeOdomCallback(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res);
    bool odomOffsetCallback(naoqi_msgs::SetTransform::Request& req, naoqi_msgs::SetTransform::Response& res);
    bool setOdomPoseCallback(naoqi_msgs::SetTransform::Request& req, naoqi_msgs::SetTransform::Response& res);

protected:

    double m_rate;

    // NAOqi
    boost::shared_ptr<AL::ALMotionProxy> m_motionProxy;
    boost::shared_ptr<AL::ALMemoryProxy> m_memoryProxy;
    AL::ALValue m_dataNamesList;

    // ROS
    ros::NodeHandle m_nh;
    ros::NodeHandle m_privateNh;

    // Services
    ros::ServiceServer m_pauseOdomSrv;
    ros::ServiceServer m_resumeOdomSrv;
    ros::ServiceServer m_odomOffsetSrv;
    ros::ServiceServer m_setOdomPoseSrv;

    std::string m_odomFrameId;
    std::string m_baseFrameId;

    nav_msgs::Odometry m_odom;
    sensor_msgs::Imu m_torsoIMU;
    sensor_msgs::JointState m_jointState;

    ros::Publisher m_odomPub;
    tf::TransformBroadcaster m_transformBroadcaster;
    ros::Publisher m_torsoIMUPub;
    ros::Publisher m_jointStatePub;

    // Odometry-specific members
    geometry_msgs::TransformStamped m_odomTransformMsg;
    tf::Pose m_odomPose; // current "real" odometry pose in original (Nao) odom frame
    tf::Transform m_odomOffset; // offset on odometry origin

    bool m_useIMUAngles;

    bool m_paused;
    double m_lastOdomTime;

    tf::Pose m_targetPose;
    bool m_mustUpdateOffset;
    bool m_initializeFromIMU;
    bool m_initializeFromOdometry;
    bool m_isInitialized;
};

bool NaoqiJointStates::connectProxy()
{
   if (!m_broker)
   {
      ROS_ERROR("Broker is not ready. Have you called connectNaoQi()?");
      return false;
   }
   try
   {
      //m_motionProxy = boost::shared_ptr<AL::ALProxy>(m_broker->getProxy("ALMotion"));
      m_motionProxy = boost::shared_ptr<AL::ALMotionProxy>(new AL::ALMotionProxy(m_broker));
   }
   catch (const AL::ALError& e)
   {
      ROS_ERROR("Could not create ALMotionProxy.");
      return false;
   }
   try
   {
      //m_memoryProxy = boost::shared_ptr<AL::ALMemoryProxy>(m_broker->getProxy("ALMemory"));
      m_memoryProxy = boost::shared_ptr<AL::ALMemoryProxy>(new AL::ALMemoryProxy(m_broker));
   }
   catch (const AL::ALError& e)
   {
      ROS_ERROR("Could not create ALMemoryProxy.");
      return false;
   }
   ROS_INFO("Proxies to ALMotion and ALMemory ready.");
   return true;
}

NaoqiJointStates::NaoqiJointStates(int argc, char ** argv)
 : NaoqiNode(argc, argv),
   m_rate(25.0), m_privateNh("~"),
   m_odomFrameId("odom"),
   m_baseFrameId("base_link"),
   m_useIMUAngles(false),
   m_paused(false),
   m_lastOdomTime(0.0),
   m_mustUpdateOffset(false), m_initializeFromIMU(false),
   m_initializeFromOdometry(false), m_isInitialized(false)
{
    parse_command_line(argc,argv);
    if (   ! connectNaoQi() || !  connectProxy() )
    {
      ROS_ERROR("Gosh! Throwsing exception");
      throw std::exception();
    }
    m_dataNamesList = AL::ALValue::array("DCM/Time",
         "Device/SubDeviceList/InertialSensor/AngleX/Sensor/Value","Device/SubDeviceList/InertialSensor/AngleY/Sensor/Value",
         "Device/SubDeviceList/InertialSensor/AngleZ/Sensor/Value",
         "Device/SubDeviceList/InertialSensor/GyroscopeX/Sensor/Value", "Device/SubDeviceList/InertialSensor/GyroscopeY/Sensor/Value",
         "Device/SubDeviceList/InertialSensor/GyroscopeZ/Sensor/Value",
         "Device/SubDeviceList/InertialSensor/AccelerometerX/Sensor/Value", "Device/SubDeviceList/InertialSensor/AccelerometerY/Sensor/Value",
         "Device/SubDeviceList/InertialSensor/AccelerometerZ/Sensor/Value");

    // get update frequency. default sensor rate: 25 Hz (50 is max, stresses Nao's CPU)
    m_privateNh.param("sensor_rate", m_rate,m_rate);

    // get base_frame_id (and fix prefix if necessary)
    m_privateNh.param("base_frame_id", m_baseFrameId, m_baseFrameId);
    m_privateNh.param("odom_frame_id", m_odomFrameId, m_odomFrameId);
    m_privateNh.param("use_imu_angles", m_useIMUAngles, m_useIMUAngles);

    m_pauseOdomSrv = m_nh.advertiseService("pause_odometry", &NaoqiJointStates::pauseOdomCallback, this);
    m_resumeOdomSrv = m_nh.advertiseService("resume_odometry", &NaoqiJointStates::resumeOdomCallback, this);
    m_odomOffsetSrv = m_nh.advertiseService("odometry_offset", &NaoqiJointStates::odomOffsetCallback, this);
    m_setOdomPoseSrv = m_nh.advertiseService("set_odometry_pose", &NaoqiJointStates::setOdomPoseCallback, this);

    m_odom.header.frame_id = m_odomFrameId;
    m_torsoIMU.header.frame_id = m_baseFrameId;
    m_jointState.name = m_motionProxy->getJointNames("Body");

    // simluated model misses some joints, we need to fill:
    if (m_jointState.name.size() == 22)
    {
      // TODO: Check this!
      m_jointState.name.insert(m_jointState.name.begin()+6,"LWristYaw");
      m_jointState.name.insert(m_jointState.name.begin()+7,"LHand");
      m_jointState.name.push_back("RWristYaw");
      m_jointState.name.push_back("RHand");
    }

    std::stringstream ss;
    std::copy(m_jointState.name.begin(), m_jointState.name.end()-1, std::ostream_iterator<std::string>(ss,","));
    std::copy(m_jointState.name.end()-1, m_jointState.name.end(), std::ostream_iterator<std::string>(ss));
    ROS_INFO("Nao joints found: %s",ss.str().c_str());

    if (m_useIMUAngles)
        ROS_INFO("Using IMU for odometry roll & pitch");

    // default values of transforms:
    m_odomTransformMsg.header.frame_id = m_odomFrameId;
    m_odomTransformMsg.child_frame_id = m_baseFrameId;

    m_odomOffset = tf::Transform(tf::createIdentityQuaternion());
    m_odomPose = tf::Transform(tf::createIdentityQuaternion());

    m_odomPub = m_nh.advertise<nav_msgs::Odometry>("odom",5);
    m_torsoIMUPub = m_nh.advertise<sensor_msgs::Imu>("imu",5);
    m_jointStatePub = m_nh.advertise<sensor_msgs::JointState>("joint_states",5);

    ROS_INFO("nao_sensors initialized");

}

NaoqiJointStates::~NaoqiJointStates()
{
}

void NaoqiJointStates::run()
{
   ros::Rate r(m_rate);
   ros::Time stamp1;
   ros::Time stamp2;
   ros::Time stamp;

   std::vector<float> odomData;
   float odomX, odomY, odomZ, odomWX, odomWY, odomWZ;

   std::vector<float> memData;

   std::vector<float> positionData;

   ROS_INFO("Staring main loop. ros::ok() is %d nh.ok() is %d",ros::ok(),m_nh.ok());
   while(ros::ok() )
   {
      r.sleep();
      ros::spinOnce();
      stamp1 = ros::Time::now();
      try
      {
         memData = m_memoryProxy->getListData(m_dataNamesList);
         // {SPACE_TORSO = 0, SPACE_WORLD = 1, SPACE_NAO = 2}. (second argument)
         odomData = m_motionProxy->getPosition("Torso", 1, true);
         positionData = m_motionProxy->getAngles("Body", true);
      }
      catch (const AL::ALError & e)
      {
         ROS_ERROR( "Error accessing ALMemory, exiting...");
         ROS_ERROR( "%s", e.what() );
         //ros.signal_shutdown("No NaoQI available anymore");
      }
      stamp2 = ros::Time::now();
      //ROS_DEBUG("dt is %f",(stamp2-stamp1).toSec()); % dt is typically around 1/1000 sec
      // TODO: Something smarter than this..
      stamp = stamp1 + ros::Duration((stamp2-stamp1).toSec()/2.0);

      /******************************************************************
       *                              IMU
       *****************************************************************/
      if (memData.size() != m_dataNamesList.getSize())
      {
         ROS_ERROR("memData length %zu does not match expected length %u",memData.size(),m_dataNamesList.getSize() );
         continue;
      }
      // IMU data:
      m_torsoIMU.header.stamp = stamp;

      float angleX = memData[1];
      float angleY = memData[2];
      float angleZ = memData[3];
      float gyroX = memData[4];
      float gyroY = memData[5];
      float gyroZ = memData[6];
      float accX = memData[7];
      float accY = memData[8];
      float accZ = memData[9];

      m_torsoIMU.orientation = tf::createQuaternionMsgFromRollPitchYaw(
                                angleX,
                                angleY,
                                angleZ); // yaw currently always 0

      m_torsoIMU.angular_velocity.x = gyroX;
      m_torsoIMU.angular_velocity.y = gyroY;
      m_torsoIMU.angular_velocity.z = gyroZ; // currently always 0

      m_torsoIMU.linear_acceleration.x = accX;
      m_torsoIMU.linear_acceleration.y = accY;
      m_torsoIMU.linear_acceleration.z = accZ;

      // covariances unknown
      // cf http://www.ros.org/doc/api/sensor_msgs/html/msg/Imu.html
      m_torsoIMU.orientation_covariance[0] = -1;
      m_torsoIMU.angular_velocity_covariance[0] = -1;
      m_torsoIMU.linear_acceleration_covariance[0] = -1;

      m_torsoIMUPub.publish(m_torsoIMU);

      /******************************************************************
       *                            Joint state
       *****************************************************************/
      m_jointState.header.stamp = stamp;
      m_jointState.header.frame_id = m_baseFrameId;
      m_jointState.position.resize(positionData.size());
      for(unsigned i = 0; i<positionData.size(); ++i)
      {
         m_jointState.position[i] = positionData[i];
      }

      // simulated model misses some joints, we need to fill:
      if (m_jointState.position.size() == 22)
      {
         m_jointState.position.insert(m_jointState.position.begin()+6,0.0);
         m_jointState.position.insert(m_jointState.position.begin()+7,0.0);
         m_jointState.position.push_back(0.0);
         m_jointState.position.push_back(0.0);
      }

      m_jointStatePub.publish(m_jointState);

        /******************************************************************
        *                            Odometry
        *****************************************************************/
        if (!m_paused) {

        // apply offset transformation:
        tf::Pose transformedPose;

        if (odomData.size()!=6)
        {
            ROS_ERROR( "Error getting odom data. length is %zu",odomData.size() );
            continue;
        }

        double dt = (stamp.toSec() - m_lastOdomTime);

        odomX = odomData[0];
        odomY = odomData[1];
        odomZ = odomData[2];
        odomWX = odomData[3];
        odomWY = odomData[4];
        odomWZ = odomData[5];

        tf::Quaternion q;
        // roll and pitch from IMU, yaw from odometry:
        if (m_useIMUAngles)
            q.setRPY(angleX, angleY, odomWZ);
        else
            q.setRPY(odomWX, odomWY, odomWZ);

        m_odomPose.setOrigin(tf::Vector3(odomX, odomY, odomZ));
        m_odomPose.setRotation(q);

        if(m_mustUpdateOffset) {
            if(!m_isInitialized) {
                if(m_initializeFromIMU) {
                    // Initialization from IMU: Take x, y, z, yaw from odometry, roll and pitch from IMU
                    m_targetPose.setOrigin(m_odomPose.getOrigin());
                    m_targetPose.setRotation(tf::createQuaternionFromRPY(angleX, angleY, odomWZ));
                } else if(m_initializeFromOdometry) {
                    m_targetPose.setOrigin(m_odomPose.getOrigin());
                    m_targetPose.setRotation(tf::createQuaternionFromRPY(odomWX, odomWY, odomWZ));
                }
                m_isInitialized = true;
            } else {
                // Overwrite target pitch and roll angles with IMU data
                const double target_yaw = tf::getYaw(m_targetPose.getRotation());
                if(m_initializeFromIMU) {
                    m_targetPose.setRotation(tf::createQuaternionFromRPY(angleX, angleY, target_yaw));
                } else if(m_initializeFromOdometry){
                    m_targetPose.setRotation(tf::createQuaternionFromRPY(odomWX, odomWY, target_yaw));
                }
            }
            m_odomOffset = m_targetPose * m_odomPose.inverse();
            transformedPose = m_targetPose;
            m_mustUpdateOffset = false;
        } else {
            transformedPose = m_odomOffset * m_odomPose;
        }

        //
        // publish the transform over tf first
        //
        m_odomTransformMsg.header.stamp = stamp;
        tf::transformTFToMsg(transformedPose, m_odomTransformMsg.transform);
        m_transformBroadcaster.sendTransform(m_odomTransformMsg);

        //
        // Fill the Odometry msg
        //
        m_odom.header.stamp = stamp;
        //set the velocity first (old values still valid)
        m_odom.twist.twist.linear.x = (odomX - m_odom.pose.pose.position.x) / dt;
        m_odom.twist.twist.linear.y = (odomY - m_odom.pose.pose.position.y) / dt;
        m_odom.twist.twist.linear.z = (odomZ - m_odom.pose.pose.position.z) / dt;

        // TODO: calc angular velocity!
        //	m_odom.twist.twist.angular.z = vth; ??

        //set the position from the above calculated transform
        m_odom.pose.pose.orientation = m_odomTransformMsg.transform.rotation;
        m_odom.pose.pose.position.x = m_odomTransformMsg.transform.translation.x;
        m_odom.pose.pose.position.y = m_odomTransformMsg.transform.translation.y;
        m_odom.pose.pose.position.z = m_odomTransformMsg.transform.translation.z;

        m_odomPub.publish(m_odom);

        m_lastOdomTime = stamp.toSec();

        }
    }
    ROS_INFO("naoqi_sensors stopped.");

}

bool NaoqiJointStates::pauseOdomCallback(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){
    if (m_paused){
        ROS_WARN("Odometry pause requested, but is already paused");
        return false;
    } else{
        ROS_INFO("Odometry paused");
        m_paused = true;
        m_targetPose = m_odomOffset * m_odomPose;
        m_mustUpdateOffset = true;
        return true;
    }
}

bool NaoqiJointStates::resumeOdomCallback(std_srvs::Empty::Request& req, std_srvs::Empty::Response& res){
    if (m_paused){
        ROS_INFO("Odometry resumed");
        m_paused = false;
        return true;
    } else{
        ROS_WARN("Odometry resume requested, but is not paused");
        return false;
    }
}

bool NaoqiJointStates::odomOffsetCallback(naoqi_msgs::SetTransform::Request& req,
                                          naoqi_msgs::SetTransform::Response& res){
    ROS_INFO("New odometry offset received");
    tf::Transform newOffset;
    tf::transformMsgToTF(req.offset, newOffset);

    // add new offset to current (transformed) odom pose:
    if(!m_mustUpdateOffset) {
        m_mustUpdateOffset = true;
        m_targetPose = m_odomOffset * m_odomPose * newOffset;
    } else {
        m_targetPose = m_targetPose * newOffset;
    }

    return true;
}

bool NaoqiJointStates::setOdomPoseCallback(naoqi_msgs::SetTransform::Request& req,
                                           naoqi_msgs::SetTransform::Response& res){
    ROS_INFO("New target for current odometry pose received");
    tf::Transform targetPose;
    tf::transformMsgToTF(req.offset, targetPose);

    m_odomOffset = targetPose * m_odomPose.inverse();

    return true;
}

int main(int argc, char ** argv)
{
   ros::init(argc, argv, "naoqi_sensors_cpp");
   cout << "I am here" << endl;
   NaoqiJointStates * sensors;
   try{
      sensors = new NaoqiJointStates(argc,argv);
      //NaoqiJointStates sensors(argc,argv);
   }
   catch (const std::exception & e)
      //catch (...)
   {
      // TODO: why does this not work?
      //ROS_ERROR("Creating NaoqiJointStates object failed with error %s",e.what());
      ROS_ERROR("Creating NaoqiJointStates object failed with error ");
      return -1;
   }

   sensors->run();

   delete sensors;

   ROS_INFO("nao_sensors stopped");
   return 0;
}


text:
package org.onosproject.app;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.onosproject.core.ApplicationRole;
import org.onosproject.core.Version;
import org.onosproject.security.AppPermission;
import org.onosproject.security.Permission;

import java.net.URI;
import java.util.List;
import java.util.Set;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.onlab.junit.ImmutableClassChecker.assertThatClassIsImmutable;

/**
 * Basic tests of the default app description.
 */
public class DefaultApplicationDescriptionTest {

    public static final String APP_NAME = "org.foo.app";
    public static final Version VER = Version.version(1, 2, "a", null);
    public static final String TITLE = "Awesome App";
    public static final String DESC = "Awesome application from Circus, Inc.";
    public static final String ORIGIN = "Circus";
    public static final String CATEGORY = "other";
    public static final String URL = "http://www.onosproject.org";
    public static final String README = "Awesome application from Circus, Inc.";
    public static final byte[] ICON = new byte[] {};
    public static final ApplicationRole ROLE = ApplicationRole.ADMIN;
    public static final Set<Permission> PERMS = ImmutableSet.of(
                            new Permission(AppPermission.class.getName(), "FLOWRULE_WRITE"),
                            new Permission(AppPermission.class.getName(), "FLOWRULE_READ"));
    public static final URI FURL = URI.create("mvn:org.foo-features/1.2a/xml/features");
    public static final List<String> FEATURES = ImmutableList.of("foo", "bar");
    public static final List<String> APPS = ImmutableList.of("fifi");

    /**
     * Checks that the DefaultApplicationDescription class is immutable.
     */
    @Test
    public void testImmutability() {
        assertThatClassIsImmutable(DefaultApplicationDescription.class);
    }

    @Test
    public void basics() {
        ApplicationDescription app =
            DefaultApplicationDescription.builder()
                .withName(APP_NAME)
                .withVersion(VER)
                .withTitle(TITLE)
                .withDescription(DESC)
                .withOrigin(ORIGIN)
                .withCategory(CATEGORY)
                .withUrl(URL)
                .withReadme(README)
                .withIcon(ICON)
                .withRole(ROLE)
                .withPermissions(PERMS)
                .withFeaturesRepo(FURL)
                .withFeatures(FEATURES)
                .withRequiredApps(APPS)
                .build();

        assertEquals("incorrect id", APP_NAME, app.name());
        assertEquals("incorrect version", VER, app.version());
        assertEquals("incorrect title", TITLE, app.title());
        assertEquals("incorrect description", DESC, app.description());
        assertEquals("incorrect origin", ORIGIN, app.origin());
        assertEquals("incorrect category", CATEGORY, app.category());
        assertEquals("incorrect URL", URL, app.url());
        assertEquals("incorrect readme", README, app.readme());
        assertEquals("incorrect role", ROLE, app.role());
        assertEquals("incorrect permissions", PERMS, app.permissions());
        assertEquals("incorrect features repo", FURL, app.featuresRepo().get());
        assertEquals("incorrect features", FEATURES, app.features());
        assertEquals("incorrect apps", APPS, app.requiredApps());
        assertTrue("incorrect toString", app.toString().contains(APP_NAME));
    }
}


text:
<?php

namespace Ongoing;

class SystemStatus
{

    /**
     * @var string $SystemStatusText
     */
    protected $SystemStatusText = null;

    /**
     * @var boolean $IsRunning
     */
    protected $IsRunning = null;

    /**
     * @var \DateTime $BuildTime
     */
    protected $BuildTime = null;

    /**
     * @param boolean $IsRunning
     * @param \DateTime $BuildTime
     */
    public function __construct($IsRunning, \DateTime $BuildTime)
    {
      $this->IsRunning = $IsRunning;
      $this->BuildTime = $BuildTime->format(\DateTime::ATOM);
    }

    /**
     * @return string
     */
    public function getSystemStatusText()
    {
      return $this->SystemStatusText;
    }

    /**
     * @param string $SystemStatusText
     * @return \Ongoing\SystemStatus
     */
    public function setSystemStatusText($SystemStatusText)
    {
      $this->SystemStatusText = $SystemStatusText;
      return $this;
    }

    /**
     * @return boolean
     */
    public function getIsRunning()
    {
      return $this->IsRunning;
    }

    /**
     * @param boolean $IsRunning
     * @return \Ongoing\SystemStatus
     */
    public function setIsRunning($IsRunning)
    {
      $this->IsRunning = $IsRunning;
      return $this;
    }

    /**
     * @return \DateTime
     */
    public function getBuildTime()
    {
      if ($this->BuildTime == null) {
        return null;
      } else {
        try {
          return new \DateTime($this->BuildTime);
        } catch (\Exception $e) {
          return false;
        }
      }
    }

    /**
     * @param \DateTime $BuildTime
     * @return \Ongoing\SystemStatus
     */
    public function setBuildTime(\DateTime $BuildTime)
    {
      $this->BuildTime = $BuildTime->format(\DateTime::ATOM);
      return $this;
    }

}


text:
 #if defined(_WIN32)
  #define WIN32_LEAN_AND_MEAN
  #include <Windows.h>
  #include <fcntl.h>
  #include <io.h>
 #elif defined(__linux__) || defined(__POSIX__)
  #include <pthread.h>
 #elif defined(__APPLE__) && defined(__MACH__)
  #error "Mac OSX is not a supported operating system yet! I just dont own a mac to test..."
 #else
  #error "Unknown operating system detected."
 #endif
#else
 #error "pbr version does not exist"
#endif

#endif // __PLATFORM_HPP


text:
$(function () {

    module("bootstrap-twipsy")

      test("should be defined on jquery object", function () {
        var div = $("

")
        ok(div.twipsy, 'popover method is defined')
      })

      test("should return element", function () {
        var div = $("

")
        ok(div.twipsy() == div, 'document.body returned')
      })

      test("should expose default settings", function () {
        ok(!!$.fn.twipsy.defaults, 'defaults is defined')
      })

      test("should remove title attribute", function () {
        var twipsy = $('').twipsy()
        ok(!twipsy.attr('title'), 'title tag was removed')
      })

      test("should add data attribute for referencing original title", function () {
        var twipsy = $('').twipsy()
        equals(twipsy.attr('data-original-title'), 'Another twipsy', 'original title preserved in data attribute')
      })

      test("should place tooltips relative to placement option", function () {
        $.support.transition = false
        var twipsy = $('')
          .appendTo('#qunit-runoff')
          .twipsy({placement: 'below'})
          .twipsy('show')

        ok($(".twipsy").hasClass('fade below in'), 'has correct classes applied')
        twipsy.twipsy('hide')
        ok(!$(".twipsy").length, 'twipsy removed')
        $('#qunit-runoff').empty()
      })

      test("should add a fallback in cases where elements have no title tag", function () {
        $.support.transition = false
        var twipsy = $('')
          .appendTo('#qunit-runoff')
          .twipsy({fallback: '@fat'})
          .twipsy('show')

        equals($(".twipsy").text(), "@fat", 'has correct default text')
        twipsy.twipsy('hide')
        ok(!$(".twipsy").length, 'twipsy removed')
        $('#qunit-runoff').empty()
      })

      test("should not allow html entities", function () {
        $.support.transition = false
        var twipsy = $('<a href="#" rel="twipsy" title="@fat">')
          .appendTo('#qunit-runoff')
          .twipsy()
          .twipsy('show')

        ok(!$('.twipsy b').length, 'b tag was not inserted')
        twipsy.twipsy('hide')
        ok(!$(".twipsy").length, 'twipsy removed')
        $('#qunit-runoff').empty()
      })

      test("should allow html entities if html option set to true", function () {
        $.support.transition = false
        var twipsy = $('<a href="#" rel="twipsy" title="@fat">')
          .appendTo('#qunit-runoff')
          .twipsy({html: true})
          .twipsy('show')

        ok($('.twipsy b').length, 'b tag was inserted')
        twipsy.twipsy('hide')
        ok(!$(".twipsy").length, 'twipsy removed')
        $('#qunit-runoff').empty()
      })

})


text:
'use strict';

var sound = require('./emitSound');
var _data = require('./dataSync');

alertify.defaults.glossary.title = "Reminder";

var reminder;

function createTR(data, key, UISync) {

    var tr = document.createElement('tr');
    tr.id = key;
    tr.style.color = (data.UIShouldSyncNotification ? 'orange' : '');
    var created = moment();

    var td1 = document.createElement('td');
    var td2 = document.createElement('td');
    var td3 = document.createElement('td');
    var td4 = document.createElement('td');
    var td5 = document.createElement('td');

    if (UISync) {
        var phone = document.createElement('span');
        phone.innerHTML = '' + data.phone + '';

        var fav = document.createElement('span');
        fav.innerHTML = '<button type="button" class="btn btn-default btn-sm">' +
            '</button>';

        var remind = document.createElement('span');
        remind.innerHTML = '<button style="margin-left:3px;" type="button" class="btn btn-default btn-sm">' +
            '</button>';

        var remove = document.createElement('span');
        remove.innerHTML = '<button style="margin-left:3px;" type="button" class="btn btn-default btn-sm"></button>';

        td1.appendChild(phone);
        td2.appendChild(document.createTextNode(data.state.toUpperCase()));
        td3.appendChild(document.createTextNode(moment().format("h:mm a")));
        td4.appendChild(document.createTextNode('a few seconds ago'));
        td5.appendChild(fav);
        td5.appendChild(remind);
        td5.appendChild(remove);

        tr.appendChild(td1);
        tr.appendChild(td2);
        tr.appendChild(td3);
        tr.appendChild(td4);
        tr.appendChild(td5);

        phone.onclick = function() {
            _data.saveNotification(key, false);
            clearTimeout(reminder);
        };

        fav.onclick = function() {
            var favIcon = this.childNodes[0].childNodes[0].style.color;
            _data.saveFav(key, favIcon);
        };

        remind.onclick = function() {

            if (!tr.style.color) {
                if (notify.permissionLevel()) {
                    alertify.prompt("Remind me in .. ? (minutes)", "10",
                        function(evt, value) {

                            var minutes = ~~value;

                            if (minutes > 0) {
                                _data.saveNotification(key, true);
                                alertify.success('I will remind you in ' + value + ' minutes');
                                reminder = setTimeout(function() {
                                    notify.createNotification("Make a call", {
                                        body: data.phone,
                                        icon: "alert.ico"
                                    });
                                    sound.playSound(function() {});
                                    //tr.style.color = '';
                                }, minutes * 60000);
                            } else {
                                alertify.error('Please type a non-zero value');
                            }
                        },
                        function() {
                            //alertify.error('Cancel');
                        });
                }
            } else {
                //tr.style.color = '';
                _data.saveNotification(key, false);
                clearTimeout(reminder);
            }
        };

        remove.onclick = function() {
            clearTimeout(reminder);
            _data.remove(key);
        };

        setInterval(function() {
            td4.innerHTML = moment().from(created, true) + " ago"
        }, 1000);

        //no sync this entry on browser reload
        _data.UISync(key);

        return listBody.appendChild(tr);
    }
}

exports.createTR = createTR;


text:
package org.olat.presentation.admin.sysinfo;

import java.util.Iterator;
import java.util.Set;

import org.apache.log4j.Logger;
import org.olat.data.basesecurity.Identity;
import org.olat.lms.admin.AdminModule;
import org.olat.presentation.commons.session.UserSession;
import org.olat.presentation.framework.core.UserRequest;
import org.olat.presentation.framework.core.Windows;
import org.olat.presentation.framework.core.components.Component;
import org.olat.presentation.framework.core.components.Window;
import org.olat.presentation.framework.core.components.link.Link;
import org.olat.presentation.framework.core.components.link.LinkFactory;
import org.olat.presentation.framework.core.components.text.TextFactory;
import org.olat.presentation.framework.core.components.velocity.VelocityContainer;
import org.olat.presentation.framework.core.control.Controller;
import org.olat.presentation.framework.core.control.DefaultController;
import org.olat.presentation.framework.core.control.WindowControl;
import org.olat.presentation.framework.core.control.controller.BasicController;
import org.olat.presentation.framework.core.control.generic.modal.DialogBoxController;
import org.olat.presentation.framework.core.control.generic.modal.DialogBoxUIFactory;
import org.olat.presentation.framework.core.translator.PackageUtil;
import org.olat.presentation.security.authentication.AuthHelper;
import org.olat.system.commons.Formatter;
import org.olat.system.coordinate.CoordinatorManager;
import org.olat.system.event.Event;
import org.olat.system.logging.log4j.LoggerHelper;

/**
 * @author Christian Guretzki
 */

public class SessionAdministrationController extends BasicController {

    private static final Logger log = LoggerHelper.getLogger();

    private static final String VELOCITY_ROOT = PackageUtil.getPackageVelocityRoot(SysinfoController.class);

    private final VelocityContainer myContent;
    private final Link invalidateAllSsssionLink;
    private DialogBoxController invalidateAllConfirmController;
    private final Link blockLoginLink;
    private final Link allowLoginLink;
    private DialogBoxController blockLoginConfirmController;
    private Link rejectDMZReuqestsLink;
    private Link allowDMZRequestsLink;
    private DialogBoxController rejectDMZRequestsConfirmController;
    private final SessionAdminForm sessionAdminForm;
    private final SessionAdminOldestSessionForm sessionAdminOldestSessionForm;

    /**
     * Controlls user session in admin view.
     *
     * @param ureq
     * @param wControl
     */
    public SessionAdministrationController(final UserRequest ureq, final WindowControl wControl) {
        super(ureq, wControl);

        myContent = createVelocityContainer("sessionadministration");

        invalidateAllSsssionLink = LinkFactory.createButton("session.admin.invalidate.all.link", myContent, this);
        myContent.contextPut("loginBlocked", AdminModule.isLoginBlocked());
        blockLoginLink = LinkFactory.createButton("session.admin.block.login.link", myContent, this);

        final boolean showRejectLink = CoordinatorManager.getInstance().getCoordinator().isClusterMode();
        myContent.contextPut("showRejectDMZRequestsLink", showRejectLink);
        if (showRejectLink) {
            myContent.contextPut("rejectingDMZRequests", AuthHelper.isRejectDMZRequests());

            TextFactory.createTextComponentFromI18nKey("session.admin.reject.dmz.requests.intro", "session.admin.reject.dmz.requests.intro", getTranslator(), null, true,
                    myContent);
            TextFactory.createTextComponentFromI18nKey("session.admin.allow.dmz.requests.intro", "session.admin.allow.dmz.requests.intro", getTranslator(), null, true,
                    myContent);
            rejectDMZReuqestsLink = LinkFactory.createButton("session.admin.reject.dmz.requests.link", myContent, this);
            allowDMZRequestsLink = LinkFactory.createButton("session.admin.allow.dmz.requests.link", myContent, this);
        }
        allowLoginLink = LinkFactory.createButton("session.admin.allow.login.link", myContent, this);
        sessionAdminOldestSessionForm = new SessionAdminOldestSessionForm(ureq, wControl, getTranslator());
        listenTo(sessionAdminOldestSessionForm);
        myContent.put("session.admin.oldest.session.form", sessionAdminOldestSessionForm.getInitialComponent());
        sessionAdminForm = new SessionAdminForm(ureq, wControl, getTranslator(), AdminModule.getSessionTimeout(), AdminModule.getMaxSessions());
        listenTo(sessionAdminForm);
        myContent.put("session.admin.form", sessionAdminForm.getInitialComponent());
        myContent.contextPut("usersessions", getUsersSessionAsString(ureq));
        putInitialPanel(myContent);
    }

    /**
	 */
    @Override
    protected void event(final UserRequest ureq, final Component source, final Event event) {
        if (source == invalidateAllSsssionLink) {
            invalidateAllConfirmController = activateYesNoDialog(ureq, null, translate("invalidate.all.sure"), invalidateAllConfirmController);
            return;
        } else if (source == blockLoginLink) {
            blockLoginConfirmController = activateYesNoDialog(ureq, null, translate("block.login.sure"), invalidateAllConfirmController);
        } else if (source == rejectDMZReuqestsLink) {
            rejectDMZRequestsConfirmController = activateYesNoDialog(ureq, null, translate("reject.dmz.requests.sure"), rejectDMZRequestsConfirmController);
        } else if (source == allowDMZRequestsLink) {
            AdminModule.setRejectDMZRequests(false);
            myContent.contextPut("rejectingDMZRequests", AdminModule.isRejectDMZRequests());
            showInfo("allow.dmz.requests.done");
        } else if (source == allowLoginLink) {
            AdminModule.setLoginBlocked(false);
            myContent.contextPut("loginBlocked", Boolean.FALSE);
            showInfo("allow.login.done");
        }
    }

    /**
	 */
    @Override
    protected void event(final UserRequest ureq, final Controller source, final Event event) {
        if (source == invalidateAllConfirmController) {
            if (DialogBoxUIFactory.isYesEvent(event)) {
                final int nbrOfInvalidatedSessions = AdminModule.invalidateAllSessions();
                showInfo("invalidate.session.done", Integer.toString(nbrOfInvalidatedSessions));
            }
        } else if (source == blockLoginConfirmController) {
            if (DialogBoxUIFactory.isYesEvent(event)) {
                AdminModule.setLoginBlocked(true);
                myContent.contextPut("loginBlocked", Boolean.TRUE);
                showInfo("block.login.done");
            }
        } else if (source == rejectDMZRequestsConfirmController) {
            if (DialogBoxUIFactory.isYesEvent(event)) {
                AdminModule.setRejectDMZRequests(true);
                myContent.contextPut("rejectingDMZRequests", AuthHelper.isRejectDMZRequests());
                showInfo("reject.dmz.requests.done");
            }
        } else if (source == sessionAdminOldestSessionForm) {
            final int nbrOfInvalidatedSessions = AdminModule.invalidateOldestSessions(sessionAdminOldestSessionForm.getNbrSessions());
            showInfo("invalidate.session.done", Integer.toString(nbrOfInvalidatedSessions));
        } else if (source == sessionAdminForm && event == Event.DONE_EVENT) {
            AdminModule.setSessionTimeout(sessionAdminForm.getSessionTimeout());
            AdminModule.setMaxSessions(sessionAdminForm.getMaxSessions());
        }

    }

    @Override
    protected void doDispose() {
        // DialogBoxController and TableController get disposed by BasicController
    }

    private String getUsersSessionAsString(final UserRequest ureq) {
        final StringBuilder sb = new StringBuilder();
        final int ucCnt = UserSession.getUserSessionsCnt();
        final Set usesss = UserSession.getAuthenticatedUserSessions();
        final int contcnt = DefaultController.getControllerCount();
        sb.append("total usersessions (auth and non auth): " + ucCnt + "
auth usersessions: " + usesss.size()
                + "
Total Controllers (active, not disposed) of all users:" + contcnt + "

");
        final Formatter f = Formatter.getInstance(ureq.getLocale());
        for (final Iterator iter = usesss.iterator(); iter.hasNext();) {
            final UserSession usess = (UserSession) iter.next();
            final Identity iden = usess.getIdentity();
            sb.append("authusersession (").append(usess.hashCode()).append(") of ");
            if (iden != null) {
                sb.append(iden.getName()).append(" ").append(iden.getKey());
            } else {
                sb.append(" - ");
            }
            sb.append("
");
            final Windows ws = Windows.getWindows(usess);
            for (final Iterator iterator = ws.getWindowIterator(); iterator.hasNext();) {
                final Window window = (Window) iterator.next();
                sb.append("- window ").append(window.getDispatchID()).append(" ").append(window.getLatestDispatchComponentInfo()).append("
");
            }
            sb.append("
");
        }
        return sb.toString();
    }

}


text:
Installation
============

To begin, add the dependent bundles to the ``vendor/bundles`` directory. Add
the following lines to the file ``deps``::

  [SonataEasyExtendsBundle]
      git=git://github.com/sonata-project/SonataEasyExtendsBundle.git
      target=endor/bundles/Sonata/EasyExtendsBundle

and run::

  bin/vendors install

Next, be sure to enable the new bundles in your application kernel:

.. code-block:: php

  <?php
  // app/appkernel.php
  public function registerBundles()
  {
      return array(
          // ...
          new Sonata\EasyExtendsBundle\SonataEasyExtendsBundle(),
          // ...
      );
  }


text:
from django.utils.text import slugify

def overlap_percent(geom1, geom2):
    # How much of the area of geom2 is also inside geom1
    # (expressed as a percentage)
    g1 = geom1.transform(27700, clone=True)
    g2 = geom2.transform(27700, clone=True)
    intersection = g1.intersection(g2)
    return (intersection.area / g1.area) * 100

def normalize_name_for_matching(name):
    # Slug a name and remove suffixes so we can compare division
    # names within a local authority ignoring minor differences
    # and the suffixes ' Ward' and ' ED' (which are appended to
    # the names of wards and electoral districts in BoundaryLine)
    slug = slugify(name)
    if slug.endswith("-ed"):
        return slug[:-3]
    if slug.endswith("-ward"):
        return slug[:-5]
    return slug

def split_code(code):
    return tuple(code.split(":"))


text:
---
title: spring Profile配置不同环境下的bean
---

开发环境和生产环境需要不同的配置, 如数据库, 使用Profile配置

# 如何设置profile

Spring按照顺序检查profile属性

- `spring.profiles.active`: 如果设置了值, spring会使用这个值作为profile创建对应Bean, 如果没有设置, 检查default设置
- `spring.profiles.default`: 如果设置了值, 使用这个值作为profile创建Bean, 如果没有设置, 创建没有设置profile的Bean

可以通过以下方法设置profile值

- `DispatcherServlet`的初始化参数传入
- web app上下文参数传入
- JNDI入口
- 环境变量
- JVM系统属性
- `@ActiveProfiles`

## 通过`web.xml`配置web app上下文参数

在`web.xml`中分别为`ContextLoaderListener`和`DispatcherServlet`设置`spring.profiles.default`为开发环境.
前面的开发环境数据库为Spring测试内部数据库, 开发人员可以直接运行项目, 不需要其他配置.

当部署到测试环境或者线上环境时, 通过系统属性, 环境变量, 或者JNDI等方法设置`spring.profiles.active`为环境值即可

这样就可以覆盖default值

具体的值可以是逗号分隔的多个值, 如`spring.profiles.default=dev,qa`

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xmlns="http://java.sun.com/xml/ns/javaee"
             xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
             id="WebApp_ID" version="3.0">

        <display-name>Spring mvc demo</display-name>

        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring/root-context.xml</param-value>
        </context-param>
        <context-param>
            <param-name>spring.profiles.default</param-name>
            <param-value>dev</param-value>
        </context-param>

        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <servlet>
            <servlet-name>spring-mvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:/spring/spring-mvc-servlet.xml</param-value>
            </init-param>
            <init-param>
                <param-name>spring.profiles.default</param-name>
                <param-value>dev</param-value>
            </init-param>
            <load-on-startup>1</load-on-startup>
        </servlet>

        <servlet-mapping>
            <servlet-name>spring-mvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>

        <filter>
            <filter-name>CharacterEncoding</filter-name>
            <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
            <init-param>
                <param-name>encoding</param-name>
                <param-value>UTF-8</param-value>
            </init-param>
            <init-param>
                <param-name>forceEncoding</param-name>
                <param-value>true</param-value>
            </init-param>
        </filter>
        <filter-mapping>
            <filter-name>CharacterEncoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>

    </web-app>

## 使用`@ActiveProfiles`设置profile

junit运行集成测试的时候也需要设置profile

    package com.qiudeqing;

    import com.qiudeqing.dao.demo.UserDao;
    import junit.framework.Assert;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.test.context.ActiveProfiles;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

    /**
     * Created by qiudeqing on 16/9/29.
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(classes = {SpringConfig.class})
    @ActiveProfiles("prod")
    public class ProfileTest {

        @Autowired
        private UserDao userDao;

        @Test
        public void testUserDao() {
            Assert.assertEquals(userDao.hello(), "userdao prod");
        }

        public UserDao getUserDao() {
            return userDao;
        }

        public void setUserDao(UserDao userDao) {
            this.userDao = userDao;
        }

    }

# java配置@Profile

在类级别使用@Profile或者方法级别使用

生产环境配置DevelopmentProfileConfig.java

    package com.qiudeqing.profile;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
    import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

    import javax.activation.DataSource;

    @Configuration
    @Profile("dev")
    public class DevelopmentProfileConfig {

        @Bean(destroyMethod= "shutdown")
        public DataSource dataSource() {
            return (DataSource) new EmbeddedDatabaseBuilder()
                    .setType(EmbeddedDatabaseType.H2)
                    .addScript("classpath:schema.sql")
                    .addScript("classpath:test-data.sql")
                    .build();
        }
    }

生产环境配置ProductionProfileConfig.java

    package com.qiudeqing.profile;

    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Profile;
    import org.springframework.jndi.JndiObjectFactoryBean;

    import javax.activation.DataSource;

    /**
     * Created by qiudeqing on 16/9/28.
     */
    @Configuration
    @Profile("prod")
    public class ProductionProfileConfig {

        @Bean
        public DataSource dataSource() {
            JndiObjectFactoryBean jndiObjectFactoryBean =
                    new JndiObjectFactoryBean();
            jndiObjectFactoryBean.setJndiName("jdbc/myDS");
            jndiObjectFactoryBean.setResourceRef(true);
            jndiObjectFactoryBean.setProxyInterface(javax.sql.DataSource.class);
            return (DataSource)jndiObjectFactoryBean.getObject();
        }
    }

# xml配置profile属性

datasource-dev.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:jdbc="http://www.springframework.org/schema/jdbc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/jdbc
                http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"
                profile="dev">

        <jdbc:embedded-database id="dataSource">
            <jdbc:script location="classpath:schema.sql"/>
            <jdbc:script location="classpath:test-data.sql"/>
        </jdbc:embedded-database>

    </beans>

datasource-prod.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xmlns:jdbc="http://www.springframework.org/schema/jdbc"
           xmlns:jee="http://www.springframework.org/schema/jee"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
                http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/jdbc
                http://www.springframework.org/schema/jdbc/spring-jdbc.xsd"
           profile="prod">

        <jee:jndi-lookup jndi-name="jdbc/myDatabase"
                         id="dataSource"
                         resource-ref="true"
                         proxy-interface="javax.sql.DataSource"
            />

    </beans>


text:
"""
Applies a K-Fold strategy with NNDSVD-initialized NMF to the specified dataset to generate an ensemble.

Sample usage:
python generate-kfold.py sample.pkl -k 4 -r 5 -f 10 --maxiters 100 -o models/base
"""
import os, sys, random
import logging as log
from optparse import OptionParser
import numpy as np
import scipy.sparse
import text.util, unsupervised.nmf, unsupervised.rankings, unsupervised.util

# --------------------------------------------------------------

def main():
	parser = OptionParser(usage="usage: %prog [options] dataset_file")
	parser.add_option("--seed", action="store", type="int", dest="seed", help="initial random seed", default=1000)
	parser.add_option("-r","--runs", action="store", type="int", dest="runs", help="number of runs", default=1)
	parser.add_option("-f","--folds", action="store", type="int", dest="num_folds", help="number of folds", default=10)
	parser.add_option("-k", action="store", type="int", dest="k", help="number of topics", default=5)
	parser.add_option("--maxiters", action="store", type="int", dest="maxiter", help="maximum number of iterations", default=100)
	parser.add_option("-s", "--sample", action="store", type="float", dest="sample_ratio", help="sampling ratio of documents to include in each run (range is 0 to 1). default is all", default=1.0)
	parser.add_option("-o","--outdir", action="store", type="string", dest="dir_out", help="base output directory (default is current directory)", default=None)
	parser.add_option('-d','--debug',type="int",help="Level of log output; 0 is less, 5 is all", default=3)
	(options, args) = parser.parse_args()
	if len(args) < 1:
		parser.error( "Must specify at least one corpus file" )
	log_level = max(50 - (options.debug * 10), 10)
	log.basicConfig(level=log_level, format='%(asctime)-18s %(levelname)-10s %(message)s', datefmt='%d/%m/%Y %H:%M',)

	if options.dir_out is None:
		dir_out_base = os.getcwd()
	else:
		dir_out_base = options.dir_out
		if not os.path.exists(dir_out_base):
			os.makedirs(dir_out_base)

	# Set random state
	random_seed = options.seed
	if random_seed < 0:
		random_seed = random.randint(1,100000)
	np.random.seed( random_seed )
	random.seed( random_seed )
	log.info("Using random seed %s" % random_seed )

	# Load the cached corpus
	corpus_path = args[0]
	(X,terms,doc_ids,classes) = text.util.load_corpus( corpus_path )
	log.debug( "Read %s document-term matrix, dictionary of %d terms, list of %d document IDs" % ( str(X.shape), len(terms), len(doc_ids) ) )

	impl = unsupervised.nmf.SklNMF( max_iters = options.maxiter, init_strategy = "nndsvd" )
	n_documents = X.shape[0]
	n_folds = options.num_folds
	fold_sizes = (n_documents // n_folds) * np.ones(n_folds, dtype=np.int)
	fold_sizes[:n_documents % n_folds] += 1

	log.debug( "Results will be written to %s" % dir_out_base )
	for run in range(options.runs):
		log.info("Run %d/%d" % ( (run+1), options.runs ) )
		idxs = np.arange(n_documents)
		np.random.shuffle( idxs )

		current = 0
		for fold, fold_size in enumerate(fold_sizes):
			file_suffix = "%s_%02d_%02d" % ( options.seed, run+1, fold+1 )
			start, stop = current, current + fold_size
			current = stop
			sample_idxs = list(idxs)
			for idx in idxs[start:stop]:
				sample_idxs.remove(idx)
			sample_doc_ids = []
			for doc_index in sample_idxs:
				sample_doc_ids.append( doc_ids[doc_index] )
			log.info("Fold %d/%d: Using fold with %d/%d documents" % ( fold+1, n_folds, len(sample_idxs), n_documents ) )
			S = X[sample_idxs,:]
			log.debug("Creating sparse matrix ...")
			S = scipy.sparse.csr_matrix(S)

			# apply NMF
			log.info("Applying NMF (k=%d) to matrix of size %d X %d ..." % ( options.k, S.shape[0], S.shape[1] ) )
			impl.apply( S, options.k )
			# Get term rankings for each topic
			term_rankings = []
			for topic_index in range(options.k):
				ranked_term_indices = impl.rank_terms( topic_index )
				term_ranking = [terms[i] for i in ranked_term_indices]
				term_rankings.append(term_ranking)
			log.debug( "Generated ranking set with %d topics covering up to %d terms" % ( len(term_rankings), unsupervised.rankings.term_rankings_size( term_rankings ) ) )
			# Write term rankings
			ranks_out_path = os.path.join( dir_out_base, "ranks_%s.pkl" % file_suffix )
			log.debug( "Writing term ranking set to %s" % ranks_out_path )
			unsupervised.util.save_term_rankings( ranks_out_path, term_rankings )
			# Write document partition
			partition = impl.generate_partition()
			partition_out_path = os.path.join( dir_out_base, "partition_%s.pkl" % file_suffix )
			log.debug( "Writing document partition to %s" % partition_out_path )
			unsupervised.util.save_partition( partition_out_path, partition, sample_doc_ids )
			# Write the complete factorization
			factor_out_path = os.path.join( dir_out_base, "factors_%s.pkl" % file_suffix )
			# NB: need to make a copy of the factors
			log.debug( "Writing factorization for %d documents to %s" % ( len(sample_doc_ids), factor_out_path ) )
			unsupervised.util.save_nmf_factors( factor_out_path, np.array( impl.W ), np.array( impl.H ), sample_doc_ids, terms )

# --------------------------------------------------------------

if __name__ == "__main__":
	main()


text:
#ifndef QMITKRENDERINGMANAGER_H_HEADER_INCLUDED_C135A197
#define QMITKRENDERINGMANAGER_H_HEADER_INCLUDED_C135A197

#include <MitkQtWidgetsExports.h>

#include "mitkRenderingManager.h"
#include <QEvent>
#include <QObject>

class QmitkRenderingManagerInternal;
class QmitkRenderingManagerFactory;

/**
 * \ingroup QmitkModule
 * \brief Qt specific implementation of mitk::RenderingManager.
 *
 * This implementation defines a QmitkRenderingRequestEvent to realize the
 * rendering request process. The event must be handled by the Qmitk
 * interface to Qt (QmitkRenderWindow).
 *
 * Note: it may be necessary to remove all pending RenderingRequestEvents
 * from the system's event processing pipeline during system shutdown to
 * make sure that dangling events do not lead to unexpected behavior.
 *
 */
class MITKQTWIDGETS_EXPORT QmitkRenderingManager : public QObject, public mitk::RenderingManager
{
  Q_OBJECT

public:
  mitkClassMacro(QmitkRenderingManager, mitk::RenderingManager);
  ~QmitkRenderingManager() override;

  void DoMonitorRendering() override;
  void DoFinishAbortRendering() override;

  bool event(QEvent *event) override;

protected:
  itkFactorylessNewMacro(Self);

  QmitkRenderingManager();

  void GenerateRenderingRequestEvent() override;

  void StartOrResetTimer() override;

  int pendingTimerCallbacks;

protected slots:

  void TimerCallback();

private:
  friend class QmitkRenderingManagerFactory;
};

class QmitkRenderingRequestEvent : public QEvent
{
public:
  enum Type
  {
    RenderingRequest = QEvent::MaxUser - 1024
  };

  QmitkRenderingRequestEvent() : QEvent((QEvent::Type)RenderingRequest){};
};

#endif /* MITKRenderingManager_H_HEADER_INCLUDED_C135A197 */


text:
let colors = new Array(3);      // create an array with three items
let names = new Array("Greg");  // create an array with one item, the string "Greg"


text:
#ifndef RESONANCE_AUDIO_UTILS_SEMI_LOCKLESS_FIFO_H_
#define RESONANCE_AUDIO_UTILS_SEMI_LOCKLESS_FIFO_H_

#include <atomic>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <vector>

#include "base/logging.h"

namespace vraudio {

// Thread-safe multiple producer - single consumer FIFO queue to share data
// between threads. The FIFO takes over ownership of the queue elements. Note
// that |PushBack| calls are synchronized with a mutex and may block. Calls to
// |PopFront| are lockless and never block.
//
// @tparam DataType Object type that the FIFO handles.
template <typename DataType>
class SemiLocklessFifo {
 public:
  typedef std::chrono::steady_clock::duration ClockDuration;

  SemiLocklessFifo();

  ~SemiLocklessFifo();

  // Takes over ownership of |input| and pushes it to the FIFO queue back.
  //
  // @param input Input element to be added to the FIFO queue.
  void PushBack(DataType&& input);

  // Pops element from FIFO queue front.
  //
  // @return Element from FIFO queue front. Must not be called if the queue is
  //     empty.
  DataType PopFront();

  // Returns true if FIFO queue is empty, false otherwise. This method is *not*
  // thread-safe and should only be called from the consumer thread.
  bool Empty() const;

  // Clears the FIFO queue and deletes all its elements. This method is *not*
  // thread-safe and should only be called from the consumer thread.
  void Clear();

  // Sleeps until the number of elements in the FIFO queue drop below a target
  // threshold. This method can be used to synchronize the producer and the
  // consumer. Sleeping is enabled by default and can be disabled via
  // |EnableBlockingSleepUntilMethods|.
  //
  // @param target_size Target size of FIFO queue.
  // @param max_wait Maximum waiting period.
  // @return True if number of FIFO elements is below target size.
  bool SleepUntilBelowSizeTarget(size_t target_size,
                                 const ClockDuration& max_wait);

  // Sleeps until the number of elements in the FIFO queue is greater or equal a
  // target threshold. This method can be used to synchronize the producer and
  // the consumer. Sleeping is enabled by default and can be disabled via
  // |EnableBlockingSleepUntilMethods|.
  //
  // @param target_size Target size of FIFO queue.
  // @param max_wait Maximum waiting period.
  // @return True if number of FIFO elements is greater or equal the target
  //     size.
  bool SleepUntilNumElementsInQueue(size_t target_size,
                                    const ClockDuration& max_wait);

  // Allows for unblocking |SleepUntil[BelowSizeTarget|NumElementsInQueue]|
  // method.
  void EnableBlockingSleepUntilMethods(bool enable);

 private:
  // Node in single-linked list.
  struct Node {
    Node() : next(nullptr) {}
    std::atomic<Node*> next;
    DataType data;
  };

  // Head of linked list.
  Node* head_;

  // Tail of linked list.
  Node* tail_;

  // Number of elements.
  std::atomic<size_t> fifo_size_;

  // Mutex to synchronize |PushBack| calls from multiple threads.
  std::mutex push_mutex_;

  // Conditional to signal consumption.
  std::condition_variable pop_conditional_;

  // Mutex to block on until signal consumption occurs.
  std::mutex pop_conditional_mutex_;

  // Conditional to signal new elements on the FIFO.
  std::condition_variable push_conditional_;

  // Mutex to block on until new elements have been added to the FIFO.
  std::mutex push_conditional_mutex_;

  // Flag to enable and disable blocking sleeping calls.
  std::atomic<bool> enable_sleeping_;
};

template <typename DataType>
SemiLocklessFifo<DataType>::SemiLocklessFifo()
    : fifo_size_(0), enable_sleeping_(true) {
  head_ = tail_ = new Node();
}

template <typename DataType>
SemiLocklessFifo<DataType>::~SemiLocklessFifo() {
  Clear();
  DCHECK_EQ(head_, tail_);
  DCHECK(head_->next.load() == nullptr);
  delete head_;
}

template <typename DataType>
void SemiLocklessFifo<DataType>::PushBack(DataType&& input) {
  std::lock_guard<std::mutex> lock(push_mutex_);
  tail_->data = std::move(input);
  Node* const new_node = new Node();
  DCHECK(tail_->next.load() == nullptr);
  tail_->next = new_node;
  tail_ = new_node;
  ++fifo_size_;

  {
    // Taking the lock and dropping it immediately assure that the notify
    // cannot happen between the check of the predicate and wait of the
    // |push_conditional_|.
    std::lock_guard<std::mutex> lock(push_conditional_mutex_);
  }
  push_conditional_.notify_all();
}

template <typename DataType>
DataType SemiLocklessFifo<DataType>::PopFront() {
  DCHECK(!Empty());

  Node* const front_node = head_;
  head_ = front_node->next;

  DataType output = std::move(front_node->data);
  delete front_node;

  DCHECK_GT(fifo_size_.load(), 0u);
  --fifo_size_;

  {
    // Taking the lock and dropping it immediately assure that the notify
    // cannot happen between the check of the predicate and wait of the
    // |pop_conditional_|.
    std::lock_guard<std::mutex> lock(pop_conditional_mutex_);
  }
  pop_conditional_.notify_one();
  return output;
}

template <typename DataType>
bool SemiLocklessFifo<DataType>::Empty() const {
  return fifo_size_.load() == 0;
}

template <typename DataType>
void SemiLocklessFifo<DataType>::Clear() {
  while (!Empty()) {
    PopFront();
  }
  DCHECK_EQ(fifo_size_, 0u);
}

template <typename DataType>
bool SemiLocklessFifo<DataType>::SleepUntilBelowSizeTarget(
    size_t target_size, const ClockDuration& max_wait) {
  DCHECK_GT(target_size, 0);
  std::unique_lock<std::mutex> lock(pop_conditional_mutex_);
  pop_conditional_.wait_for(lock, max_wait, [this, target_size]() {
    return fifo_size_ < target_size || !enable_sleeping_.load();
  });
  return fifo_size_ < target_size;
}

template <typename DataType>
bool SemiLocklessFifo<DataType>::SleepUntilNumElementsInQueue(
    size_t target_size, const ClockDuration& max_wait) {
  DCHECK_GT(target_size, 0u);
  std::unique_lock<std::mutex> lock(push_conditional_mutex_);
  push_conditional_.wait_for(lock, max_wait, [this, target_size]() {
    return fifo_size_ >= target_size || !enable_sleeping_.load();
  });
  return fifo_size_ >= target_size;
}

template <typename DataType>
void SemiLocklessFifo<DataType>::EnableBlockingSleepUntilMethods(bool enable) {
  enable_sleeping_ = enable;
  // Taking the lock and dropping it immediately assure that the notify
  // cannot happen between the check of the predicate and wait of the
  // |pop_conditional_| and |push_conditional_|.
  { std::lock_guard<std::mutex> lock(pop_conditional_mutex_); }
  { std::lock_guard<std::mutex> lock(push_conditional_mutex_); }
  pop_conditional_.notify_one();
  push_conditional_.notify_one();
}

}  // namespace vraudio

#endif  // RESONANCE_AUDIO_UTILS_SEMI_LOCKLESS_FIFO_H_


text:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var csso = require('gulp-csso');
var autoprefixer = require('gulp-autoprefixer');
var sass = require('gulp-ruby-sass');

function handleError(err) {
  console.log(err.toString());
  this.emit('end');
}

var sassOptions = { // The options to be passed to sass()
    style: 'expanded',
    'sourcemap=none': true
};

//https://github.com/jgoux/generator-angulpify/issues/19
module.exports = gulp.task('styles', function () {
  return gulp.src(config.paths.src.mainStyles)
    .pipe(autoprefixer('last 1 version'))
    .pipe(gulpif(release, csso()))
    .pipe(gulpif(release, sass(sassOptions).on('error', handleError), sass(sassOptions).on('error', handleError)))
    .pipe(rename(config.filenames.styles))
    .pipe(gulpif(release, gulp.dest(config.paths.dest.phonegap.styles), gulp.dest(config.paths.dest.build.styles) ))
    .pipe(reload({stream:true}));
});


text:
function [result,mot,skel] = readMotion(mot,skel,fid,range,compute_quats)

tic
fseek(fid,0,'bof');
lc = 0;
[result,line,pos,line_count] = findKeyword(fid,'MOTION');
if ~result
    fclose(fid);
    error(['BVH section MOTION not found in file ' mot.filename '!']);
end
lc = lc + line_count;

[result,line,pos,line_count] = findKeyword(fid,'Frames:');
if ~result
    fclose(fid);
    error(['BVH section Frames not found in file ' mot.filename '!']);
end
line = deblank(line(8:size(line,2)));
frame_num = str2num(line);
lc = lc + line_count;

[result,line,pos,line_count] = findKeyword(fid,'Frame Time:');
if ~result
    fclose(fid);
    error(['BVH section Frame Time not found in file ' mot.filename '!']);
end
line = deblank(line(13:size(line,2)));
mot.frameTime = str2num(line);
mot.samplingRate = 1 / mot.frameTime;
lc = lc + line_count;

%%%%%%%%%%%%%%%% determine frame range to be read
if (length(range)<=0)
    start_frame = 1;
    end_frame = frame_num;
elseif (length(range)==1)
    start_frame = 1;
    end_frame = range(1);
else
    start_frame = range(1);
    end_frame = range(2);
end
if (start_frame > end_frame) % swap, if necessary
    h = end_frame;
    end_frame = start_frame;
    start_frame = h;
end
if (start_frame == -inf)
    start_frame = 1;
end
if (end_frame == inf)
    end_frame = frame_num;
end
if (end_frame > frame_num)
    error('end_frame greater than number of frames in file!');
end

fclose(fid);
mot.nframes = end_frame - start_frame + 1;
data = textread(mot.filename,'',mot.nframes,'headerlines',lc + start_frame - 1)';
if max(abs(data(size(data,1),:))) == 0
    data = data(1:size(data,1)-1,:);
end
t = toc;

disp(['Read ' num2str(mot.nframes) ' frames of motion data from ' mot.filename ' in ' num2str(t) ' seconds.']);

mot.rootTranslation = extractRootTranslation(skel,data);
%%%%%%%% extract and convert data
tic
[mot.rotationEuler, mot.rotationQuat] = extractRotation(skel, 1, data, 1, cell(mot.njoints,1), cell(mot.njoints,1), compute_quats);
t = toc;
if (compute_quats)
    disp(['Converted motion data from ' mot.filename ' in ' num2str(t) ' seconds.']);
end

mot.njoints = skel.njoints;
mot.jointNames = skel.jointNames;
mot.boneNames = skel.boneNames;
mot.animated = skel.animated;
mot.unanimated = skel.unanimated;

result = true;