text:
package cgeo.geocaching.utils;

import cgeo.geocaching.R;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.export.IndividualRouteExport;
import cgeo.geocaching.files.GPXIndividualRouteImporter;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.maps.routing.RouteSortActivity;
import cgeo.geocaching.models.IndividualRoute;
import cgeo.geocaching.models.Route;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.ContentStorageActivityHelper;
import cgeo.geocaching.storage.PersistableFolder;
import cgeo.geocaching.ui.dialog.Dialogs;
import cgeo.geocaching.utils.functions.Action2;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;

public class IndividualRouteUtils {

    private static final int REQUEST_SORT_INDIVIDUAL_ROUTE = 4712;
    private static final String STATE_CSAH = "csah";

    private final Activity activity;
    private final ContentStorageActivityHelper fileSelector;

    private final Runnable reloadIndividualRoute;
    private final Runnable clearIndividualRoute;

    public IndividualRouteUtils(final Activity activity, final Bundle savedState, final Runnable clearIndividualRoute, final Runnable reloadIndividualRoute) {
        this.activity = activity;
        this.clearIndividualRoute = clearIndividualRoute;
        this.reloadIndividualRoute = reloadIndividualRoute;
        this.fileSelector = new ContentStorageActivityHelper(activity, savedState == null ? null : savedState.getBundle(STATE_CSAH))
        .addSelectActionCallback(ContentStorageActivityHelper.SelectAction.SELECT_FILE, Uri.class, uri -> {
            if (uri != null) {
                GPXIndividualRouteImporter.doImport(activity, uri);
                reloadIndividualRoute.run();
            }
        });
    }

    /**
     * Enable/disable track related menu entries
     *
     * @param menu menu to be configured
     */
    public void onPrepareOptionsMenu(final Menu menu, final IndividualRoute route, final boolean targetIsSet) {
        final boolean isVisible = route != null && route.getNumSegments() > 0;
        menu.findItem(R.id.menu_sort_individual_route).setVisible(isVisible);
        menu.findItem(R.id.menu_center_on_route).setVisible(isVisible);
        menu.findItem(R.id.menu_export_individual_route).setVisible(isVisible);
        menu.findItem(R.id.menu_export_individual_route_as_track).setVisible(isVisible);
        menu.findItem(R.id.menu_clear_individual_route).setVisible(isVisible);
        menu.findItem(R.id.menu_clear_targets).setVisible(targetIsSet || Settings.isAutotargetIndividualRoute());
        menu.findItem(R.id.menu_autotarget_individual_route).setVisible(true).setChecked(Settings.isAutotargetIndividualRoute());
    }

    /**
     * Check if selected menu entry is regarding individual routes
     *
     * @param id       menu entry id
     * @param route    current route
     * @param centerOnPosition  method to call to center on route
     * @param setTarget         method to call on set target
     * @return true, if selected menu entry is individual route related and consumed / false else
     */
    public boolean onOptionsItemSelected(final int id, final IndividualRoute route, final Route.CenterOnPosition centerOnPosition, final Action2<Geopoint, String> setTarget) {
        if (id == R.id.menu_load_individual_route) {
            if (null == route || route.getNumSegments() == 0) {
                startIndividualRouteFileSelector();
            } else {
                Dialogs.confirm(activity, R.string.map_load_individual_route, R.string.map_load_individual_route_confirm, (dialog, which) -> startIndividualRouteFileSelector());
            }
        } else if (id == R.id.menu_sort_individual_route) {
            activity.startActivityForResult(new Intent(activity, RouteSortActivity.class), REQUEST_SORT_INDIVIDUAL_ROUTE);
        } else if (id == R.id.menu_center_on_route) {
            route.setCenter(centerOnPosition);
        } else if (id == R.id.menu_export_individual_route) {
            new IndividualRouteExport(activity, route, false);
        } else if (id == R.id.menu_export_individual_route_as_track) {
            new IndividualRouteExport(activity, route, true);
        } else if (id == R.id.menu_clear_individual_route) {
            Dialogs.confirm(activity, R.string.map_clear_individual_route, R.string.map_clear_individual_route_confirm, (dialog, which) -> {
                clearIndividualRoute.run();
                ActivityMixin.invalidateOptionsMenu(activity);
            });
        } else if (id == R.id.menu_autotarget_individual_route) {
            setAutotargetIndividualRoute(activity, route, !Settings.isAutotargetIndividualRoute());
        } else if (id == R.id.menu_clear_targets) {
            if (setTarget != null) {
                setTarget.call(null, null);
            }
            Settings.setAutotargetIndividualRoute(false);
            route.triggerTargetUpdate(true);
            ActivityMixin.invalidateOptionsMenu(activity);
            ActivityMixin.showToast(activity, R.string.map_manual_targets_cleared);
        } else {
            return false;
        }
        return true;
    }

    private void startIndividualRouteFileSelector() {

        fileSelector.selectFile(null, PersistableFolder.GPX.getUri());
    }

    public boolean onActivityResult(final int requestCode, final int resultCode, final Intent data) {
        if (fileSelector.onActivityResult(requestCode, resultCode, data)) {
            return true;
        }
        if (requestCode == REQUEST_SORT_INDIVIDUAL_ROUTE) {
            reloadIndividualRoute.run();
            return true;
        }
        return false;
    }

    public  Bundle getState() {
        final Bundle bundle = new Bundle();
        bundle.putBundle(STATE_CSAH, this.fileSelector.getState());
        return bundle;
    }

    public static void setAutotargetIndividualRoute(final Activity activity, final IndividualRoute route, final boolean newValue) {
        Settings.setAutotargetIndividualRoute(newValue);
        route.triggerTargetUpdate(!Settings.isAutotargetIndividualRoute());
        ActivityMixin.invalidateOptionsMenu(activity);
    }

}


text:
#include <grpc/support/port_platform.h>

#include "src/core/lib/channel/connected_channel.h"

#include <inttypes.h>
#include <string.h>

#include <algorithm>
#include <memory>
#include <string>
#include <utility>
#include <vector>

#include "absl/base/thread_annotations.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "absl/types/optional.h"
#include "absl/types/variant.h"

#include <grpc/impl/codegen/grpc_types.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>

#include "src/core/lib/channel/channel_args.h"
#include "src/core/lib/channel/channel_fwd.h"
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/context.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gpr/alloc.h"
#include "src/core/lib/gprpp/debug_location.h"
#include "src/core/lib/gprpp/match.h"
#include "src/core/lib/gprpp/orphanable.h"
#include "src/core/lib/gprpp/status_helper.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/closure.h"
#include "src/core/lib/iomgr/error.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/polling_entity.h"
#include "src/core/lib/promise/activity.h"
#include "src/core/lib/promise/arena_promise.h"
#include "src/core/lib/promise/context.h"
#include "src/core/lib/promise/latch.h"
#include "src/core/lib/promise/pipe.h"
#include "src/core/lib/promise/poll.h"
#include "src/core/lib/resource_quota/arena.h"
#include "src/core/lib/slice/slice_buffer.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/call_trace.h"
#include "src/core/lib/surface/channel_stack_type.h"
#include "src/core/lib/transport/metadata_batch.h"
#include "src/core/lib/transport/transport.h"
#include "src/core/lib/transport/transport_fwd.h"
#include "src/core/lib/transport/transport_impl.h"

#define MAX_BUFFER_LENGTH 8192

typedef struct connected_channel_channel_data {
  grpc_transport* transport;
} channel_data;

struct callback_state {
  grpc_closure closure;
  grpc_closure* original_closure;
  grpc_core::CallCombiner* call_combiner;
  const char* reason;
};
typedef struct connected_channel_call_data {
  grpc_core::CallCombiner* call_combiner;
  // Closures used for returning results on the call combiner.
  callback_state on_complete[6];  // Max number of pending batches.
  callback_state recv_initial_metadata_ready;
  callback_state recv_message_ready;
  callback_state recv_trailing_metadata_ready;
} call_data;

static void run_in_call_combiner(void* arg, grpc_error_handle error) {
  callback_state* state = static_cast<callback_state*>(arg);
  GRPC_CALL_COMBINER_START(state->call_combiner, state->original_closure, error,
                           state->reason);
}

static void run_cancel_in_call_combiner(void* arg, grpc_error_handle error) {
  run_in_call_combiner(arg, error);
  gpr_free(arg);
}

static void intercept_callback(call_data* calld, callback_state* state,
                               bool free_when_done, const char* reason,
                               grpc_closure** original_closure) {
  state->original_closure = *original_closure;
  state->call_combiner = calld->call_combiner;
  state->reason = reason;
  *original_closure = GRPC_CLOSURE_INIT(
      &state->closure,
      free_when_done ? run_cancel_in_call_combiner : run_in_call_combiner,
      state, grpc_schedule_on_exec_ctx);
}

static callback_state* get_state_for_batch(
    call_data* calld, grpc_transport_stream_op_batch* batch) {
  if (batch->send_initial_metadata) return &calld->on_complete[0];
  if (batch->send_message) return &calld->on_complete[1];
  if (batch->send_trailing_metadata) return &calld->on_complete[2];
  if (batch->recv_initial_metadata) return &calld->on_complete[3];
  if (batch->recv_message) return &calld->on_complete[4];
  if (batch->recv_trailing_metadata) return &calld->on_complete[5];
  GPR_UNREACHABLE_CODE(return nullptr);
}

/* We perform a small hack to locate transport data alongside the connected
   channel data in call allocations, to allow everything to be pulled in minimal
   cache line requests */
#define TRANSPORT_STREAM_FROM_CALL_DATA(calld) \
  ((grpc_stream*)(((char*)(calld)) +           \
                  GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(call_data))))
#define CALL_DATA_FROM_TRANSPORT_STREAM(transport_stream) \
  ((call_data*)(((char*)(transport_stream)) -             \
                GPR_ROUND_UP_TO_ALIGNMENT_SIZE(sizeof(call_data))))

/* Intercept a call operation and either push it directly up or translate it
   into transport stream operations */
static void connected_channel_start_transport_stream_op_batch(
    grpc_call_element* elem, grpc_transport_stream_op_batch* batch) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  channel_data* chand = static_cast<channel_data*>(elem->channel_data);
  if (batch->recv_initial_metadata) {
    callback_state* state = &calld->recv_initial_metadata_ready;
    intercept_callback(
        calld, state, false, "recv_initial_metadata_ready",
        &batch->payload->recv_initial_metadata.recv_initial_metadata_ready);
  }
  if (batch->recv_message) {
    callback_state* state = &calld->recv_message_ready;
    intercept_callback(calld, state, false, "recv_message_ready",
                       &batch->payload->recv_message.recv_message_ready);
  }
  if (batch->recv_trailing_metadata) {
    callback_state* state = &calld->recv_trailing_metadata_ready;
    intercept_callback(
        calld, state, false, "recv_trailing_metadata_ready",
        &batch->payload->recv_trailing_metadata.recv_trailing_metadata_ready);
  }
  if (batch->cancel_stream) {
    // There can be more than one cancellation batch in flight at any
    // given time, so we can't just pick out a fixed index into
    // calld->on_complete like we can for the other ops.  However,
    // cancellation isn't in the fast path, so we just allocate a new
    // closure for each one.
    callback_state* state =
        static_cast<callback_state*>(gpr_malloc(sizeof(*state)));
    intercept_callback(calld, state, true, "on_complete (cancel_stream)",
                       &batch->on_complete);
  } else if (batch->on_complete != nullptr) {
    callback_state* state = get_state_for_batch(calld, batch);
    intercept_callback(calld, state, false, "on_complete", &batch->on_complete);
  }
  grpc_transport_perform_stream_op(
      chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld), batch);
  GRPC_CALL_COMBINER_STOP(calld->call_combiner, "passed batch to transport");
}

static void connected_channel_start_transport_op(grpc_channel_element* elem,
                                                 grpc_transport_op* op) {
  channel_data* chand = static_cast<channel_data*>(elem->channel_data);
  grpc_transport_perform_op(chand->transport, op);
}

/* Constructor for call_data */
static grpc_error_handle connected_channel_init_call_elem(
    grpc_call_element* elem, const grpc_call_element_args* args) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  channel_data* chand = static_cast<channel_data*>(elem->channel_data);
  calld->call_combiner = args->call_combiner;
  int r = grpc_transport_init_stream(
      chand->transport, TRANSPORT_STREAM_FROM_CALL_DATA(calld),
      &args->call_stack->refcount, args->server_transport_data, args->arena);
  return r == 0 ? absl::OkStatus()
                : GRPC_ERROR_CREATE("transport stream initialization failed");
}

static void set_pollset_or_pollset_set(grpc_call_element* elem,
                                       grpc_polling_entity* pollent) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  channel_data* chand = static_cast<channel_data*>(elem->channel_data);
  grpc_transport_set_pops(chand->transport,
                          TRANSPORT_STREAM_FROM_CALL_DATA(calld), pollent);
}

/* Destructor for call_data */
static void connected_channel_destroy_call_elem(
    grpc_call_element* elem, const grpc_call_final_info* /*final_info*/,
    grpc_closure* then_schedule_closure) {
  call_data* calld = static_cast<call_data*>(elem->call_data);
  channel_data* chand = static_cast<channel_data*>(elem->channel_data);
  grpc_transport_destroy_stream(chand->transport,
                                TRANSPORT_STREAM_FROM_CALL_DATA(calld),
                                then_schedule_closure);
}

/* Constructor for channel_data */
static grpc_error_handle connected_channel_init_channel_elem(
    grpc_channel_element* elem, grpc_channel_element_args* args) {
  channel_data* cd = static_cast<channel_data*>(elem->channel_data);
  GPR_ASSERT(args->is_last);
  cd->transport = grpc_channel_args_find_pointer<grpc_transport>(
      args->channel_args, GRPC_ARG_TRANSPORT);
  return absl::OkStatus();
}

/* Destructor for channel_data */
static void connected_channel_destroy_channel_elem(grpc_channel_element* elem) {
  channel_data* cd = static_cast<channel_data*>(elem->channel_data);
  if (cd->transport) {
    grpc_transport_destroy(cd->transport);
  }
}

/* No-op. */
static void connected_channel_get_channel_info(
    grpc_channel_element* /*elem*/, const grpc_channel_info* /*channel_info*/) {
}

namespace grpc_core {
namespace {

class ClientStream : public Orphanable {
 public:
  ClientStream(grpc_transport* transport, CallArgs call_args)
      : transport_(transport),
        stream_(nullptr, StreamDeleter(this)),
        server_initial_metadata_latch_(call_args.server_initial_metadata),
        client_to_server_messages_(call_args.outgoing_messages),
        server_to_client_messages_(call_args.incoming_messages),
        client_initial_metadata_(std::move(call_args.client_initial_metadata)) {
    call_context_->IncrementRefCount("client_stream");
    GRPC_STREAM_REF_INIT(
        &stream_refcount_, 1,
        [](void* p, grpc_error_handle) {
          static_cast<ClientStream*>(p)->BeginDestroy();
        },
        this, "client_stream");
    if (grpc_call_trace.enabled()) {
      gpr_log(GPR_INFO, "%sInitImpl: intitial_metadata=%s",
              Activity::current()->DebugTag().c_str(),
              client_initial_metadata_->DebugString().c_str());
    }
  }

  void Orphan() override {
    bool finished;
    {
      MutexLock lock(&mu_);
      if (grpc_call_trace.enabled()) {
        gpr_log(GPR_INFO, "%sDropStream: %s",
                Activity::current()->DebugTag().c_str(),
                ActiveOpsString().c_str());
      }
      finished = finished_;
    }
    // If we hadn't already observed the stream to be finished, we need to
    // cancel it at the transport.
    if (!finished) {
      IncrementRefCount("shutdown client stream");
      auto* cancel_op =
          GetContext<Arena>()->New<grpc_transport_stream_op_batch>();
      cancel_op->cancel_stream = true;
      cancel_op->payload = &batch_payload_;
      auto* stream = stream_.get();
      cancel_op->on_complete = NewClosure(
          [this](grpc_error_handle) { Unref("shutdown client stream"); });
      batch_payload_.cancel_stream.cancel_error = absl::CancelledError();
      grpc_transport_perform_stream_op(transport_, stream, cancel_op);
    }
    Unref("orphan client stream");
  }

  void IncrementRefCount(const char* reason) {
#ifndef NDEBUG
    grpc_stream_ref(&stream_refcount_, reason);
#else
    (void)reason;
    grpc_stream_ref(&stream_refcount_);
#endif
  }

  void Unref(const char* reason) {
#ifndef NDEBUG
    grpc_stream_unref(&stream_refcount_, reason);
#else
    (void)reason;
    grpc_stream_unref(&stream_refcount_);
#endif
  }

  void BeginDestroy() {
    if (stream_ != nullptr) {
      stream_.reset();
    } else {
      StreamDestroyed();
    }
  }

  Poll<ServerMetadataHandle> PollOnce() {
    MutexLock lock(&mu_);
    GPR_ASSERT(!finished_);

    if (grpc_call_trace.enabled()) {
      gpr_log(GPR_INFO, "%sPollConnectedChannel: %s",
              Activity::current()->DebugTag().c_str(),
              ActiveOpsString().c_str());
    }

    auto push_recv_message = [this]() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
      recv_message_state_ = PendingReceiveMessage{};
      auto& pending_recv_message =
          absl::get<PendingReceiveMessage>(recv_message_state_);
      memset(&recv_message_, 0, sizeof(recv_message_));
      recv_message_.payload = &batch_payload_;
      recv_message_.on_complete = nullptr;
      recv_message_.recv_message = true;
      batch_payload_.recv_message.recv_message = &pending_recv_message.payload;
      batch_payload_.recv_message.flags = &pending_recv_message.flags;
      batch_payload_.recv_message.call_failed_before_recv_message = nullptr;
      batch_payload_.recv_message.recv_message_ready =
          &recv_message_batch_done_;
      IncrementRefCount("recv_message");
      recv_message_waker_ = Activity::current()->MakeOwningWaker();
      push_recv_message_ = true;
      SchedulePush();
    };

    if (!std::exchange(requested_metadata_, true)) {
      if (grpc_call_trace.enabled()) {
        gpr_log(GPR_INFO, "%sPollConnectedChannel: requesting metadata",
                Activity::current()->DebugTag().c_str());
      }
      stream_.reset(static_cast<grpc_stream*>(
          GetContext<Arena>()->Alloc(transport_->vtable->sizeof_stream)));
      grpc_transport_init_stream(transport_, stream_.get(), &stream_refcount_,
                                 nullptr, GetContext<Arena>());
      grpc_transport_set_pops(transport_, stream_.get(),
                              GetContext<CallContext>()->polling_entity());
      memset(&metadata_, 0, sizeof(metadata_));
      metadata_.send_initial_metadata = true;
      metadata_.recv_initial_metadata = true;
      metadata_.recv_trailing_metadata = true;
      metadata_.payload = &batch_payload_;
      metadata_.on_complete = &metadata_batch_done_;
      batch_payload_.send_initial_metadata.send_initial_metadata =
          client_initial_metadata_.get();
      batch_payload_.send_initial_metadata.peer_string =
          GetContext<CallContext>()->peer_string_atm_ptr();
      server_initial_metadata_ =
          GetContext<Arena>()->MakePooled<ServerMetadata>(GetContext<Arena>());
      batch_payload_.recv_initial_metadata.recv_initial_metadata =
          server_initial_metadata_.get();
      batch_payload_.recv_initial_metadata.recv_initial_metadata_ready =
          &recv_initial_metadata_ready_;
      batch_payload_.recv_initial_metadata.trailing_metadata_available =
          nullptr;
      batch_payload_.recv_initial_metadata.peer_string = nullptr;
      server_trailing_metadata_ =
          GetContext<Arena>()->MakePooled<ServerMetadata>(GetContext<Arena>());
      batch_payload_.recv_trailing_metadata.recv_trailing_metadata =
          server_trailing_metadata_.get();
      batch_payload_.recv_trailing_metadata.collect_stats =
          &GetContext<CallContext>()->call_stats()->transport_stream_stats;
      batch_payload_.recv_trailing_metadata.recv_trailing_metadata_ready =
          &recv_trailing_metadata_ready_;
      push_metadata_ = true;
      IncrementRefCount("metadata_batch_done");
      IncrementRefCount("initial_metadata_ready");
      IncrementRefCount("trailing_metadata_ready");
      initial_metadata_waker_ = Activity::current()->MakeOwningWaker();
      trailing_metadata_waker_ = Activity::current()->MakeOwningWaker();
      SchedulePush();
    }
    if (absl::holds_alternative<Closed>(send_message_state_)) {
      message_to_send_.reset();
    }
    if (absl::holds_alternative<Idle>(send_message_state_)) {
      message_to_send_.reset();
      send_message_state_ = client_to_server_messages_->Next();
    }
    if (auto* next = absl::get_if<PipeReceiver<MessageHandle>::NextType>(
            &send_message_state_)) {
      auto r = (*next)();
      if (auto* p = absl::get_if<NextResult<MessageHandle>>(&r)) {
        memset(&send_message_, 0, sizeof(send_message_));
        send_message_.payload = &batch_payload_;
        send_message_.on_complete = &send_message_batch_done_;
        // No value => half close from above.
        if (p->has_value()) {
          message_to_send_ = std::move(**p);
          send_message_state_ = SendMessageToTransport{};
          send_message_.send_message = true;
          batch_payload_.send_message.send_message =
              message_to_send_->payload();
          batch_payload_.send_message.flags = message_to_send_->flags();
        } else {
          GPR_ASSERT(!absl::holds_alternative<Closed>(send_message_state_));
          client_trailing_metadata_ =
              GetContext<Arena>()->MakePooled<ClientMetadata>(
                  GetContext<Arena>());
          send_message_state_ = Closed{};
          send_message_.send_trailing_metadata = true;
          batch_payload_.send_trailing_metadata.send_trailing_metadata =
              client_trailing_metadata_.get();
          batch_payload_.send_trailing_metadata.sent = nullptr;
        }
        IncrementRefCount("send_message");
        send_message_waker_ = Activity::current()->MakeOwningWaker();
        push_send_message_ = true;
        SchedulePush();
      }
    }
    if (auto* pending =
            absl::get_if<PendingReceiveMessage>(&recv_message_state_)) {
      if (pending->received) {
        if (pending->payload.has_value()) {
          if (grpc_call_trace.enabled()) {
            gpr_log(GPR_INFO,
                    "%sRecvMessageBatchDone: received payload of %" PRIdPTR
                    " bytes",
                    recv_message_waker_.ActivityDebugTag().c_str(),
                    pending->payload->Length());
          }
          recv_message_state_ = server_to_client_messages_->Push(
              GetContext<Arena>()->MakePooled<Message>(
                  std::move(*pending->payload), pending->flags));
        } else {
          if (grpc_call_trace.enabled()) {
            gpr_log(GPR_INFO, "%sRecvMessageBatchDone: received no payload",
                    recv_message_waker_.ActivityDebugTag().c_str());
          }
          recv_message_state_ = Closed{};
          std::exchange(server_to_client_messages_, nullptr)->Close();
        }
      }
    }
    if (server_initial_metadata_state_ ==
        ServerInitialMetadataState::kReceivedButNotSet) {
      server_initial_metadata_state_ = ServerInitialMetadataState::kSet;
      server_initial_metadata_latch_->Set(server_initial_metadata_.get());
    }
    if (absl::holds_alternative<Idle>(recv_message_state_)) {
      if (grpc_call_trace.enabled()) {
        gpr_log(GPR_INFO, "%sPollConnectedChannel: requesting message",
                Activity::current()->DebugTag().c_str());
      }
      push_recv_message();
    }
    if (server_initial_metadata_state_ == ServerInitialMetadataState::kSet &&
        !absl::holds_alternative<PipeSender<MessageHandle>::PushType>(
            recv_message_state_) &&
        std::exchange(queued_trailing_metadata_, false)) {
      if (grpc_call_trace.enabled()) {
        gpr_log(GPR_INFO,
                "%sPollConnectedChannel: finished request, returning: {%s}; "
                "active_ops: %s",
                Activity::current()->DebugTag().c_str(),
                server_trailing_metadata_->DebugString().c_str(),
                ActiveOpsString().c_str());
      }
      finished_ = true;
      return ServerMetadataHandle(std::move(server_trailing_metadata_));
    }
    if (auto* push = absl::get_if<PipeSender<MessageHandle>::PushType>(
            &recv_message_state_)) {
      auto r = (*push)();
      if (bool* result = absl::get_if<bool>(&r)) {
        if (*result) {
          if (!finished_) {
            if (grpc_call_trace.enabled()) {
              gpr_log(GPR_INFO,
                      "%sPollConnectedChannel: pushed message; requesting next",
                      Activity::current()->DebugTag().c_str());
            }
            push_recv_message();
          } else {
            if (grpc_call_trace.enabled()) {
              gpr_log(GPR_INFO,
                      "%sPollConnectedChannel: pushed message and finished; "
                      "marking closed",
                      Activity::current()->DebugTag().c_str());
            }
            recv_message_state_ = Closed{};
          }
        } else {
          if (grpc_call_trace.enabled()) {
            gpr_log(GPR_INFO,
                    "%sPollConnectedChannel: failed to push message; marking "
                    "closed",
                    Activity::current()->DebugTag().c_str());
          }
          recv_message_state_ = Closed{};
        }
      }
    }
    return Pending{};
  }

  void RecvInitialMetadataReady(grpc_error_handle error) {
    GPR_ASSERT(error == absl::OkStatus());
    {
      MutexLock lock(&mu_);
      server_initial_metadata_state_ =
          ServerInitialMetadataState::kReceivedButNotSet;
      initial_metadata_waker_.Wakeup();
    }
    Unref("initial_metadata_ready");
  }

  void RecvTrailingMetadataReady(grpc_error_handle error) {
    GPR_ASSERT(error == absl::OkStatus());
    {
      MutexLock lock(&mu_);
      queued_trailing_metadata_ = true;
      trailing_metadata_waker_.Wakeup();
    }
    Unref("trailing_metadata_ready");
  }

  void MetadataBatchDone(grpc_error_handle error) {
    GPR_ASSERT(error == absl::OkStatus());
    Unref("metadata_batch_done");
  }

  void SendMessageBatchDone(grpc_error_handle error) {
    {
      MutexLock lock(&mu_);
      if (error != absl::OkStatus()) {
        // Note that we're in error here, the call will be closed by the
        // transport in a moment, and we'll return from the promise with an
        // error - so we don't need to do any extra work to close out pipes or
        // the like.
        send_message_state_ = Closed{};
      }
      if (!absl::holds_alternative<Closed>(send_message_state_)) {
        send_message_state_ = Idle{};
      }
      send_message_waker_.Wakeup();
    }
    Unref("send_message");
  }

  void RecvMessageBatchDone(grpc_error_handle error) {
    {
      MutexLock lock(&mu_);
      if (error != absl::OkStatus()) {
        if (grpc_call_trace.enabled()) {
          gpr_log(GPR_INFO, "%sRecvMessageBatchDone: error=%s",
                  recv_message_waker_.ActivityDebugTag().c_str(),
                  StatusToString(error).c_str());
        }
      } else if (absl::holds_alternative<Closed>(recv_message_state_)) {
        if (grpc_call_trace.enabled()) {
          gpr_log(GPR_INFO, "%sRecvMessageBatchDone: already closed, ignoring",
                  recv_message_waker_.ActivityDebugTag().c_str());
        }
      } else {
        auto pending =
            absl::get_if<PendingReceiveMessage>(&recv_message_state_);
        GPR_ASSERT(pending != nullptr);
        GPR_ASSERT(pending->received == false);
        pending->received = true;
      }
      recv_message_waker_.Wakeup();
    }
    Unref("recv_message");
  }

  // Called from outside the activity to push work down to the transport.
  void Push() {
    auto do_push = [this](grpc_transport_stream_op_batch* batch) {
      if (stream_ != nullptr) {
        grpc_transport_perform_stream_op(transport_, stream_.get(), batch);
      } else {
        grpc_transport_stream_op_batch_finish_with_failure_from_transport(
            batch, absl::CancelledError());
      }
    };
    bool push_metadata;
    bool push_send_message;
    bool push_recv_message;
    {
      MutexLock lock(&mu_);
      push_metadata = std::exchange(push_metadata_, false);
      push_send_message = std::exchange(push_send_message_, false);
      push_recv_message = std::exchange(push_recv_message_, false);
      scheduled_push_ = false;
    }
    if (push_metadata) do_push(&metadata_);
    if (push_send_message) do_push(&send_message_);
    if (push_recv_message) do_push(&recv_message_);
    Unref("push");
  }

  void StreamDestroyed() {
    call_context_->RunInContext([this] {
      auto* cc = call_context_;
      this->~ClientStream();
      cc->Unref("child_stream");
    });
  }

 private:
  struct Idle {};
  struct Closed {};
  struct SendMessageToTransport {};

  enum class ServerInitialMetadataState : uint8_t {
    // Initial metadata has not been received from the server.
    kNotReceived,
    // Initial metadata has been received from the server via the transport, but
    // has not yet been set on the latch to publish it up the call stack.
    kReceivedButNotSet,
    // Initial metadata has been received from the server via the transport and
    // has been set on the latch to publish it up the call stack.
    kSet,
  };

  class StreamDeleter {
   public:
    explicit StreamDeleter(ClientStream* impl) : impl_(impl) {}
    void operator()(grpc_stream* stream) const {
      if (stream == nullptr) return;
      grpc_transport_destroy_stream(impl_->transport_, stream,
                                    &impl_->stream_destroyed_);
    }

   private:
    ClientStream* impl_;
  };
  using StreamPtr = std::unique_ptr<grpc_stream, StreamDeleter>;

  void SchedulePush() ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    if (std::exchange(scheduled_push_, true)) return;
    IncrementRefCount("push");
    ExecCtx::Run(DEBUG_LOCATION, &push_, absl::OkStatus());
  }

  std::string ActiveOpsString() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    std::vector<std::string> ops;
    if (finished_) ops.push_back("FINISHED");
    // Pushes
    std::vector<std::string> pushes;
    if (push_metadata_) pushes.push_back("metadata");
    if (push_send_message_) pushes.push_back("send_message");
    if (push_recv_message_) pushes.push_back("recv_message");
    if (!pushes.empty()) {
      ops.push_back(
          absl::StrCat(scheduled_push_ ? "push:" : "unscheduled-push:",
                       absl::StrJoin(pushes, ",")));
    } else if (scheduled_push_) {
      ops.push_back("push:nothing");
    }
    // Results from transport
    std::vector<std::string> queued;
    if (server_initial_metadata_state_ ==
        ServerInitialMetadataState::kReceivedButNotSet) {
      queued.push_back("initial_metadata");
    }
    if (queued_trailing_metadata_) queued.push_back("trailing_metadata");
    if (!queued.empty()) {
      ops.push_back(absl::StrCat("queued:", absl::StrJoin(queued, ",")));
    }
    // Send message
    std::string send_message_state = SendMessageString();
    if (send_message_state != "WAITING") {
      ops.push_back(absl::StrCat("send_message:", send_message_state));
    }
    // Receive message
    std::string recv_message_state = RecvMessageString();
    if (recv_message_state != "IDLE") {
      ops.push_back(absl::StrCat("recv_message:", recv_message_state));
    }
    return absl::StrJoin(ops, " ");
  }

  std::string SendMessageString() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    return Match(
        send_message_state_, [](Idle) -> std::string { return "IDLE"; },
        [](Closed) -> std::string { return "CLOSED"; },
        [](const PipeReceiver<MessageHandle>::NextType&) -> std::string {
          return "WAITING";
        },
        [](SendMessageToTransport) -> std::string { return "SENDING"; });
  }

  std::string RecvMessageString() const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mu_) {
    return Match(
        recv_message_state_, [](Idle) -> std::string { return "IDLE"; },
        [](Closed) -> std::string { return "CLOSED"; },
        [](const PendingReceiveMessage&) -> std::string { return "WAITING"; },
        [](const absl::optional<MessageHandle>& message) -> std::string {
          return absl::StrCat(
              "READY:", message.has_value()
                            ? absl::StrCat((*message)->payload()->Length(), "b")
                            : "EOS");
        },
        [](const PipeSender<MessageHandle>::PushType&) -> std::string {
          return "PUSHING";
        });
  }

  Mutex mu_;
  bool requested_metadata_ = false;
  bool push_metadata_ ABSL_GUARDED_BY(mu_) = false;
  bool push_send_message_ ABSL_GUARDED_BY(mu_) = false;
  bool push_recv_message_ ABSL_GUARDED_BY(mu_) = false;
  bool scheduled_push_ ABSL_GUARDED_BY(mu_) = false;
  ServerInitialMetadataState server_initial_metadata_state_
      ABSL_GUARDED_BY(mu_) = ServerInitialMetadataState::kNotReceived;
  bool queued_trailing_metadata_ ABSL_GUARDED_BY(mu_) = false;
  bool finished_ ABSL_GUARDED_BY(mu_) = false;
  CallContext* const call_context_{GetContext<CallContext>()};
  Waker initial_metadata_waker_ ABSL_GUARDED_BY(mu_);
  Waker trailing_metadata_waker_ ABSL_GUARDED_BY(mu_);
  Waker send_message_waker_ ABSL_GUARDED_BY(mu_);
  Waker recv_message_waker_ ABSL_GUARDED_BY(mu_);
  grpc_transport* const transport_;
  grpc_stream_refcount stream_refcount_;
  StreamPtr stream_;
  Latch<ServerMetadata*>* server_initial_metadata_latch_;
  PipeReceiver<MessageHandle>* client_to_server_messages_;
  PipeSender<MessageHandle>* server_to_client_messages_;
  MessageHandle message_to_send_ ABSL_GUARDED_BY(mu_);
  absl::variant<Idle, Closed, PipeReceiver<MessageHandle>::NextType,
                SendMessageToTransport>
      send_message_state_ ABSL_GUARDED_BY(mu_);
  struct PendingReceiveMessage {
    absl::optional<SliceBuffer> payload;
    uint32_t flags;
    bool received = false;
  };
  absl::variant<Idle, PendingReceiveMessage, Closed,
                PipeSender<MessageHandle>::PushType>
      recv_message_state_ ABSL_GUARDED_BY(mu_);
  grpc_closure recv_initial_metadata_ready_ =
      MakeMemberClosure<ClientStream, &ClientStream::RecvInitialMetadataReady>(
          this, DEBUG_LOCATION);
  grpc_closure recv_trailing_metadata_ready_ =
      MakeMemberClosure<ClientStream, &ClientStream::RecvTrailingMetadataReady>(
          this, DEBUG_LOCATION);
  grpc_closure push_ = MakeMemberClosure<ClientStream, &ClientStream::Push>(
      this, DEBUG_LOCATION);
  ClientMetadataHandle client_initial_metadata_;
  ClientMetadataHandle client_trailing_metadata_;
  ServerMetadataHandle server_initial_metadata_;
  ServerMetadataHandle server_trailing_metadata_;
  grpc_transport_stream_op_batch metadata_;
  grpc_closure metadata_batch_done_ =
      MakeMemberClosure<ClientStream, &ClientStream::MetadataBatchDone>(
          this, DEBUG_LOCATION);
  grpc_transport_stream_op_batch send_message_;
  grpc_closure send_message_batch_done_ =
      MakeMemberClosure<ClientStream, &ClientStream::SendMessageBatchDone>(
          this, DEBUG_LOCATION);
  grpc_closure recv_message_batch_done_ =
      MakeMemberClosure<ClientStream, &ClientStream::RecvMessageBatchDone>(
          this, DEBUG_LOCATION);
  grpc_transport_stream_op_batch recv_message_;
  grpc_transport_stream_op_batch_payload batch_payload_{
      GetContext<grpc_call_context_element>()};
  grpc_closure stream_destroyed_ =
      MakeMemberClosure<ClientStream, &ClientStream::StreamDestroyed>(
          this, DEBUG_LOCATION);
};

class ClientConnectedCallPromise {
 public:
  ClientConnectedCallPromise(grpc_transport* transport, CallArgs call_args)
      : impl_(GetContext<Arena>()->New<ClientStream>(transport,
                                                     std::move(call_args))) {}

  ClientConnectedCallPromise(const ClientConnectedCallPromise&) = delete;
  ClientConnectedCallPromise& operator=(const ClientConnectedCallPromise&) =
      delete;
  ClientConnectedCallPromise(ClientConnectedCallPromise&& other) noexcept
      : impl_(std::exchange(other.impl_, nullptr)) {}
  ClientConnectedCallPromise& operator=(
      ClientConnectedCallPromise&& other) noexcept {
    impl_ = std::move(other.impl_);
    return *this;
  }

  static ArenaPromise<ServerMetadataHandle> Make(grpc_transport* transport,
                                                 CallArgs call_args) {
    return ClientConnectedCallPromise(transport, std::move(call_args));
  }

  Poll<ServerMetadataHandle> operator()() { return impl_->PollOnce(); }

 private:
  OrphanablePtr<ClientStream> impl_;
};

template <ArenaPromise<ServerMetadataHandle> (*make_call_promise)(
    grpc_transport*, CallArgs)>
grpc_channel_filter MakeConnectedFilter() {
  // Create a vtable that contains both the legacy call methods (for filter
  // stack based calls) and the new promise based method for creating promise
  // based calls (the latter iff make_call_promise != nullptr).
  // In this way the filter can be inserted into either kind of channel stack,
  // and only if all the filters in the stack are promise based will the call
  // be promise based.
  return {
    connected_channel_start_transport_stream_op_batch,
        make_call_promise == nullptr
            ? nullptr
            : +[](grpc_channel_element* elem, CallArgs call_args,
                 NextPromiseFactory) {
                grpc_transport* transport =
                    static_cast<channel_data*>(elem->channel_data)->transport;
                return make_call_promise(transport, std::move(call_args));
              },
      connected_channel_start_transport_op,
      sizeof(call_data),
      connected_channel_init_call_elem,
      set_pollset_or_pollset_set,
      connected_channel_destroy_call_elem,
      sizeof(channel_data),
      connected_channel_init_channel_elem,
      +[](grpc_channel_stack* channel_stack, grpc_channel_element* elem) {
        /* HACK(ctiller): increase call stack size for the channel to make space
           for channel data. We need a cleaner (but performant) way to do this,
           and I'm not sure what that is yet.
           This is only "safe" because call stacks place no additional data
           after the last call element, and the last call element MUST be the
           connected channel. */
        channel_stack->call_stack_size += grpc_transport_stream_size(
            static_cast<channel_data*>(elem->channel_data)->transport);
      },
      connected_channel_destroy_channel_elem,
      connected_channel_get_channel_info,
      "connected",
  };
}

ArenaPromise<ServerMetadataHandle> MakeTransportCallPromise(
    grpc_transport* transport, CallArgs call_args) {
  return transport->vtable->make_call_promise(transport, std::move(call_args));
}

const grpc_channel_filter kPromiseBasedTransportFilter =
    MakeConnectedFilter<MakeTransportCallPromise>();

const grpc_channel_filter kClientEmulatedFilter =
    MakeConnectedFilter<ClientConnectedCallPromise::Make>();

const grpc_channel_filter kNoPromiseFilter = MakeConnectedFilter<nullptr>();

}  // namespace
}  // namespace grpc_core

bool grpc_add_connected_filter(grpc_core::ChannelStackBuilder* builder) {
  grpc_transport* t = builder->transport();
  GPR_ASSERT(t != nullptr);
  // Choose the right vtable for the connected filter.
  // We can't know promise based call or not here (that decision needs the
  // collaboration of all of the filters on the channel, and we don't want
  // ordering constraints on when we add filters).
  // We can know if this results in a promise based call how we'll create our
  // promise (if indeed we can), and so that is the choice made here.
  if (t->vtable->make_call_promise != nullptr) {
    // Option 1, and our ideal: the transport supports promise based calls, and
    // so we simply use the transport directly.
    builder->AppendFilter(&grpc_core::kPromiseBasedTransportFilter);
  } else if (grpc_channel_stack_type_is_client(builder->channel_stack_type())) {
    // Option 2: the transport does not support promise based calls, but we're
    // on the client and so we have an implementation that we can use to convert
    // to batches.
    builder->AppendFilter(&grpc_core::kClientEmulatedFilter);
  } else {
    // Option 3: the transport does not support promise based calls, and we're
    // on the server so we can't construct promise based calls just yet.
    builder->AppendFilter(&grpc_core::kNoPromiseFilter);
  }
  return true;
}

redpajama_set_name: RedPajamaGithub


text:
use std::{mem, process};
use std::ops::Deref;
use std::os::raw::c_int;

use super::Tag;
use ffi;
use ffi::{MPI_Comm, MPI_Group};

use raw::traits::*;

use datatype::traits::*;

/// Topology traits
pub mod traits {
    pub use super::{Communicator, AsCommunicator, Group};
}

/// Something that has a communicator associated with it
pub trait AsCommunicator {
    /// The type of the associated communicator
    type Out: Communicator;
    /// Returns the associated communicator.
    fn as_communicator(&self) -> &Self::Out;
}

/// Identifies a certain process within a communicator.
pub type Rank = c_int;

/// A built-in communicator, e.g. `MPI_COMM_WORLD`
///
/// # Standard section(s)
///
/// 6.4
#[derive(Copy, Clone, Debug)]
pub struct SystemCommunicator(MPI_Comm);

impl SystemCommunicator {
    /// The 'world communicator'
    ///
    /// Contains all processes initially partaking in the computation.
    ///
    /// # Examples
    /// See `examples/simple.rs`
    pub fn world() -> SystemCommunicator {
        SystemCommunicator::from_raw_unchecked(unsafe_extern_static!(ffi::RSMPI_COMM_WORLD))
    }

    /// If the raw value is the null handle returns `None`
    #[allow(dead_code)]
    fn from_raw(raw: MPI_Comm) -> Option<SystemCommunicator> {
        if raw == unsafe_extern_static!(ffi::RSMPI_COMM_NULL) {
            None
        } else {
            Some(SystemCommunicator(raw))
        }
    }

    /// Wraps the raw value without checking for null handle
    fn from_raw_unchecked(raw: MPI_Comm) -> SystemCommunicator {
        debug_assert_ne!(raw, unsafe_extern_static!(ffi::RSMPI_COMM_NULL));
        SystemCommunicator(raw)
    }
}

unsafe impl AsRaw for SystemCommunicator {
    type Raw = MPI_Comm;
    fn as_raw(&self) -> Self::Raw {
        self.0
    }
}

impl Communicator for SystemCommunicator {}

impl AsCommunicator for SystemCommunicator {
    type Out = SystemCommunicator;
    fn as_communicator(&self) -> &Self::Out {
        self
    }
}

/// A user-defined communicator
///
/// # Standard section(s)
///
/// 6.4
#[derive(Debug)]
pub struct UserCommunicator(MPI_Comm);

impl UserCommunicator {
    /// If the raw value is the null handle returns `None`
    fn from_raw(raw: MPI_Comm) -> Option<UserCommunicator> {
        if raw == unsafe_extern_static!(ffi::RSMPI_COMM_NULL) {
            None
        } else {
            Some(UserCommunicator(raw))
        }
    }

    /// Wraps the raw value without checking for null handle
    fn from_raw_unchecked(raw: MPI_Comm) -> UserCommunicator {
        debug_assert_ne!(raw, unsafe_extern_static!(ffi::RSMPI_COMM_NULL));
        UserCommunicator(raw)
    }
}

impl AsCommunicator for UserCommunicator {
    type Out = UserCommunicator;
    fn as_communicator(&self) -> &Self::Out {
        self
    }
}

unsafe impl AsRaw for UserCommunicator {
    type Raw = MPI_Comm;
    fn as_raw(&self) -> Self::Raw {
        self.0
    }
}

impl Communicator for UserCommunicator {}

impl Drop for UserCommunicator {
    fn drop(&mut self) {
        unsafe {
            ffi::MPI_Comm_free(&mut self.0);
        }
        assert_eq!(self.0, unsafe_extern_static!(ffi::RSMPI_COMM_NULL));
    }
}

/// A color used in a communicator split
#[derive(Copy, Clone, Debug)]
pub struct Color(c_int);

impl Color {
    /// Special color of undefined value
    pub fn undefined() -> Color {
        Color(unsafe_extern_static!(ffi::RSMPI_UNDEFINED))
    }

    /// A color of a certain value
    ///
    /// Valid values are non-negative.
    pub fn with_value(value: c_int) -> Color {
        if value < 0 {
            panic!("Value of color must be non-negative.")
        }
        Color(value)
    }

    /// The raw value understood by the MPI C API
    fn as_raw(&self) -> c_int {
        self.0
    }
}

/// A key used when determining the rank order of processes after a communicator split.
pub type Key = c_int;

/// Communicators are contexts for communication
pub trait Communicator: AsRaw<Raw = MPI_Comm> {
    /// Number of processes in this communicator
    ///
    /// # Examples
    /// See `examples/simple.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.1
    fn size(&self) -> Rank {
        let mut res: Rank = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_size(self.as_raw(), &mut res);
        }
        res
    }

    /// The `Rank` that identifies the calling process within this communicator
    ///
    /// # Examples
    /// See `examples/simple.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.1
    fn rank(&self) -> Rank {
        let mut res: Rank = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_rank(self.as_raw(), &mut res);
        }
        res
    }

    /// Bundles a reference to this communicator with a specific `Rank` into a `Process`.
    ///
    /// # Examples
    /// See `examples/broadcast.rs` `examples/gather.rs` `examples/send_receive.rs`
    fn process_at_rank(self, r: Rank) -> Process<Self>
        where Self: Sized
    {
        assert!(0 <= r && r < self.size());
        Process::by_rank_unchecked(self, r)
    }

    /// Returns an `AnyProcess` identifier that can be used, e.g. as a `Source` in point to point
    /// communication.
    fn any_process(self) -> AnyProcess<Self>
        where Self: Sized
    {
        AnyProcess(self)
    }

    /// A `Process` for the calling process
    fn this_process(self) -> Process<Self>
        where Self: Sized
    {
        let rank = self.rank();
        Process::by_rank_unchecked(self, rank)
    }

    /// Compare two communicators.
    ///
    /// See enum `CommunicatorRelation`.
    ///
    /// # Standard section(s)
    ///
    /// 6.4.1
    fn compare<C: ?Sized>(&self, other: &C) -> CommunicatorRelation
        where C: Communicator
    {
        let mut res: c_int = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_compare(self.as_raw(), other.as_raw(), &mut res);
        }
        res.into()
    }

    /// Duplicate a communicator.
    ///
    /// # Examples
    ///
    /// See `examples/duplicate.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn duplicate(&self) -> UserCommunicator {
        let mut newcomm: MPI_Comm = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_dup(self.as_raw(), &mut newcomm);
        }
        UserCommunicator::from_raw_unchecked(newcomm)
    }

    /// Split a communicator by color.
    ///
    /// Creates as many new communicators as distinct values of `color` are given. All processes
    /// with the same value of `color` join the same communicator. A process that passes the
    /// special undefined color will not join a new communicator and `None` is returned.
    ///
    /// # Examples
    ///
    /// See `examples/split.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn split_by_color(&self, color: Color) -> Option<UserCommunicator> {
        self.split_by_color_with_key(color, Key::default())
    }

    /// Split a communicator by color.
    ///
    /// Like `split()` but orders processes according to the value of `key` in the new
    /// communicators.
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn split_by_color_with_key(&self, color: Color, key: Key) -> Option<UserCommunicator> {
        let mut newcomm: MPI_Comm = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_split(self.as_raw(), color.as_raw(), key, &mut newcomm);
        }
        UserCommunicator::from_raw(newcomm)
    }

    /// Split a communicator collectively by subgroup.
    ///
    /// Proceses pass in a group that is a subgroup of the group associated with the old
    /// communicator. Different processes may pass in different groups, but if two groups are
    /// different, they have to be disjunct. One new communicator is created for each distinct
    /// group. The new communicator is returned if a process is a member of the group he passed in,
    /// otherwise `None`.
    ///
    /// This call is a collective operation on the old communicator so all processes have to
    /// partake.
    ///
    /// # Examples
    ///
    /// See `examples/split.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn split_by_subgroup_collective<G: ?Sized>(&self, group: &G) -> Option<UserCommunicator>
        where G: Group
    {
        let mut newcomm: MPI_Comm = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_create(self.as_raw(), group.as_raw(), &mut newcomm);
        }
        UserCommunicator::from_raw(newcomm)
    }

    /// Split a communicator by subgroup.
    ///
    /// Like `split_by_subgroup_collective()` but not a collective operation.
    ///
    /// # Examples
    ///
    /// See `examples/split.rs`
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn split_by_subgroup<G: ?Sized>(&self, group: &G) -> Option<UserCommunicator>
        where G: Group
    {
        self.split_by_subgroup_with_tag(group, Tag::default())
    }

    /// Split a communicator by subgroup
    ///
    /// Like `split_by_subgroup()` but can avoid collision of concurrent calls
    /// (i.e. multithreaded) by passing in distinct tags.
    ///
    /// # Standard section(s)
    ///
    /// 6.4.2
    fn split_by_subgroup_with_tag<G: ?Sized>(&self, group: &G, tag: Tag) -> Option<UserCommunicator>
        where G: Group
    {
        let mut newcomm: MPI_Comm = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_create_group(self.as_raw(), group.as_raw(), tag, &mut newcomm);
        }
        UserCommunicator::from_raw(newcomm)
    }

    /// The group associated with this communicator
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn group(&self) -> UserGroup {
        let mut group: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Comm_group(self.as_raw(), &mut group);
        }
        UserGroup(group)
    }

    /// Abort program execution
    ///
    /// # Standard section(s)
    ///
    /// 8.7
    fn abort(&self, errorcode: c_int) -> ! {
        unsafe {
            ffi::MPI_Abort(self.as_raw(), errorcode);
        }
        process::abort();
    }
}

impl<T> Communicator for T where T: Deref, T::Target: Communicator {}

/// The relation between two communicators.
///
/// # Standard section(s)
///
/// 6.4.1
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum CommunicatorRelation {
    /// Identical groups and same contexts
    Identical,
    /// Groups match in constituents and rank order, contexts differ
    Congruent,
    /// Group constituents match but rank order differs
    Similar,
    /// Otherwise
    Unequal
}

impl From<c_int> for CommunicatorRelation {
    fn from(i: c_int) -> CommunicatorRelation {
        use self::CommunicatorRelation::*;
        // FIXME: Yuck! These should be made const.
        if i == unsafe_extern_static!(ffi::RSMPI_IDENT) {
            return Identical;
        } else if i == unsafe_extern_static!(ffi::RSMPI_CONGRUENT) {
            return Congruent;
        } else if i == unsafe_extern_static!(ffi::RSMPI_SIMILAR) {
            return Similar;
        } else if i == unsafe_extern_static!(ffi::RSMPI_UNEQUAL) {
            return Unequal;
        }
        panic!("Unknown communicator relation: {}", i)
    }
}

/// Identifies a process by its `Rank` within a certain communicator.
#[derive(Copy, Clone, Debug)]
pub struct Process<C>
    where C: Communicator
{
    comm: C,
    rank: Rank
}

impl<C> Process<C> where C: Communicator
{
    #[allow(dead_code)]
    fn by_rank(c: C, r: Rank) -> Option<Self> {
        if r != unsafe_extern_static!(ffi::RSMPI_PROC_NULL) {
            Some(Process { comm: c, rank: r })
        } else {
            None
        }
    }

    fn by_rank_unchecked(c: C, r: Rank) -> Self {
        Process { comm: c, rank: r }
    }

    /// The process rank
    pub fn rank(&self) -> Rank {
        self.rank
    }
}

impl<C> AsCommunicator for Process<C> where C: Communicator
{
    type Out = C;
    fn as_communicator(&self) -> &Self::Out {
        &self.comm
    }
}

/// Identifies an arbitrary process that is a member of a certain communicator, e.g. for use as a
/// `Source` in point to point communication.
#[derive(Copy, Clone, Debug)]
pub struct AnyProcess<C>(C) where C: Communicator;

impl<C> AsCommunicator for AnyProcess<C> where C: Communicator
{
    type Out = C;
    fn as_communicator(&self) -> &Self::Out {
        &self.0
    }
}

/// A built-in group, e.g. `MPI_GROUP_EMPTY`
///
/// # Standard section(s)
///
/// 6.2.1
#[derive(Copy, Clone, Debug)]
pub struct SystemGroup(MPI_Group);

impl SystemGroup {
    /// An empty group
    pub fn empty() -> SystemGroup {
        SystemGroup(unsafe_extern_static!(ffi::RSMPI_GROUP_EMPTY))
    }
}

unsafe impl AsRaw for SystemGroup {
    type Raw = MPI_Group;
    fn as_raw(&self) -> Self::Raw {
        self.0
    }
}

impl Group for SystemGroup {}

/// A user-defined group of processes
///
/// # Standard section(s)
///
/// 6.2.1
#[derive(Debug)]
pub struct UserGroup(MPI_Group);

impl Drop for UserGroup {
    fn drop(&mut self) {
        unsafe {
            ffi::MPI_Group_free(&mut self.0);
        }
        assert_eq!(self.0, unsafe_extern_static!(ffi::RSMPI_GROUP_NULL));
    }
}

unsafe impl AsRaw for UserGroup {
    type Raw = MPI_Group;
    fn as_raw(&self) -> Self::Raw {
        self.0
    }
}

impl Group for UserGroup {}

/// Groups are collections of parallel processes
pub trait Group: AsRaw<Raw = MPI_Group> {
    /// Group union
    ///
    /// Constructs a new group that contains all members of the first group followed by all members
    /// of the second group that are not also members of the first group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn union<G>(&self, other: &G) -> UserGroup
        where G: Group
    {
        let mut newgroup: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_union(self.as_raw(), other.as_raw(), &mut newgroup);
        }
        UserGroup(newgroup)
    }

    /// Group intersection
    ///
    /// Constructs a new group that contains all processes that are members of both the first and
    /// second group in the order they have in the first group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn intersection<G>(&self, other: &G) -> UserGroup
        where G: Group
    {
        let mut newgroup: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_intersection(self.as_raw(), other.as_raw(), &mut newgroup);
        }
        UserGroup(newgroup)
    }

    /// Group difference
    ///
    /// Constructs a new group that contains all members of the first group that are not also
    /// members of the second group in the order they have in the first group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn difference<G>(&self, other: &G) -> UserGroup
        where G: Group
    {
        let mut newgroup: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_difference(self.as_raw(), other.as_raw(), &mut newgroup);
        }
        UserGroup(newgroup)
    }

    /// Subgroup including specified ranks
    ///
    /// Constructs a new group where the process with rank `ranks[i]` in the old group has rank `i`
    /// in the new group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn include(&self, ranks: &[Rank]) -> UserGroup {
        let mut newgroup: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_incl(self.as_raw(), ranks.count(), ranks.as_ptr(), &mut newgroup);
        }
        UserGroup(newgroup)
    }

    /// Subgroup including specified ranks
    ///
    /// Constructs a new group containing those processes from the old group that are not mentioned
    /// in `ranks`.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.2
    fn exclude(&self, ranks: &[Rank]) -> UserGroup {
        let mut newgroup: MPI_Group = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_excl(self.as_raw(), ranks.count(), ranks.as_ptr(), &mut newgroup);
        }
        UserGroup(newgroup)
    }

    /// Number of processes in the group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.1
    fn size(&self) -> Rank {
        let mut res: Rank = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_size(self.as_raw(), &mut res);
        }
        res
    }

    /// Rank of this process within the group.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.1
    fn rank(&self) -> Option<Rank> {
        let mut res: Rank = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_rank(self.as_raw(), &mut res);
        }
        if res == unsafe_extern_static!(ffi::RSMPI_UNDEFINED) {
            None
        } else {
            Some(res)
        }
    }

    /// Find the rank in group `other' of the process that has rank `rank` in this group.
    ///
    /// If the process is not a member of the other group, returns `None`.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.1
    fn translate_rank<G>(&self, rank: Rank, other: &G) -> Option<Rank>
        where G: Group
    {
        let mut res: Rank = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_translate_ranks(self.as_raw(), 1, &rank, other.as_raw(), &mut res);
        }
        if res == unsafe_extern_static!(ffi::RSMPI_UNDEFINED) {
            None
        } else {
            Some(res)
        }
    }

    /// Find the ranks in group `other' of the processes that have ranks `ranks` in this group.
    ///
    /// If a process is not a member of the other group, returns `None`.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.1
    fn translate_ranks<G>(&self, ranks: &[Rank], other: &G) -> Vec<Option<Rank>>
        where G: Group
    {
        ranks.iter().map(|&r| self.translate_rank(r, other)).collect()
    }

    /// Compare two groups.
    ///
    /// # Standard section(s)
    ///
    /// 6.3.1
    fn compare<G>(&self, other: &G) -> GroupRelation
        where G: Group
    {
        let mut relation: c_int = unsafe { mem::uninitialized() };
        unsafe {
            ffi::MPI_Group_compare(self.as_raw(), other.as_raw(), &mut relation);
        }
        relation.into()
    }
}

/// The relation between two groups.
///
/// # Standard section(s)
///
/// 6.3.1
#[derive(Copy, Clone, PartialEq, Eq, Debug)]
pub enum GroupRelation {
    /// Identical group members in identical order
    Identical,
    /// Identical group members in different order
    Similar,
    /// Otherwise
    Unequal
}

impl From<c_int> for GroupRelation {
    fn from(i: c_int) -> GroupRelation {
        use self::GroupRelation::*;
        // FIXME: Yuck! These should be made const.
        if i == unsafe_extern_static!(ffi::RSMPI_IDENT) {
            return Identical;
        } else if i == unsafe_extern_static!(ffi::RSMPI_SIMILAR) {
            return Similar;
        } else if i == unsafe_extern_static!(ffi::RSMPI_UNEQUAL) {
            return Unequal;
        }
        panic!("Unknown group relation: {}", i)
    }
}


text:
<!DOCTYPE html>

        <meta name="viewport" content="width=device-width, initial-scale=1">
        <title>LoLDex</title>

                Back

Fill In Champions Name

Place Image here

Copyright - Mark-Jan de Jong & Milan Damen


text:
using System.Collections.Generic;
using Nop.Core.Domain.Localization;

namespace Nop.Core.Domain.Catalog
{
    /// <summary>
    /// Represents a specification attribute option
    /// </summary>
    public partial class SpecificationAttributeOption : BaseEntity, ILocalizedEntity
    {
        private ICollection<ProductSpecificationAttribute> _productSpecificationAttributes;

        /// <summary>
        /// Gets or sets the specification attribute identifier
        /// </summary>
        public int SpecificationAttributeId { get; set; }

        /// <summary>
        /// Gets or sets the name
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Gets or sets the display order
        /// </summary>
        public int DisplayOrder { get; set; }

        /// <summary>
        /// Gets or sets the specification attribute
        /// </summary>
        public virtual SpecificationAttribute SpecificationAttribute { get; set; }

        /// <summary>
        /// Gets or sets the product specification attribute
        /// </summary>
        public virtual ICollection<ProductSpecificationAttribute> ProductSpecificationAttributes
        {
            get { return _productSpecificationAttributes ?? (_productSpecificationAttributes = new List<ProductSpecificationAttribute>()); }
            protected set { _productSpecificationAttributes = value; }
        }
    }
}


text:
"""Generated class for state_discovery.json"""
from .state_discovery_family import FamilyDiscoveryState
from .state_discovery_family import FamilyDiscoveryState

class DiscoveryState:
  """Generated schema class"""

  def __init__(self):
    self.enumeration = None
    self.families = None

  @staticmethod
  def from_dict(source):
    if not source:
      return None
    result = DiscoveryState()
    result.enumeration = FamilyDiscoveryState.from_dict(source.get('enumeration'))
    result.families = FamilyDiscoveryState.map_from(source.get('families'))
    return result

  @staticmethod
  def map_from(source):
    if not source:
      return None
    result = {}
    for key in source:
      result[key] = DiscoveryState.from_dict(source[key])
    return result

  @staticmethod
  def expand_dict(input):
    result = {}
    for property in input:
      result[property] = input[property].to_dict() if input[property] else {}
    return result

  def to_dict(self):
    result = {}
    if self.enumeration:
      result['enumeration'] = self.enumeration.to_dict() # 4
    if self.families:
      result['families'] = FamilyDiscoveryState.expand_dict(self.families) # 2
    return result


text:
using System;
using System.Collections.Specialized;
using System.Globalization;
using System.Web;

namespace HttpParamsUtility
{
    /// <summary>
    /// Convienience class wrapping access to an HTTP friendly <see cref="NameValueCollection"/> with a fluent interface.
    /// </summary>
    public class HttpParams
    {
        private readonly NameValueCollection parameters;

        /// <summary>
        /// Initializes a new instance of the <see cref="HttpParams" /> class.
        /// </summary>
        public HttpParams()
        {
            parameters = HttpUtility.ParseQueryString("");
        }

        /// <summary>
        /// Gets the number of key/value pairs contained in the NameObjectCollectionBase instance.
        /// </summary>
        /// <value>
        /// The count.
        /// </value>
        public int Count => parameters.Count;

        /// <summary>
        /// Gets a <see cref="NameObjectCollectionBase.KeysCollection" /> instance that contains all the keys in the NameObjectCollectionBase instance.
        /// </summary>
        /// <value>
        /// The keys.
        /// </value>
        public virtual NameObjectCollectionBase.KeysCollection Keys => parameters.Keys;

        /// <summary>
        /// Adds an entry with the specified key and value into the <see cref="NameValueCollection" /> instance.
        /// </summary>
        /// <param name="c">The nave value collection.</param>
        /// <returns></returns>
        public HttpParams Add(NameValueCollection c)
        {
            parameters.Add(c);

            return this;
        }

        /// <summary>
        /// Adds an entry with the specified key and value into the <see cref="NameValueCollection" /> instance.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The int value.</param>
        /// <returns></returns>
        /// <remarks>The value is converted to a string with the <see cref="CultureInfo.InvariantCulture"/> </remarks>
        public HttpParams Add(string name, int value)
        {
            parameters.Add(name, value.ToString(CultureInfo.InvariantCulture));

            return this;
        }

        /// <summary>
        /// Adds an entry with the specified key and value into the <see cref="NameValueCollection" /> instance.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The Int64 value.</param>
        /// <returns></returns>
        /// <remarks>The value is converted to a string with the <see cref="CultureInfo.InvariantCulture"/> </remarks>
        public HttpParams Add(string name, Int64 value)
        {
            parameters.Add(name, value.ToString(CultureInfo.InvariantCulture));

            return this;
        }

        /// <summary>
        /// Adds an entry with the specified key and value into the <see cref="NameValueCollection" /> instance.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public HttpParams Add(string name, string value)
        {
            parameters.Add(name, value);

            return this;
        }

        /// <summary>
        /// Adds an entry with specified key and value into to the <see cref="NameValueCollection"/> only if the value is not null or empty.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="value">The value.</param>
        /// <returns></returns>
        public HttpParams AddWhenSet(string name, string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                parameters.Add(name, value);
            }

            return this;
        }

        /// <summary>
        /// Removes the entries with the specified key from the NameObjectCollectionBase instance.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <returns></returns>
        public HttpParams Remove(string name)
        {
            parameters.Remove(name);

            return this;
        }

        /// <summary>
        /// Removes all entries from the NameObjectCollectionBase instance.
        /// </summary>
        /// <returns></returns>
        public HttpParams Clear()
        {
            parameters.Clear();

            return this;
        }

        /// <summary>
        /// Serializes this instance as HTTP friendly and encoded parameters.
        /// </summary>
        /// <returns>
        /// A <see cref="System.String" /> that represents this instance.
        /// </returns>
        public override string ToString()
        {
            return parameters.ToString();
        }

        /// <summary>
        /// Return this instance's internal name value collection.
        /// </summary>
        /// <returns></returns>
        public NameValueCollection ToNameValueCollection()
        {
            return parameters;
        }
    }
}


text:
cask 'klayout' do
  version '0.25.7'
  sha256 'd05d090956700e9f5349c1f7ac1773a6a1df893263ddd81097135610e49dd49e'

  # klayout.org was verified as official when first introduced to the cask
  url "https://www.klayout.org/downloads/MacOS/klayout-#{version}-macOS-Mojave-1-Qt5120mp.dmg"
  name 'KLayout'
  homepage 'https://www.klayout.de/'

  depends_on macos: '>= :mojave'

  suite 'KLayout'

  preflight do
    # There is no sub-folder in the DMG; the root *is* the folder
    FileUtils.mv(staged_path.children, staged_path.join('KLayout').tap(&:mkpath))
  end

  uninstall pkgutil: 'klayout.de',
            quit:    'klayout.de'
end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Coniosporium arundinae var. arundinae

### Remarks
null


text:
import ChevronDown20 from '@carbon/icons-react/lib/chevron--down/20';
import { settings } from 'carbon-components';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';

const { prefix } = settings;

const SideNavSwitcher = React.forwardRef(function SideNavSwitcher(props, ref) {
  const { className: customClassName, labelText, onChange, options } = props;
  const className = cx(`${prefix}--side-nav__switcher`, customClassName);
  // Note for usage around `onBlur`: https://github.com/evcohen/eslint-plugin-jsx-a11y/blob/master/docs/rules/no-onchange.md
  return (

      <label
        htmlFor="side-nav-switcher"
        className={`${prefix}--assistive-text`}>
        {labelText}

      <select
        id="carbon-side-nav-switcher"
        className={`${prefix}--side-nav__select`}
        defaultValue=""
        onBlur={onChange}
        onChange={onChange}
        ref={ref}>
        <option
          className={`${prefix}--side-nav__option`}
          disabled
          hidden
          value="">
          {labelText}
        </option>
        {options.map(option => (
          <option
            key={option}
            className={`${prefix}--side-nav__option`}
            value={option}>
            {option}
          </option>
        ))}
      </select>
      <div className={`${prefix}--side-nav__switcher-chevron`}>
        <ChevronDown20 />

  );
});

SideNavSwitcher.propTypes = {
  /**
   * Provide an optional class to be applied to the containing node
   */
  className: PropTypes.string,

  /**
   * Provide the label for the switcher. This will be the firt visible option
   * when someone views this control
   */
  labelText: PropTypes.string.isRequired,

  /**
   * Provide a callback function that is called whenever the switcher value is
   * updated
   */
  onChange: PropTypes.func,

  /**
   * Provide an array of options to be rendered in the switcher as an
   * `<option>`. The text value will be what is displayed to the user and is set
   * as the `value` prop for each `<option>`.
   */
  options: PropTypes.arrayOf(PropTypes.string).isRequired,
};

export default SideNavSwitcher;


text:
package nz.cri.gns.springs.db;

import java.io.Serializable;

import com.j256.ormlite.field.DatabaseField;

public abstract class PersistentObject implements Serializable {

	private static final long serialVersionUID = 4338757173717410713L;

	@DatabaseField(generatedId = true)
	protected Long id;

	@DatabaseField protected Long createdDate = System.currentTimeMillis();
	@DatabaseField protected Long updatedDate = System.currentTimeMillis();
	@DatabaseField protected Status status = Status.NEW;

	/**
	 * NEW: object has not been exported since creation
	 * EXPORTED: object has been exported, but has not been updated since last export
	 * UPDATE: object has been updated since last export
	 * @author duncanw
	 */
	public enum Status {
		NEW, UPDATED, EXPORTED
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public Long getCreatedDate() {
		return createdDate;
	}

	public void setCreatedDate(Long createdDate) {
		this.createdDate = createdDate;
	}

	public Long getUpdatedDate() {
		return updatedDate;
	}

	public void setUpdatedDate(Long updatedDate) {
		this.updatedDate = updatedDate;
	}

	public Status getStatus() {
		return status;
	}

	public void setStatus(Status status) {
		this.status = status;
	};

}


text:
The design and planning of the app of own idea.

## Please check prototype_and_design_doc.pdf and updated-prototype directory for updated product design doc and prototype.

prototype_and_design_doc.pdf is the updated version of App prototype designed for App showcase event to be held at Google India , Bangalore in September.


text:
<?xml version="1.0" encoding="utf-8"?>
<openerp>
<data noupdate="0">

    <record id="group_account_payment" model="res.groups">
        <field name="name">Accounting / Payments</field>
        <field name="users" eval="[(4, ref('base.user_root'))]"/>
    </record>
    <record id="account.group_account_invoice" model="res.groups">
        <field name="implied_ids" eval="[(4, ref('group_account_payment'))]"/>
    </record>

</data>
<data noupdate="1">

    <record id="payment_mode_comp_rule" model="ir.rule">
        <field name="name">Payment Mode company rule</field>
        <field name="model_id" ref="model_payment_mode"/>
        <field eval="True" name="global"/>
        <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field>
    </record>

    <record id="payment_order_comp_rule" model="ir.rule">
        <field name="name">Payment order multi company rule</field>
        <field name="model_id" ref="model_payment_order"/>
        <field eval="True" name="global"/>
        <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field>
    </record>

    <record id="payment_line_comp_rule" model="ir.rule">
        <field name="name">Payment line multi company rule</field>
        <field name="model_id" ref="model_payment_line"/>
        <field eval="True" name="global"/>
        <field name="domain_force">['|',('company_id','=',False),('company_id','child_of',[user.company_id.id])]</field>
    </record>

</data>
</openerp>


text:
<?php
	$curdir = dirname(__FILE__);
	include_once "$curdir/fhq_class_security.php";
	include_once "$curdir/fhq_class_database.php";
	include_once "$curdir/fhq_class_mail.php";

	//---------------------------------------------------------------------
	class fhq_teams
	{
		function echo_insert_form()
		{
			/*$content = '
				Add News

				<textarea class="full_text" id="news_text"></textarea>

        <input type="checkbox" id="send_as_copies" />  Send as copies

				Add
				';
      */
			echo $content;
		}

		function add_team($text, $send_as_copies)
		{
			$security = new fhq_security();
			$db = new fhq_database();
			if( !$security->isAdmin() && !$security->isTester() && !$security->isGod())
				exit;

			/*$query = 'insert into news (text, author, datetime_) values(\''.base64_encode($text).'\','.$security->iduser().', now())';
			$result = $db->query( $query );

			$mail = new fhq_mail();
			$mail->send_to_all('Free-Hack-Quest: News', $text, $send_as_copies);*/
		}

		function save_team($id_news, $text)
		{
			$security = new fhq_security();
			$db = new fhq_database();
			if( !$security->isAdmin() && !$security->isTester() && !$security->isGod())
				exit;

			/*$query = 'UPDATE news SET text = \''.base64_encode($text).'\', datetime_ = now() WHERE id = '.$id_news.';';
			$result = $db->query( $query );

			$mail = new fhq_mail();
			$mail->send_to_all('Free-Hack-Quest: News', $text, true);*/
		}

		function echo_teams()
		{
			$security = new fhq_security();
			$db = new fhq_database();
			// $allow_edit = $security->isAdmin() || $security->isTester() || $security->isGod();

			// $query = 'SELECT * FROM games INNER JOIN user ON news.author = user.iduser ORDER BY datetime_ DESC LIMIT 0,5;';
			// WHERE end_date < NOW()
			$query = 'SELECT * FROM teams INNER JOIN user ON teams.owner = user.iduser ORDER BY date_change DESC LIMIT 0,10;';
			$result = $db->query( $query );
			echo "Teams:

						Logo
						Name
						Owner

			";

			$bClass = false;
			while ($row = mysql_fetch_row($result, MYSQL_ASSOC)) // Data
			{
				$id_news = $row['id'];
				$name = $row['title'];
				$logo = $row['logo'];
				$owner = $row['nick'];

				$strclass = '';
				if ($bClass)
					$strclass = " class='alt' ";
				$bClass = !$bClass;

				echo "

$name

					$owner

";
			}
			echo "
";

			if ($security->isAdmin()) {

			}
		}
	}
?>


text:
FuzzyOctoTribble.DialogBox = function (spec, my) {
    var that = {};
    var dialog = spec.dialogContent;
    var onComplete = spec.onComplete;
    var displayedText = "";
    my = my || {};

    var $dialogContainer = $(document.createElement('div'));
    $dialogContainer.addClass('dialog-container text-font');
    var $innerDialog = $(document.createElement('div'));
    $dialogContainer.append($innerDialog);
    var $next = $(document.createElement('div'));
    $next.text('>');
    $next.css('position', 'absolute');
    $next.css('bottom', '0px');
    $next.css('right', '10px');
    $next.css('font-size', '30px');
    $next.hide();
    $dialogContainer.append($next);
    $('.game-window').append($dialogContainer);

    var showDialog = function () {
        $innerDialog.empty();
        var writer = dialog.split(' ');
        var showArrow = false;
        for (var i = 0; i < writer.length; i++) {
            var currentText = $innerDialog.text();
            $innerDialog.text(currentText + ' ' + writer[i]);
            if ($innerDialog.innerHeight() > $dialogContainer.height()) {
                $innerDialog.text(currentText);
                writer.splice(0, i);
                showArrow = true;
                dialog = writer.join(' ');
                break;
            }
        }

        displayedText = $innerDialog.text();

        if (showArrow) {
            $next.show();
        }
        else {
            $next.hide();
            dialog = '';
        }

    }

    var nextDialog = function () {
        if (dialog) {
            showDialog();
        }
        else {
            $dialogContainer.remove();
            $(window).unbind('resize', resizeDialog);
            if (that.onComplete) {
                that.onComplete();
            }
            if (onComplete) {
                onComplete();
            }
        }
    }

    resizeDialog = function () {
        if (dialog) {
            dialog = displayedText + ' ' + dialog;
        } else {
            dialog = displayedText;
        }

        nextDialog();
    }

    $(window).bind('resize', resizeDialog);

    that.confirm = function () {
        nextDialog();
    }

    $dialogContainer.on('click', function () {
        that.confirm();
    });

    showDialog();

    return that;
}


text:
FROM python:3.6-slim

COPY requirements.txt .
RUN python3 -m pip install -r \
    requirements.txt --quiet --no-cache-dir \
    && rm -f requirements.txt

ENV APP_HOME /app
COPY src $APP_HOME
WORKDIR $APP_HOME

ENTRYPOINT ["python", "train.py"]


text:
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/PuerkitoBio/goquery"
	"github.com/dpapathanasiou/go-recaptcha"
	"io/ioutil"
	"log"
	"net/http"
	"net/smtp"
	"regexp"
	"strconv"
	"strings"
	"text/template"
)

type ParsedResponse struct {
	Success bool     `json:"success"`
	Links   []map[string]string `json:"links"`
}

type EmailUser struct {
	Username    string
	Password    string
	EmailServer string
	Port        int
}

type SmtpTemplateData struct {
	From    string
	To      string
	Subject string
	Body    string
}

type Configuration struct {
	Smtp                EmailUser
	RecaptchaPrivateKey string
}

type ReCaptcha struct {
	Response  string
	Challenge string
}

type SendEmailData struct {
	YourEmail string
	YourName  string
	Feedback  string
	Captcha   ReCaptcha
}

var conf Configuration

func sendMail(emailUser EmailUser, auth smtp.Auth, from string, to string, subject string, body string) error {
	const emailTemplate = `From: {{.From}}
To: {{.To}}
Subject: {{.Subject}}

{{.Body}}

Sincerely,

{{.From}}
`
	var err error
	var doc bytes.Buffer
	context := &SmtpTemplateData{from, to, subject, body}
	t := template.New("emailTemplate")
	if t, err = t.Parse(emailTemplate); err != nil {
		log.Print("error trying to parse mail template ", err)
	}
	if err = t.Execute(&doc, context); err != nil {
		log.Print("error trying to execute mail template ", err)
	}
	err = smtp.SendMail(emailUser.EmailServer+":"+strconv.Itoa(emailUser.Port),
		auth,
		emailUser.Username,
		[]string{"nathanleclaire@gmail.com"},
		doc.Bytes())
	if err != nil {
		log.Print("ERROR: attempting to send a mail ", err)
	}

	return nil
}

func readConfigurationFile(filepath string) Configuration {
	var (
		rawConfigurationJson []byte
		conf Configuration
		err error
	)
	if rawConfigurationJson, err = ioutil.ReadFile(filepath); err != nil {
		log.Print("error reading smtp config file ", err)
	}
	if err = json.Unmarshal(rawConfigurationJson, &conf); err != nil {
		log.Print("error unmarshalling config ", err)
	}
	return conf
}

func connectToSmtpServer(emailUser EmailUser) smtp.Auth {
	auth := smtp.PlainAuth("", emailUser.Username, emailUser.Password, emailUser.EmailServer)
	return auth
}

func getFailedSlurpResponse() []byte {
	var (
		failResponseJSON []byte
		err error
	)
	failResponse := &ParsedResponse{false, nil}
	if failResponseJSON, err = json.Marshal(failResponse); err != nil {
		log.Print("something went really weird in attempt to marshal a fail json ", err)
		failResponseJSON, _ = json.Marshal(nil)
	}
	return failResponseJSON
}

func slurpHandler(w http.ResponseWriter, r *http.Request) {
	urlToScrape := strings.ToLower(r.URL.Query().Get("urlToScrape"))
	var (
		crossDomainRegex *regexp.Regexp
		doc *goquery.Document
		err error
		parsedResponseJSON []byte
		link map[string]string
		href string
		exists bool
		content string
		links []map[string]string
	)

	if doc, err = goquery.NewDocument(urlToScrape); err == nil {
		if crossDomainRegex, err = regexp.Compile(`^http`); err != nil {
			log.Printf("issue compiling regular expression to validate cross domain URLs")
		}

		doc.Find("a").Each(func(i int, selection *goquery.Selection) {
			link = make(map[string]string)
			if href, exists = selection.Attr("href"); !exists {
				log.Print("href does not exist for: ", selection)
				href = ""
			}
			content = selection.Contents().Text()
			if !crossDomainRegex.Match([]byte(href)) {
				href = urlToScrape+href // same origin link
			}
			link["href"] = href
			link["content"] = content
			links = append(links, link)
		})
		parsedResponse := &ParsedResponse{true, links}
		if parsedResponseJSON, err = json.Marshal(parsedResponse); err != nil {
			parsedResponseJSON = getFailedSlurpResponse()
		}
	} else {
		log.Print("error querying for document: ", urlToScrape, "err : ", err)
		parsedResponseJSON = getFailedSlurpResponse()
	}

	w.Write(parsedResponseJSON)

}

func checkHandler(w http.ResponseWriter, r *http.Request) {
	var (
		err error
		externalServerResponse *http.Response
		responseJSON []byte
	)
	urlToCheck := r.URL.Query().Get("urlToCheck")
	if externalServerResponse, err = http.Get(urlToCheck); err != nil {
		log.Print("error getting in checkHandler ", urlToCheck)
	}

	response := map[string]interface{}{
		"status":     externalServerResponse.Status,
		"statusCode": externalServerResponse.StatusCode,
	}

	if responseJSON, err = json.Marshal(response); err != nil {
		log.Print("error Marshalling check response json: ", err)
	}
	w.Write(responseJSON)
}

func emailHandlerClosure(auth smtp.Auth, recaptchaPrivateKey string, emailUser EmailUser) http.HandlerFunc {
	// Use a closure so we can pass auth to the handler
	return (func(w http.ResponseWriter, r *http.Request) {

		var jsonResponse []byte
		var err error
		response := map[string]interface{}{
			"success": true,
		}
		dec := json.NewDecoder(r.Body)
		contactData := SendEmailData{}
		if dec.Decode(&contactData) != nil {
			log.Print(err)
			response["success"] = false
		}

		// call the recaptcha server
		recaptcha.Init(recaptchaPrivateKey)
		captchaIsValid := recaptcha.Confirm(r.RemoteAddr, contactData.Captcha.Challenge, contactData.Captcha.Response)

		if captchaIsValid {
			go sendMail(emailUser,
				auth,
				contactData.YourName+fmt.Sprintf(" <%s>", contactData.YourEmail),
				"Nathan LeClaire <nathan.leclaire@gmail.com>",
				"CFBL Feedback from "+contactData.YourName,
				contactData.Feedback)
		} else {
			response["success"] = false
		}
		if jsonResponse, err = json.Marshal(response); err != nil {
			log.Print("marshalling r ", err)
		}
		w.Write(jsonResponse)
	})
}

func main() {
	conf = readConfigurationFile("conf/conf.json")
	auth := connectToSmtpServer(conf.Smtp)
	http.HandleFunc("/slurp", slurpHandler)
	http.HandleFunc("/check", checkHandler)
	http.HandleFunc("/email", emailHandlerClosure(auth, conf.RecaptchaPrivateKey, conf.Smtp))
	http.Handle("/", http.FileServer(http.Dir("../client/app")))
	http.Handle("/css/", http.FileServer(http.Dir("../client/app")))
	http.Handle("/img/", http.FileServer(http.Dir("../client/app")))
	http.Handle("/lib/", http.FileServer(http.Dir("../client/app")))
	http.Handle("/partials/", http.FileServer(http.Dir("../client/app")))
	http.Handle("/js/", http.FileServer(http.Dir("../client/app")))
	if err := http.ListenAndServe(":8000", nil); err != nil {
		log.Fatal("ListenAndServe: ", err)
	}
}


text:
from __future__ import unicode_literals

from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion

class Migration(migrations.Migration):

    initial = True

    dependencies = [
        migrations.swappable_dependency(settings.AUTH_USER_MODEL),
        ('links', '0001_initial'),
    ]

    operations = [
        migrations.CreateModel(
            name='Vote',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('created_on', models.DateTimeField(auto_now_add=True, verbose_name='Created on')),
                ('updated_on', models.DateTimeField(auto_now=True, verbose_name='Updated on')),
                ('link', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='links.Link', verbose_name='Link')),
                ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, verbose_name='User')),
            ],
            options={
                'verbose_name': 'Vote',
                'verbose_name_plural': 'Votes',
            },
        ),
        migrations.AlterUniqueTogether(
            name='vote',
            unique_together=set([('user', 'link')]),
        ),
    ]


text:
require "rubygems"
require "bundler/setup"
require "sinatra"
require "yaml"
require "json"
require "uri"
require "net/http"
require "digest/sha1"

$LOAD_PATH.unshift(File.expand_path("../", __FILE__))

if File.exists?("./config/config.yml")
  $config = YAML::load_file("./config/config.yml")
else
  $config = {}
end

$hue = YAML::load_file("./config/hue.yml")

Dir["./controllers/*.rb"].each {|f| require f}


text:
{% extends "/pyshop/layout.html" %}

{% block maintitle %}{% endblock %}
{% block subnav %}{% endblock %}

{% block nav_bar %}{% endblock %}
{% block nav_third %}{% endblock %}

{% block toolbar %}
{% endblock %}

{% block main %}

Install with QPYPI

You can install or upgrade Python packages for android platform through qpython's qpypi.

QPYPI

Install with official pypi

Besides qpypi, you can install many pure python packages from python's pypi through pip console manually

Pip console

{% endblock %}


text:
[Helm](https://helm.sh) is a package manager for Kubernetes that automates the release and management of software on Kubernetes. The Telepresence Traffic Manager can be installed via a Helm chart with a few simple steps.

**Note** that installing the Traffic Manager through Helm will prevent `telepresence connect` from ever upgrading it. If you wish to upgrade a Traffic Manager that was installed via the Helm chart, please see the steps [below](#upgrading-the-traffic-manager)

For more details on what the Helm chart installs and what can be configured, see the Helm chart [README](https://github.com/telepresenceio/telepresence/tree/release/v2/charts/telepresence).

## Before you begin

The Telepresence Helm chart is hosted by Ambassador Labs and published at `https://app.getambassador.io`.

Start by adding this repo to your Helm client with the following command:

```shell
helm repo add datawire  https://app.getambassador.io
helm repo update
```

## Install with Helm

When you run the Helm chart, it installs all the components required for the Telepresence Traffic Manager.

1. If you are installing the Telepresence Traffic Manager **for the first time on your cluster**, create the `ambassador` namespace in your cluster:

   ```shell
   kubectl create namespace ambassador
   ```

2. Install the Telepresence Traffic Manager with the following command:

   ```shell
   helm install traffic-manager --namespace ambassador datawire/telepresence
   ```

### Install into custom namespace

The Helm chart supports being installed into any namespace, not necessarily `ambassador`. Simply pass a different `namespace` argument to `helm install`.
For example, if you wanted to deploy the traffic manager to the `staging` namespace:

```bash
helm install traffic-manager --namespace staging datawire/telepresence
```

Note that users of Telepresence will need to configure their kubeconfig to find this installation of the Traffic Manager:

```yaml
apiVersion: v1
clusters:
- cluster:
    server: https://127.0.0.1
    extensions:
    - name: telepresence.io
      extension:
        manager:
          namespace: staging
  name: example-cluster
```

See [the kubeconfig documentation](../../reference/config#manager) for more information.

### Upgrading the Traffic Manager.

Versions of the Traffic Manager Helm chart are coupled to the versions of the Telepresence CLI that they are intended for.
Thus, for example, if you wish to use Telepresence `v2.4.0`, you'll need to install version `v2.4.0` of the Traffic Manager Helm chart.

Upgrading the Traffic Manager is the same as upgrading any other Helm chart; for example, if you installed the release into the `ambassador` namespace, and you just wished to upgrade it to the latest version without changing any configuration values:

```shell
helm repo up
helm upgrade traffic-manager datawire/telepresence --reuse-values --namespace ambassador
```

If you want to upgrade the Traffic-Manager to a specific version, add a `--version` flag with the version number to the upgrade command. For example: `--version v2.4.1`

## RBAC

### Installing a namespace-scoped traffic manager

You might not want the Traffic Manager to have permissions across the entire kubernetes cluster, or you might want to be able to install multiple traffic managers per cluster (for example, to separate them by environment).
In these cases, the traffic manager supports being installed with a namespace scope, allowing cluster administrators to limit the reach of a traffic manager's permissions.

For example, suppose you want a Traffic Manager that only works on namespaces `dev` and `staging`.
To do this, create a `values.yaml` like the following:

```yaml
managerRbac:
  create: true
  namespaced: true
  namespaces:
  - dev
  - staging
```

This can then be installed via:

```bash
helm install traffic-manager --namespace staging datawire/telepresence -f ./values.yaml
```

**NOTE** Do not install namespace-scoped Traffic Managers and a global Traffic Manager in the same cluster, as it could have unexpected effects.

#### Namespace collision detection

The Telepresence Helm chart will try to prevent namespace-scoped Traffic Managers from managing the same namespaces.
It will do this by creating a ConfigMap, called `traffic-manager-claim`, in each namespace that a given install manages.

So, for example, suppose you install one Traffic Manager to manage namespaces `dev` and `staging`, as:

```bash
helm install traffic-manager --namespace dev datawire/telepresence --set 'managerRbac.namespaced=true' --set 'managerRbac.namespaces={dev,staging}'
```

You might then attempt to install another Traffic Manager to manage namespaces `staging` and `prod`:

```bash
helm install traffic-manager --namespace prod datawire/telepresence --set 'managerRbac.namespaced=true' --set 'managerRbac.namespaces={staging,prod}'
```

This would fail with an error:

```
Error: rendered manifests contain a resource that already exists. Unable to continue with install: ConfigMap "traffic-manager-claim" in namespace "staging" exists and cannot be imported into the current release: invalid ownership metadata; annotation validation error: key "meta.helm.sh/release-namespace" must equal "prod": current value is "dev"
```

To fix this error, fix the overlap either by removing `staging` from the first install, or from the second.

#### Namespace scoped user permissions

Optionally, you can also configure user rbac to be scoped to the same namespaces as the manager itself.
You might want to do this if you don't give your users permissions throughout the cluster, and want to make sure they only have the minimum set required to perform telepresence commands on certain namespaces.

Continuing with the `dev` and `staging` example from the previous section, simply add the following to `values.yaml` (make sure you set the `subjects`!):

```yaml
clientRbac:
  create: true

  # These are the users or groups to which the user rbac will be bound.
  # This MUST be set.
  subjects: {}
  # - kind: User
  #   name: jane
  #   apiGroup: rbac.authorization.k8s.io

  namespaced: true

  namespaces:
  - dev
  - staging
```

#### Namespace-scoped webhook

If you wish to use the traffic-manager's [mutating webhook](../../reference/cluster-config#mutating-webhook) with a namespace-scoped traffic manager, you will have to ensure that each namespace has an `app.kubernetes.io/name` label that is identical to its name:

```yaml
apiVersion: v1
kind: Namespace
metadata:
  name: staging
  labels:
    app.kubernetes.io/name: staging
```

You can also use `kubectl label` to add the label to an existing namespace, e.g.:

```shell
kubectl label namespace staging app.kubernetes.io/name=staging
```

This is required because the mutating webhook will use the name label to find namespaces to operate on.

**NOTE** This labelling happens automatically in kubernetes >= 1.21.

### Installing RBAC only

Telepresence Traffic Manager does require some [RBAC](../../reference/rbac/) for the traffic-manager deployment itself, as well as for users.
To make it easier for operators to introspect / manage RBAC separately, you can use `rbac.only=true` to
only create the rbac-related objects.
Additionally, you can use `clientRbac.create=true` and `managerRbac.create=true` to toggle which subset(s) of RBAC objects you wish to create.