text:
namespace full_restore {

namespace {

//  These are temporary estimate of how long it takes full restore to launch
//  apps.
constexpr base::TimeDelta kFullRestoreEstimateDuration = base::Seconds(5);
constexpr base::TimeDelta kFullRestoreARCEstimateDuration = base::Minutes(3);
constexpr base::TimeDelta kFullRestoreLacrosEstimateDuration = base::Minutes(1);

}  // namespace

FullRestoreReadHandler* FullRestoreReadHandler::GetInstance() {
  static base::NoDestructor<FullRestoreReadHandler> full_restore_read_handler;
  return full_restore_read_handler.get();
}

FullRestoreReadHandler::FullRestoreReadHandler() {
  if (aura::Env::HasInstance())
    env_observer_.Observe(aura::Env::GetInstance());
  arc_info_observer_.Observe(app_restore::AppRestoreArcInfo::GetInstance());
}

FullRestoreReadHandler::~FullRestoreReadHandler() = default;

void FullRestoreReadHandler::OnWindowInitialized(aura::Window* window) {
  int32_t window_id = window->GetProperty(app_restore::kRestoreWindowIdKey);

  if (app_restore::IsArcWindow(window)) {
    // If there isn't restore data for ARC apps, we don't need to handle ARC app
    // windows restoration.
    if (!arc_read_handler_)
      return;

    if (window_id == app_restore::kParentToHiddenContainer ||
        arc_read_handler_->HasRestoreData(window_id)) {
      observed_windows_.AddObservation(window);
      arc_read_handler_->AddArcWindowCandidate(window);
      app_restore::AppRestoreInfo::GetInstance()->OnWindowInitialized(window);
    }
    return;
  }

  if (app_restore::IsLacrosWindow(window)) {
    DCHECK(window_id > app_restore::kParentToHiddenContainer);

    return;
  }

  if (!SessionID::IsValidValue(window_id)) {
    return;
  }

  observed_windows_.AddObservation(window);
  app_restore::AppRestoreInfo::GetInstance()->OnWindowInitialized(window);
}

void FullRestoreReadHandler::OnWindowDestroyed(aura::Window* window) {
  DCHECK(observed_windows_.IsObservingSource(window));
  observed_windows_.RemoveObservation(window);

  if (app_restore::IsArcWindow(window)) {
    if (arc_read_handler_)
      arc_read_handler_->OnWindowDestroyed(window);
    return;
  }

  int32_t restore_window_id =
      window->GetProperty(app_restore::kRestoreWindowIdKey);
  DCHECK(SessionID::IsValidValue(restore_window_id));

  RemoveAppRestoreData(restore_window_id);
}

std::unique_ptr<app_restore::AppLaunchInfo>
FullRestoreReadHandler::GetAppLaunchInfo(const base::FilePath& profile_path,
                                         const std::string& app_id,
                                         int32_t restore_window_id) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return nullptr;

  return restore_data->GetAppLaunchInfo(app_id, restore_window_id);
}

std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo(
    const base::FilePath& profile_path,
    const std::string& app_id,
    int32_t restore_window_id) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return nullptr;

  return restore_data->GetWindowInfo(app_id, restore_window_id);
}

void FullRestoreReadHandler::RemoveAppRestoreData(
    const base::FilePath& profile_path,
    const std::string& app_id,
    int32_t restore_window_id) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return;

  restore_data->RemoveAppRestoreData(app_id, restore_window_id);
}

void FullRestoreReadHandler::OnTaskCreated(const std::string& app_id,
                                           int32_t task_id,
                                           int32_t session_id) {
  if (arc_read_handler_)
    arc_read_handler_->OnTaskCreated(app_id, task_id, session_id);
}

void FullRestoreReadHandler::OnTaskDestroyed(int32_t task_id) {
  if (arc_read_handler_)
    arc_read_handler_->OnTaskDestroyed(task_id);
}

void FullRestoreReadHandler::SetPrimaryProfilePath(
    const base::FilePath& profile_path) {
  primary_profile_path_ = profile_path;
}

void FullRestoreReadHandler::SetActiveProfilePath(
    const base::FilePath& profile_path) {
  active_profile_path_ = profile_path;
}

void FullRestoreReadHandler::SetCheckRestoreData(
    const base::FilePath& profile_path) {
  should_check_restore_data_.insert(profile_path);
}

void FullRestoreReadHandler::ReadFromFile(const base::FilePath& profile_path,
                                          Callback callback) {
  auto it = profile_path_to_restore_data_.find(profile_path);
  if (it != profile_path_to_restore_data_.end()) {
    // If the restore data has been read from the file, just use it, and don't
    // need to read it again.
    //
    // We must use post task here, because FullRestoreAppLaunchHandler calls
    // ReadFromFile in FullRestoreService construct function, and the callback
    // in FullRestoreAppLaunchHandler calls the init function of
    // FullRestoreService. If we don't use post task, and call the callback
    // function directly, it could cause deadloop.
    base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(std::move(callback),
                       (it->second ? it->second->Clone() : nullptr)));
    return;
  }

  auto file_handler =
      base::MakeRefCounted<FullRestoreFileHandler>(profile_path);
  file_handler->owning_task_runner()->PostTaskAndReplyWithResult(
      FROM_HERE,
      base::BindOnce(&FullRestoreFileHandler::ReadFromFile, file_handler.get()),
      base::BindOnce(&FullRestoreReadHandler::OnGetRestoreData,
                     weak_factory_.GetWeakPtr(), profile_path,
                     std::move(callback)));
}

void FullRestoreReadHandler::SetNextRestoreWindowIdForChromeApp(
    const base::FilePath& profile_path,
    const std::string& app_id) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return;

  restore_data->SetNextRestoreWindowIdForChromeApp(app_id);
}

void FullRestoreReadHandler::RemoveApp(const base::FilePath& profile_path,
                                       const std::string& app_id) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return;

  restore_data->RemoveApp(app_id);
}

bool FullRestoreReadHandler::HasAppTypeBrowser(
    const base::FilePath& profile_path) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return false;

  return restore_data->HasAppTypeBrowser();
}

bool FullRestoreReadHandler::HasBrowser(const base::FilePath& profile_path) {
  auto* restore_data = GetRestoreData(profile_path);
  if (!restore_data)
    return false;

  return restore_data->HasBrowser();
}

bool FullRestoreReadHandler::HasWindowInfo(int32_t restore_window_id) {
  if (!SessionID::IsValidValue(restore_window_id) ||
      !base::Contains(should_check_restore_data_, active_profile_path_)) {
    return false;
  }

  auto it = window_id_to_app_restore_info_.find(restore_window_id);
  if (it == window_id_to_app_restore_info_.end())
    return false;

  return true;
}

std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo(
    aura::Window* window) {
  if (!window)
    return nullptr;

  const int32_t restore_window_id =
      window->GetProperty(app_restore::kRestoreWindowIdKey);

  if (app_restore::IsArcWindow(window)) {
    return arc_read_handler_
               ? arc_read_handler_->GetWindowInfo(restore_window_id)
               : nullptr;
  }

  return GetWindowInfo(restore_window_id);
}

std::unique_ptr<app_restore::WindowInfo>
FullRestoreReadHandler::GetWindowInfoForActiveProfile(
    int32_t restore_window_id) {
  if (!base::Contains(should_check_restore_data_, active_profile_path_))
    return nullptr;
  return GetWindowInfo(restore_window_id);
}

std::unique_ptr<app_restore::AppLaunchInfo>
FullRestoreReadHandler::GetArcAppLaunchInfo(const std::string& app_id,
                                            int32_t session_id) {
  return arc_read_handler_
             ? arc_read_handler_->GetArcAppLaunchInfo(app_id, session_id)
             : nullptr;
}

int32_t FullRestoreReadHandler::FetchRestoreWindowId(
    const std::string& app_id) {
  auto* restore_data = GetRestoreData(active_profile_path_);
  if (!restore_data)
    return 0;

  return restore_data->FetchRestoreWindowId(app_id);
}

int32_t FullRestoreReadHandler::GetArcRestoreWindowIdForTaskId(
    int32_t task_id) {
  if (!arc_read_handler_)
    return 0;

  return arc_read_handler_->GetArcRestoreWindowIdForTaskId(task_id);
}

int32_t FullRestoreReadHandler::GetArcRestoreWindowIdForSessionId(
    int32_t session_id) {
  if (!arc_read_handler_)
    return 0;

  return arc_read_handler_->GetArcRestoreWindowIdForSessionId(session_id);
}

int32_t FullRestoreReadHandler::GetLacrosRestoreWindowId(
    const std::string& lacros_window_id) const {
  return full_restore::FullRestoreReadHandler::GetInstance()
      ->FetchRestoreWindowId(lacros_window_id);
}

void FullRestoreReadHandler::SetArcSessionIdForWindowId(int32_t arc_session_id,
                                                        int32_t window_id) {
  if (arc_read_handler_)
    arc_read_handler_->SetArcSessionIdForWindowId(arc_session_id, window_id);
}

void FullRestoreReadHandler::SetStartTimeForProfile(
    const base::FilePath& profile_path) {
  profile_path_to_start_time_data_[profile_path] = base::TimeTicks::Now();
}

bool FullRestoreReadHandler::IsFullRestoreRunning() const {
  auto it = profile_path_to_start_time_data_.find(active_profile_path_);
  if (it == profile_path_to_start_time_data_.end())
    return false;

  if (IsArcRestoreRunning() || IsLacrosRestoreRunning())
    return true;

  // We estimate that full restore is still running if it has been less than
  // five seconds since it started.
  return base::TimeTicks::Now() - it->second < kFullRestoreEstimateDuration;
}

void FullRestoreReadHandler::AddChromeBrowserLaunchInfoForTesting(
    const base::FilePath& profile_path) {
  auto session_id = SessionID::NewUnique();
  auto app_launch_info = std::make_unique<app_restore::AppLaunchInfo>(
      app_constants::kChromeAppId, session_id.id());
  app_launch_info->app_type_browser = true;

  if (profile_path_to_restore_data_.find(profile_path) ==
      profile_path_to_restore_data_.end()) {
    profile_path_to_restore_data_[profile_path] =
        std::make_unique<app_restore::RestoreData>();
  }

  profile_path_to_restore_data_[profile_path]->AddAppLaunchInfo(
      std::move(app_launch_info));
  window_id_to_app_restore_info_[session_id.id()] =
      std::make_pair(profile_path, app_constants::kChromeAppId);
}

std::unique_ptr<app_restore::WindowInfo> FullRestoreReadHandler::GetWindowInfo(
    int32_t restore_window_id) {
  if (!SessionID::IsValidValue(restore_window_id))
    return nullptr;

  auto it = window_id_to_app_restore_info_.find(restore_window_id);
  if (it == window_id_to_app_restore_info_.end())
    return nullptr;

  const base::FilePath& profile_path = it->second.first;
  const std::string& app_id = it->second.second;
  return GetWindowInfo(profile_path, app_id, restore_window_id);
}

bool FullRestoreReadHandler::IsArcRestoreRunning() const {
  if (!arc_read_handler_ || active_profile_path_ != primary_profile_path_)
    return false;

  auto it = profile_path_to_start_time_data_.find(primary_profile_path_);
  if (it == profile_path_to_start_time_data_.end())
    return false;

  // We estimate that full restore is still running for ARC windows if it has
  // been less than five minutes since it started, when there is at least one
  // ARC app, since it might take long time to boot ARC.
  return base::TimeTicks::Now() - it->second < kFullRestoreARCEstimateDuration;
}

bool FullRestoreReadHandler::IsLacrosRestoreRunning() const {
  if (active_profile_path_ != primary_profile_path_)
    return false;

  auto it = profile_path_to_start_time_data_.find(primary_profile_path_);
  if (it == profile_path_to_start_time_data_.end())
    return false;

  // We estimate that full restore is still running if it has been less than
  // one minute since it started, when Lacros is available.
  return base::TimeTicks::Now() - it->second <
         kFullRestoreLacrosEstimateDuration;
}

void FullRestoreReadHandler::OnGetRestoreData(
    const base::FilePath& profile_path,
    Callback callback,
    std::unique_ptr<app_restore::RestoreData> restore_data) {
  if (restore_data) {
    profile_path_to_restore_data_[profile_path] = restore_data->Clone();
    for (auto it = restore_data->app_id_to_launch_list().begin();
         it != restore_data->app_id_to_launch_list().end(); it++) {
      const std::string& app_id = it->first;
      for (auto data_it = it->second.begin(); data_it != it->second.end();
           data_it++) {
        int32_t window_id = data_it->first;
        // Only ARC app launch parameters have event_flag.
        if (data_it->second->event_flag.has_value()) {
          if (!arc_read_handler_) {
            arc_read_handler_ = std::make_unique<app_restore::ArcReadHandler>(
                profile_path, this);
          }
          arc_read_handler_->AddRestoreData(app_id, window_id);
        } else {
          window_id_to_app_restore_info_[window_id] =
              std::make_pair(profile_path, app_id);
        }
      }
    }
  } else {
    profile_path_to_restore_data_[profile_path] = nullptr;
  }

  std::move(callback).Run(std::move(restore_data));

  // Call FullRestoreSaveHandler to start a timer to clear the restore data
  // after reading the restore data. Otherwise, if the user doesn't select
  // restore, and never launch a new app, the restore data is not cleared. So
  // when the system is reboot, the restore process could restore the previous
  // record before the last reboot.
  FullRestoreSaveHandler::GetInstance()->ClearRestoreData(profile_path);
}

void FullRestoreReadHandler::RemoveAppRestoreData(int32_t window_id) {
  auto it = window_id_to_app_restore_info_.find(window_id);
  if (it == window_id_to_app_restore_info_.end())
    return;

  const base::FilePath& profile_path = it->second.first;
  const std::string& app_id = it->second.second;
  RemoveAppRestoreData(profile_path, app_id, window_id);

  window_id_to_app_restore_info_.erase(it);
}

app_restore::RestoreData* FullRestoreReadHandler::GetRestoreData(
    const base::FilePath& profile_path) {
  auto it = profile_path_to_restore_data_.find(profile_path);
  if (it == profile_path_to_restore_data_.end() || !it->second) {
    return nullptr;
  }
  return it->second.get();
}

}  // namespace full_restore


text:
/*
 * rc-service.c
 * Finds all OpenRC services
 */

/*
 * Copyright (c) 2008-2015 The OpenRC Authors.
 * See the Authors file at the top-level directory of this distribution and
 * https://github.com/OpenRC/openrc/blob/master/AUTHORS
 *
 * This file is part of OpenRC. It is subject to the license terms in
 * the LICENSE file found in the top-level directory of this
 * distribution and at https://github.com/OpenRC/openrc/blob/master/LICENSE
 * This file may not be copied, modified, propagated, or distributed
 *    except according to the terms contained in the LICENSE file.
 */

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

#include "einfo.h"
#include "queue.h"
#include "rc.h"
#include "rc-misc.h"
#include "_usage.h"

const char *applet = NULL;
const char *extraopts = NULL;
const char *getoptstring = "cdDe:ilr:INsSZ" getoptstring_COMMON;
const struct option longopts[] = {
	{ "debug",     0, NULL, 'd' },
	{ "nodeps",     0, NULL, 'D' },
	{ "exists",   1, NULL, 'e' },
	{ "ifcrashed", 0, NULL, 'c' },
	{ "ifexists", 0, NULL, 'i' },
	{ "ifinactive", 0, NULL, 'I' },
	{ "ifnotstarted", 0, NULL, 'N' },
	{ "ifstarted", 0, NULL, 's' },
	{ "ifstopped", 0, NULL, 'S' },
	{ "list",     0, NULL, 'l' },
	{ "resolve",  1, NULL, 'r' },
	{ "dry-run",     0, NULL, 'Z' },
	longopts_COMMON
};
const char * const longopts_help[] = {
	"set xtrace when running the command",
	"ignore dependencies",
	"tests if the service exists or not",
	"if the service is crashed run the command",
	"if the service exists run the command",
	"if the service is inactive run the command",
	"if the service is not started run the command",
	"if the service is started run the command",
	"if the service is stopped run the command",
	"list all available services",
	"resolve the service name to an init script",
	"dry run (show what would happen)",
	longopts_help_COMMON
};
const char *usagestring = ""							\
	"Usage: rc-service [options] [-i] <service> <cmd>...\n"		\
	"   or: rc-service [options] -e <service>\n"			\
	"   or: rc-service [options] -l\n"				\
	"   or: rc-service [options] -r <service>";

int main(int argc, char **argv)
{
	int opt;
	char *service;
	RC_STRINGLIST *list;
	RC_STRING *s;
	RC_SERVICE state;
	bool if_crashed = false;
	bool if_exists = false;
	bool if_inactive = false;
	bool if_notstarted = false;
	bool if_started = false;
	bool if_stopped = false;

	applet = basename_c(argv[0]);
	/* Ensure that we are only quiet when explicitly told to be */
	unsetenv("EINFO_QUIET");

	while ((opt = getopt_long(argc, argv, getoptstring,
		    longopts, (int *) 0)) != -1)
	{
		switch (opt) {
		case 'd':
			setenv("RC_DEBUG", "yes", 1);
			break;
		case 'D':
			setenv("RC_NODEPS", "yes", 1);
			break;
		case 'e':
			service = rc_service_resolve(optarg);
			opt = service ? EXIT_SUCCESS : EXIT_FAILURE;
			free(service);
			return opt;
			/* NOTREACHED */
		case 'c':
			if_crashed = true;
			break;
		case 'i':
			if_exists = true;
			break;
		case 'I':
			if_inactive = true;
			break;
		case 'N':
			if_notstarted = true;
			break;
		case 'l':
			list = rc_services_in_runlevel(NULL);
			if (TAILQ_FIRST(list) == NULL)
				return EXIT_FAILURE;
			rc_stringlist_sort(&list);
			TAILQ_FOREACH(s, list, entries)
			    printf("%s\n", s->value);
			rc_stringlist_free(list);
			return EXIT_SUCCESS;
			/* NOTREACHED */
		case 'r':
			service = rc_service_resolve(optarg);
			if (service == NULL)
				return EXIT_FAILURE;
			printf("%s\n", service);
			free(service);
			return EXIT_SUCCESS;
			/* NOTREACHED */
		case 's':
			if_started = true;
			break;
		case 'S':
			if_stopped = true;
			break;
		case 'Z':
			setenv("IN_DRYRUN", "yes", 1);
			break;

		case_RC_COMMON_GETOPT
		}
	}

	argc -= optind;
	argv += optind;
	if (*argv == NULL)
		eerrorx("%s: you need to specify a service", applet);
	if ((service = rc_service_resolve(*argv)) == NULL) {
		if (if_exists)
			return 0;
		eerrorx("%s: service `%s' does not exist", applet, *argv);
	}
	state = rc_service_state(*argv);
	if (if_crashed &&  ! (rc_service_daemons_crashed(*argv) && errno != EACCES))
		return 0;
	if (if_inactive && ! (state & RC_SERVICE_INACTIVE))
		return 0;
	if (if_notstarted && (state & RC_SERVICE_STARTED))
		return 0;
	if (if_started && ! (state & RC_SERVICE_STARTED))
		return 0;
	if (if_stopped && ! (state & RC_SERVICE_STOPPED))
		return 0;
	*argv = service;
	execv(*argv, argv);
	eerrorx("%s: %s", applet, strerror(errno));
	/* NOTREACHED */
}

redpajama_set_name: RedPajamaGithub


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

package net.starlark.java.eval;

import static com.google.common.truth.Truth.assertThat;
import static org.junit.Assert.assertThrows;

import java.util.Iterator;
import net.starlark.java.eval.Mutability.Freezable;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;

/** Tests for {@link Mutability}. */
@RunWith(JUnit4.class)
public final class MutabilityTest {

  /** A trivial Freezable that can do nothing but freeze. */
  private static class DummyFreezable extends StarlarkIterable<String> {
    private final Mutability mutability;

    public DummyFreezable(Mutability mutability) {
      this.mutability = mutability;
    }

    @Override
    public Mutability mutability() {
      return mutability;
    }

    @Override
    public Iterator<String> iterator() {
      throw new AssertionError();
    }
  }

  private static void assertCheckMutableFailsBecauseFrozen(DummyFreezable x) {
    EvalException ex = assertThrows(EvalException.class, () -> x.checkMutable());
    assertThat(ex).hasMessageThat().contains("trying to mutate a frozen DummyFreezable value");
  }

  @Test
  public void freeze() throws Exception {
    Mutability mutability = Mutability.create("test");
    DummyFreezable dummy = new DummyFreezable(mutability);

    dummy.checkMutable();
    mutability.freeze();
    assertCheckMutableFailsBecauseFrozen(dummy);
  }

  @Test
  public void tryWithResources() throws Exception {
    DummyFreezable dummy;
    try (Mutability mutability = Mutability.create("test")) {
      dummy = new DummyFreezable(mutability);
      dummy.checkMutable();
    }
    assertCheckMutableFailsBecauseFrozen(dummy);
  }

  @Test
  public void initiallyMutable() throws Exception {
    Mutability mutability = Mutability.create("test");
    DummyFreezable dummy = new DummyFreezable(mutability);

    dummy.checkMutable();
  }

  @Test
  public void temporarilyImmutableDuringIteration() throws Exception {
    Mutability mutability = Mutability.create("test");
    DummyFreezable x = new DummyFreezable(mutability);
    x.updateIteratorCount(+1);
    EvalException ex = assertThrows(EvalException.class, () -> x.checkMutable());
    assertThat(ex)
        .hasMessageThat()
        .contains("DummyFreezable value is temporarily immutable due to active for-loop iteration");

    x.updateIteratorCount(+1);
    x.updateIteratorCount(-1); // net +1 => still immutable
    ex = assertThrows(EvalException.class, () -> x.checkMutable());
    assertThat(ex)
        .hasMessageThat()
        .contains("DummyFreezable value is temporarily immutable due to active for-loop iteration");

    x.updateIteratorCount(-1); // net 0 => mutable
    x.checkMutable(); // ok

    assertThrows(IllegalStateException.class, () -> x.updateIteratorCount(-1)); // underflow
  }

  @Test
  public void addIteratorAndThenFreeze() throws Exception {
    Mutability mutability = Mutability.create("test");
    DummyFreezable dummy = new DummyFreezable(mutability);
    dummy.updateIteratorCount(+1);
    mutability.freeze();
    // Should fail with frozen error, not temporarily immutable error.
    assertCheckMutableFailsBecauseFrozen(dummy);
  }

  @Test
  public void checkUnsafeShallowFreezePrecondition_FailsWhenAlreadyFrozen() throws Exception {
    Mutability mutability = Mutability.create("test").freeze();
    assertThrows(
        IllegalArgumentException.class,
        () -> Freezable.checkUnsafeShallowFreezePrecondition(new DummyFreezable(mutability)));
  }

  @Test
  public void checkUnsafeShallowFreezePrecondition_FailsWhenDisallowed() throws Exception {
    Mutability mutability = Mutability.create("test");
    assertThrows(
        IllegalArgumentException.class,
        () -> Freezable.checkUnsafeShallowFreezePrecondition(new DummyFreezable(mutability)));
  }

  @Test
  public void checkUnsafeShallowFreezePrecondition_SucceedsWhenAllowed() throws Exception {
    Mutability mutability = Mutability.createAllowingShallowFreeze("test");
    Freezable.checkUnsafeShallowFreezePrecondition(new DummyFreezable(mutability));
  }
}


text:
package org.apache.beam.runners.core.metrics;

import java.io.Serializable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import javax.annotation.Nullable;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.MoreObjects;
import org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Iterables;

/**
 * A map from {@code K} to {@code T} that supports getting or creating values associated with a key
 * in a thread-safe manner.
 */
public class MetricsMap<K, T> implements Serializable {

  /** Interface for creating instances to populate the {@link MetricsMap}. */
  public interface Factory<K, T> extends Serializable {
    /**
     * Create an instance of {@code T} to use with the given {@code key}.
     *
     * <p>It must be safe to call this from multiple threads.
     */
    T createInstance(K key);
  }

  private final Factory<K, T> factory;
  private final ConcurrentMap<K, T> metrics = new ConcurrentHashMap<>();

  public MetricsMap(Factory<K, T> factory) {
    this.factory = factory;
  }

  /** Get or create the value associated with the given key. */
  public T get(K key) {
    T metric = metrics.get(key);
    if (metric == null) {
      metric = factory.createInstance(key);
      metric = MoreObjects.firstNonNull(metrics.putIfAbsent(key, metric), metric);
    }
    return metric;
  }

  /** Get the value associated with the given key, if it exists. */
  @Nullable
  public T tryGet(K key) {
    return metrics.get(key);
  }

  /** Return an iterable over the entries in the current {@link MetricsMap}. */
  public Iterable<Map.Entry<K, T>> entries() {
    return Iterables.unmodifiableIterable(metrics.entrySet());
  }

  /** Return an iterable over the values in the current {@link MetricsMap}. */
  public Iterable<T> values() {
    return Iterables.unmodifiableIterable(metrics.values());
  }

  @Override
  public boolean equals(Object object) {
    if (object instanceof MetricsMap) {
      MetricsMap<?, ?> metricsMap = (MetricsMap<?, ?>) object;
      return Objects.equals(metrics, metricsMap.metrics);
    }

    return false;
  }

  @Override
  public int hashCode() {
    return metrics.hashCode();
  }
}


text:
#include "StudioSetupWidget.hpp"

#include <QApplication>
#include <QPainter>
#include <QScrollBar>
#include <QStylePainter>

#include <amuse/EffectBase.hpp>
#include <amuse/EffectChorus.hpp>
#include <amuse/EffectDelay.hpp>
#include <amuse/EffectReverb.hpp>
#include <amuse/Studio.hpp>
#include <amuse/Submix.hpp>

using namespace std::literals;

struct EffectIntrospection {
  struct Field {
    enum class Type {
      Invalid,
      UInt32,
      UInt32x8,
      Float,
    };

    Type m_tp{};
    std::string_view m_name;
    float m_min{};
    float m_max{};
    float m_default{};
  };
  amuse::EffectType m_tp;
  std::string_view m_name;
  std::string_view m_description;
  std::array<Field, 7> m_fields;
};

namespace {
constexpr EffectIntrospection ReverbStdIntrospective = {
    amuse::EffectType::ReverbStd,
    "Reverb Std"sv,
    "Standard Reverb"sv,
    {
        {{EffectIntrospection::Field::Type::Float, "Coloration"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Mix"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Time"sv, 0.01f, 10.f, 0.01f},
         {EffectIntrospection::Field::Type::Float, "Damping"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Pre Delay"sv, 0.f, 0.1f, 0.f}},
    },
};

using ReverbStdGetFunc = float (amuse::EffectReverbStd::*)() const;
using ReverbStdSetFunc = void (amuse::EffectReverbStd::*)(float);
constexpr std::array<ReverbStdGetFunc, 5> ReverbStdGetters{
    &amuse::EffectReverbStd::getColoration, &amuse::EffectReverbStd::getMix,      &amuse::EffectReverbStd::getTime,
    &amuse::EffectReverbStd::getDamping,    &amuse::EffectReverbStd::getPreDelay,
};
constexpr std::array<ReverbStdSetFunc, 5> ReverbStdSetters{
    &amuse::EffectReverbStd::setColoration, &amuse::EffectReverbStd::setMix,      &amuse::EffectReverbStd::setTime,
    &amuse::EffectReverbStd::setDamping,    &amuse::EffectReverbStd::setPreDelay,
};

constexpr EffectIntrospection ReverbHiIntrospective = {
    amuse::EffectType::ReverbHi,
    "Reverb Hi"sv,
    "High Reverb"sv,
    {
        {{EffectIntrospection::Field::Type::Float, "Coloration"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Mix"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Time"sv, 0.01f, 10.f, 0.01f},
         {EffectIntrospection::Field::Type::Float, "Damping"sv, 0.f, 1.f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Pre Delay"sv, 0.f, 0.1f, 0.f},
         {EffectIntrospection::Field::Type::Float, "Crosstalk"sv, 0.f, 1.f, 0.f}},
    },
};

using ReverbHiGetFunc = float (amuse::EffectReverbHi::*)() const;
using ReverbHiSetFunc = void (amuse::EffectReverbHi::*)(float);
constexpr std::array<ReverbHiGetFunc, 6> ReverbHiGetters{
    &amuse::EffectReverbHi::getColoration, &amuse::EffectReverbHi::getMix,      &amuse::EffectReverbHi::getTime,
    &amuse::EffectReverbHi::getDamping,    &amuse::EffectReverbHi::getPreDelay, &amuse::EffectReverbHi::getCrosstalk,
};
constexpr std::array<ReverbHiSetFunc, 6> ReverbHiSetters{
    &amuse::EffectReverbHi::setColoration, &amuse::EffectReverbHi::setMix,      &amuse::EffectReverbHi::setTime,
    &amuse::EffectReverbHi::setDamping,    &amuse::EffectReverbHi::setPreDelay, &amuse::EffectReverbHi::setCrosstalk,
};

constexpr EffectIntrospection DelayIntrospective = {
    amuse::EffectType::Delay,
    "Delay"sv,
    "Delay"sv,
    {{
        {EffectIntrospection::Field::Type::UInt32x8, "Delay"sv, 10, 5000, 10},
        {EffectIntrospection::Field::Type::UInt32x8, "Feedback"sv, 0, 100, 0},
        {EffectIntrospection::Field::Type::UInt32x8, "Output"sv, 0, 100, 0},
    }},
};

using DelayGetFunc = uint32_t (amuse::EffectDelay::*)(int) const;
using DelaySetFunc = void (amuse::EffectDelay::*)(int, uint32_t);
constexpr std::array<DelayGetFunc, 3> DelayGetters{
    &amuse::EffectDelay::getChanDelay,
    &amuse::EffectDelay::getChanFeedback,
    &amuse::EffectDelay::getChanOutput,
};
constexpr std::array<DelaySetFunc, 3> DelaySetters{
    &amuse::EffectDelay::setChanDelay,
    &amuse::EffectDelay::setChanFeedback,
    &amuse::EffectDelay::setChanOutput,
};

constexpr EffectIntrospection ChorusIntrospective = {
    amuse::EffectType::Chorus,
    "Chorus"sv,
    "Chorus"sv,
    {{
        {EffectIntrospection::Field::Type::UInt32, "Base Delay"sv, 5, 15, 5},
        {EffectIntrospection::Field::Type::UInt32, "Variation"sv, 0, 5, 0},
        {EffectIntrospection::Field::Type::UInt32, "Period"sv, 500, 10000, 500},
    }},
};

using ChorusGetFunc = uint32_t (amuse::EffectChorus::*)() const;
using ChorusSetFunc = void (amuse::EffectChorus::*)(uint32_t);
constexpr std::array<ChorusGetFunc, 3> ChorusGetters{
    &amuse::EffectChorus::getBaseDelay,
    &amuse::EffectChorus::getVariation,
    &amuse::EffectChorus::getPeriod,
};
constexpr std::array<ChorusSetFunc, 3> ChorusSetters{
    &amuse::EffectChorus::setBaseDelay,
    &amuse::EffectChorus::setVariation,
    &amuse::EffectChorus::setPeriod,
};

constexpr const EffectIntrospection* GetEffectIntrospection(amuse::EffectType type) {
  switch (type) {
  case amuse::EffectType::ReverbStd:
    return &ReverbStdIntrospective;
  case amuse::EffectType::ReverbHi:
    return &ReverbHiIntrospective;
  case amuse::EffectType::Delay:
    return &DelayIntrospective;
  case amuse::EffectType::Chorus:
    return &ChorusIntrospective;
  default:
    return nullptr;
  }
}

template <typename T>
T GetEffectParm(const amuse::EffectBaseTypeless* effect, int idx, int chanIdx) {
  switch (effect->Isa()) {
  case amuse::EffectType::ReverbStd:
    return (static_cast<const amuse::EffectReverbStdImp<float>*>(effect)->*ReverbStdGetters[idx])();
  case amuse::EffectType::ReverbHi:
    return (static_cast<const amuse::EffectReverbHiImp<float>*>(effect)->*ReverbHiGetters[idx])();
  case amuse::EffectType::Delay:
    return (static_cast<const amuse::EffectDelayImp<float>*>(effect)->*DelayGetters[idx])(chanIdx);
  case amuse::EffectType::Chorus:
    return (static_cast<const amuse::EffectChorusImp<float>*>(effect)->*ChorusGetters[idx])();
  default:
    return 0.f;
  }
}

template <typename T>
void SetEffectParm(amuse::EffectBaseTypeless* effect, int idx, int chanIdx, T val) {
  switch (effect->Isa()) {
  case amuse::EffectType::ReverbStd:
    (static_cast<amuse::EffectReverbStdImp<float>*>(effect)->*ReverbStdSetters[idx])(val);
    break;
  case amuse::EffectType::ReverbHi:
    (static_cast<amuse::EffectReverbHiImp<float>*>(effect)->*ReverbHiSetters[idx])(val);
    break;
  case amuse::EffectType::Delay:
    (static_cast<amuse::EffectDelayImp<float>*>(effect)->*DelaySetters[idx])(chanIdx, val);
    break;
  case amuse::EffectType::Chorus:
    (static_cast<amuse::EffectChorusImp<float>*>(effect)->*ChorusSetters[idx])(val);
    break;
  default:
    break;
  }
}

constexpr int NumChanNames = 8;
constexpr std::array<const char*, NumChanNames> ChanNames{
    QT_TRANSLATE_NOOP("Uint32X8Popup", "Front Left"),   QT_TRANSLATE_NOOP("Uint32X8Popup", "Front Right"),
    QT_TRANSLATE_NOOP("Uint32X8Popup", "Rear Left"),    QT_TRANSLATE_NOOP("Uint32X8Popup", "Rear Right"),
    QT_TRANSLATE_NOOP("Uint32X8Popup", "Front Center"), QT_TRANSLATE_NOOP("Uint32X8Popup", "LFE"),
    QT_TRANSLATE_NOOP("Uint32X8Popup", "Side Left"),    QT_TRANSLATE_NOOP("Uint32X8Popup", "Side Right"),
};

constexpr std::array<const char*, 4> EffectStrings{
    QT_TRANSLATE_NOOP("EffectCatalogue", "Reverb Standard"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Reverb High"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Delay"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Chorus"),
};

constexpr std::array<const char*, 4> EffectDocStrings{
    QT_TRANSLATE_NOOP("EffectCatalogue", "Reverb Standard"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Reverb High"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Delay"),
    QT_TRANSLATE_NOOP("EffectCatalogue", "Chorus"),
};
} // Anonymous namespace

Uint32X8Popup::Uint32X8Popup(int min, int max, QWidget* parent) : QFrame(parent, Qt::Popup) {
  setAttribute(Qt::WA_WindowPropagation);
  setAttribute(Qt::WA_X11NetWmWindowTypeCombo);
  Uint32X8Button* combo = static_cast<Uint32X8Button*>(parent);
  QStyleOptionComboBox opt = combo->comboStyleOption();
  setFrameStyle(combo->style()->styleHint(QStyle::SH_ComboBox_PopupFrameStyle, &opt, combo));

  QGridLayout* layout = new QGridLayout;
  for (int i = 0; i < NumChanNames; ++i) {
    layout->addWidget(new QLabel(tr(ChanNames[i])), i, 0);
    FieldSlider* slider = new FieldSlider(this);
    m_sliders[i] = slider;
    slider->setToolTip(QStringLiteral("[%1,%2]").arg(min).arg(max));
    slider->setProperty("chanIdx", i);
    slider->setRange(min, max);
    connect(slider, qOverload<int>(&FieldSlider::valueChanged), this, &Uint32X8Popup::doValueChanged);
    layout->addWidget(slider, i, 1);
  }
  setLayout(layout);
}

Uint32X8Popup::~Uint32X8Popup() = default;

void Uint32X8Popup::setValue(int chanIdx, int val) { m_sliders[chanIdx]->setValue(val); }

void Uint32X8Popup::doValueChanged(int val) {
  FieldSlider* slider = static_cast<FieldSlider*>(sender());
  int chanIdx = slider->property("chanIdx").toInt();
  emit valueChanged(chanIdx, val);
}

Uint32X8Button::Uint32X8Button(int min, int max, QWidget* parent)
: QPushButton(parent), m_popup(new Uint32X8Popup(min, max, this)) {
  connect(this, &Uint32X8Button::pressed, this, &Uint32X8Button::onPressed);
}

Uint32X8Button::~Uint32X8Button() = default;

void Uint32X8Button::paintEvent(QPaintEvent*) {
  QStylePainter painter(this);
  painter.setPen(palette().color(QPalette::Text));

  // draw the combobox frame, focusrect and selected etc.
  QStyleOptionComboBox opt = comboStyleOption();
  painter.drawComplexControl(QStyle::CC_ComboBox, opt);

  // draw the icon and text
  painter.drawControl(QStyle::CE_ComboBoxLabel, opt);
}

QStyleOptionComboBox Uint32X8Button::comboStyleOption() const {
  QStyleOptionComboBox opt;
  opt.initFrom(this);
  opt.editable = false;
  opt.frame = true;
  opt.currentText = tr("Channels");
  return opt;
}

void Uint32X8Button::onPressed() {
  QPoint pt = parentWidget()->mapToGlobal(pos());
  m_popup->move(pt.x(), pt.y());
  m_popup->show();
}

EffectWidget::EffectWidget(QWidget* parent, amuse::EffectBaseTypeless* effect, amuse::EffectType type)
: QWidget(parent)
, m_titleLabel(this)
, m_deleteButton(this)
, m_effect(effect)
, m_introspection(GetEffectIntrospection(type)) {
  QFont titleFont = m_titleLabel.font();
  titleFont.setWeight(QFont::Bold);
  m_titleLabel.setFont(titleFont);
  m_titleLabel.setForegroundRole(QPalette::Window);
  m_titleLabel.setContentsMargins(46, 0, 0, 0);
  m_titleLabel.setFixedHeight(20);
  m_numberText.setTextOption(QTextOption(Qt::AlignRight));
  m_numberText.setTextWidth(25);
  setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
  m_numberFont.setWeight(QFont::Bold);
  m_numberFont.setStyleHint(QFont::Monospace);
  m_numberFont.setPointSize(m_numberFont.pointSize() * 2);

  setContentsMargins(QMargins());
  setFixedHeight(100);

  QVBoxLayout* mainLayout = new QVBoxLayout;
  mainLayout->setContentsMargins(QMargins());
  mainLayout->setSpacing(0);

  QHBoxLayout* headLayout = new QHBoxLayout;
  headLayout->setContentsMargins(QMargins());
  headLayout->setSpacing(0);
  headLayout->addWidget(&m_titleLabel);

  m_deleteButton.setVisible(true);
  connect(&m_deleteButton, &ListingDeleteButton::clicked, this, &EffectWidget::deleteClicked);
  headLayout->addWidget(&m_deleteButton);

  mainLayout->addLayout(headLayout);
  mainLayout->addSpacing(8);

  QGridLayout* layout = new QGridLayout;
  layout->setSpacing(6);
  layout->setContentsMargins(64, 0, 12, 12);
  if (m_introspection) {
    m_titleLabel.setText(tr(m_introspection->m_name.data()));
    m_titleLabel.setToolTip(tr(m_introspection->m_description.data()));

    for (int f = 0; f < int(m_introspection->m_fields.size()); ++f) {
      const EffectIntrospection::Field& field = m_introspection->m_fields[f];
      if (!field.m_name.empty()) {
        QString fieldName = tr(field.m_name.data());
        layout->addWidget(new QLabel(fieldName, this), 0, f);
        switch (field.m_tp) {
        case EffectIntrospection::Field::Type::UInt32: {
          FieldSlider* sb = new FieldSlider(this);
          sb->setProperty("fieldIndex", f);
          sb->setRange(int(field.m_min), int(field.m_max));
          sb->setToolTip(QStringLiteral("[%1,%2]").arg(int(field.m_min)).arg(int(field.m_max)));
          sb->setValue(GetEffectParm<uint32_t>(m_effect, f, 0));
          connect(sb, qOverload<int>(&FieldSlider::valueChanged), this, qOverload<int>(&EffectWidget::numChanged));
          layout->addWidget(sb, 1, f);
          break;
        }
        case EffectIntrospection::Field::Type::UInt32x8: {
          Uint32X8Button* sb = new Uint32X8Button(int(field.m_min), int(field.m_max), this);
          sb->popup()->setProperty("fieldIndex", f);
          for (int i = 0; i < Uint32X8Popup::NumSliders; ++i) {
            sb->popup()->setValue(i, GetEffectParm<uint32_t>(m_effect, f, i));
          }
          connect(sb->popup(), &Uint32X8Popup::valueChanged, this, &EffectWidget::chanNumChanged);
          layout->addWidget(sb, 1, f);
          break;
        }
        case EffectIntrospection::Field::Type::Float: {
          FieldDoubleSlider* sb = new FieldDoubleSlider(this);
          sb->setProperty("fieldIndex", f);
          sb->setRange(field.m_min, field.m_max);
          sb->setToolTip(QStringLiteral("[%1,%2]").arg(field.m_min).arg(field.m_max));
          sb->setValue(GetEffectParm<float>(m_effect, f, 0));
          connect(sb, qOverload<double>(&FieldDoubleSlider::valueChanged), this,
                  qOverload<double>(&EffectWidget::numChanged));
          layout->addWidget(sb, 1, f);
          break;
        }
        default:
          break;
        }
      }
    }
  }

  mainLayout->addLayout(layout);
  layout->setRowMinimumHeight(0, 22);
  layout->setRowMinimumHeight(1, 22);
  setLayout(mainLayout);
}

EffectWidget::~EffectWidget() = default;

void EffectWidget::paintEvent(QPaintEvent* event) {
  /* Rounded frame */
  QPainter painter(this);
  painter.setRenderHint(QPainter::Antialiasing);

  const std::array<QPoint, 6> points{{
      {1, 20},
      {1, 99},
      {width() - 1, 99},
      {width() - 1, 1},
      {20, 1},
      {1, 20},
  }};
  painter.setBrush(palette().brush(QPalette::Window));
  painter.drawPolygon(points.data(), int(points.size()));
  painter.setPen(QPen(QColor(127, 127, 127), 2.0));
  painter.drawPolyline(points.data(), int(points.size()));

  const std::array<QPoint, 7> headPoints{{
      {1, 20},
      {1, 55},
      {35, 20},
      {width() - 1, 20},
      {width() - 1, 1},
      {20, 1},
      {1, 20},
  }};
  painter.setBrush(QColor(127, 127, 127));
  painter.drawPolygon(headPoints.data(), int(headPoints.size()));

  painter.drawRect(17, 51, 32, 32);

  QTransform rotate;
  rotate.rotate(-45.0).translate(-15, 8);
  painter.setTransform(rotate);
  painter.setFont(m_numberFont);
  painter.setPen(palette().color(QPalette::Window));
  painter.drawStaticText(0, 0, m_numberText);
}

EffectWidget::EffectWidget(QWidget* parent, amuse::EffectBaseTypeless* cmd) : EffectWidget(parent, cmd, cmd->Isa()) {}

EffectWidget::EffectWidget(QWidget* parent, amuse::EffectType type) : EffectWidget(parent, nullptr, type) {}

void EffectWidget::numChanged(int value) {
  SetEffectParm<uint32_t>(m_effect, sender()->property("fieldIndex").toInt(), 0, value);
}

void EffectWidget::numChanged(double value) {
  SetEffectParm<float>(m_effect, sender()->property("fieldIndex").toInt(), 0, value);
}

void EffectWidget::chanNumChanged(int chanIdx, int value) {
  SetEffectParm<uint32_t>(m_effect, sender()->property("fieldIndex").toInt(), chanIdx, value);
}

void EffectWidget::deleteClicked() {
  if (m_index != -1)
    if (EffectListing* listing = getParent())
      listing->deleteEffect(m_index);
}

EffectListing* EffectWidget::getParent() const { return qobject_cast<EffectListing*>(parentWidget()->parentWidget()); }

void EffectWidget::setIndex(int index) {
  m_index = index;
  m_numberText.setText(QString::number(index));
  update();
}

void EffectWidgetContainer::animateOpen() {
  int newHeight = 200 + parentWidget()->layout()->spacing();
  m_animation = new QPropertyAnimation(this, "minimumHeight");
  m_animation->setDuration(abs(minimumHeight() - newHeight) * 4);
  m_animation->setStartValue(minimumHeight());
  m_animation->setEndValue(newHeight);
  m_animation->setEasingCurve(QEasingCurve::InOutExpo);
  connect(m_animation, &QPropertyAnimation::valueChanged, parentWidget(), qOverload<>(&QWidget::update));
  connect(m_animation, &QPropertyAnimation::destroyed, this, &EffectWidgetContainer::animationDestroyed);
  m_animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void EffectWidgetContainer::animateClosed() {
  m_animation = new QPropertyAnimation(this, "minimumHeight");
  m_animation->setDuration(abs(minimumHeight() - 100) * 4);
  m_animation->setStartValue(minimumHeight());
  m_animation->setEndValue(100);
  m_animation->setEasingCurve(QEasingCurve::InOutExpo);
  connect(m_animation, &QPropertyAnimation::valueChanged, parentWidget(), qOverload<>(&QWidget::update));
  connect(m_animation, &QPropertyAnimation::destroyed, this, &EffectWidgetContainer::animationDestroyed);
  m_animation->start(QAbstractAnimation::DeleteWhenStopped);
}

void EffectWidgetContainer::snapOpen() {
  if (m_animation)
    m_animation->stop();
  setMinimumHeight(200 + parentWidget()->layout()->spacing());
}

void EffectWidgetContainer::snapClosed() {
  if (m_animation)
    m_animation->stop();
  setMinimumHeight(100);
}

void EffectWidgetContainer::animationDestroyed() { m_animation = nullptr; }

template <class... _Args>
EffectWidgetContainer::EffectWidgetContainer(QWidget* parent, _Args&&... args)
: QWidget(parent), m_effectWidget(new EffectWidget(this, std::forward<_Args>(args)...)) {
  setMinimumHeight(100);
  setContentsMargins(QMargins());
  QVBoxLayout* outerLayout = new QVBoxLayout;
  outerLayout->setAlignment(Qt::AlignBottom);
  outerLayout->setContentsMargins(QMargins());
  outerLayout->setSpacing(0);
  outerLayout->addWidget(m_effectWidget);
  setLayout(outerLayout);
}

EffectWidgetContainer::~EffectWidgetContainer() = default;

void EffectListing::startAutoscroll(QWidget* source, QMouseEvent* event, int delta) {
  if (m_autoscrollTimer == -1)
    m_autoscrollTimer = startTimer(50);
  m_autoscrollDelta = delta;
  m_autoscrollSource = source;
  if (m_autoscrollEvent != nullptr) {
    delete m_autoscrollEvent;
    m_autoscrollEvent = nullptr;
  }
  m_autoscrollEvent = event->clone();
}

void EffectListing::stopAutoscroll() {
  if (m_autoscrollTimer != -1) {
    killTimer(m_autoscrollTimer);
    m_autoscrollTimer = -1;
  }
  m_autoscrollDelta = 0;
  if (m_autoscrollEvent != nullptr) {
    delete m_autoscrollEvent;
    m_autoscrollEvent = nullptr;
  }
  m_autoscrollSource = nullptr;
}

void EffectListing::timerEvent(QTimerEvent* event) {
  if (QScrollArea* scrollArea = qobject_cast<QScrollArea*>(parentWidget()->parentWidget())) {
    QScrollBar* bar = scrollArea->verticalScrollBar();
    int oldValue = bar->value();
    bar->setValue(oldValue + m_autoscrollDelta);
    int valueDelta = bar->value() - oldValue;
    if (valueDelta != 0) {
      if (m_autoscrollSource)
        QApplication::sendEvent(m_autoscrollSource, m_autoscrollEvent);
      update();
    }
  }
}

bool EffectListing::beginDrag(EffectWidget* widget) {
  int origIdx = m_layout->indexOf(widget->parentWidget());
  if (origIdx < 0 || origIdx >= m_layout->count() - 1)
    return false;
  if (origIdx < m_layout->count() - 1) {
    // Animate next item open
    m_dragOpenIdx = origIdx;
    if (EffectWidgetContainer* nextItem = qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(origIdx + 1)->widget()))
      nextItem->snapOpen();
  } else {
    m_dragOpenIdx = -1;
  }
  m_origIdx = origIdx;
  m_dragItem = m_layout->takeAt(origIdx);
  m_dragItem->widget()->raise();
  return true;
}

void EffectListing::endDrag() {
  int insertIdx;
  if (m_dragOpenIdx != -1) {
    if (EffectWidgetContainer* prevItem =
            qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(m_dragOpenIdx)->widget()))
      prevItem->snapClosed();
    insertIdx = m_dragOpenIdx;
    m_dragOpenIdx = -1;
  } else {
    insertIdx = m_layout->count() - 1;
  }

  if (m_prevDragOpen) {
    m_prevDragOpen->snapClosed();
    m_prevDragOpen = nullptr;
  }

  if (m_origIdx != insertIdx)
    std::swap(m_submix->getEffectStack()[m_origIdx], m_submix->getEffectStack()[insertIdx]);
  m_layout->insertItem(insertIdx, m_dragItem);
  m_dragItem = nullptr;
  stopAutoscroll();
  reindex();
}

void EffectListing::cancelDrag() {
  if (m_dragOpenIdx != -1) {
    if (EffectWidgetContainer* prevItem =
            qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(m_dragOpenIdx)->widget()))
      prevItem->snapClosed();
    m_dragOpenIdx = -1;
  }
  m_layout->insertItem(m_origIdx, m_dragItem);
  if (m_prevDragOpen) {
    m_prevDragOpen->snapClosed();
    m_prevDragOpen = nullptr;
  }
  m_dragItem = nullptr;
  stopAutoscroll();
}

void EffectListing::_moveDrag(int hoverIdx, const QPoint& pt, QWidget* source, QMouseEvent* event) {
  QRect scrollVpRect = parentWidget()->parentWidget()->rect();
  QPoint scrollVpPoint = mapTo(parentWidget()->parentWidget(), pt);
  if (scrollVpRect.bottom() - scrollVpPoint.y() < 50)
    startAutoscroll(source, event, 10); // Scroll Down
  else if (scrollVpRect.top() - scrollVpPoint.y() > -50)
    startAutoscroll(source, event, -10);
  else
    stopAutoscroll();

  hoverIdx = std::max(0, std::min(hoverIdx, m_layout->count() - 1));
  if (hoverIdx != m_dragOpenIdx) {
    if (m_dragOpenIdx != -1)
      if (EffectWidgetContainer* prevItem =
              qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(m_dragOpenIdx)->widget())) {
        m_prevDragOpen = prevItem;
        prevItem->animateClosed();
      }
    if (EffectWidgetContainer* nextItem = qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(hoverIdx)->widget()))
      nextItem->animateOpen();
    m_dragOpenIdx = hoverIdx;
  }
  update();
}

void EffectListing::moveDrag(EffectWidget* widget, const QPoint& pt, QWidget* source, QMouseEvent* event) {
  EffectWidgetContainer* container = static_cast<EffectWidgetContainer*>(widget->parentWidget());
  int pitch = 100 + m_layout->spacing();
  _moveDrag((container->pos().y() - m_layout->contentsMargins().top() + pitch / 2) / pitch, pt, source, event);
}

int EffectListing::moveInsertDrag(const QPoint& pt, QWidget* source, QMouseEvent* event) {
  int pitch = 100 + m_layout->spacing();
  _moveDrag(pt.y() / pitch, pt, source, event);
  return m_dragOpenIdx;
}

void EffectListing::insertDragout() {
  if (m_dragOpenIdx != -1) {
    if (EffectWidgetContainer* prevItem =
            qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(m_dragOpenIdx)->widget())) {
      m_prevDragOpen = prevItem;
      prevItem->animateClosed();
    }
    m_dragOpenIdx = -1;
  }
  stopAutoscroll();
}

void EffectListing::insert(amuse::EffectType type, const QString& text) {
  int insertIdx;
  if (m_dragOpenIdx != -1) {
    if (EffectWidgetContainer* prevItem =
            qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(m_dragOpenIdx)->widget()))
      prevItem->snapClosed();
    insertIdx = m_dragOpenIdx;
    m_dragOpenIdx = -1;
  } else {
    insertIdx = m_layout->count() - 1;
  }

  if (m_prevDragOpen) {
    m_prevDragOpen->snapClosed();
    m_prevDragOpen = nullptr;
  }

  std::unique_ptr<amuse::EffectBaseTypeless> newEffect;
  switch (type) {
  case amuse::EffectType::ReverbStd:
    newEffect = m_submix->_makeEffect<amuse::EffectReverbStd>(amuse::EffectReverbStdInfo{});
    break;
  case amuse::EffectType::ReverbHi:
    newEffect = m_submix->_makeEffect<amuse::EffectReverbHi>(amuse::EffectReverbHiInfo{});
    break;
  case amuse::EffectType::Delay:
    newEffect = m_submix->_makeEffect<amuse::EffectDelay>(amuse::EffectDelayInfo{});
    break;
  case amuse::EffectType::Chorus:
    newEffect = m_submix->_makeEffect<amuse::EffectChorus>(amuse::EffectChorusInfo{});
    break;
  default:
    break;
  }
  auto it = m_submix->getEffectStack().insert(m_submix->getEffectStack().begin() + insertIdx, std::move(newEffect));
  m_layout->insertWidget(insertIdx, new EffectWidgetContainer(this, it->get()));

  stopAutoscroll();
  reindex();
}

void EffectListing::deleteEffect(int index) {
  QLayoutItem* item = m_layout->takeAt(index);
  m_submix->getEffectStack().erase(m_submix->getEffectStack().begin() + index);
  item->widget()->deleteLater();
  delete item;
  reindex();
}

void EffectListing::reindex() {
  for (int i = 0; i < m_layout->count() - 1; ++i)
    if (EffectWidgetContainer* item = qobject_cast<EffectWidgetContainer*>(m_layout->itemAt(i)->widget()))
      item->m_effectWidget->setIndex(i);
}

void EffectListing::clear() {
  while (m_layout->count() > 2) {
    QLayoutItem* item = m_layout->takeAt(0);
    item->widget()->deleteLater();
    delete item;
  }
}

bool EffectListing::loadData(amuse::Submix* submix) {
  m_submix = submix;
  clear();
  int i = 0;
  for (auto& effect : submix->getEffectStack())
    m_layout->insertWidget(i++, new EffectWidgetContainer(this, effect.get()));
  reindex();
  update();
  return true;
}

void EffectListing::unloadData() {
  m_submix = nullptr;
  clear();
  reindex();
  update();
}

EffectListing::EffectListing(QWidget* parent) : QWidget(parent), m_layout(new QVBoxLayout) {
  m_layout->addStretch();
  setLayout(m_layout);
  reindex();
}

EffectListing::~EffectListing() = default;

EffectCatalogueItem::EffectCatalogueItem(amuse::EffectType type, const QString& name, const QString& doc,
                                         QWidget* parent)
: QWidget(parent), m_type(type), m_iconLab(this), m_label(name, this) {
  QHBoxLayout* layout = new QHBoxLayout;
  QString iconPath = QStringLiteral(":/commands/%1.svg").arg(name);
  if (QFile(iconPath).exists())
    m_iconLab.setPixmap(QIcon(iconPath).pixmap(32, 32));
  else
    m_iconLab.setPixmap(QIcon(QStringLiteral(":/icons/IconOpen.svg")).pixmap(32, 32));
  layout->addWidget(&m_iconLab);
  layout->addWidget(&m_label);
  layout->addStretch();
  layout->setContentsMargins(QMargins());
  setLayout(layout);
  setToolTip(doc);
}

EffectCatalogueItem::EffectCatalogueItem(const EffectCatalogueItem& other, QWidget* parent)
: QWidget(parent), m_type(other.getType()) {
  QHBoxLayout* layout = new QHBoxLayout;
  QHBoxLayout* oldLayout = static_cast<QHBoxLayout*>(other.layout());
  m_iconLab.setPixmap(static_cast<QLabel*>(oldLayout->itemAt(0)->widget())->pixmap(Qt::ReturnByValue));
  layout->addWidget(&m_iconLab);
  m_label.setText(static_cast<QLabel*>(oldLayout->itemAt(1)->widget())->text());
  layout->addWidget(&m_label);
  layout->addStretch();
  layout->setContentsMargins(QMargins());
  setLayout(layout);
}

EffectCatalogueItem::~EffectCatalogueItem() = default;

EffectCatalogue::EffectCatalogue(QWidget* parent) : QTreeWidget(parent) {
  setSelectionMode(QAbstractItemView::NoSelection);
  setColumnCount(1);
  setHeaderHidden(true);

  for (int i = 1; i < int(amuse::EffectType::EffectTypeMAX); ++i) {
    QTreeWidgetItem* item = new QTreeWidgetItem(this);
    setItemWidget(
        item, 0,
        new EffectCatalogueItem(amuse::EffectType(i), tr(EffectStrings[i - 1]), tr(EffectDocStrings[i - 1]), this));
  }
}

void EffectCatalogue::mousePressEvent(QMouseEvent* event) {
  QTreeWidget::mousePressEvent(event);
  event->ignore();
}

void EffectCatalogue::mouseReleaseEvent(QMouseEvent* event) {
  QTreeWidget::mouseReleaseEvent(event);
  event->ignore();
}

void EffectCatalogue::mouseMoveEvent(QMouseEvent* event) {
  StudioSetupWidget* editor = qobject_cast<StudioSetupWidget*>(parentWidget()->parentWidget()->parentWidget());
  if (!editor || !editor->m_draggedItem)
    QTreeWidget::mouseMoveEvent(event);
  event->ignore();
}

EffectListing* StudioSetupWidget::getCurrentListing() const {
  return static_cast<EffectListing*>(static_cast<QScrollArea*>(m_tabs->currentWidget())->widget());
}

void StudioSetupWidget::beginCommandDrag(EffectWidget* widget, const QPoint& eventPt, const QPoint& pt) {
  if (widget->getParent()->beginDrag(widget)) {
    m_draggedPt = pt;
    m_draggedCmd = widget;
  }
}

void StudioSetupWidget::beginCatalogueDrag(EffectCatalogueItem* item, const QPoint& eventPt, const QPoint& pt) {
  m_draggedPt = pt;
  m_draggedItem = new EffectCatalogueItem(*item, this);
  m_draggedItem->setGeometry(item->geometry());
  m_draggedItem->move(eventPt - m_draggedPt);
  m_draggedItem->raise();
  m_draggedItem->show();
}

void StudioSetupWidget::mousePressEvent(QMouseEvent* event) {
  if (m_catalogue->geometry().contains(event->pos())) {
    QPoint fromParent1 = m_catalogue->mapFrom(this, event->pos());
    QWidget* ch = m_catalogue->childAt(fromParent1);
    if (ch) {
      EffectCatalogueItem* child = nullptr;
      while (ch && !(child = qobject_cast<EffectCatalogueItem*>(ch)))
        ch = ch->parentWidget();
      if (child) {
        QPoint fromParent2 = child->mapFrom(m_catalogue, fromParent1);
        beginCatalogueDrag(child, event->pos(), fromParent2);
      }
    }
  } else {
    EffectListing* listing = getCurrentListing();
    if (listing->parentWidget()->parentWidget()->parentWidget()->geometry().contains(event->pos())) {
      QPoint fromParent1 = listing->mapFrom(this, event->pos());
      QWidget* ch = listing->childAt(fromParent1);
      if (ch) {
        EffectWidget* child = nullptr;
        while (ch && !(child = qobject_cast<EffectWidget*>(ch)))
          ch = ch->parentWidget();
        if (child) {
          QPoint fromParent2 = child->mapFrom(listing, fromParent1);
          beginCommandDrag(child, event->pos(), fromParent2);
        }
      }
    }
  }
}

void StudioSetupWidget::mouseReleaseEvent(QMouseEvent* event) {
  EffectListing* listing = getCurrentListing();
  if (m_draggedItem) {
    amuse::EffectType type = m_draggedItem->getType();
    QString text = m_draggedItem->getText();
    m_draggedItem->deleteLater();
    m_draggedItem = nullptr;

    if (listing->parentWidget()->parentWidget()->parentWidget()->geometry().contains(event->pos())) {
      if (m_dragInsertIdx != -1)
        listing->insert(type, text);
      else
        listing->insertDragout();
    } else {
      listing->insertDragout();
    }
    m_dragInsertIdx = -1;
  } else if (m_draggedCmd) {
    listing->endDrag();
    m_draggedCmd = nullptr;
  }
}

void StudioSetupWidget::mouseMoveEvent(QMouseEvent* event) {
  EffectListing* listing = getCurrentListing();
  if (m_draggedItem) {
    m_draggedItem->move(event->pos() - m_draggedPt);
    if (listing->parentWidget()->parentWidget()->parentWidget()->geometry().contains(event->pos())) {
      m_dragInsertIdx = listing->moveInsertDrag(listing->mapFrom(this, event->pos()), this, event);
    } else if (m_dragInsertIdx != -1) {
      listing->insertDragout();
      m_dragInsertIdx = -1;
    }
    m_catalogue->update();
    update();
  } else if (m_draggedCmd) {
    QPoint listingPt = listing->mapFrom(this, event->pos());
    EffectWidgetContainer* container = static_cast<EffectWidgetContainer*>(m_draggedCmd->parentWidget());
    container->move(container->x(), listingPt.y() - m_draggedPt.y());
    if (listing->parentWidget()->parentWidget()->parentWidget()->geometry().contains(event->pos()))
      listing->moveDrag(m_draggedCmd, listingPt, this, event);
    listing->update();
    update();
  }
}

void StudioSetupWidget::keyPressEvent(QKeyEvent* event) {
  if (event->key() == Qt::Key_Escape) {
    EffectListing* listing = getCurrentListing();
    if (m_draggedItem) {
      m_draggedItem->deleteLater();
      m_draggedItem = nullptr;
      listing->insertDragout();
    } else if (m_draggedCmd) {
      listing->cancelDrag();
      m_draggedCmd = nullptr;
    }
  }
}

void StudioSetupWidget::hideEvent(QHideEvent* event) { emit hidden(); }

void StudioSetupWidget::showEvent(QShowEvent* event) { emit shown(); }

void StudioSetupWidget::updateWindowPosition() {
  QWidget* parent = parentWidget();
  move(parent->width() / 2 - width() / 2 + parent->x(), parent->height() / 2 - height() / 2 + parent->y());
}

void StudioSetupWidget::catalogueDoubleClicked(QTreeWidgetItem* item, int column) {
  if (EffectCatalogueItem* cItem = qobject_cast<EffectCatalogueItem*>(m_catalogue->itemWidget(item, column))) {
    amuse::EffectType type = cItem->getType();
    if (type != amuse::EffectType::Invalid) {
      EffectListing* listing = getCurrentListing();
      listing->insert(type, cItem->getText());
    }
  }
}

bool StudioSetupWidget::loadData(amuse::Studio* studio) {
  m_listing[0]->loadData(&studio->getAuxA());
  m_listing[1]->loadData(&studio->getAuxB());
  return true;
}

void StudioSetupWidget::unloadData() {
  m_listing[0]->unloadData();
  m_listing[1]->unloadData();
}

StudioSetupWidget::StudioSetupWidget(QWidget* parent)
: QWidget(parent, Qt::Tool), m_splitter(new QSplitter), m_tabs(new QTabWidget), m_catalogue(new EffectCatalogue) {
  setWindowTitle(tr("Studio Setup"));
  setGeometry(0, 0, 900, 450);

  std::array<QScrollArea*, 2> scrollAreas{};
  for (size_t i = 0; i < m_listing.size(); ++i) {
    m_listing[i] = new EffectListing;
    QScrollArea* listingScroll = new QScrollArea;
    scrollAreas[i] = listingScroll;
    listingScroll->setWidget(m_listing[i]);
    listingScroll->setWidgetResizable(true);
    QSizePolicy sizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
    sizePolicy.setHorizontalStretch(1);
    sizePolicy.setVerticalStretch(0);
    listingScroll->setSizePolicy(sizePolicy);
    listingScroll->setMinimumWidth(350);
    m_splitter->addWidget(listingScroll);
  }
  m_tabs->addTab(scrollAreas[0], tr("Aux A"));
  m_tabs->addTab(scrollAreas[1], tr("Aux B"));
  m_splitter->addWidget(m_tabs);

  {
    QSizePolicy sizePolicy(QSizePolicy::Preferred, QSizePolicy::Preferred);
    sizePolicy.setHorizontalStretch(0);
    sizePolicy.setVerticalStretch(0);
    m_catalogue->setSizePolicy(sizePolicy);
    m_catalogue->setMinimumWidth(150);
    m_catalogue->setGeometry(0, 0, 215, 0);
    m_catalogue->setMaximumWidth(300);
    m_splitter->addWidget(m_catalogue);
  }

  connect(m_catalogue, &EffectCatalogue::itemDoubleClicked, this, &StudioSetupWidget::catalogueDoubleClicked);

  m_splitter->setCollapsible(0, false);
  QGridLayout* layout = new QGridLayout;
  layout->setContentsMargins(QMargins());
  layout->addWidget(m_splitter);
  setLayout(layout);
}

StudioSetupWidget::~StudioSetupWidget() = default;


text:
import logging
import argparse
import yaml
import subprocess
import sys

from pathlib import Path
sys.path.append(str(Path('.').cwd().parent))
from swen import flowexecutor

logging.basicConfig(
    format="%(asctime)s %(name)s %(levelname)s: %(message)s",
    level=logging.DEBUG
)

def main():
    parser = argparse.ArgumentParser(prog='swen')
    parser.add_argument('-f', '--flow', required=True)

    args = parser.parse_args()

    with open(args.flow) as yml:
        fe = flowexecutor.FlowExecutor(yml)
        return fe.execute()

if __name__ == '__main__':
    main()


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Tests.Events;
using System.Diagnostics.Tracing;
using System.Reflection;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Utility;

namespace Tests
{
    public abstract class EventSourceBase : EventSource
    {
        private readonly ObservableEventListener m_listener;
        public MemoryRetentionSink Sink { get; private set; }

        public void DisposeListener()
        {
            m_listener.Dispose();
        }

        protected EventSourceBase()
        {
            m_listener = new ObservableEventListener();
            m_listener.EnableEvents(this, EventLevel.Verbose);
            Sink = m_listener.RetainEventRecords().Sink;
        }
    }

    [TestClass]
    public class BaseClassEventsTests
    {
        private static BaseClassEvents s_baseClassEvents;

        [ClassInitialize]
        public static void BeforeAll(TestContext context)
        {
            s_baseClassEvents = new BaseClassEvents();
        }

        [TestCleanup]
        public void AfterEach()
        {
            BaseClassEventSource.Log.Sink.Clear();
        }

        [ClassCleanup]
        public static void AfterAll()
        {
            BaseClassEventSource.Log.DisposeListener();
        }

        [TestMethod]
        public void AnalyzeEventSource()
        {
            EventSourceAnalyzer.InspectAll(BaseClassEventSource.Log);
        }

        [TestMethod]
        public void TestBaseEventSource()
        {
            Assert.IsInstanceOfType(BaseClassEventSource.Log, typeof(EventSourceBase), "Event source class doesn't inherit from the expected base class");

            Assert.AreEqual("OS-Test-BaseClass", typeof(BaseClassEventSource).GetCustomAttribute<EventSourceAttribute>().Name, "Mismatched event source name");
            AssertHelper.AssertEventAttributes<BaseClassEventSource>("Foo", 10, 0, EventChannel.None, EventLevel.Informational, "Foo: {0}", EventKeywords.None, EventTask.None, null);
            s_baseClassEvents.Foo("bar");
            BaseClassEventSource.Log.Sink.AssertEventRecord(10, "Foo: bar", new object[] { "bar" });
        }
    }
}


text:
#ifndef _RDKAFKA_CONFVAL_H_
#define _RDKAFKA_CONFVAL_H_
/**
 * @name Next generation configuration values
 * @{
 *
 */

/**
 * @brief Configuration value type
 */
typedef enum rd_kafka_confval_type_t {
        RD_KAFKA_CONFVAL_INT,
        RD_KAFKA_CONFVAL_STR,
        RD_KAFKA_CONFVAL_PTR,
} rd_kafka_confval_type_t;

/**
 * @brief Configuration value (used by AdminOption).
 *        Comes with a type, backed by a union, and a flag to indicate
 *        if the value has been set or not.
 */
typedef struct rd_kafka_confval_s {
        const char *name;                  /**< Property name */
        rd_kafka_confval_type_t valuetype; /**< Value type, maps to union.*/
        int is_set;                        /**< Value has been set. */
        int is_enabled;                    /**< Confval is enabled. */
        union {
                struct {
                        int v;             /**< Current value */
                        int vmin;          /**< Minimum value (inclusive) */
                        int vmax;          /**< Maximum value (inclusive) */
                        int vdef;          /**< Default value */
                } INT;
                struct {
                        char  *v;          /**< Current value */
                        int    allowempty; /**< Allow empty string as value */
                        size_t minlen;     /**< Minimum string length excl \0 */
                        size_t maxlen;     /**< Maximum string length excl \0 */
                        const char *vdef;  /**< Default value */
                } STR;
                void *PTR;                 /**< Pointer */
        } u;
} rd_kafka_confval_t;

void rd_kafka_confval_init_int (rd_kafka_confval_t *confval,
                                const char *name,
                                int vmin, int vmax, int vdef);
void rd_kafka_confval_init_ptr (rd_kafka_confval_t *confval,
                                const char *name);
void rd_kafka_confval_disable (rd_kafka_confval_t *confval, const char *name);

rd_kafka_resp_err_t
rd_kafka_confval_set_type (rd_kafka_confval_t *confval,
                           rd_kafka_confval_type_t valuetype,
                           const void *valuep,
                           char *errstr, size_t errstr_size);

int rd_kafka_confval_get_int (const rd_kafka_confval_t *confval);
const char *rd_kafka_confval_get_str (const rd_kafka_confval_t *confval);
void *rd_kafka_confval_get_ptr (const rd_kafka_confval_t *confval);

/**@}*/

#endif /* _RDKAFKA_CONFVAL_H_ */


text:
/*
 * Interface to the hardware Packet Input Processing unit.
 *
 */

#ifndef __CVMX_PIP_H__
#define __CVMX_PIP_H__

#include "cvmx-wqe.h"
#include "cvmx-fpa.h"
#include "cvmx-pip-defs.h"

#define CVMX_PIP_NUM_INPUT_PORTS                40
#define CVMX_PIP_NUM_WATCHERS                   4

/*
 * Encodes the different error and exception codes
 */
typedef enum {
	CVMX_PIP_L4_NO_ERR = 0ull,
	/*
	 * 1 = TCP (UDP) packet not long enough to cover TCP (UDP)
	 * header
	 */
	CVMX_PIP_L4_MAL_ERR = 1ull,
	/* 2  = TCP/UDP checksum failure */
	CVMX_PIP_CHK_ERR = 2ull,
	/*
	 * 3 = TCP/UDP length check (TCP/UDP length does not match IP
	 * length).
	 */
	CVMX_PIP_L4_LENGTH_ERR = 3ull,
	/* 4  = illegal TCP/UDP port (either source or dest port is zero) */
	CVMX_PIP_BAD_PRT_ERR = 4ull,
	/* 8  = TCP flags = FIN only */
	CVMX_PIP_TCP_FLG8_ERR = 8ull,
	/* 9  = TCP flags = 0 */
	CVMX_PIP_TCP_FLG9_ERR = 9ull,
	/* 10 = TCP flags = FIN+RST+* */
	CVMX_PIP_TCP_FLG10_ERR = 10ull,
	/* 11 = TCP flags = SYN+URG+* */
	CVMX_PIP_TCP_FLG11_ERR = 11ull,
	/* 12 = TCP flags = SYN+RST+* */
	CVMX_PIP_TCP_FLG12_ERR = 12ull,
	/* 13 = TCP flags = SYN+FIN+* */
	CVMX_PIP_TCP_FLG13_ERR = 13ull
} cvmx_pip_l4_err_t;

typedef enum {

	CVMX_PIP_IP_NO_ERR = 0ull,
	/* 1 = not IPv4 or IPv6 */
	CVMX_PIP_NOT_IP = 1ull,
	/* 2 = IPv4 header checksum violation */
	CVMX_PIP_IPV4_HDR_CHK = 2ull,
	/* 3 = malformed (packet not long enough to cover IP hdr) */
	CVMX_PIP_IP_MAL_HDR = 3ull,
	/* 4 = malformed (packet not long enough to cover len in IP hdr) */
	CVMX_PIP_IP_MAL_PKT = 4ull,
	/* 5 = TTL / hop count equal zero */
	CVMX_PIP_TTL_HOP = 5ull,
	/* 6 = IPv4 options / IPv6 early extension headers */
	CVMX_PIP_OPTS = 6ull
} cvmx_pip_ip_exc_t;

/**
 * NOTES
 *       late collision (data received before collision)
 *            late collisions cannot be detected by the receiver
 *            they would appear as JAM bits which would appear as bad FCS
 *            or carrier extend error which is CVMX_PIP_EXTEND_ERR
 */
typedef enum {
	/* No error */
	CVMX_PIP_RX_NO_ERR = 0ull,
	/* RGM+SPI 1 = partially received packet (buffering/bandwidth
	 * not adequate) */
	CVMX_PIP_PARTIAL_ERR = 1ull,
	/* RGM+SPI 2 = receive packet too large and truncated */
	CVMX_PIP_JABBER_ERR = 2ull,
	/*
	 * RGM 3 = max frame error (pkt len > max frame len) (with FCS
	 * error)
	 */
	CVMX_PIP_OVER_FCS_ERR = 3ull,
	/* RGM+SPI 4 = max frame error (pkt len > max frame len) */
	CVMX_PIP_OVER_ERR = 4ull,
	/*
	 * RGM 5 = nibble error (data not byte multiple - 100M and 10M
	 * only)
	 */
	CVMX_PIP_ALIGN_ERR = 5ull,
	/*
	 * RGM 6 = min frame error (pkt len < min frame len) (with FCS
	 * error)
	 */
	CVMX_PIP_UNDER_FCS_ERR = 6ull,
	/* RGM     7 = FCS error */
	CVMX_PIP_GMX_FCS_ERR = 7ull,
	/* RGM+SPI 8 = min frame error (pkt len < min frame len) */
	CVMX_PIP_UNDER_ERR = 8ull,
	/* RGM     9 = Frame carrier extend error */
	CVMX_PIP_EXTEND_ERR = 9ull,
	/*
	 * RGM 10 = length mismatch (len did not match len in L2
	 * length/type)
	 */
	CVMX_PIP_LENGTH_ERR = 10ull,
	/* RGM 11 = Frame error (some or all data bits marked err) */
	CVMX_PIP_DAT_ERR = 11ull,
	/*     SPI 11 = DIP4 error */
	CVMX_PIP_DIP_ERR = 11ull,
	/*
	 * RGM 12 = packet was not large enough to pass the skipper -
	 * no inspection could occur.
	 */
	CVMX_PIP_SKIP_ERR = 12ull,
	/*
	 * RGM 13 = studder error (data not repeated - 100M and 10M
	 * only)
	 */
	CVMX_PIP_NIBBLE_ERR = 13ull,
	/* RGM+SPI 16 = FCS error */
	CVMX_PIP_PIP_FCS = 16L,
	/*
	 * RGM+SPI+PCI 17 = packet was not large enough to pass the
	 * skipper - no inspection could occur.
	 */
	CVMX_PIP_PIP_SKIP_ERR = 17L,
	/*
	 * RGM+SPI+PCI 18 = malformed l2 (packet not long enough to
	 * cover L2 hdr).
	 */
	CVMX_PIP_PIP_L2_MAL_HDR = 18L
	/*
	 * NOTES: xx = late collision (data received before collision)
	 *       late collisions cannot be detected by the receiver
	 *       they would appear as JAM bits which would appear as
	 *       bad FCS or carrier extend error which is
	 *       CVMX_PIP_EXTEND_ERR
	 */
} cvmx_pip_rcv_err_t;

/**
 * This defines the err_code field errors in the work Q entry
 */
typedef union {
	cvmx_pip_l4_err_t l4_err;
	cvmx_pip_ip_exc_t ip_exc;
	cvmx_pip_rcv_err_t rcv_err;
} cvmx_pip_err_t;

/**
 * Status statistics for a port
 */
typedef struct {
	/* Inbound octets marked to be dropped by the IPD */
	uint32_t dropped_octets;
	/* Inbound packets marked to be dropped by the IPD */
	uint32_t dropped_packets;
	/* RAW PCI Packets received by PIP per port */
	uint32_t pci_raw_packets;
	/* Number of octets processed by PIP */
	uint32_t octets;
	/* Number of packets processed by PIP */
	uint32_t packets;
	/*
	 * Number of indentified L2 multicast packets.  Does not
	 * include broadcast packets.  Only includes packets whose
	 * parse mode is SKIP_TO_L2
	 */
	uint32_t multicast_packets;
	/*
	 * Number of indentified L2 broadcast packets.  Does not
	 * include multicast packets.  Only includes packets whose
	 * parse mode is SKIP_TO_L2
	 */
	uint32_t broadcast_packets;
	/* Number of 64B packets */
	uint32_t len_64_packets;
	/* Number of 65-127B packets */
	uint32_t len_65_127_packets;
	/* Number of 128-255B packets */
	uint32_t len_128_255_packets;
	/* Number of 256-511B packets */
	uint32_t len_256_511_packets;
	/* Number of 512-1023B packets */
	uint32_t len_512_1023_packets;
	/* Number of 1024-1518B packets */
	uint32_t len_1024_1518_packets;
	/* Number of 1519-max packets */
	uint32_t len_1519_max_packets;
	/* Number of packets with FCS or Align opcode errors */
	uint32_t fcs_align_err_packets;
	/* Number of packets with length < min */
	uint32_t runt_packets;
	/* Number of packets with length < min and FCS error */
	uint32_t runt_crc_packets;
	/* Number of packets with length > max */
	uint32_t oversize_packets;
	/* Number of packets with length > max and FCS error */
	uint32_t oversize_crc_packets;
	/* Number of packets without GMX/SPX/PCI errors received by PIP */
	uint32_t inb_packets;
	/*
	 * Total number of octets from all packets received by PIP,
	 * including CRC
	 */
	uint64_t inb_octets;
	/* Number of packets with GMX/SPX/PCI errors received by PIP */
	uint16_t inb_errors;
} cvmx_pip_port_status_t;

/**
 * Definition of the PIP custom header that can be prepended
 * to a packet by external hardware.
 */
typedef union {
	uint64_t u64;
	struct {
		/*
		 * Documented as R - Set if the Packet is RAWFULL. If
		 * set, this header must be the full 8 bytes.
		 */
		uint64_t rawfull:1;
		/* Must be zero */
		uint64_t reserved0:5;
		/* PIP parse mode for this packet */
		uint64_t parse_mode:2;
		/* Must be zero */
		uint64_t reserved1:1;
		/*
		 * Skip amount, including this header, to the
		 * beginning of the packet
		 */
		uint64_t skip_len:7;
		/* Must be zero */
		uint64_t reserved2:6;
		/* POW input queue for this packet */
		uint64_t qos:3;
		/* POW input group for this packet */
		uint64_t grp:4;
		/*
		 * Flag to store this packet in the work queue entry,
		 * if possible
		 */
		uint64_t rs:1;
		/* POW input tag type */
		uint64_t tag_type:2;
		/* POW input tag */
		uint64_t tag:32;
	} s;
} cvmx_pip_pkt_inst_hdr_t;

/* CSR typedefs have been moved to cvmx-csr-*.h */

/**
 * Configure an ethernet input port
 *
 * @port_num: Port number to configure
 * @port_cfg: Port hardware configuration
 * @port_tag_cfg:
 *                 Port POW tagging configuration
 */
static inline void cvmx_pip_config_port(uint64_t port_num,
					union cvmx_pip_prt_cfgx port_cfg,
					union cvmx_pip_prt_tagx port_tag_cfg)
{
	cvmx_write_csr(CVMX_PIP_PRT_CFGX(port_num), port_cfg.u64);
	cvmx_write_csr(CVMX_PIP_PRT_TAGX(port_num), port_tag_cfg.u64);
}
#if 0
/**
 * @deprecated      This function is a thin wrapper around the Pass1 version
 *                  of the CVMX_PIP_QOS_WATCHX CSR; Pass2 has added a field for
 *                  setting the group that is incompatible with this function,
 *                  the preferred upgrade path is to use the CSR directly.
 *
 * Configure the global QoS packet watchers. Each watcher is
 * capable of matching a field in a packet to determine the
 * QoS queue for scheduling.
 *
 * @watcher:    Watcher number to configure (0 - 3).
 * @match_type: Watcher match type
 * @match_value:
 *                   Value the watcher will match against
 * @qos:        QoS queue for packets matching this watcher
 */
static inline void cvmx_pip_config_watcher(uint64_t watcher,
					   cvmx_pip_qos_watch_types match_type,
					   uint64_t match_value, uint64_t qos)
{
	cvmx_pip_port_watcher_cfg_t watcher_config;

	watcher_config.u64 = 0;
	watcher_config.s.match_type = match_type;
	watcher_config.s.match_value = match_value;
	watcher_config.s.qos = qos;

	cvmx_write_csr(CVMX_PIP_QOS_WATCHX(watcher), watcher_config.u64);
}
#endif
/**
 * Configure the VLAN priority to QoS queue mapping.
 *
 * @vlan_priority:
 *               VLAN priority (0-7)
 * @qos:    QoS queue for packets matching this watcher
 */
static inline void cvmx_pip_config_vlan_qos(uint64_t vlan_priority,
					    uint64_t qos)
{
	union cvmx_pip_qos_vlanx pip_qos_vlanx;
	pip_qos_vlanx.u64 = 0;
	pip_qos_vlanx.s.qos = qos;
	cvmx_write_csr(CVMX_PIP_QOS_VLANX(vlan_priority), pip_qos_vlanx.u64);
}

/**
 * Configure the Diffserv to QoS queue mapping.
 *
 * @diffserv: Diffserv field value (0-63)
 * @qos:      QoS queue for packets matching this watcher
 */
static inline void cvmx_pip_config_diffserv_qos(uint64_t diffserv, uint64_t qos)
{
	union cvmx_pip_qos_diffx pip_qos_diffx;
	pip_qos_diffx.u64 = 0;
	pip_qos_diffx.s.qos = qos;
	cvmx_write_csr(CVMX_PIP_QOS_DIFFX(diffserv), pip_qos_diffx.u64);
}

/**
 * Get the status counters for a port.
 *
 * @port_num: Port number to get statistics for.
 * @clear:    Set to 1 to clear the counters after they are read
 * @status:   Where to put the results.
 */
static inline void cvmx_pip_get_port_status(uint64_t port_num, uint64_t clear,
					    cvmx_pip_port_status_t *status)
{
	union cvmx_pip_stat_ctl pip_stat_ctl;
	union cvmx_pip_stat0_prtx stat0;
	union cvmx_pip_stat1_prtx stat1;
	union cvmx_pip_stat2_prtx stat2;
	union cvmx_pip_stat3_prtx stat3;
	union cvmx_pip_stat4_prtx stat4;
	union cvmx_pip_stat5_prtx stat5;
	union cvmx_pip_stat6_prtx stat6;
	union cvmx_pip_stat7_prtx stat7;
	union cvmx_pip_stat8_prtx stat8;
	union cvmx_pip_stat9_prtx stat9;
	union cvmx_pip_stat_inb_pktsx pip_stat_inb_pktsx;
	union cvmx_pip_stat_inb_octsx pip_stat_inb_octsx;
	union cvmx_pip_stat_inb_errsx pip_stat_inb_errsx;

	pip_stat_ctl.u64 = 0;
	pip_stat_ctl.s.rdclr = clear;
	cvmx_write_csr(CVMX_PIP_STAT_CTL, pip_stat_ctl.u64);

	stat0.u64 = cvmx_read_csr(CVMX_PIP_STAT0_PRTX(port_num));
	stat1.u64 = cvmx_read_csr(CVMX_PIP_STAT1_PRTX(port_num));
	stat2.u64 = cvmx_read_csr(CVMX_PIP_STAT2_PRTX(port_num));
	stat3.u64 = cvmx_read_csr(CVMX_PIP_STAT3_PRTX(port_num));
	stat4.u64 = cvmx_read_csr(CVMX_PIP_STAT4_PRTX(port_num));
	stat5.u64 = cvmx_read_csr(CVMX_PIP_STAT5_PRTX(port_num));
	stat6.u64 = cvmx_read_csr(CVMX_PIP_STAT6_PRTX(port_num));
	stat7.u64 = cvmx_read_csr(CVMX_PIP_STAT7_PRTX(port_num));
	stat8.u64 = cvmx_read_csr(CVMX_PIP_STAT8_PRTX(port_num));
	stat9.u64 = cvmx_read_csr(CVMX_PIP_STAT9_PRTX(port_num));
	pip_stat_inb_pktsx.u64 =
	    cvmx_read_csr(CVMX_PIP_STAT_INB_PKTSX(port_num));
	pip_stat_inb_octsx.u64 =
	    cvmx_read_csr(CVMX_PIP_STAT_INB_OCTSX(port_num));
	pip_stat_inb_errsx.u64 =
	    cvmx_read_csr(CVMX_PIP_STAT_INB_ERRSX(port_num));

	status->dropped_octets = stat0.s.drp_octs;
	status->dropped_packets = stat0.s.drp_pkts;
	status->octets = stat1.s.octs;
	status->pci_raw_packets = stat2.s.raw;
	status->packets = stat2.s.pkts;
	status->multicast_packets = stat3.s.mcst;
	status->broadcast_packets = stat3.s.bcst;
	status->len_64_packets = stat4.s.h64;
	status->len_65_127_packets = stat4.s.h65to127;
	status->len_128_255_packets = stat5.s.h128to255;
	status->len_256_511_packets = stat5.s.h256to511;
	status->len_512_1023_packets = stat6.s.h512to1023;
	status->len_1024_1518_packets = stat6.s.h1024to1518;
	status->len_1519_max_packets = stat7.s.h1519;
	status->fcs_align_err_packets = stat7.s.fcs;
	status->runt_packets = stat8.s.undersz;
	status->runt_crc_packets = stat8.s.frag;
	status->oversize_packets = stat9.s.oversz;
	status->oversize_crc_packets = stat9.s.jabber;
	status->inb_packets = pip_stat_inb_pktsx.s.pkts;
	status->inb_octets = pip_stat_inb_octsx.s.octs;
	status->inb_errors = pip_stat_inb_errsx.s.errs;

	if (cvmx_octeon_is_pass1()) {
		/*
		 * Kludge to fix Octeon Pass 1 errata - Drop counts
		 * don't work.
		 */
		if (status->inb_packets > status->packets)
			status->dropped_packets =
			    status->inb_packets - status->packets;
		else
			status->dropped_packets = 0;
		if (status->inb_octets - status->inb_packets * 4 >
		    status->octets)
			status->dropped_octets =
			    status->inb_octets - status->inb_packets * 4 -
			    status->octets;
		else
			status->dropped_octets = 0;
	}
}

/**
 * Configure the hardware CRC engine
 *
 * @interface: Interface to configure (0 or 1)
 * @invert_result:
 *                 Invert the result of the CRC
 * @reflect:  Reflect
 * @initialization_vector:
 *                 CRC initialization vector
 */
static inline void cvmx_pip_config_crc(uint64_t interface,
				       uint64_t invert_result, uint64_t reflect,
				       uint32_t initialization_vector)
{
	if (OCTEON_IS_MODEL(OCTEON_CN38XX) || OCTEON_IS_MODEL(OCTEON_CN58XX)) {
		union cvmx_pip_crc_ctlx config;
		union cvmx_pip_crc_ivx pip_crc_ivx;

		config.u64 = 0;
		config.s.invres = invert_result;
		config.s.reflect = reflect;
		cvmx_write_csr(CVMX_PIP_CRC_CTLX(interface), config.u64);

		pip_crc_ivx.u64 = 0;
		pip_crc_ivx.s.iv = initialization_vector;
		cvmx_write_csr(CVMX_PIP_CRC_IVX(interface), pip_crc_ivx.u64);
	}
}

/**
 * Clear all bits in a tag mask. This should be called on
 * startup before any calls to cvmx_pip_tag_mask_set. Each bit
 * set in the final mask represent a byte used in the packet for
 * tag generation.
 *
 * @mask_index: Which tag mask to clear (0..3)
 */
static inline void cvmx_pip_tag_mask_clear(uint64_t mask_index)
{
	uint64_t index;
	union cvmx_pip_tag_incx pip_tag_incx;
	pip_tag_incx.u64 = 0;
	pip_tag_incx.s.en = 0;
	for (index = mask_index * 16; index < (mask_index + 1) * 16; index++)
		cvmx_write_csr(CVMX_PIP_TAG_INCX(index), pip_tag_incx.u64);
}

/**
 * Sets a range of bits in the tag mask. The tag mask is used
 * when the cvmx_pip_port_tag_cfg_t tag_mode is non zero.
 * There are four separate masks that can be configured.
 *
 * @mask_index: Which tag mask to modify (0..3)
 * @offset: Offset into the bitmask to set bits at. Use the GCC macro
 *          offsetof() to determine the offsets into packet headers.
 *          For example, offsetof(ethhdr, protocol) returns the offset
 *          of the ethernet protocol field.  The bitmask selects which
 *          bytes to include the the tag, with bit offset X selecting
 *          byte at offset X from the beginning of the packet data.
 * @len:    Number of bytes to include. Usually this is the sizeof()
 *          the field.
 */
static inline void cvmx_pip_tag_mask_set(uint64_t mask_index, uint64_t offset,
					 uint64_t len)
{
	while (len--) {
		union cvmx_pip_tag_incx pip_tag_incx;
		uint64_t index = mask_index * 16 + offset / 8;
		pip_tag_incx.u64 = cvmx_read_csr(CVMX_PIP_TAG_INCX(index));
		pip_tag_incx.s.en |= 0x80 >> (offset & 0x7);
		cvmx_write_csr(CVMX_PIP_TAG_INCX(index), pip_tag_incx.u64);
		offset++;
	}
}

#endif /*  __CVMX_PIP_H__ */


text:
<?xml version="1.0" encoding="UTF-8"?>

<rootTag>
  <Award>
    <AwardTitle>Agreement w/CRREL for Arctic Program Support</AwardTitle>
    <AwardEffectiveDate>02/15/2016</AwardEffectiveDate>
    <AwardExpirationDate>01/31/2017</AwardExpirationDate>
    <AwardAmount>450519</AwardAmount>
    <AwardInstrument>
      <Value>Contract Interagency Agreement</Value>
    </AwardInstrument>
    <Organization>
      06090100
      <Directorate>
        <LongName>Directorate For Geosciences</LongName>
      </Directorate>
      <Division>
        <LongName>Division Of Polar Programs</LongName>
      </Division>
    </Organization>
    <ProgramOfficer>
      <SignBlockName>Patrick R. Haggerty</SignBlockName>
    </ProgramOfficer>
    <AbstractNarration/>
    <MinAmdLetterDate>02/25/2016</MinAmdLetterDate>
    <MaxAmdLetterDate>02/25/2016</MaxAmdLetterDate>
    <ARRAAmount/>
    <AwardID>1632742</AwardID>
    <Investigator>
      <FirstName>Robert</FirstName>
      <LastName>Davis</LastName>
      <EmailAddress/>
      <StartDate>02/25/2016</StartDate>
      <EndDate/>
      <RoleCode>Principal Investigator</RoleCode>
    </Investigator>
    <Institution>
      <Name>Department of Army Cold Regions Research & Engineering Lab</Name>
      <CityName>Hanover</CityName>
      <ZipCode>037551290</ZipCode>
      <PhoneNumber>6036464219</PhoneNumber>
      <StreetAddress>72 Lyme Road</StreetAddress>
      <CountryName>United States</CountryName>
      <StateName>New Hampshire</StateName>
      <StateCode>NH</StateCode>
    </Institution>
    <ProgramElement>
      5205
      <Text>ARCTIC RESRCH SUPPRT & LOGISTI</Text>
    </ProgramElement>
    <ProgramReference>
      1079
      <Text>ARCTIC RESEARCH</Text>
    </ProgramReference>
  </Award>
</rootTag>


text:
import { Box } from "../core";
import { NodeFlags } from "./node_flags";
import { OpState } from "./state";
import { getDOMNode, VisitNodesDirective, visitNodes } from "./reconciler";
import { Component } from "./component";
import { useReducer } from "./hooks";

/**
 * findDOMNode finds a closest DOM node.
 *
 * @typeparam T DOM Node type.
 * @param box Boxed op node state.
 * @returns DOM Node or a `null` value.
 */
export const findDOMNode = <T extends Node>(
  box: Box<OpState | null>,
) => box.v === null ? null : getDOMNode<T>(box.v);

/**
 * containsDOMElement returns `true` when `parent` contains a DOM element `element`.
 *
 * @param parent Op state node.
 * @param element DOM element.
 * @returns `true` when `parent` contains a DOM element `element`.
 */
export function containsDOMElement(parent: OpState, element: Element): boolean {
  let result = false;
  visitNodes(parent, (node) => (
    ((node.f & NodeFlags.Element) !== 0) ?
      (((node.s as Element).contains(element) === true) ?
        (result = true, VisitNodesDirective.StopImmediate) :
        VisitNodesDirective.Stop) :
      VisitNodesDirective.Continue
  ));
  return result;
}

/**
 * hasDOMElementChild returns `true` when `parent` has a DOM element child `child`.
 *
 * @param parent Op state node.
 * @param child DOM element.
 * @returns `true` when `parent` has a DOM element child `child`.
 */
export function hasDOMElementChild(parent: OpState, child: Element): boolean {
  let result = false;
  visitNodes(parent, (node) => (
    ((node.f & NodeFlags.Element) !== 0) ?
      ((node.s === child) ?
        (result = true, VisitNodesDirective.StopImmediate) :
        VisitNodesDirective.Stop) :
      VisitNodesDirective.Continue
  ));
  return result;
}

/**
 * reducer creates a state reducer hook.
 *
 * @typeparam T State type.
 * @typeparam U Reducer type.
 * @param reducerFn Reducer function.
 * @param initialState Initial state.
 * @returns State reducer hook.
 */
export const reducer = <T, U>(reducerFn: (state: T, action: U) => T, initialState: T) => (
  (component: Component) => useReducer(component, reducerFn, initialState)
);


text:
package org.apache.hyracks.storage.am.lsm.btree.dataflow;

import org.apache.hyracks.api.context.IHyracksTaskContext;
import org.apache.hyracks.api.exceptions.HyracksDataException;
import org.apache.hyracks.api.io.FileReference;
import org.apache.hyracks.storage.am.common.api.IIndex;
import org.apache.hyracks.storage.am.common.api.IMetadataPageManagerFactory;
import org.apache.hyracks.storage.am.common.dataflow.AbstractTreeIndexOperatorDescriptor;
import org.apache.hyracks.storage.am.common.dataflow.IIndexOperatorDescriptor;
import org.apache.hyracks.storage.am.common.util.IndexFileNameUtil;
import org.apache.hyracks.storage.am.lsm.btree.utils.LSMBTreeUtil;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationCallbackFactory;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMIOOperationScheduler;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMMergePolicy;
import org.apache.hyracks.storage.am.lsm.common.api.ILSMOperationTrackerFactory;
import org.apache.hyracks.storage.am.lsm.common.dataflow.AbstractLSMIndexDataflowHelper;

public class ExternalBTreeWithBuddyDataflowHelper extends AbstractLSMIndexDataflowHelper {

    private final int[] buddyBtreeFields;
    private final int version;

    public ExternalBTreeWithBuddyDataflowHelper(IIndexOperatorDescriptor opDesc, IHyracksTaskContext ctx,
            int partition, ILSMMergePolicy mergePolicy, ILSMOperationTrackerFactory opTrackerFactory,
            ILSMIOOperationScheduler ioScheduler, ILSMIOOperationCallbackFactory ioOpCallbackFactory,
            int[] buddyBtreeFields, int version, boolean durable) throws HyracksDataException {
        super(opDesc, ctx, partition, null, mergePolicy, opTrackerFactory, ioScheduler, ioOpCallbackFactory, null,
                null, null, durable);
        this.buddyBtreeFields = buddyBtreeFields;
        this.version = version;
    }

    public ExternalBTreeWithBuddyDataflowHelper(IIndexOperatorDescriptor opDesc, IHyracksTaskContext ctx,
            int partition, double bloomFilterFalsePositiveRate, ILSMMergePolicy mergePolicy,
            ILSMOperationTrackerFactory opTrackerFactory, ILSMIOOperationScheduler ioScheduler,
            ILSMIOOperationCallbackFactory ioOpCallbackFactory, int[] buddyBtreeFields, int version, boolean durable)
            throws HyracksDataException {
        super(opDesc, ctx, partition, null, bloomFilterFalsePositiveRate, mergePolicy, opTrackerFactory, ioScheduler,
                ioOpCallbackFactory, null, null, null, durable);
        this.buddyBtreeFields = buddyBtreeFields;
        this.version = version;
    }

    @Override
    public IIndex getIndexInstance() {
        synchronized (lcManager) {
            if (index == null) {
                try {
                    index = lcManager.get(resourceName);
                } catch (HyracksDataException e) {
                    return null;
                }
            }
        }
        return index;
    }

    @Override
    protected IIndex createIndexInstance() throws HyracksDataException {
        AbstractTreeIndexOperatorDescriptor treeOpDesc = (AbstractTreeIndexOperatorDescriptor) opDesc;
        FileReference fileRef = IndexFileNameUtil.getIndexAbsoluteFileRef(treeOpDesc, ctx.getTaskAttemptId()
                .getTaskId().getPartition(), ctx.getIOManager());
        return LSMBTreeUtil.createExternalBTreeWithBuddy(ctx.getIOManager(), fileRef,
                opDesc.getStorageManager().getBufferCache(ctx),
                opDesc.getStorageManager().getFileMapProvider(ctx), treeOpDesc.getTreeIndexTypeTraits(),
                treeOpDesc.getTreeIndexComparatorFactories(), bloomFilterFalsePositiveRate, mergePolicy,
                opTrackerFactory.getOperationTracker(ctx.getJobletContext().getApplicationContext()), ioScheduler,
                ioOpCallbackFactory.createIoOpCallback(), buddyBtreeFields, version, durable,
                (IMetadataPageManagerFactory) opDesc.getPageManagerFactory());
    }
    public int getTargetVersion() {
        return version;
    }
}


text:
package com.bjzjnsdemo.ui.view;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;

/**
 * 修复图片在ViewPager控件中缩放报错的BUG
 */
public class ViewPagerFixed extends ViewPager {

    public ViewPagerFixed(Context context) {
        super(context);
    }

    public ViewPagerFixed(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        try {
            return super.onTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        try {
            return super.onInterceptTouchEvent(ev);
        } catch (IllegalArgumentException ex) {
            ex.printStackTrace();
        }
        return false;
    }
}


text:
package org.exoplatform.portal.application.localization;

import java.util.List;
import java.util.Locale;

import org.exoplatform.services.resources.LocaleContextInfo;
import org.exoplatform.services.resources.LocalePolicy;
import org.picocontainer.Startable;

/**
 * This service represents a default policy for determining LocaleConfig to be used for user's session. This service is
 * registered through portal services configuration file: conf/portal/configuration.xml Custom locale determination policy can
 * be implemented by overriding or completely replacing this class, and registering an alternative implementation.
 *
 * To gracefully fallback from more specific locales (lang_COUNTRY) to more generic (lang) without loss of information about
 * user's language selection use {@link LocaleContextInfo#getLocaleIfLangSupported(java.util.Locale)} and return a more specific
 * Locale. The Locale will be appropriately narrowed by LocalePolicy caller.
 *
 * Special care needs to be taken to assure Locale consistency between portal requests and non-portal requests - like login
 * redirect upon failed authentication attempt. To keep consistency at least one of {@link LocaleContextInfo#cookieLocales} and
 * {@link LocaleContextInfo#sessionLocale} needs to be enabled.
 *
 * @see NoBrowserLocalePolicyService
 * @see LocalizationFilter
 *
 * @author Marko Strukelj
 */
public class DefaultLocalePolicyService implements LocalePolicy, Startable {
    /**
     * @see LocalePolicy#determineLocale(LocaleContextInfo)
     */
    public Locale determineLocale(LocaleContextInfo context) {
        if (context.getRequestLocale() != null) {
            return context.getRequestLocale();
        }

        //
        Locale locale = null;
        if (context.getRemoteUser() == null)
            locale = getLocaleConfigForAnonymous(context);
        else
            locale = getLocaleConfigForRegistered(context);

        if (locale == null)
            locale = context.getPortalLocale();

        return locale;
    }

    /**
     * Override this method to change the LocaleConfig determination for registered users. Default is: use user's profile
     * language, if not available fall back to LOCALE cookie, and finally if that is not available either fall back to browser
     * language preference.
     *
     * @param context locale context info available to implementations in order to determine appropriate Locale
     * @return Locale representing a language to use, or null
     */
    protected Locale getLocaleConfigForRegistered(LocaleContextInfo context) {
        Locale locale = context.getLocaleIfLangSupported(context.getUserProfileLocale());
        if (locale == null)
            locale = getLocaleConfigFromCookie(context);
        if (locale == null)
            locale = getLocaleConfigFromSession(context);
        if (locale == null)
            locale = getLocaleConfigFromBrowser(context);

        return locale;
    }

    /**
     * Override this method to change the Locale determination based on browser language preferences. If you want to disable the
     * use of browser language preferences simply return null.
     *
     * @param context locale context info available to implementations in order to determine appropriate Locale
     * @return Locale representing a language to use, or null
     */
    protected Locale getLocaleConfigFromBrowser(LocaleContextInfo context) {
        List<Locale> locales = context.getBrowserLocales();
        if (locales != null) {
            for (Locale loc : locales)
                return context.getLocaleIfLangSupported(loc);
        }
        return null;
    }

    /**
     * Override this method to change Locale determination for users that aren't logged in. By default the request's LOCALE
     * cookie is used, if that is not available the browser language preferences are used.
     *
     * @param context locale context info available to implementations in order to determine appropriate Locale
     * @return Locale representing a language to use, or null
     */
    protected Locale getLocaleConfigForAnonymous(LocaleContextInfo context) {
        Locale locale = getLocaleConfigFromCookie(context);
        if (locale == null)
            locale = getLocaleConfigFromSession(context);
        if (locale == null)
            locale = getLocaleConfigFromBrowser(context);

        return locale;
    }

    /**
     * Override this method to change the Locale determination based on session attribute. Note: this is mostly a backup for
     * cookie, as either one usually has to be enabled for locale to remain synchronized between portal and non-portal pages.
     *
     * @param context locale context info available to implementations in order to determine appropriate Locale
     * @return Locale representing a language to use, or null
     */
    protected Locale getLocaleConfigFromSession(LocaleContextInfo context) {
        return context.getSessionLocale();
    }

    /**
     * Override this method to change the Locale determination based on browser cookie. If you want to disable the use of
     * browser cookies simply return null.
     *
     * @param context locale context info available to implementations in order to determine appropriate Locale
     * @return Locale representing a language to use, or null
     */
    protected Locale getLocaleConfigFromCookie(LocaleContextInfo context) {
        List<Locale> locales = context.getCookieLocales();
        if (locales != null) {
            for (Locale locale : locales)
                return context.getLocaleIfLangSupported(locale);
        }
        return null;
    }

    /**
     * Starter interface method
     */
    public void start() {
    }

    /**
     * Starter interface method
     */
    public void stop() {
    }

}