text:
#pragma GCC diagnostic warning "-Wuninitialized"

#include <aruco/boarddetector.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <cstdlib>
#include <ctime>
#include <cassert>
#include <fstream>
using namespace std;
using namespace cv;
namespace aruco
{

  BoardDetector::BoardDetector(bool setYPerpendicular)
    : _setYPerpendicular(setYPerpendicular),
      _areParamsSet(false),
      _markerSize(0)
  {}
  /**
   * Use if you plan to let this class to perform marker detection too
   */
  void BoardDetector::setParams(const BoardConfiguration &bc,const CameraParameters &cp, float markerSizeMeters)
  {
    _camParams = cp;
    _markerSize = markerSizeMeters;
    _bconf = bc;
    _areParamsSet = true;
  }

  void BoardDetector::setParams(const BoardConfiguration &bc)
  {
    _bconf = bc;
    _areParamsSet = true;
  }

  float  BoardDetector::detect(const cv::Mat &im)throw (cv::Exception)
  {
    _mdetector.detect(im,_vmarkers);

    float res;

    if (_camParams.isValid())
      res=detect(_vmarkers,_bconf,_boardDetected,_camParams.CameraMatrix,_camParams.Distorsion,_markerSize);
    else res=detect(_vmarkers,_bconf,_boardDetected);
    return res;
  }

  float BoardDetector::detect ( const vector<Marker> &detectedMarkers,const  BoardConfiguration &BConf, Board &Bdetected,const CameraParameters &cp, float markerSizeMeters ) throw ( cv::Exception )
  {
    return detect ( detectedMarkers, BConf,Bdetected,cp.CameraMatrix,cp.Distorsion,markerSizeMeters );
  }

  float BoardDetector::detect ( const vector<Marker> &detectedMarkers,const  BoardConfiguration &BConf, Board &Bdetected, Mat camMatrix,Mat distCoeff,float markerSizeMeters ) throw ( cv::Exception )
  {
    if (BConf.size()==0) throw cv::Exception(8881,"BoardDetector::detect","Invalid BoardConfig that is empty",__FILE__,__LINE__);
    if (BConf[0].size()<2) throw cv::Exception(8881,"BoardDetector::detect","Invalid BoardConfig that is empty 2",__FILE__,__LINE__);
    //compute the size of the markers in meters, which is used for some routines(mostly drawing)
    float ssize;
    if ( BConf.mInfoType==BoardConfiguration::PIX && markerSizeMeters>0 ) ssize=markerSizeMeters;
    else if ( BConf.mInfoType==BoardConfiguration::METERS )
    {
      ssize=cv::norm ( BConf[0][0]-BConf[0][1] );
    }

    // cout<<"markerSizeMeters="<<markerSizeMeters<<endl;
    Bdetected.clear();
    ///find among detected markers these that belong to the board configuration
    for ( unsigned int i=0;i<detectedMarkers.size();i++ )
    {
      int idx=BConf.getIndexOfMarkerId(detectedMarkers[i].id);
      if (idx!=-1) {
        Bdetected.push_back ( detectedMarkers[i] );
        Bdetected.back().ssize=ssize;
      }
    }
    //copy configuration
    Bdetected.conf=BConf;
    //

    bool hasEnoughInfoForRTvecCalculation=false;
    if ( Bdetected.size() >=1 )
    {
      if ( camMatrix.rows!=0 )
      {
        if ( markerSizeMeters>0 && BConf.mInfoType==BoardConfiguration::PIX ) hasEnoughInfoForRTvecCalculation=true;
        else if ( BConf.mInfoType==BoardConfiguration::METERS ) hasEnoughInfoForRTvecCalculation=true;
      }
    }

    //calculate extrinsic if there is information for that
    if ( hasEnoughInfoForRTvecCalculation )
    {
      //calculate the size of the markers in meters if expressed in pixels
      double marker_meter_per_pix=0;
      if ( BConf.mInfoType==BoardConfiguration::PIX ) marker_meter_per_pix=markerSizeMeters /  cv::norm ( BConf[0][0]-BConf[0][1] );
      else marker_meter_per_pix=1;//to avoind interferring the process below

      // now, create the matrices for finding the extrinsics
      Mat objPoints ( 4*Bdetected.size(),3,CV_32FC1 );
      Mat imagePoints ( 4*Bdetected.size(),2,CV_32FC1 );
      //size in meters of inter-marker distance

      for ( size_t i=0;i<Bdetected.size();i++ )
      {
        int idx=Bdetected.conf.getIndexOfMarkerId(Bdetected[i].id);
        assert(idx!=-1);
        for ( int p=0;p<4;p++ )
        {
          imagePoints.at<float> ( ( i*4 ) +p,0 ) =Bdetected[i][p].x;
          imagePoints.at<float> ( ( i*4 ) +p,1 ) =Bdetected[i][p].y;
          const aruco::MarkerInfo &Minfo=Bdetected.conf.getMarkerInfo( Bdetected[i].id);

          objPoints.at<float> ( ( i*4 ) +p,0 ) = Minfo[p].x*marker_meter_per_pix;
          objPoints.at<float> ( ( i*4 ) +p,1 ) = Minfo[p].y*marker_meter_per_pix;
          objPoints.at<float> ( ( i*4 ) +p,2 ) = Minfo[p].z*marker_meter_per_pix;
          // 		cout<<objPoints.at<float>( (i*4)+p,0)<<" "<<objPoints.at<float>( (i*4)+p,1)<<" "<<objPoints.at<float>( (i*4)+p,2)<<endl;
        }
      }
      if (distCoeff.total()==0) distCoeff=cv::Mat::zeros(1,4,CV_32FC1 );

      cv::Mat rvec,tvec;
      cv::solvePnP(objPoints,imagePoints,camMatrix,distCoeff,rvec,tvec );
      rvec.convertTo(Bdetected.Rvec,CV_32FC1);
      tvec.convertTo(Bdetected.Tvec,CV_32FC1);
      //now, rotate 90 deg in X so that Y axis points up
      if (_setYPerpendicular)
        rotateXAxis ( Bdetected.Rvec );
      //         cout<<Bdetected.Rvec.at<float>(0,0)<<" "<<Bdetected.Rvec.at<float>(1,0)<<" "<<Bdetected.Rvec.at<float>(2,0)<<endl;
      //         cout<<Bdetected.Tvec.at<float>(0,0)<<" "<<Bdetected.Tvec.at<float>(1,0)<<" "<<Bdetected.Tvec.at<float>(2,0)<<endl;
    }

    float prob=float( Bdetected.size() ) /double ( Bdetected.conf.size() );
    return prob;
  }

  void BoardDetector::rotateXAxis ( Mat &rotation )
  {
    cv::Mat R ( 3,3,CV_32FC1 );
    Rodrigues ( rotation, R );
    //create a rotation matrix for x axis
    cv::Mat RX=cv::Mat::eye ( 3,3,CV_32FC1 );
    float angleRad=-M_PI/2;
    RX.at<float> ( 1,1 ) =cos ( angleRad );
    RX.at<float> ( 1,2 ) =-sin ( angleRad );
    RX.at<float> ( 2,1 ) =sin ( angleRad );
    RX.at<float> ( 2,2 ) =cos ( angleRad );
    //now multiply
    R=R*RX;
    //finally, the the rodrigues back
    Rodrigues ( R,rotation );

  }

}


text:
package org.stummi.ivcalculator;

import java.io.IOException;
import java.io.PrintStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import lombok.RequiredArgsConstructor;

@RequiredArgsConstructor
public class CliTool {
	final PrintStream out;
	private PokemonDb db;
	private PokemonStatFinder finder;

	private static final Map<String, BiConsumer<CliTool, String>> ARGUMENT_HANDLERS = new HashMap<>();

	static {
		ARGUMENT_HANDLERS.put("cp", CliTool::cp);
		ARGUMENT_HANDLERS.put("hp", CliTool::hp);
		ARGUMENT_HANDLERS.put("stardust", CliTool::stardust);
		ARGUMENT_HANDLERS.put("ivsumrating", CliTool::ivsumrating);
		ARGUMENT_HANDLERS.put("bestivrating", CliTool::bestivrating);
		ARGUMENT_HANDLERS.put("beststat", CliTool::beststat);
	}

	public static void main(String[] args) throws IOException {
		try {
			new CliTool(System.out).run(args);
		} catch (Exception e) {
			System.out.println("ERROR: " + e.getLocalizedMessage());

			e.printStackTrace();
		}
	}

	public void run(String[] args) throws IOException {
		if (args.length == 0) {
			usage();
			return;
		}

		this.db = PokemonDb.loadDefault();
		PokemonType type = selectPokemon(args[0]);
		this.finder = type.createStatFinder();

		Stream.of(args).skip(1).forEach(this::handleArgument);
		List<Pokemon> pokelist = finder.findAllPossibleStats().collect(Collectors.toList());
		new StatFindReport(pokelist, out).print();
	}

	private PokemonType selectPokemon(String string) {
		PokemonType type;
		try {
			Integer id = Integer.parseInt(string);
			type = db.typeById(id);
			if (type == null) {
				throw new IllegalArgumentException("not a known pokemon id: " + string);
			} else {
				return type;
			}
		} catch (NumberFormatException nfe) {
			// argument was not a number, continue with looking up by name
		}

		type = db.typeByExactName(string);
		if (type != null) {
			return type;
		}
		List<PokemonType> types = db.typesByPartName(string);
		if (types.size() == 0) {
			throw new IllegalArgumentException("not a known pokemon name: " + string);
		} else if (types.size() > 1) {
			throw new IllegalArgumentException("ambigous pokemon name: " + string + ", candidates are: "
					+ types.stream().map(PokemonType::getName).collect(Collectors.joining(", ")));
		} else {
			return types.get(0);
		}
	}

	public void handleArgument(String argument) {
		String[] spl = argument.split("=");
		if (spl.length < 2) {
			throw new IllegalArgumentException("argument expected: " + argument);
		}

		BiConsumer<CliTool, String> func = ARGUMENT_HANDLERS.get(spl[0].toLowerCase());
		if (func == null) {
			throw new IllegalArgumentException("unknown argument: " + spl[0]);
		}

		func.accept(this, spl[1]);
	}

	public void cp(String cp) {
		finder.hasCp(Integer.parseInt(cp));
	}

	public void hp(String hp) {
		finder.hasHp(Integer.parseInt(hp));
	}

	public void stardust(String stardust) {
		finder.hasStardustCost(Integer.parseInt(stardust));
	}

	public void ivsumrating(String ivsumrating) {
		finder.hasIvSumRating(parseRating(ivsumrating));
	}

	public void bestivrating(String bestivrating) {
		finder.hasBestIvRating(parseRating(bestivrating));
	}

	private StatRating parseRating(String rating) {
		try {
			return StatRating.values()[Integer.parseInt(rating)];
		} catch (NumberFormatException nfe) {
			return StatRating.valueOf(rating.toUpperCase());
		}
	}

	public void beststat(String beststat) {
		for (String s : beststat.split(",")) {
			switch (Character.toUpperCase(s.charAt(0))) {
			case 'A':
				finder.attackIsBest();
				break;
			case 'D':
				finder.defenseIsBest();
				break;
			case 'S':
				finder.staminaIsBest();
				break;
			default:
				throw new IllegalArgumentException("not a valid stat: " + s);
			}
		}
	}

	public void usage() {
		out.println("Usage: iv-tool <pokemon-Id> [cp=<val>] [hp=<val>] "
				+ "[stardust=<val>] [ivsumrating=<0..3|WORST|BAD|GOOD|BEST>] " + "[beststat=<A,D,S>]"
				+ "[bestivrating=<0..3|WORST|BAD|GOOD|BEST>]");
	}
}

redpajama_set_name: RedPajamaGithub


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

// Represents the browser side of the browser <--> renderer communication
// channel. There will be one RenderProcessHost per renderer process.

#include "chrome/browser/renderer_host/browser_render_process_host.h"

#include <algorithm>
#include <limits>
#include <vector>

#if defined(OS_POSIX)
#include <utility>  // for pair<>
#endif

#include "app/app_switches.h"
#include "base/command_line.h"
#include "base/field_trial.h"
#include "base/logging.h"
#include "base/stl_util-inl.h"
#include "base/string_util.h"
#include "base/thread.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/child_process_security_policy.h"
#include "chrome/browser/extensions/extension_function_dispatcher.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/extensions_service.h"
#include "chrome/browser/extensions/user_script_master.h"
#include "chrome/browser/history/history.h"
#include "chrome/browser/net/url_request_context_getter.h"
#include "chrome/browser/plugin_service.h"
#include "chrome/browser/profile.h"
#include "chrome/browser/renderer_host/audio_renderer_host.h"
#include "chrome/browser/renderer_host/render_view_host.h"
#include "chrome/browser/renderer_host/render_view_host_delegate.h"
#include "chrome/browser/renderer_host/render_widget_helper.h"
#include "chrome/browser/renderer_host/render_widget_host.h"
#include "chrome/browser/renderer_host/resource_message_filter.h"
#include "chrome/browser/renderer_host/web_cache_manager.h"
#include "chrome/browser/spellcheck_host.h"
#include "chrome/browser/visitedlink_master.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/child_process_info.h"
#include "chrome/common/child_process_host.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/notification_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/process_watcher.h"
#include "chrome/common/render_messages.h"
#include "chrome/common/result_codes.h"
#include "chrome/renderer/render_process.h"
#include "chrome/renderer/render_thread.h"
#include "grit/generated_resources.h"
#include "ipc/ipc_logging.h"
#include "ipc/ipc_message.h"
#include "ipc/ipc_platform_file.h"
#include "ipc/ipc_switches.h"

#if defined(OS_WIN)
#include "app/win_util.h"
#endif

using WebKit::WebCache;

#include "third_party/skia/include/core/SkBitmap.h"

// This class creates the IO thread for the renderer when running in
// single-process mode.  It's not used in multi-process mode.
class RendererMainThread : public base::Thread {
 public:
  explicit RendererMainThread(const std::string& channel_id)
      : base::Thread("Chrome_InProcRendererThread"),
        channel_id_(channel_id),
        render_process_(NULL) {
  }

  ~RendererMainThread() {
    Stop();
  }

 protected:
  virtual void Init() {
#if defined(OS_WIN)
    CoInitialize(NULL);
#endif

    render_process_ = new RenderProcess();
    render_process_->set_main_thread(new RenderThread(channel_id_));
    // It's a little lame to manually set this flag.  But the single process
    // RendererThread will receive the WM_QUIT.  We don't need to assert on
    // this thread, so just force the flag manually.
    // If we want to avoid this, we could create the InProcRendererThread
    // directly with _beginthreadex() rather than using the Thread class.
    base::Thread::SetThreadWasQuitProperly(true);
  }

  virtual void CleanUp() {
    delete render_process_;

#if defined(OS_WIN)
    CoUninitialize();
#endif
  }

 private:
  std::string channel_id_;
  // Deleted in CleanUp() on the renderer thread, so don't use a smart pointer.
  RenderProcess* render_process_;
};

// Size of the buffer after which individual link updates deemed not warranted
// and the overall update should be used instead.
static const unsigned kVisitedLinkBufferThreshold = 50;

// This class manages buffering and sending visited link hashes (fingerprints)
// to renderer based on widget visibility.
// As opposed to the VisitedLinkEventListener in profile.cc, which coalesces to
// reduce the rate of messages being sent to render processes, this class
// ensures that the updates occur only when explicitly requested. This is
// used by BrowserRenderProcessHost to only send Add/Reset link events to the
// renderers when their tabs are visible and the corresponding RenderViews are
// created.
class VisitedLinkUpdater {
 public:
  VisitedLinkUpdater() : reset_needed_(false), has_receiver_(false) {}

  // Buffers |links| to update, but doesn't actually relay them.
  void AddLinks(const VisitedLinkCommon::Fingerprints& links) {
    if (reset_needed_)
      return;

    if (pending_.size() + links.size() > kVisitedLinkBufferThreshold) {
      // Once the threshold is reached, there's no need to store pending visited
      // link updates -- we opt for resetting the state for all links.
      AddReset();
      return;
    }

    pending_.insert(pending_.end(), links.begin(), links.end());
  }

  // Tells the updater that sending individual link updates is no longer
  // necessary and the visited state for all links should be reset.
  void AddReset() {
    reset_needed_ = true;
    pending_.clear();
  }

  // Sends visited link update messages: a list of links whose visited state
  // changed or reset of visited state for all links.
  void Update(IPC::Channel::Sender* sender) {
    DCHECK(sender);

    if (!has_receiver_)
      return;

    if (reset_needed_) {
      sender->Send(new ViewMsg_VisitedLink_Reset());
      reset_needed_ = false;
      return;
    }

    if (pending_.size() == 0)
      return;

    sender->Send(new ViewMsg_VisitedLink_Add(pending_));

    pending_.clear();
  }

  // Notifies the updater that it is now safe to send visited state updates.
  void ReceiverReady(IPC::Channel::Sender* sender) {
    has_receiver_ = true;
    // Go ahead and send whatever we already have buffered up.
    Update(sender);
  }

 private:
  bool reset_needed_;
  bool has_receiver_;
  VisitedLinkCommon::Fingerprints pending_;
};

BrowserRenderProcessHost::BrowserRenderProcessHost(Profile* profile)
    : RenderProcessHost(profile),
      visible_widgets_(0),
      backgrounded_(true),
      ALLOW_THIS_IN_INITIALIZER_LIST(cached_dibs_cleaner_(
            base::TimeDelta::FromSeconds(5),
            this, &BrowserRenderProcessHost::ClearTransportDIBCache)),
      extension_process_(false) {
  widget_helper_ = new RenderWidgetHelper();

  registrar_.Add(this, NotificationType::USER_SCRIPTS_UPDATED,
                 Source<Profile>(profile));
  registrar_.Add(this, NotificationType::SPELLCHECK_HOST_REINITIALIZED,
                 NotificationService::AllSources());
  registrar_.Add(this, NotificationType::SPELLCHECK_WORD_ADDED,
                 NotificationService::AllSources());
  registrar_.Add(this, NotificationType::SPELLCHECK_AUTOSPELL_TOGGLED,
                 NotificationService::AllSources());

  visited_link_updater_.reset(new VisitedLinkUpdater());

  WebCacheManager::GetInstance()->Add(id());
  ChildProcessSecurityPolicy::GetInstance()->Add(id());

  // Note: When we create the BrowserRenderProcessHost, it's technically
  //       backgrounded, because it has no visible listeners.  But the process
  //       doesn't actually exist yet, so we'll Background it later, after
  //       creation.
}

BrowserRenderProcessHost::~BrowserRenderProcessHost() {
  WebCacheManager::GetInstance()->Remove(id());
  ChildProcessSecurityPolicy::GetInstance()->Remove(id());

  // We may have some unsent messages at this point, but that's OK.
  channel_.reset();
  while (!queued_messages_.empty()) {
    delete queued_messages_.front();
    queued_messages_.pop();
  }

  // Destroy the AudioRendererHost properly.
  if (audio_renderer_host_.get())
    audio_renderer_host_->Destroy();

  ClearTransportDIBCache();

  NotificationService::current()->Notify(
      NotificationType::EXTENSION_PORT_DELETED_DEBUG,
      Source<IPC::Message::Sender>(this),
      NotificationService::NoDetails());
}

bool BrowserRenderProcessHost::Init(bool is_extensions_process,
                                    URLRequestContextGetter* request_context) {
  // calling Init() more than once does nothing, this makes it more convenient
  // for the view host which may not be sure in some cases
  if (channel_.get()) {
    // Ensure that |is_extensions_process| doesn't change across multiple calls
    // to Init().
    if (!run_renderer_in_process()) {
      DCHECK_EQ(extension_process_, is_extensions_process);
    }
    return true;
  }

  extension_process_ = is_extensions_process;

  // run the IPC channel on the shared IO thread.
  base::Thread* io_thread = g_browser_process->io_thread();

  // Construct the AudioRendererHost with the IO thread.
  audio_renderer_host_ = new AudioRendererHost();

  scoped_refptr<ResourceMessageFilter> resource_message_filter =
      new ResourceMessageFilter(g_browser_process->resource_dispatcher_host(),
                                id(),
                                audio_renderer_host_.get(),
                                PluginService::GetInstance(),
                                g_browser_process->print_job_manager(),
                                profile(),
                                widget_helper_,
                                request_context);

  // Find the renderer before creating the channel so if this fails early we
  // return without creating the channel.
  FilePath renderer_path = ChildProcessHost::GetChildPath();
  if (renderer_path.empty())
    return false;

  // Setup the IPC channel.
  const std::string channel_id =
      ChildProcessInfo::GenerateRandomChannelID(this);
  channel_.reset(
      new IPC::SyncChannel(channel_id, IPC::Channel::MODE_SERVER, this,
                           resource_message_filter,
                           io_thread->message_loop(), true,
                           g_browser_process->shutdown_event()));
  // As a preventive mesure, we DCHECK if someone sends a synchronous message
  // with no time-out, which in the context of the browser process we should not
  // be doing.
  channel_->set_sync_messages_with_no_timeout_allowed(false);

  if (run_renderer_in_process()) {
    // Crank up a thread and run the initialization there.  With the way that
    // messages flow between the browser and renderer, this thread is required
    // to prevent a deadlock in single-process mode.  Since the primordial
    // thread in the renderer process runs the WebKit code and can sometimes
    // make blocking calls to the UI thread (i.e. this thread), they need to run
    // on separate threads.
    in_process_renderer_.reset(new RendererMainThread(channel_id));

    base::Thread::Options options;
#if !defined(USE_X11)
    // In-process plugins require this to be a UI message loop.
    options.message_loop_type = MessageLoop::TYPE_UI;
#else
    // We can't have multiple UI loops on X, so we don't support
    // in-process plugins.
    options.message_loop_type = MessageLoop::TYPE_DEFAULT;
#endif
    in_process_renderer_->StartWithOptions(options);

    OnProcessLaunched();  // Fake a callback that the process is ready.
  } else {
    // Build command line for renderer.  We call AppendRendererCommandLine()
    // first so the process type argument will appear first.
    CommandLine* cmd_line = new CommandLine(renderer_path);
    AppendRendererCommandLine(cmd_line);
    cmd_line->AppendSwitchWithValue(switches::kProcessChannelID,
                                    ASCIIToWide(channel_id));

    // Spawn the child process asynchronously to avoid blocking the UI thread.
    child_process_.reset(new ChildProcessLauncher(
#if defined(OS_WIN)
        FilePath(),
#elif defined(POSIX)
        base::environment_vector(),
        channel_->GetClientFileDescriptor(),
#endif
        cmd_line,
        this));

    fast_shutdown_started_ = false;
  }

  return true;
}

int BrowserRenderProcessHost::GetNextRoutingID() {
  return widget_helper_->GetNextRoutingID();
}

void BrowserRenderProcessHost::CancelResourceRequests(int render_widget_id) {
  widget_helper_->CancelResourceRequests(render_widget_id);
}

void BrowserRenderProcessHost::CrossSiteClosePageACK(
    const ViewMsg_ClosePage_Params& params) {
  widget_helper_->CrossSiteClosePageACK(params);
}

bool BrowserRenderProcessHost::WaitForUpdateMsg(
    int render_widget_id,
    const base::TimeDelta& max_delay,
    IPC::Message* msg) {
  // The post task to this thread with the process id could be in queue, and we
  // don't want to dispatch a message before then since it will need the handle.
  if (child_process_.get() && child_process_->IsStarting())
    return false;

  return widget_helper_->WaitForUpdateMsg(render_widget_id, max_delay, msg);
}

void BrowserRenderProcessHost::ReceivedBadMessage(uint32 msg_type) {
  BadMessageTerminateProcess(msg_type, GetHandle());
}

void BrowserRenderProcessHost::ViewCreated() {
  visited_link_updater_->ReceiverReady(this);
}

void BrowserRenderProcessHost::WidgetRestored() {
  // Verify we were properly backgrounded.
  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
  visible_widgets_++;
  visited_link_updater_->Update(this);
  SetBackgrounded(false);
}

void BrowserRenderProcessHost::WidgetHidden() {
  // On startup, the browser will call Hide
  if (backgrounded_)
    return;

  DCHECK_EQ(backgrounded_, (visible_widgets_ == 0));
  visible_widgets_--;
  DCHECK_GE(visible_widgets_, 0);
  if (visible_widgets_ == 0) {
    DCHECK(!backgrounded_);
    SetBackgrounded(true);
  }
}

void BrowserRenderProcessHost::SendVisitedLinkTable(
    base::SharedMemory* table_memory) {
  // Check if the process is still starting and we don't have a handle for it
  // yet, in which case this will happen later when InitVisitedLinks is called.
  if (!run_renderer_in_process() &&
      (!child_process_.get() || child_process_->IsStarting())) {
    return;
  }

  base::SharedMemoryHandle handle_for_process;
  table_memory->ShareToProcess(GetHandle(), &handle_for_process);
  if (base::SharedMemory::IsHandleValid(handle_for_process))
    Send(new ViewMsg_VisitedLink_NewTable(handle_for_process));
}

void BrowserRenderProcessHost::AddVisitedLinks(
    const VisitedLinkCommon::Fingerprints& links) {
  visited_link_updater_->AddLinks(links);
  if (visible_widgets_ == 0)
    return;

  visited_link_updater_->Update(this);
}

void BrowserRenderProcessHost::ResetVisitedLinks() {
  visited_link_updater_->AddReset();
  if (visible_widgets_ == 0)
    return;

  visited_link_updater_->Update(this);
}

void BrowserRenderProcessHost::AppendRendererCommandLine(
    CommandLine* command_line) const {
  // Pass the process type first, so it shows first in process listings.
  // Extensions use a special pseudo-process type to make them distinguishable,
  // even though they're just renderers.
  command_line->AppendSwitchWithValue(switches::kProcessType,
      extension_process_ ? switches::kExtensionProcess :
                           switches::kRendererProcess);

  if (logging::DialogsAreSuppressed())
    command_line->AppendSwitch(switches::kNoErrorDialogs);

  // Now send any options from our own command line we want to propogate.
  const CommandLine& browser_command_line = *CommandLine::ForCurrentProcess();
  PropogateBrowserCommandLineToRenderer(browser_command_line, command_line);

  // Pass on the browser locale.
  const std::string locale = g_browser_process->GetApplicationLocale();
  command_line->AppendSwitchWithValue(switches::kLang, ASCIIToWide(locale));

  // If we run FieldTrials, we want to pass to their state to the renderer so
  // that it can act in accordance with each state, or record histograms
  // relating to the FieldTrial states.
  std::string field_trial_states;
  FieldTrialList::StatesToString(&field_trial_states);
  if (!field_trial_states.empty()) {
    command_line->AppendSwitchWithValue(switches::kForceFieldTestNameAndValue,
        field_trial_states);
  }

  // A command prefix is something prepended to the command line of the spawned
  // process. It is supported only on POSIX systems.
#if defined(OS_POSIX)
  if (browser_command_line.HasSwitch(switches::kRendererCmdPrefix)) {
    // launch the renderer child with some prefix (usually "gdb --args")
    const std::wstring prefix =
        browser_command_line.GetSwitchValue(switches::kRendererCmdPrefix);
    command_line->PrependWrapper(prefix);
  }
#endif  // defined(OS_POSIX)

  ChildProcessHost::SetCrashReporterCommandLine(command_line);

  const std::string user_data_dir =
      browser_command_line.GetSwitchValueASCII(switches::kUserDataDir);
  if (!user_data_dir.empty())
    command_line->AppendSwitchWithValue(switches::kUserDataDir, user_data_dir);
#if defined(OS_CHROMEOS)
  const std::string& profile =
      browser_command_line.GetSwitchValueASCII(switches::kProfile);
  if (!profile.empty())
    command_line->AppendSwitchWithValue(switches::kProfile, profile);
#endif
}

void BrowserRenderProcessHost::PropogateBrowserCommandLineToRenderer(
    const CommandLine& browser_cmd,
    CommandLine* renderer_cmd) const {
  // Propagate the following switches to the renderer command line (along
  // with any associated values) if present in the browser command line.
  static const char* const switch_names[] = {
    switches::kRendererAssertTest,
    switches::kRendererCrashTest,
    switches::kRendererStartupDialog,
    switches::kNoSandbox,
    switches::kTestSandbox,
    switches::kEnableSeccompSandbox,
#if !defined (GOOGLE_CHROME_BUILD)
    // This is an unsupported and not fully tested mode, so don't enable it for
    // official Chrome builds.
    switches::kInProcessPlugins,
#endif
    switches::kDomAutomationController,
    switches::kUserAgent,
    switches::kJavaScriptFlags,
    switches::kRecordMode,
    switches::kPlaybackMode,
    switches::kNoJsRandomness,
    switches::kDisableBreakpad,
    switches::kFullMemoryCrashReport,
    switches::kEnableLogging,
    switches::kDumpHistogramsOnExit,
    switches::kDisableLogging,
    switches::kLoggingLevel,
    switches::kDebugPrint,
    switches::kMemoryProfiling,
    switches::kEnableWatchdog,
    switches::kMessageLoopHistogrammer,
    switches::kEnableDCHECK,
    switches::kSilentDumpOnDCHECK,
    switches::kUseLowFragHeapCrt,
    switches::kEnableStatsTable,
    switches::kExperimentalSpellcheckerFeatures,
    switches::kDisableAudio,
    switches::kSimpleDataSource,
    switches::kEnableBenchmarking,
    switches::kInternalNaCl,
    switches::kInternalPepper,
    switches::kDisableByteRangeSupport,
    switches::kDisableDatabases,
    switches::kDisableDesktopNotifications,
    switches::kDisableWebSockets,
    switches::kDisableLocalStorage,
    switches::kEnableSessionStorage,
    switches::kDisableSharedWorkers,
    switches::kEnableApplicationCache,
    switches::kShowPaintRects,
    // We propagate the Chrome Frame command line here as well in case the
    // renderer is not run in the sandbox.
    switches::kChromeFrame,
#if defined(OS_MACOSX)
    // Allow this to be set when invoking the browser and relayed along.
    switches::kEnableSandboxLogging,
#endif
  };

  for (size_t i = 0; i < arraysize(switch_names); ++i) {
    if (browser_cmd.HasSwitch(switch_names[i])) {
      renderer_cmd->AppendSwitchWithValue(switch_names[i],
          browser_cmd.GetSwitchValueASCII(switch_names[i]));
    }
  }

  // Disable databases in incognito mode.
  if (profile()->IsOffTheRecord() &&
      !browser_cmd.HasSwitch(switches::kDisableDatabases)) {
    renderer_cmd->AppendSwitch(switches::kDisableDatabases);
  }
}

base::ProcessHandle BrowserRenderProcessHost::GetHandle() {
  // child_process_ is null either because we're in single process mode, we have
  // done fast termination, or the process has crashed.
  if (run_renderer_in_process() || !child_process_.get())
    return base::Process::Current().handle();

  if (child_process_->IsStarting())
    return base::kNullProcessHandle;

  return child_process_->GetHandle();
}

void BrowserRenderProcessHost::InitVisitedLinks() {
  VisitedLinkMaster* visitedlink_master = profile()->GetVisitedLinkMaster();
  if (!visitedlink_master)
    return;

  SendVisitedLinkTable(visitedlink_master->shared_memory());
}

void BrowserRenderProcessHost::InitUserScripts() {
  UserScriptMaster* user_script_master = profile()->GetUserScriptMaster();

  // Incognito profiles won't have user scripts.
  if (!user_script_master)
    return;

  if (!user_script_master->ScriptsReady()) {
    // No scripts ready.  :(
    return;
  }

  // Update the renderer process with the current scripts.
  SendUserScriptsUpdate(user_script_master->GetSharedMemory());
}

void BrowserRenderProcessHost::InitExtensions() {
  // TODO(aa): Should only bother sending these function names if this is an
  // extension process.
  std::vector<std::string> function_names;
  ExtensionFunctionDispatcher::GetAllFunctionNames(&function_names);
  Send(new ViewMsg_Extension_SetFunctionNames(function_names));
}

void BrowserRenderProcessHost::SendUserScriptsUpdate(
    base::SharedMemory *shared_memory) {
  // Process is being started asynchronously.  We'll end up calling
  // InitUserScripts when it's created which will call this again.
  if (child_process_.get() && child_process_->IsStarting())
    return;

  base::SharedMemoryHandle handle_for_process;
  if (!shared_memory->ShareToProcess(GetHandle(), &handle_for_process)) {
    // This can legitimately fail if the renderer asserts at startup.
    return;
  }

  if (base::SharedMemory::IsHandleValid(handle_for_process)) {
    Send(new ViewMsg_UserScripts_UpdatedScripts(handle_for_process));
  }
}

bool BrowserRenderProcessHost::FastShutdownIfPossible() {
  if (run_renderer_in_process())
    return false;  // Single process mode can't do fast shutdown.

  if (!child_process_.get() || child_process_->IsStarting() || !GetHandle())
    return false;  // Render process hasn't started or is probably crashed.

  // Test if there's an unload listener.
  // NOTE: It's possible that an onunload listener may be installed
  // while we're shutting down, so there's a small race here.  Given that
  // the window is small, it's unlikely that the web page has much
  // state that will be lost by not calling its unload handlers properly.
  if (!sudden_termination_allowed())
    return false;

  // Check for any external tab containers, since they may still be running even
  // though this window closed.
  listeners_iterator iter(ListenersIterator());
  while (!iter.IsAtEnd()) {
    // NOTE: This is a bit dangerous.  We know that for now, listeners are
    // always RenderWidgetHosts.  But in theory, they don't have to be.
    const RenderWidgetHost* widget =
        static_cast<const RenderWidgetHost*>(iter.GetCurrentValue());
    DCHECK(widget);
    if (widget && widget->IsRenderView()) {
      const RenderViewHost* rvh = static_cast<const RenderViewHost*>(widget);
      if (rvh->delegate()->IsExternalTabContainer())
        return false;
    }

    iter.Advance();
  }

  child_process_.reset();
  fast_shutdown_started_ = true;
  return true;
}

bool BrowserRenderProcessHost::SendWithTimeout(IPC::Message* msg,
                                               int timeout_ms) {
  if (!channel_.get()) {
    delete msg;
    return false;
  }
  return channel_->SendWithTimeout(msg, timeout_ms);
}

// This is a platform specific function for mapping a transport DIB given its id
TransportDIB* BrowserRenderProcessHost::MapTransportDIB(
    TransportDIB::Id dib_id) {
#if defined(OS_WIN)
  // On Windows we need to duplicate the handle from the remote process
  HANDLE section = win_util::GetSectionFromProcess(
      dib_id.handle, GetHandle(), false /* read write */);
  return TransportDIB::Map(section);
#elif defined(OS_MACOSX) || defined(CHROMIUM_CAPSICUM)
  // On OSX, the browser allocates all DIBs and keeps a file descriptor around
  // for each.
  return widget_helper_->MapTransportDIB(dib_id);
#elif defined(OS_NIX)
  return TransportDIB::Map(dib_id);
#endif  // defined(OS_NIX)
}

TransportDIB* BrowserRenderProcessHost::GetTransportDIB(
    TransportDIB::Id dib_id) {
  const std::map<TransportDIB::Id, TransportDIB*>::iterator
      i = cached_dibs_.find(dib_id);
  if (i != cached_dibs_.end()) {
    cached_dibs_cleaner_.Reset();
    return i->second;
  }

  TransportDIB* dib = MapTransportDIB(dib_id);
  if (!dib)
    return NULL;

  if (cached_dibs_.size() >= MAX_MAPPED_TRANSPORT_DIBS) {
    // Clean a single entry from the cache
    std::map<TransportDIB::Id, TransportDIB*>::iterator smallest_iterator;
    size_t smallest_size = std::numeric_limits<size_t>::max();

    for (std::map<TransportDIB::Id, TransportDIB*>::iterator
         i = cached_dibs_.begin(); i != cached_dibs_.end(); ++i) {
      if (i->second->size() <= smallest_size) {
        smallest_iterator = i;
        smallest_size = i->second->size();
      }
    }

    delete smallest_iterator->second;
    cached_dibs_.erase(smallest_iterator);
  }

  cached_dibs_[dib_id] = dib;
  cached_dibs_cleaner_.Reset();
  return dib;
}

void BrowserRenderProcessHost::ClearTransportDIBCache() {
  STLDeleteContainerPairSecondPointers(
      cached_dibs_.begin(), cached_dibs_.end());
  cached_dibs_.clear();
}

bool BrowserRenderProcessHost::Send(IPC::Message* msg) {
  if (!channel_.get()) {
    delete msg;
    return false;
  }

  if (child_process_.get() && child_process_->IsStarting()) {
    queued_messages_.push(msg);
    return true;
  }

  return channel_->Send(msg);
}

void BrowserRenderProcessHost::OnMessageReceived(const IPC::Message& msg) {
  mark_child_process_activity_time();
  if (msg.routing_id() == MSG_ROUTING_CONTROL) {
    // dispatch control messages
    bool msg_is_ok = true;
    IPC_BEGIN_MESSAGE_MAP_EX(BrowserRenderProcessHost, msg, msg_is_ok)
      IPC_MESSAGE_HANDLER(ViewHostMsg_PageContents, OnPageContents)
      IPC_MESSAGE_HANDLER(ViewHostMsg_UpdatedCacheStats,
                          OnUpdatedCacheStats)
      IPC_MESSAGE_HANDLER(ViewHostMsg_SuddenTerminationChanged,
                          SuddenTerminationChanged);
      IPC_MESSAGE_HANDLER(ViewHostMsg_ExtensionAddListener,
                          OnExtensionAddListener)
      IPC_MESSAGE_HANDLER(ViewHostMsg_ExtensionRemoveListener,
                          OnExtensionRemoveListener)
      IPC_MESSAGE_HANDLER(ViewHostMsg_ExtensionCloseChannel,
                          OnExtensionCloseChannel)
      IPC_MESSAGE_HANDLER(ViewHostMsg_SpellChecker_RequestDictionary,
                          OnSpellCheckerRequestDictionary)
      IPC_MESSAGE_UNHANDLED_ERROR()
    IPC_END_MESSAGE_MAP_EX()

    if (!msg_is_ok) {
      // The message had a handler, but its de-serialization failed.
      // We consider this a capital crime. Kill the renderer if we have one.
      ReceivedBadMessage(msg.type());
    }
    return;
  }

  // dispatch incoming messages to the appropriate TabContents
  IPC::Channel::Listener* listener = GetListenerByID(msg.routing_id());
  if (!listener) {
    if (msg.is_sync()) {
      // The listener has gone away, so we must respond or else the caller will
      // hang waiting for a reply.
      IPC::Message* reply = IPC::SyncMessage::GenerateReply(&msg);
      reply->set_reply_error();
      Send(reply);
    }
    return;
  }
  listener->OnMessageReceived(msg);
}

void BrowserRenderProcessHost::OnChannelConnected(int32 peer_pid) {
#if defined(IPC_MESSAGE_LOG_ENABLED)
  Send(new ViewMsg_SetIPCLoggingEnabled(IPC::Logging::current()->Enabled()));
#endif
}

// Static. This function can be called from any thread.
void BrowserRenderProcessHost::BadMessageTerminateProcess(
    uint32 msg_type, base::ProcessHandle process) {
  LOG(ERROR) << "bad message " << msg_type << " terminating renderer.";
  if (run_renderer_in_process()) {
    // In single process mode it is better if we don't suicide but just crash.
    CHECK(false);
  }
  NOTREACHED();
  base::KillProcess(process, ResultCodes::KILLED_BAD_MESSAGE, false);
}

void BrowserRenderProcessHost::OnChannelError() {
  // Our child process has died.  If we didn't expect it, it's a crash.
  // In any case, we need to let everyone know it's gone.
  // The OnChannelError notification can fire multiple times due to nested sync
  // calls to a renderer. If we don't have a valid channel here it means we
  // already handled the error.
  if (!channel_.get())
    return;

  // NULL in single process mode or if fast termination happened.
  bool did_crash =
      child_process_.get() ? child_process_->DidProcessCrash() : false;

  if (did_crash) {
    UMA_HISTOGRAM_PERCENTAGE("BrowserRenderProcessHost.ChildCrashes",
                             extension_process_ ? 2 : 1);
  }

  RendererClosedDetails details(did_crash, extension_process_);
  NotificationService::current()->Notify(
      NotificationType::RENDERER_PROCESS_CLOSED,
      Source<RenderProcessHost>(this),
      Details<RendererClosedDetails>(&details));

  WebCacheManager::GetInstance()->Remove(id());
  child_process_.reset();
  channel_.reset();

  IDMap<IPC::Channel::Listener>::iterator iter(&listeners_);
  while (!iter.IsAtEnd()) {
    iter.GetCurrentValue()->OnMessageReceived(
        ViewHostMsg_RenderViewGone(iter.GetCurrentKey()));
    iter.Advance();
  }

  ClearTransportDIBCache();

  // this object is not deleted at this point and may be reused later.
  // TODO(darin): clean this up
}

void BrowserRenderProcessHost::OnPageContents(const GURL& url,
                                              int32 page_id,
                                              const std::wstring& contents) {
  Profile* p = profile();
  if (!p || p->IsOffTheRecord())
    return;

  HistoryService* hs = p->GetHistoryService(Profile::IMPLICIT_ACCESS);
  if (hs)
    hs->SetPageContents(url, contents);
}

void BrowserRenderProcessHost::OnUpdatedCacheStats(
    const WebCache::UsageStats& stats) {
  WebCacheManager::GetInstance()->ObserveStats(id(), stats);
}

void BrowserRenderProcessHost::SuddenTerminationChanged(bool enabled) {
  set_sudden_termination_allowed(enabled);
}

void BrowserRenderProcessHost::SetBackgrounded(bool backgrounded) {
  // Note: we always set the backgrounded_ value.  If the process is NULL
  // (and hence hasn't been created yet), we will set the process priority
  // later when we create the process.
  backgrounded_ = backgrounded;
  if (!child_process_.get() || child_process_->IsStarting())
    return;

#if defined(OS_WIN)
  // The cbstext.dll loads as a global GetMessage hook in the browser process
  // and intercepts/unintercepts the kernel32 API SetPriorityClass in a
  // background thread. If the UI thread invokes this API just when it is
  // intercepted the stack is messed up on return from the interceptor
  // which causes random crashes in the browser process. Our hack for now
  // is to not invoke the SetPriorityClass API if the dll is loaded.
  if (GetModuleHandle(L"cbstext.dll"))
    return;
#endif  // OS_WIN

  child_process_->SetProcessBackgrounded(backgrounded);
}

void BrowserRenderProcessHost::Observe(NotificationType type,
                                       const NotificationSource& source,
                                       const NotificationDetails& details) {
  switch (type.value) {
    case NotificationType::USER_SCRIPTS_UPDATED: {
      base::SharedMemory* shared_memory =
          Details<base::SharedMemory>(details).ptr();
      if (shared_memory) {
        SendUserScriptsUpdate(shared_memory);
      }
      break;
    }
    case NotificationType::SPELLCHECK_HOST_REINITIALIZED: {
      InitSpellChecker();
      break;
    }
    case NotificationType::SPELLCHECK_WORD_ADDED: {
      AddSpellCheckWord(
          reinterpret_cast<const Source<SpellCheckHost>*>(&source)->
          ptr()->last_added_word());
      break;
    }
    case NotificationType::SPELLCHECK_AUTOSPELL_TOGGLED: {
      PrefService* prefs = profile()->GetPrefs();
      EnableAutoSpellCorrect(
          prefs->GetBoolean(prefs::kEnableAutoSpellCorrect));
      break;
    }
    default: {
      NOTREACHED();
      break;
    }
  }
}

void BrowserRenderProcessHost::OnProcessLaunched() {
  // Now that the process is created, set its backgrounding accordingly.
  SetBackgrounded(backgrounded_);

  InitVisitedLinks();
  InitUserScripts();
  InitExtensions();
  // We don't want to initialize the spellchecker unless SpellCheckHost has been
  // created. In InitSpellChecker(), we know if GetSpellCheckHost() is NULL
  // then the spellchecker has been turned off, but here, we don't know if
  // it's been turned off or just not loaded yet.
  if (profile()->GetSpellCheckHost())
    InitSpellChecker();

  if (max_page_id_ != -1)
    Send(new ViewMsg_SetNextPageID(max_page_id_ + 1));

  while (!queued_messages_.empty()) {
    Send(queued_messages_.front());
    queued_messages_.pop();
  }

  NotificationService::current()->Notify(
      NotificationType::RENDERER_PROCESS_CREATED,
      Source<RenderProcessHost>(this), NotificationService::NoDetails());
}

void BrowserRenderProcessHost::OnExtensionAddListener(
    const std::string& event_name) {
  if (profile()->GetExtensionMessageService()) {
    profile()->GetExtensionMessageService()->AddEventListener(
        event_name, id());
  }
}

void BrowserRenderProcessHost::OnExtensionRemoveListener(
    const std::string& event_name) {
  if (profile()->GetExtensionMessageService()) {
    profile()->GetExtensionMessageService()->RemoveEventListener(
        event_name, id());
  }
}

void BrowserRenderProcessHost::OnExtensionCloseChannel(int port_id) {
  if (profile()->GetExtensionMessageService()) {
    profile()->GetExtensionMessageService()->CloseChannel(port_id);
  }
}

void BrowserRenderProcessHost::OnSpellCheckerRequestDictionary() {
  // We may have gotten multiple requests from different renderers. We don't
  // want to initialize multiple times in this case, so we set |force| to false.
  profile()->ReinitializeSpellCheckHost(false);
}

void BrowserRenderProcessHost::AddSpellCheckWord(const std::string& word) {
  Send(new ViewMsg_SpellChecker_WordAdded(word));
}

void BrowserRenderProcessHost::InitSpellChecker() {
  SpellCheckHost* spellcheck_host = profile()->GetSpellCheckHost();
  if (spellcheck_host) {
    PrefService* prefs = profile()->GetPrefs();
    IPC::PlatformFileForTransit file;

    if (spellcheck_host->bdict_file() != base::kInvalidPlatformFileValue) {
#if defined(OS_POSIX)
      file = base::FileDescriptor(spellcheck_host->bdict_file(), false);
#elif defined(OS_WIN)
      ::DuplicateHandle(::GetCurrentProcess(), spellcheck_host->bdict_file(),
                        GetHandle(), &file, 0, false, DUPLICATE_SAME_ACCESS);
#endif
    }

    Send(new ViewMsg_SpellChecker_Init(
        file,
        spellcheck_host->custom_words(),
        spellcheck_host->language(),
        prefs->GetBoolean(prefs::kEnableAutoSpellCorrect)));
  } else {
    Send(new ViewMsg_SpellChecker_Init(
        IPC::InvalidPlatformFileForTransit(),
        std::vector<std::string>(),
        std::string(),
        false));
  }
}

void BrowserRenderProcessHost::EnableAutoSpellCorrect(bool enable) {
  Send(new ViewMsg_SpellChecker_EnableAutoSpellCorrect(enable));
}


text:
export const baseOptions = {
  tags: {
    p: {},
    br: false,
    b: {},
    strong: {},
    i: {},
    em: {},
    strike: {},
    ol: {},
    ul: {},
    li: {},
    a: { href: true, target: true, },
    h2: {},
    h3: {},
    u: {},
  },
};

export const baseTextOptions = Object.assign({}, baseOptions, {
  tags: Object.assign({}, baseOptions.tags, {
    blockquote: {},
  })
});

export const baseInlineOptions = {
  tags: {
    br: false,
    b: {},
    strong: {},
    em: {},
    i: {},
    u: {},
    a: { href: true, target: true },
    strike: {},
  },
};

export const toolbarButtons = [{
  command: 'bold',
  icon: 'bold',
}, {
  command: 'italic',
  icon: 'italic',
}, {
  command: 'underline',
  icon: 'underline',
}, {
  command: 'link',
  icon: 'link',
}, {
  command: 'h3',
  icon: 'header',
}];

const normalizeLink = (link) => {
  if (link.indexOf('http://') === 0 || link.indexOf('https://') === 0) {
    return link;
  }
  if (link.indexOf('@') >= 0) {
    return 'mailto:' + link;
  }
  if (link.indexOf('+') === 0) {
    return 'tel:' + link;
  }
  return 'http://' + link;
};

export const linkCommand = function () {
  return function (scribe) {
    const linkPromptCommand = new scribe.api.Command('createLink');
    linkPromptCommand.nodeName = 'A';

    linkPromptCommand.execute = function (passedLink) {
      const selection = new scribe.api.Selection();
      const range = selection.range;
      const anchorNode = selection.getContaining((node) => {
        return node.nodeName === this.nodeName;
      });

      // const initialLink = anchorNode ? anchorNode.href : '';
      if (anchorNode) {
        range.selectNode(anchorNode);
        selection.selection.removeAllRanges();
        selection.selection.addRange(range);
      }
      if (passedLink) {
        scribe.api.SimpleCommand.prototype.execute.call(this, normalizeLink(passedLink));
      }
    };

    linkPromptCommand.queryState = function() {
      const selection = new scribe.api.Selection();
      return !! selection.getContaining(function (node) {
        return node.nodeName === this.nodeName;
      }.bind(this));
    };

    linkPromptCommand.getCurrentLink = function() {
      const selection = new scribe.api.Selection();
      const anchorNode = selection.getContaining((node) => {
        return node.nodeName === this.nodeName;
      });
      return anchorNode ? anchorNode.href : '';
    };

    scribe.commands.setLink = linkPromptCommand;
  };
};

export const isEditorEmpty = (scribe) => {
  var childNodes = scribe.el.childNodes;
  var blockCount = childNodes.length;

  if (blockCount === 0) {
    return true;
  } else if (blockCount === 1) {
    var node = childNodes[0];
    var nodeName = node.nodeName.toLowerCase();

    if (nodeName === 'p' && node.textContent === '')   {
      return true;
    }
  }

  return false;
};

export const defaultCommands = {
  // bold: (e) => ((e.metaKey || e.ctrlKey) && e.which === 66),
  // italic: (e) => ((e.metaKey || e.ctrlKey) && e.which === 73),
  h3: (e) => ((e.metaKey || e.ctrlKey) && e.which === 51), // 3
};

export const keyboardPlugin = (commandsToKeyboardShortcutsMap = defaultCommands) => (scribe) => {

  scribe.el.addEventListener('keydown', function (event) {
    let commandName = '';
    for (var key in commandsToKeyboardShortcutsMap) {
      if (commandsToKeyboardShortcutsMap.hasOwnProperty(key)) {
        if (commandsToKeyboardShortcutsMap[key](event)) {
          commandName = key;
          break;
        }
      }
    }

    if (commandName) {
      var command = scribe.getCommand(commandName);
      event.preventDefault();

      if (command.queryEnabled()) {
        command.execute();
      }
    }
  });
};


text:
package co.yiiu.module.attachment.model;

import lombok.Getter;
import lombok.Setter;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by tomoya at 2018/1/24
 */
@Entity
@Table(name = "yiiu_attachment")
@Getter
@Setter
public class Attachment {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  private Integer id;
  // 文件存储的本地路径
  private String localPath;
  // 文件名字
  private String fileName;
  private Date inTime;
  // 文件访问地址
  private String requestUrl;
  private String type;
  private Integer width;
  private Integer height;
  // 文件大小
  private String size;
  // 文件后缀
  private String suffix;
  // 文件的MD5值,用于防止文件重复
  @Column(unique = true)
  private String md5;
}


text:
<?php

require_once(APPPATH.'modules/api/libraries/REST_Controller.php');

/**
 * Base Controller for API module
 */
class API_Controller extends REST_Controller {

	// The user who is consuming the API endpoint
	protected $mApiKey;
	protected $mUserID;
	protected $mUser;

	// Constructor
	public function __construct()
	{
		parent::__construct();

		// send PHP headers when necessary (e.g. enable CORS)
		$site_config = $this->config->item('site');
		$headers = empty($site_config['headers']) ? array() : $site_config['headers'];
		foreach ($headers as $header)
		{
			header($header);
		}

		$this->verify_token();
	}

	// Verify access token (e.g. API Key, JSON Web Token)
	protected function verify_token()
	{
		$this->mApiKey = $this->input->get_request_header('X-API-KEY');
		$key = $this->api_keys->get_by('key', $this->mApiKey);
		$this->mUserID = empty($key) ? NULL : $key->user_id;
		$this->mUser = empty($this->mUserID) ? NULL : $this->users->get($this->mUserID);
	}

	// Verify user authentication
	// $group parameter can be name, ID, name array, ID array, or mixed array
	// Reference: http://benedmunds.com/ion_auth/#in_group
	protected function verify_auth($groups = 'members')
	{
		$groups = is_string($groups) ? array($groups) : $groups;

		// user groups not match with requirement
		if ( !$this->ion_auth->in_group($groups, $this->mUserID) )
			$this->error_unauthorized();
	}

	// Shortcut functions following REST_Controller convention
	protected function success($msg = NULL)
	{
		$data = array('status' => TRUE);
		if ( !empty($msg) ) $data['message'] = $msg;
		$this->response($data, REST_Controller::HTTP_OK);
	}

	protected function created($msg = NULL)
	{
		$data = array('status' => TRUE);
		if ( !empty($msg) ) $data['message'] = $msg;
		$this->response($data, REST_Controller::HTTP_CREATED);
	}

	protected function accepted($msg = NULL)
	{
		$data = array('status' => TRUE);
		if ( !empty($msg) ) $data['message'] = $msg;
		$this->response($data, REST_Controller::HTTP_ACCEPTED);
	}

	protected function error($msg = 'An error occurs', $code = REST_Controller::HTTP_OK, $additional_data = array())
	{
		$data = array('status' => FALSE, 'error' => $msg);

		// (optional) append additional data
		if (!empty($additional_data))
			$data['data'] = $additional_data;

		$this->response($data, $code);
	}

	protected function error_bad_request()
	{
		$data = array('status' => FALSE);
		$this->response($data, REST_Controller::HTTP_BAD_REQUEST);
	}

	protected function error_unauthorized()
	{
		$data = array('status' => FALSE);
		$this->response($data, REST_Controller::HTTP_UNAUTHORIZED);
	}

	protected function error_forbidden()
	{
		$data = array('status' => FALSE);
		$this->response($data, REST_Controller::HTTP_FORBIDDEN);
	}

	protected function error_not_found()
	{
		$data = array('status' => FALSE);
		$this->response($data, REST_Controller::HTTP_NOT_FOUND);
	}

	protected function error_method_not_allowed()
	{
		$data = array('status' => FALSE);
		$this->response($data, REST_Controller::HTTP_METHOD_NOT_ALLOWED);
	}

	protected function error_not_implemented($additional_data = array())
	{
		// show "not implemented" info only during development mode
		if (ENVIRONMENT=='development')
		{
			$trace = debug_backtrace();
			$caller = $trace[1];

			$data = array(
				'url'			=> current_url(),
				'module'		=> $this->router->fetch_module(),
				'controller'	=> $this->router->fetch_class(),
				'action'		=> $this->router->fetch_method(),
			);

			if (!empty($additional_data))
				$data = array_merge($data, $additional_data);

			$this->error('Not implemented', REST_Controller::HTTP_NOT_IMPLEMENTED, $data);
		}
		else
		{
			$this->error_not_found();
		}
	}
}


text:
require 'rails_helper'

RSpec.describe "tenants/new", :type => :view do
  before(:each) do
    assign(:tenant, Tenant.new(
      :first_name => "MyString",
      :last_name => "MyString",
      :telephone_number => "MyString",
      :email_address => "MyString"
    ))
  end

  it "renders new tenant form" do
    render

    assert_select "form[action=?][method=?]", tenants_path, "post" do

      assert_select "input#tenant_first_name[name=?]", "tenant[first_name]"

      assert_select "input#tenant_last_name[name=?]", "tenant[last_name]"

      assert_select "input#tenant_telephone_number[name=?]", "tenant[telephone_number]"

      assert_select "input#tenant_email_address[name=?]", "tenant[email_address]"
    end
  end
end


text:
<?php

namespace Google\Service\CloudSearch;

class AclFixRequest extends \Google\Collection
{
  protected $collection_key = 'recipientEmails';
  /**
   * @var string[]
   */
  public $recipientEmails;
  /**
   * @var string
   */
  public $role;
  /**
   * @var bool
   */
  public $shouldFix;

  /**
   * @param string[]
   */
  public function setRecipientEmails($recipientEmails)
  {
    $this->recipientEmails = $recipientEmails;
  }
  /**
   * @return string[]
   */
  public function getRecipientEmails()
  {
    return $this->recipientEmails;
  }
  /**
   * @param string
   */
  public function setRole($role)
  {
    $this->role = $role;
  }
  /**
   * @return string
   */
  public function getRole()
  {
    return $this->role;
  }
  /**
   * @param bool
   */
  public function setShouldFix($shouldFix)
  {
    $this->shouldFix = $shouldFix;
  }
  /**
   * @return bool
   */
  public function getShouldFix()
  {
    return $this->shouldFix;
  }
}

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


text:
describe "check:branch" do
  let(:environment) { build(:environment, :production) }
  include_context "rake"

  it "invokes :check_branch" do
    Heroploy::Tasks::CheckTaskLib.any_instance.stub(:current_branch).and_return("my-branch")
    expect_any_instance_of(Heroploy::Tasks::CheckTaskLib).to receive(:check_branch).with("my-branch", "master", "production")
    task.invoke
  end
end


text: {{watcher}}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=11"/>
<meta name="generator" content="Doxygen 1.9.2"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>O2: O2sm_info Class Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

O2 2.0

A communication protocol for interactive music and media applications.

Public Member Functions |
Public Attributes |
List of all members

O2sm_info Class Reference

Inheritance diagram for O2sm_info:

  <map id="O2sm_5Finfo_map" name="O2sm_5Finfo_map">
<area href="class_bridge__info.html" alt="Bridge_info" shape="rect" coords="49,168,137,192"/>
<area href="class_proxy__info.html" alt="Proxy_info" shape="rect" coords="49,112,137,136"/>
<area href="class_o2node.html" alt="O2node" shape="rect" coords="0,56,88,80"/>
<area href="class_net__interface.html" alt="Net_interface" shape="rect" coords="98,56,186,80"/>
<area href="class_o2obj.html" alt="O2obj" shape="rect" coords="0,0,88,24"/>
  </map>

Public Member Functions

virtual bool 	local_is_synchronized ()

virtual bool 	schedule_before_send ()

virtual O2err 	send (bool block)

void 	poll_outgoing ()

void 	free_outgoing ()

virtual void 	show (int indent)

O2err 	accepted (Fds_info *conn)

O2err 	connected ()

 Public Member Functions inherited from Bridge_info

 	Bridge_info (Bridge_protocol *proto_)

O2err 	send_to_taps (O2message_ptr msg)

O2status 	status (const char **process)

 Public Member Functions inherited from Proxy_info

 	Proxy_info (const char *key, int tag)

virtual void 	remove ()

void 	delete_fds_info ()

virtual O2err 	deliver (O2netmsg_ptr msg)

O2message_ptr 	pre_send (int *tcp_flag)

void 	co_info (Fds_info *fds_info, const char *msg)

 Public Member Functions inherited from O2node

 	O2node (const char *key_, int tag_)

virtual const char * 	get_proc_name ()

 Public Member Functions inherited from O2obj

void * 	operator new (size_t size)

void 	operator delete (void *ptr)

 Public Member Functions inherited from Net_interface

virtual O2err 	writeable ()

Public Attributes

O2queue 	outgoing

 Public Attributes inherited from Bridge_info

int 	id

Bridge_protocol * 	proto

 Public Attributes inherited from O2node

int 	tag

O2string 	key

O2node * 	next

 Public Attributes inherited from Net_interface

Fds_info * 	fds_info

Member Function Documentation

◆ accepted()

          O2err O2sm_info::accepted
          (
          Fds_info *
          conn	)

inlinevirtual

Implements Net_interface.

◆ connected()

          O2err O2sm_info::connected
          (
          	)

inlinevirtual

Reimplemented from Net_interface.

◆ local_is_synchronized()

          virtual bool O2sm_info::local_is_synchronized
          (
          	)

inlinevirtual

Reimplemented from Bridge_info.

◆ schedule_before_send()

          virtual bool O2sm_info::schedule_before_send
          (
          	)

inlinevirtual

Reimplemented from Proxy_info.

◆ send()

          virtual O2err O2sm_info::send
          (
          bool
          block	)

inlinevirtual

Implements Bridge_info.

◆ show()

          virtual void O2sm_info::show
          (
          int
          indent	)

inlinevirtual

Reimplemented from Bridge_info.

The documentation for this class was generated from the following file:

/Users/rbd/o2/src/sharedmem.cpp

<address class="footer">
Generated by  1.9.2
</address>


text:
<?php

/** PHPExcel_IComparable */
require_once 'PHPExcel/IComparable.php';

/**
 * PHPExcel_Style_Alignment
 *
 * @category   PHPExcel
 * @package    PHPExcel_Style
 * @copyright  Copyright (c) 2006 - 2007 PHPExcel (http://www.codeplex.com/PHPExcel)
 */
class PHPExcel_Style_Alignment implements PHPExcel_IComparable
{
	/* Horizontal alignment styles */
	const HORIZONTAL_GENERAL				= 'general';
	const HORIZONTAL_LEFT					= 'left';
	const HORIZONTAL_RIGHT					= 'right';
	const HORIZONTAL_CENTER					= 'center';
	const HORIZONTAL_JUSTIFY				= 'justify';

	/* Vertical alignment styles */
	const VERTICAL_BOTTOM					= 'bottom';
	const VERTICAL_TOP						= 'top';
	const VERTICAL_CENTER					= 'center';
	const VERTICAL_JUSTIFY					= 'justify';

	/**
	 * Horizontal
	 *
	 * @var string
	 */
	private $_horizontal;

	/**
	 * Vertical
	 *
	 * @var string
	 */
	private $_vertical;

	/**
	 * Text rotation
	 *
	 * @var int
	 */
	private $_textRotation;

    /**
     * Create a new PHPExcel_Style_Alignment
     */
    public function __construct()
    {
    	// Initialise values
    	$this->_horizontal			= PHPExcel_Style_Alignment::HORIZONTAL_GENERAL;
    	$this->_vertical			= PHPExcel_Style_Alignment::VERTICAL_BOTTOM;
    	$this->_textRotation		= 0;
    }

    /**
     * Get Horizontal
     *
     * @return string
     */
    public function getHorizontal() {
    	return $this->_horizontal;
    }

    /**
     * Set Horizontal
     *
     * @param string $pValue
     */
    public function setHorizontal($pValue = PHPExcel_Style_Alignment::HORIZONTAL_GENERAL) {
    	$this->_horizontal = $pValue;
    }

    /**
     * Get Vertical
     *
     * @return string
     */
    public function getVertical() {
    	return $this->_vertical;
    }

    /**
     * Set Vertical
     *
     * @param string $pValue
     */
    public function setVertical($pValue = PHPExcel_Style_Alignment::VERTICAL_BOTTOM) {
    	$this->_vertical = $pValue;
    }

    /**
     * Get TextRotation
     *
     * @return int
     */
    public function getTextRotation() {
    	return $this->_textRotation;
    }

    /**
     * Set TextRotation
     *
     * @param int $pValue
     * @throws Exception
     */
    public function setTextRotation($pValue = 0) {
    	if ($pValue >= 0 && $pValue <= 180) {
    		$this->_textRotation = $pValue;
    	} else {
    		throw new Exception("Text rotation should be a value between 0 and 180.");
    	}
    }

	/**
	 * Get hash code
	 *
	 * @return string	Hash code
	 */
	public function getHashCode() {
    	return md5(
    		  $this->_horizontal
    		. $this->_vertical
    		. $this->_textRotation
    		. __CLASS__
    	);
    }

    /**
     * Duplicate object
     *
     * Duplicates the current object, also duplicating referenced objects (deep cloning).
     * Standard PHP clone does not copy referenced objects!
     *
     * @return PHPExcel_Style_Alignment
     */
	public function duplicate() {
		return unserialize(serialize($this));
	}
}


text:
.. image:: https://travis-ci.org/MagicStack/uvloop.svg?branch=master
    :target: https://travis-ci.org/MagicStack/uvloop

.. image:: https://img.shields.io/pypi/status/uvloop.svg?maxAge=2592000?style=plastic
    :target: https://pypi.python.org/pypi/uvloop

.. image:: https://img.shields.io/github/stars/magicstack/uvloop.svg?style=social&label=GitHub
    :target: https://github.com/MagicStack/uvloop

uvloop
======

`uvloop` is a fast, drop-in replacement of the built-in asyncio event loop.
`uvloop` is released under the MIT license.

`uvloop` and asyncio, combined with the power of async/await in Python 3.7,
makes it easier than ever to write high-performance networking code in Python.

`uvloop` makes asyncio fast. In fact, it is at least 2x faster than nodejs,
gevent, as well as any other Python asynchronous framework. The performance of
uvloop-based asyncio is close to that of Go programs.

You can read more about uvloop in this
`blog post <http://magic.io/blog/uvloop-blazing-fast-python-networking/>`_.

Architecture
------------

The asyncio module, introduced by PEP 3156, is a collection of network
transports, protocols, and streams abstractions, with a pluggable event loop.
The event loop is the heart of asyncio. It provides APIs for:

- scheduling calls,
- transmitting data over the network,
- performing DNS queries,
- handling OS signals,
- convenient abstractions to create servers and connections,
- working with subprocesses asynchronously.

`uvloop` implements the :class:`asyncio.AbstractEventLoop` interface which
means that it provides a drop-in replacement of the asyncio event loop.

`uvloop` is written in Cython and is built on top of libuv.

libuv is a high performance, multiplatform asynchronous I/O library used by
nodejs. Because of how wide-spread and popular nodejs is, libuv is fast and
stable.

`uvloop` implements all asyncio event loop APIs. High-level Python objects
wrap low-level libuv structs and functions. Inheritance is used to keep the
code DRY and ensure that any manual memory management is in sync with libuv
primitives' lifespans.

Contents
--------

.. toctree::
   :maxdepth: 1

   user/index
   dev/index


text:
//
//  BBBTOCCellConfigrator.h
//  BBBIosApp
//
//  Created by Owen Worley, Tomek Kuźma, Eric Yuan on 15/10/2014.
//

#import <Foundation/Foundation.h>
#import "BBBCellConfigurator.h"

/**
 *  Object used to configure `BBBTOCTableViewCell` with `BBBTOCItem`.
 *  Throws if passed other class objects to `configureCell:forObject`
 */
@interface BBBTOCCellConfigrator : NSObject <BBBCellConfigurator>

@end


text:
require File.expand_path("../../../setup", __FILE__)
require "omniconfig"

describe OmniConfig::Type::Base do
  let(:instance) { described_class.new }

  it "should set options from initialization" do
    instance = described_class.new(:foo => :bar)
    instance.options[:foo].should == :bar
  end

  it "should use UNSET_VALUE as a default" do
    instance.default.should == OmniConfig::UNSET_VALUE
  end

  it "should just let values pass through" do
    value = Object.new
    instance.value(value).should eql(value)
  end

  it "should use the newest value for a merge" do
    old = Object.new
    new = Object.new
    instance.merge(old, new).should eql(new)
  end

  it "should allow options to be set" do
    instance.options.should be_kind_of(Hash)
    instance.options["foo"] = "bar"
    instance.options["foo"].should == "bar"
  end

  describe "validations" do
    it "should raise an error if both a validator and a block are given" do
      expect { instance.add_validator(5) { |block| } }.
        to raise_error(ArgumentError)
    end

    it "should error if the validator doesn't validate properly" do
      validator = Object.new
      expect { instance.add_validator(validator) }.
        to raise_error(ArgumentError)
    end

    it "should add a validator instance" do
      klass = Class.new do
        def validate; end
      end

      instance.add_validator(klass.new)
    end

    it "should add a validator block" do
      instance.add_validator { |recorder, errors| }
    end

    it "should call the validators in order" do
      klass = Class.new do
        def validate(errors, value)
          value << "A"
        end
      end

      instance.add_validator(klass.new)
      instance.add_validator { |_, value| value << "B" }
      instance.add_validator { |_, value| value << "C" }

      result = []
      instance.validate(nil, result)

      result.should == ["A", "B", "C"]
    end
  end
end


text:
<?php

namespace SelfService\Controller\Api;

use SelfService\Document\Exception\NotFoundException;
use Zend\Http\Request;
use Zend\Http\Response;
use Zend\View\Model\JsonModel;
use Zend\Mvc\Controller\AbstractRestfulController;

class ProductController extends AbstractRestfulController {

  /**
   * @return \SelfService\Service\Entity\ProductService
   */
  protected function getProductService() {
    return $this->getServiceLocator()->get('SelfService\Service\Entity\ProductService');
  }

  /**
   * @return \SelfService\Service\Entity\ProvisionedProductService
   */
  protected function getProvisionedProductService() {
    return $this->getServiceLocator()->get('SelfService\Service\Entity\ProvisionedProductService');
  }

  /**
   * @return \SelfService\Provisioner\AbstractProvisioner
   */
  protected function getProvisioningAdapter() {
    return $this->getServiceLocator()->get('Provisioner');
  }

  /**
   * @return \Zend\Log\Logger
   */
  protected function getLogger() {
    return $this->getServiceLocator()->get('logger');
  }

  /**
   * Get response object
   *
   * @return \Zend\Http\Response
   */
  public function getResponse()
  {
    return parent::getResponse();
  }

  /**
   * Create a new resource
   *
   * @param  mixed $data
   * @return mixed
   */
  public function create($data)
  {
    $this->getResponse()->setStatusCode(Response::STATUS_CODE_501);
    $this->getResponse()->sendHeaders();
    return new JsonModel();
  }

  /**
   * Delete an existing resource
   *
   * @param  mixed $id
   * @return mixed
   */
  public function delete($id)
  {
    $this->getResponse()->setStatusCode(Response::STATUS_CODE_501);
    $this->getResponse()->sendHeaders();
    return new JsonModel();
  }

  /**
   * Return single resource
   *
   * @param  mixed $id
   * @return mixed
   */
  public function get($id)
  {
    $this->getResponse()->setStatusCode(Response::STATUS_CODE_501);
    $this->getResponse()->sendHeaders();
    return new JsonModel();
  }

  /**
   * Return list of resources
   *
   * @return mixed
   */
  public function getList()
  {
    $this->getResponse()->setStatusCode(Response::STATUS_CODE_501);
    $this->getResponse()->sendHeaders();
    return new JsonModel();
  }

  /**
   * Update an existing resource
   *
   * @param  mixed $id
   * @param  mixed $data
   * @return mixed
   */
  public function update($id, $data)
  {
    $this->getResponse()->setStatusCode(Response::STATUS_CODE_501);
    $this->getResponse()->sendHeaders();
    return new JsonModel();
  }

  /**
   * Note: When parameters are provided for instance_type or datacenter inputs the default_value
   * is overwritten with the selection which was passed in.
   * @return JsonModel
   */
  public function inputsAction() {
    $retval = array();
    if($this->getRequest()->getMethod() != Request::METHOD_POST) {
      $this->getResponse()->setStatusCode(Response::STATUS_CODE_405);
      $this->getResponse()->getHeaders()->addHeaderLine('Allow', array('POST'));
      $retval['messages'][] = "Only the POST method is allowed.";
    } else {
      $this->getResponse()->setStatusCode(Response::STATUS_CODE_200);
      try {
        $inputs = $this->getProductService()->inputs($this->params('id'), $this->params()->fromPost());
        foreach($inputs as $input) {
          $stdClass = $this->getProductService()->odmToStdClass($input);
          $stdClass->values = $input->values;
          $stdClass->cloud_href = $input->cloud_href;
          $retval[] = $stdClass;
        }
      } catch (NotFoundException $e) {
        $this->getResponse()->setStatusCode(Response::STATUS_CODE_404);
        $retval['messages'] = array($e->getMessage());
      }
    }
    return new JsonModel($retval);
  }

  public function provisionAction() {
    $retval = array();
    if($this->getRequest()->getMethod() != Request::METHOD_POST) {
      $this->getResponse()->setStatusCode(Response::STATUS_CODE_405);
      $this->getResponse()->getHeaders()->addHeaderLine('Allow', array('POST'));
      $retval['messages'][] = "Only the POST method is allowed.";
    } else {
      $product_id = $this->params('id');
      try {
        $provisioning_adapter = $this->getProvisioningAdapter();
        $prov_prod = $this->getProvisionedProductService()->create(array());

        $this->getResponse()->setStatusCode(Response::STATUS_CODE_201);

        $this->getLogger()->debug("Calling toOutputJson with the following params ".print_r($this->params()->fromPost(), true));
        $output_json = $this->getProductService()->toOutputJson($product_id, $this->params()->fromPost());

        $retval['messages'][] = sprintf(
          "View your provisioned product in the admin panel here.",
          $this->url()->fromRoute('provisionedproducts', array('action' => 'show', 'id' => $prov_prod->id))
        );

        $provisioning_adapter->provision($prov_prod->id, $output_json);
        $retval['messages'] = array_merge($retval['messages'], $provisioning_adapter->getMessages(true));

        $this->getResponse()->getHeaders()->addHeaderLine('Location',
          $this->url()->fromRoute('api-provisionedproduct', array('id' => $prov_prod->id)));
      } catch (NotFoundException $e) {
        $this->getResponse()->setStatusCode(Response::STATUS_CODE_404);
        $retval['messages'] = array($e->getMessage());
      } catch (\Exception $e) {
        $this->getResponse()->setStatusCode(Response::STATUS_CODE_500);
        $retval['messages'] = array($e->getMessage());
        $this->getLogger()->err("An error occurred attempting to provision ".$product_id." Error: ".$e->getMessage()." Trace: ".$e->getTraceAsString());
      }
    }
    return new JsonModel($retval);
  }
}


text:
class AddModelToCars < ActiveRecord::Migration
  def change
    add_column :cars, :model, :string
  end
end


text: ALTER IGNORE TABLE `watchlist` ADD UNIQUE KEY `watchlist_event_user` (`event_id`, `user_id`);


text:
require 'ansible/ruby/modules/base'

module Ansible
  module Ruby
    module Modules
      # The C(win_dns_client) module configures the DNS client on Windows network adapters.
      class Win_dns_client < Base
        # @return [String] Adapter name or list of adapter names for which to manage DNS settings ('*' is supported as a wildcard value). The adapter name used is the connection caption in the Network Control Panel or via C(Get-NetAdapter), eg C(Local Area Connection).
        attribute :adapter_names
        validates :adapter_names, presence: true, type: String

        # @return [Array<String>, String] Single or ordered list of DNS server IPv4 addresses to configure for lookup. An empty list will configure the adapter to use the DHCP-assigned values on connections where DHCP is enabled, or disable DNS lookup on statically-configured connections.
        attribute :ipv4_addresses
        validates :ipv4_addresses, presence: true, type: TypeGeneric.new(String, NilClass)
      end
    end
  end
end


text:
<?php

namespace NWJeffM\Generators;

use Illuminate\Support\ServiceProvider;

class GeneratorsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        $this->publishes([
            __DIR__ . '/config/repository.php' => config_path('repository.php')
        ], 'config');
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        $this->registerRepositoryGenerator();
    }

    /**
     * Register the make:repository command.
     */
    private function registerRepositoryGenerator()
    {
        $this->app->singleton('command.nwjeffm.repository', function($app) {
            return $app['NWJeffM\Generators\Commands\MakeRepositoryCommand'];
        });

        $this->commands('command.nwjeffm.repository');
    }
}


text:
module Spec
  module Support
    module ActiveResource
      module RepairHelper
        def record_validations(*klasses)
          klasses.inject({}) do |repair, klass|
            repair[klass] ||= {}
            [ :validate, :validate_on_create, :validate_on_update ].each do |phase|
              callbacks = klass.instance_variable_get("@#{phase.to_s}_callbacks")
              repair[klass][phase] = (callbacks.nil? ? nil : callbacks.dup)
            end
            repair
          end
        end

        def reset_validations(repairs)
          repairs.each do |klass, repair|
            [ :validate, :validate_on_create, :validate_on_update ].each do |phase|
              klass.instance_variable_set("@#{phase.to_s}_callbacks", repair[phase])
            end
          end
        end
      end
    end
  end
end


text:
using Microsoft.AspNetCore.Mvc;
using RedFolder.Services;

namespace RedFolder.Controllers.Api
{
    [Produces("application/xml")]
    [Route("sitemap.xml")]
    public class SiteMapController : Controller
    {
        [HttpGet]
        public IActionResult Get([FromServices]ISiteMapRepository repo)
        {
            return Ok(repo.GetSiteMap());
        }
    }
}


text:
<!doctype html>

		<title>Madison [builds] Sites - About</title>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
		<link href="https://fonts.googleapis.com/css?family=Open+Sans:400,300,700|Merriweather:400,400italic,700italic" rel="stylesheet" type="text/css">
		<link rel="stylesheet" href="../css/bootstrap.min.css">
		<link rel="stylesheet" href="../css/style.css">
		<link rel="stylesheet" href="../css/icons.css">
		<link rel="stylesheet" href="../css/animate.min.css">
		<link rel="stylesheet" href="../css/font-awesome.min.css">

Home

About

Contact

							Madison Sites

Technical Blog: Week 6

July 26, 2015

Home

...

					I traversed that hallowed grounds of classes, attribute readers/writers/accesors, and scope this week. And, after all that, when presented with the option to blog on any of the above, I chose something completely different: Blocks, Procs, and Lambdas.

Blocks

					Blocks are easy to understand in that Procs and Lambdas are applied to them. They're simply code blocks or methods: think of something as simple as the method to add numbers or as complicated as entering your order into a machine at a restaurant. The key to understanding the other two is how they react to the use of return...

Lambdas

					If a block is made with Lambda (lambda {return "code block!"}), and uses return, it immediately exits itself not only itself but looks to the rest of the method for what to do next. If we revert back to ordering food (with a human this time), think of the process of a restaurant like a method: a host seats you, a server asks for drink, a server returns with drinks, the server asks for appetizers, the server returns for re-fills, the server asks for your main dish, the server returns with appetizers, and, eventually your meal. This is a bit like your server calling lambda on "what can I get you to drink?": they move to the next item in the method of "serve_meals". They don't just walk out of the restaurant.

Procs

					If a block is made with Proc (Proc.new), and uses return, it immediately exits itself as well as the whole code block. Again with the food. What if you already know what you want as soon as you sit down to eat? Well, then your server can skip the rest of the "ordering food" method once they've asked you what you want to drink and you replied with "actually, here's everything I want".

Created by Madison Sites


text:
<?xml version="1.0" encoding="utf-8"?>
<CrawlItem xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Text>Ne razumijem ako več postoji, napomena restoranu zašto se ta napomena nikad ne ispuni, svaki put tražim više umaka u meksičku hranu a nikad ga ne dobijem, može odgovor zašto??</Text>
  <Rating>1.5</Rating>
  <Source>http://pauza.hr/menu/meduza-catering-savica</Source>
</CrawlItem>


text:
\documentclass[12pt,a4paper]{article}
\usepackage{graphicx}
\usepackage[margin=0.5in]{geometry}
\begin{document}
\thispagestyle{empty}
\begin{table}[]
\centering
\Huge
\begin{tabular}{cccc}
 Seahorse& Snake& Fork& Hammer\\  & & & \\
 Guitar& Fan& Cupcake& Mirror\\  & & & \\
 Horse& Sink& Keys& Skateboard\\  & & & \\
 Hanger& Firetruck& Paintbrush& Lock\\  & & & \\
 Pants& Pool& Magnet& Cloud\\  & & & \\
\end{tabular}
\end{table}
\end{document}


text:
package sonata.kernel.vimadaptor.wrapper.openstack;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;

import org.slf4j.LoggerFactory;

import sonata.kernel.vimadaptor.commons.NetworkConfigurePayload;
import sonata.kernel.vimadaptor.commons.ServiceDeployPayload;
import sonata.kernel.vimadaptor.commons.ServiceDeployResponse;
import sonata.kernel.vimadaptor.commons.ServiceRecord;
import sonata.kernel.vimadaptor.commons.Status;
import sonata.kernel.vimadaptor.commons.VduRecord;
import sonata.kernel.vimadaptor.commons.VnfRecord;
import sonata.kernel.vimadaptor.commons.VnfcInstance;
import sonata.kernel.vimadaptor.commons.nsd.ConnectionPoint;
import sonata.kernel.vimadaptor.commons.nsd.ConnectionPointRecord;
import sonata.kernel.vimadaptor.commons.nsd.InterfaceRecord;
import sonata.kernel.vimadaptor.commons.vnfd.VirtualDeploymentUnit;
import sonata.kernel.vimadaptor.commons.vnfd.VnfDescriptor;
import sonata.kernel.vimadaptor.wrapper.NetworkWrapper;
import sonata.kernel.vimadaptor.wrapper.WrapperBay;
import sonata.kernel.vimadaptor.wrapper.WrapperStatusUpdate;
import sonata.kernel.vimadaptor.wrapper.openstack.heat.HeatPort;
import sonata.kernel.vimadaptor.wrapper.openstack.heat.HeatServer;
import sonata.kernel.vimadaptor.wrapper.openstack.heat.HeatTemplate;
import sonata.kernel.vimadaptor.wrapper.openstack.heat.StackComposition;

import java.util.ArrayList;
import java.util.Hashtable;

public class DeployServiceFsm implements Runnable {

  private static final org.slf4j.Logger Logger = LoggerFactory.getLogger(DeployServiceFsm.class);
  private static final int maxCounter = 10;
  private OpenStackHeatClient client;
  private ServiceDeployPayload data;
  private String sid;
  private HeatTemplate stack;
  private OpenStackHeatWrapper wrapper;

  /**
   * Return an object that handles the FSM needed to deploy a service in OpenStackHeat.
   *
   * @param wrapper the Compute wrapper issuing this FSM
   * @param client the OpenStack client to use for the deployment
   * @param sid the session ID of the service platform call
   * @param data the payload of the service platform call
   * @param stack the HeatStack result of the translation
   */
  public DeployServiceFsm(OpenStackHeatWrapper wrapper, OpenStackHeatClient client, String sid,
      ServiceDeployPayload data, HeatTemplate stack) {

    this.wrapper = wrapper;
    this.client = client;
    this.sid = sid;
    this.data = data;
    this.stack = stack;
  }

  @Override
  public void run() {
    ServiceDeployResponse response = new ServiceDeployResponse();

    Logger.info("Deploying new stack");
    ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
    mapper.disable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
    mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
    mapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
    mapper.setSerializationInclusion(Include.NON_NULL);
    Logger.info("Serializing stack...");
    try {
      String stackString = mapper.writeValueAsString(stack);
      Logger.debug(stackString);
      String stackName = data.getNsd().getName() + data.getNsd().getInstanceUuid();
      Logger.info("Pushing stack to Heat...");
      String stackUuid = client.createStack(stackName, stackString);

      if (stackUuid == null) {
        WrapperStatusUpdate update = new WrapperStatusUpdate(this.sid, "FAIL",
            "{\"message\":\"unable to contact the VIM to instantiate the service\"}");
        wrapper.markAsChanged();
        wrapper.notifyObservers(update);
        return;
      }
      Logger.info("Stack pushed. Getting deployment status...");
      int counter = 0;
      int wait = 1000;
      String status = null;
      while ((status == null || !status.equals("CREATE_COMPLETE")
          || !status.equals("CREATE_FAILED")) && counter < DeployServiceFsm.maxCounter) {
        status = client.getStackStatus(stackName, stackUuid);
        Logger.debug("Status of stack " + stackUuid + ": " + status);
        if (status != null
            && (status.equals("CREATE_COMPLETE") || status.equals("CREATE_FAILED"))) {
          break;
        }
        try {
          Thread.sleep(wait);
        } catch (InterruptedException e) {
          Logger.error(e.getMessage(), e);
        }
        counter++;
        wait *= 2;
      }

      if (status == null) {
        WrapperStatusUpdate update = new WrapperStatusUpdate(this.sid, "ERROR",
            "unable to contact the VIM to check the instantiation status");
        wrapper.markAsChanged();
        wrapper.notifyObservers(update);
        return;
      }
      if (status.equals("CREATE_FAILED")) {
        // client.deleteStack(stackName, instanceUuid);
        WrapperStatusUpdate update =
            new WrapperStatusUpdate(this.sid, "ERROR", "Stack Creation Failed.");
        wrapper.markAsChanged();
        wrapper.notifyObservers(update);
        return;
      }
      Logger.info("Stack deployment complete");
      counter = 0;
      wait = 1000;
      StackComposition composition = null;
      while (composition == null && counter < DeployServiceFsm.maxCounter) {
        Logger.info("Getting composition of stack " + stackUuid);
        composition = client.getStackComposition(stackName, stackUuid);
        try {
          Thread.sleep(wait);
        } catch (InterruptedException e) {
          Logger.error(e.getMessage(), e);
        }
        counter++;
        wait *= 2;
      }

      if (composition == null) {
        WrapperStatusUpdate update = new WrapperStatusUpdate(this.sid, "ERROR",
            "unable to contact the VIM to check the instantiation status");
        wrapper.markAsChanged();
        wrapper.notifyObservers(update);
        return;
      }

      // Aux data structures for efficient mapping
      Hashtable<String, VnfDescriptor> vnfTable = new Hashtable<>();
      Hashtable<String, VirtualDeploymentUnit> vduTable =
          new Hashtable<String, VirtualDeploymentUnit>();
      Hashtable<String, VduRecord> vdurTable = new Hashtable<String, VduRecord>();

      // Create the response
      Logger.info("Creating deploy response");
      ServiceRecord sr = new ServiceRecord();
      sr.setStatus(Status.offline);
      sr.setDescriptorVersion("nsr-schema-01");
      sr.setId(data.getNsd().getInstanceUuid());
      sr.setDescriptorReference(data.getNsd().getUuid());
      for (VnfDescriptor vnf : data.getVnfdList()) {
        vnfTable.put(vnf.getName(), vnf);
        VnfRecord vnfr = new VnfRecord();
        vnfr.setDescriptorVersion("vnfr-schema-01");
        vnfr.setDescriptorReference(vnf.getUuid());
        // vnfr.setDescriptorReferenceName(vnf.getName());
        // vnfr.setDescriptorReferenceVendor(vnf.getVendor());
        // vnfr.setDescriptorReferenceVersion(vnf.getVersion());
        vnfr.setStatus(Status.offline);
        // TODO addresses are added next step
        // vnfr.setVnfAddress("0.0.0.0");

        vnfr.setId(vnf.getInstanceUuid());
        for (VirtualDeploymentUnit vdu : vnf.getVirtualDeploymentUnits()) {
          vduTable.put(vnf.getName() + ":" + vdu.getId(), vdu);
          VduRecord vdur = new VduRecord();
          vdur.setId(vdu.getId());
          vdur.setNumberOfInstances(1);
          vdur.setVduReference(vnf.getName() + ":" + vdu.getId());
          vdur.setVmImage(vdu.getVmImage());
          vdurTable.put(vdur.getVduReference(), vdur);
          vnfr.addVdu(vdur);
        }
        response.addVnfRecord(vnfr);
      }
      response.setNsr(sr);

      // Put each composition.server data in a VNFC instance in the relevant VDU

      for (HeatServer server : composition.getServers()) {
        String[] identifiers = server.getServerName().split(":");
        String vnfName = identifiers[0];
        String vduName = identifiers[1];
        String instanceId = identifiers[2];

        VnfcInstance vnfc = new VnfcInstance();
        vnfc.setId(instanceId);
        vnfc.setVimId(data.getVimUuid());
        vnfc.setVcId(server.getServerId());
        VnfDescriptor referenceVnf = vnfTable.get(vnfName);
        VirtualDeploymentUnit referenceVdu = vduTable.get(vnfName + ":" + vduName);

        ArrayList<ConnectionPointRecord> cpRecords = new ArrayList<ConnectionPointRecord>();

        for (ConnectionPoint cp : referenceVdu.getConnectionPoints()) {
          ConnectionPointRecord cpr = new ConnectionPointRecord();
          cpr.setId(cp.getId());

          // add each composition.ports information in the response. The IP, the netmask (and maybe
          // MAC address)
          for (HeatPort port : composition.getPorts()) {
            if (port.getPortName().equals(referenceVnf.getName() + ":" + cp.getId() + ":"
                + data.getNsd().getInstanceUuid())) {
              InterfaceRecord ip = new InterfaceRecord();
              if (port.getFloatinIp() != null) {
                ip.setAddress(port.getFloatinIp());
                ip.setHardwareAddress(port.getMacAddress());
                // Logger.info("Port:" + port.getPortName() + "- Addr: " +
                // port.getFloatinIp());
              } else {
                ip.setAddress(port.getIpAddress());
                ip.setHardwareAddress(port.getMacAddress());
                // Logger.info("Port:" + port.getPortName() + "- Addr: " +
                // port.getFloatinIp());
                ip.setNetmask("255.255.255.248");

              }
              cpr.setInterface(ip);
              cpr.setType(cp.getType());
              break;
            }
          }

          cpRecords.add(cpr);
        }
        vnfc.setConnectionPoints(cpRecords);
        VduRecord referenceVdur =
            vdurTable.get(referenceVnf.getName() + ":" + referenceVdu.getId());
        referenceVdur.addVnfcInstance(vnfc);
      }

      NetworkWrapper netVim =
          WrapperBay.getInstance().getNetworkVimFromComputeVimUuid(this.data.getVimUuid());

      response.setVimUuid(data.getVimUuid());
      response.setInstanceName(stackName);
      response.setInstanceVimUuid(stackUuid);
      response.setRequestStatus("COMPLETED");
      response.setMessage("");

      NetworkConfigurePayload netData = new NetworkConfigurePayload();
      netData.setNsd(data.getNsd());
      netData.setServiceInstanceId(data.getNsd().getInstanceUuid());
      netData.setVnfds(data.getVnfdList());
      netData.setVnfrs(response.getVnfrs());
      netVim.configureNetworking(netData);

      // Set to null hardware addresses from VNFR:VDU:CONNECTION_POINT to ensure compatibility with
      // VNFR_V1.0

      for (VnfRecord vnfr : response.getVnfrs()) {
        for (VduRecord vdur : vnfr.getVirtualDeploymentUnits()) {
          for (VnfcInstance vnfc : vdur.getVnfcInstance()) {
            for (ConnectionPointRecord cpr : vnfc.getConnectionPoints()) {
              cpr.getInterface().setHardwareAddress(null);
            }
          }
        }
      }

      String body = mapper.writeValueAsString(response);
      Logger.info("Response created");
      Logger.info(body);
      WrapperBay.getInstance().getVimRepo().writeServiceInstanceEntry(response.getNsr().getId(),
          response.getInstanceVimUuid(), response.getInstanceName(), data.getVimUuid());

      WrapperStatusUpdate update = new WrapperStatusUpdate(this.sid, "SUCCESS", body);
      wrapper.markAsChanged();
      wrapper.notifyObservers(update);
    } catch (Exception e) {
      Logger.error(e.getMessage(), e);
      response.setRequestStatus("ERROR");
      response.setMessage(e.getMessage());
      response.setNsr(null);
      response.setVnfrs(null);
      try {
        String body = mapper.writeValueAsString(response);
        Logger.info("Error response created");
        // Logger.info("body");

        // WrapperBay.getInstance().getVimRepo().writeInstanceEntry(response.getNsr().getId(),
        // response.getInstanceVimUuid(), response.getInstanceVimUuid());

        WrapperStatusUpdate update = new WrapperStatusUpdate(this.sid, "ERROR", body);
        wrapper.markAsChanged();
        wrapper.notifyObservers(update);
      } catch (Exception f) {
        Logger.error("Error while handling Error!", e);
      }
    }
  }

}