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

#include "ash/app_list/views/assistant/assistant_main_stage.h"

#include "ash/assistant/model/assistant_interaction_model.h"
#include "ash/assistant/model/assistant_query.h"
#include "ash/assistant/model/assistant_ui_model.h"
#include "ash/assistant/ui/assistant_ui_constants.h"
#include "ash/assistant/ui/assistant_view_delegate.h"
#include "ash/assistant/ui/assistant_view_ids.h"
#include "ash/assistant/ui/base/stack_layout.h"
#include "ash/assistant/ui/main_stage/assistant_footer_view.h"
#include "ash/assistant/ui/main_stage/assistant_progress_indicator.h"
#include "ash/assistant/ui/main_stage/assistant_query_view.h"
#include "ash/assistant/ui/main_stage/assistant_zero_state_view.h"
#include "ash/assistant/ui/main_stage/ui_element_container_view.h"
#include "ash/assistant/util/animation_util.h"
#include "ash/assistant/util/assistant_util.h"
#include "ash/constants/ash_features.h"
#include "ash/public/cpp/assistant/controller/assistant_interaction_controller.h"
#include "ash/public/cpp/assistant/controller/assistant_ui_controller.h"
#include "ash/public/cpp/style/color_provider.h"
#include "base/bind.h"
#include "base/time/time.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/color/color_id.h"
#include "ui/compositor/layer.h"
#include "ui/compositor/layer_animation_element.h"
#include "ui/compositor/layer_animator.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/color_palette.h"
#include "ui/gfx/geometry/insets.h"
#include "ui/views/background.h"
#include "ui/views/border.h"
#include "ui/views/controls/separator.h"
#include "ui/views/layout/box_layout.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/layout/layout_manager.h"

namespace ash {

namespace {

using assistant::util::CreateLayerAnimationSequence;
using assistant::util::CreateOpacityElement;
using assistant::util::CreateTransformElement;

// Appearance.
constexpr int kSeparatorThicknessDip = 1;
constexpr int kSeparatorWidthDip = 64;

// Footer entry animation.
constexpr base::TimeDelta kFooterEntryAnimationFadeInDelay =
    base::Milliseconds(283);
constexpr base::TimeDelta kFooterEntryAnimationFadeInDuration =
    base::Milliseconds(167);

// Divider animation.
constexpr base::TimeDelta kDividerAnimationFadeInDelay =
    base::Milliseconds(233);
constexpr base::TimeDelta kDividerAnimationFadeInDuration =
    base::Milliseconds(167);
constexpr base::TimeDelta kDividerAnimationFadeOutDuration =
    base::Milliseconds(83);

// Zero state animation.
constexpr base::TimeDelta kZeroStateAnimationFadeOutDuration =
    base::Milliseconds(83);
constexpr int kZeroStateAnimationTranslationDip = 115;
constexpr base::TimeDelta kZeroStateAnimationFadeInDelay =
    base::Milliseconds(33);
constexpr base::TimeDelta kZeroStateAnimationFadeInDuration =
    base::Milliseconds(167);
constexpr base::TimeDelta kZeroStateAnimationTranslateUpDuration =
    base::Milliseconds(250);

// Helpers ---------------------------------------------------------------------

// These classes exist to solely to provide a class name to UI devtools. They
// don't follow the style guide so they can be shorter.
class ContentContainer : public views::View {
 public:
  const char* GetClassName() const override { return "ContentContainer"; }
};

class MainContentContainer : public views::View {
 public:
  const char* GetClassName() const override { return "MainContentContainer"; }
};

class DividerContainer : public views::View {
 public:
  const char* GetClassName() const override { return "DividerContainer"; }
};

class FooterContainer : public views::View {
 public:
  const char* GetClassName() const override { return "FooterContainer"; }
};

// A view is considered shown when it is visible and not in the process of
// fading out.
bool IsShown(const views::View* view) {
  DCHECK(view->layer());
  bool is_fading_out =
      cc::MathUtil::IsWithinEpsilon(view->layer()->GetTargetOpacity(), 0.f);

  return view->GetVisible() && !is_fading_out;
}

}  // namespace

// AppListAssistantMainStage ---------------------------------------------------

AppListAssistantMainStage::AppListAssistantMainStage(
    AssistantViewDelegate* delegate)
    : delegate_(delegate) {
  SetID(AssistantViewID::kMainStage);
  InitLayout();

  assistant_controller_observation_.Observe(AssistantController::Get());
  AssistantInteractionController::Get()->GetModel()->AddObserver(this);
  AssistantUiController::Get()->GetModel()->AddObserver(this);
}

AppListAssistantMainStage::~AppListAssistantMainStage() {
  if (AssistantUiController::Get())
    AssistantUiController::Get()->GetModel()->RemoveObserver(this);

  if (AssistantInteractionController::Get())
    AssistantInteractionController::Get()->GetModel()->RemoveObserver(this);
}

void AppListAssistantMainStage::ChildPreferredSizeChanged(views::View* child) {
  PreferredSizeChanged();
}

void AppListAssistantMainStage::OnThemeChanged() {
  views::View::OnThemeChanged();
  horizontal_separator_->SetColorId(ui::kColorAshSystemUIMenuSeparator);
}

void AppListAssistantMainStage::OnViewPreferredSizeChanged(views::View* view) {
  PreferredSizeChanged();
  Layout();
  SchedulePaint();
}

void AppListAssistantMainStage::InitLayout() {
  // The children of AppListAssistantMainStage will be animated on their own
  // layers and we want them to be clipped by their parent layer.
  SetPaintToLayer();
  layer()->SetFillsBoundsOpaquely(false);
  layer()->SetMasksToBounds(true);

  views::BoxLayout* layout =
      SetLayoutManager(std::make_unique<views::BoxLayout>(
          views::BoxLayout::Orientation::kVertical));
  layout->set_main_axis_alignment(views::BoxLayout::MainAxisAlignment::kCenter);
  layout->set_cross_axis_alignment(
      views::BoxLayout::CrossAxisAlignment::kCenter);

  layout->SetFlexForView(AddChildView(CreateContentLayoutContainer()), 1);

  AddChildView(CreateFooterLayoutContainer());
}

std::unique_ptr<views::View>
AppListAssistantMainStage::CreateContentLayoutContainer() {
  // The content layout container stacks two views.
  // On top is a main content container including the line separator, progress
  // indicator query view and |ui_element_container_|.
  // The |zero_state_view_| is laid out above of the main content container. As
  // such, it floats above and does not cause repositioning to any of content
  // layout's underlying views.
  auto content_layout_container = std::make_unique<ContentContainer>();

  auto* stack_layout = content_layout_container->SetLayoutManager(
      std::make_unique<StackLayout>());

  auto* main_content_layout_container = content_layout_container->AddChildView(
      CreateMainContentLayoutContainer());

  // Do not respect height, otherwise bounds will not be set correctly for
  // scrolling.
  stack_layout->SetRespectDimensionForView(
      main_content_layout_container, StackLayout::RespectDimension::kWidth);

  // Zero state, which will be animated on its own layer.
  zero_state_view_ = content_layout_container->AddChildView(
      std::make_unique<AssistantZeroStateView>(delegate_));
  zero_state_view_->SetPaintToLayer();
  zero_state_view_->layer()->SetFillsBoundsOpaquely(false);

  return content_layout_container;
}

std::unique_ptr<views::View>
AppListAssistantMainStage::CreateMainContentLayoutContainer() {
  auto content_layout_container = std::make_unique<MainContentContainer>();
  views::BoxLayout* content_layout = content_layout_container->SetLayoutManager(
      std::make_unique<views::BoxLayout>(
          views::BoxLayout::Orientation::kVertical));
  content_layout->set_main_axis_alignment(
      views::BoxLayout::MainAxisAlignment::kCenter);
  content_layout->set_cross_axis_alignment(
      views::BoxLayout::CrossAxisAlignment::kCenter);

  content_layout_container->AddChildView(CreateDividerLayoutContainer());

  // Query view. Will be animated on its own layer.
  query_view_ = content_layout_container->AddChildView(
      std::make_unique<AssistantQueryView>());
  query_view_->SetPaintToLayer();
  query_view_->layer()->SetFillsBoundsOpaquely(false);
  query_view_->AddObserver(this);

  // UI element container.
  ui_element_container_ = content_layout_container->AddChildView(
      std::make_unique<UiElementContainerView>(delegate_));
  ui_element_container_->AddObserver(this);
  content_layout->SetFlexForView(ui_element_container_, 1,
                                 /*use_min_size=*/true);

  return content_layout_container;
}

std::unique_ptr<views::View>
AppListAssistantMainStage::CreateDividerLayoutContainer() {
  // Dividers: the progress indicator and the horizontal separator will be the
  // separator when querying and showing the results, respectively.
  auto divider_container = std::make_unique<DividerContainer>();
  divider_container->SetLayoutManager(std::make_unique<StackLayout>());

  // Progress indicator, which will be animated on its own layer.
  progress_indicator_ = divider_container->AddChildView(
      std::make_unique<AssistantProgressIndicator>());
  progress_indicator_->SetPaintToLayer();
  progress_indicator_->layer()->SetFillsBoundsOpaquely(false);

  // Horizontal separator, which will be animated on its own layer.
  horizontal_separator_ =
      divider_container->AddChildView(std::make_unique<views::Separator>());
  horizontal_separator_->SetID(kHorizontalSeparator);
  // views::Separator always secure at least 1px even if insets make separator
  // drawable height to 0px.
  int vertical_inset = (progress_indicator_->GetPreferredSize().height() -
                        kSeparatorThicknessDip) /
                       2;
  horizontal_separator_->SetBorder(
      views::CreateEmptyBorder(gfx::Insets::VH(vertical_inset, 0)));
  horizontal_separator_->SetColorId(ui::kColorAshSystemUIMenuSeparator);
  horizontal_separator_->SetPreferredSize(gfx::Size(
      kSeparatorWidthDip, progress_indicator_->GetPreferredSize().height()));
  horizontal_separator_->SetPaintToLayer();
  horizontal_separator_->layer()->SetFillsBoundsOpaquely(false);

  return divider_container;
}

std::unique_ptr<views::View>
AppListAssistantMainStage::CreateFooterLayoutContainer() {
  // Footer.
  // Note that the |footer_| is placed within its own view container so that as
  // its visibility changes, its parent container will still reserve the same
  // layout space. This prevents jank that would otherwise occur due to
  // |ui_element_container_| claiming that empty space.
  auto footer_container = std::make_unique<FooterContainer>();
  footer_container->SetLayoutManager(std::make_unique<views::FillLayout>());

  footer_ = footer_container->AddChildView(
      std::make_unique<AssistantFooterView>(delegate_));
  footer_->AddObserver(this);

  // The footer will be animated on its own layer.
  footer_->SetPaintToLayer();
  footer_->layer()->SetFillsBoundsOpaquely(false);

  return footer_container;
}

void AppListAssistantMainStage::AnimateInZeroState() {
  zero_state_view_->layer()->GetAnimator()->StopAnimating();

  // We're going to animate the zero state view up into position so we'll need
  // to apply an initial transformation.
  gfx::Transform transform;
  transform.Translate(0, kZeroStateAnimationTranslationDip);

  // Set up our pre-animation values.
  zero_state_view_->layer()->SetOpacity(0.f);
  zero_state_view_->layer()->SetTransform(transform);
  zero_state_view_->SetVisible(true);

  // Start animating the zero state view.
  zero_state_view_->layer()->GetAnimator()->StartTogether(
      {// Animate the transformation.
       CreateLayerAnimationSequence(CreateTransformElement(
           gfx::Transform(), kZeroStateAnimationTranslateUpDuration,
           gfx::Tween::Type::FAST_OUT_SLOW_IN_2)),
       // Animate the opacity to 100% with delay.
       CreateLayerAnimationSequence(
           ui::LayerAnimationElement::CreatePauseElement(
               ui::LayerAnimationElement::AnimatableProperty::OPACITY,
               kZeroStateAnimationFadeInDelay),
           CreateOpacityElement(1.f, kZeroStateAnimationFadeInDuration))});
}

void AppListAssistantMainStage::AnimateInFooter() {
  // Set up our pre-animation values.
  footer_->layer()->SetOpacity(0.f);

  // Animate the footer to 100% opacity with delay.
  footer_->layer()->GetAnimator()->StartAnimation(CreateLayerAnimationSequence(
      ui::LayerAnimationElement::CreatePauseElement(
          ui::LayerAnimationElement::AnimatableProperty::OPACITY,
          kFooterEntryAnimationFadeInDelay),
      CreateOpacityElement(1.f, kFooterEntryAnimationFadeInDuration)));
}

void AppListAssistantMainStage::OnAssistantControllerDestroying() {
  AssistantUiController::Get()->GetModel()->RemoveObserver(this);
  AssistantInteractionController::Get()->GetModel()->RemoveObserver(this);
  DCHECK(assistant_controller_observation_.IsObservingSource(
      AssistantController::Get()));
  assistant_controller_observation_.Reset();
}

void AppListAssistantMainStage::OnCommittedQueryChanged(
    const AssistantQuery& query) {
  // Update the view.
  query_view_->SetQuery(query);

  // If query is empty and we are showing zero state, do not update the Ui.
  if (query.Empty() && IsShown(zero_state_view_))
    return;

  // Hide the horizontal separator.
  horizontal_separator_->layer()->GetAnimator()->StartAnimation(
      CreateLayerAnimationSequence(
          CreateOpacityElement(0.f, kDividerAnimationFadeOutDuration)));

  // Show the progress indicator.
  progress_indicator_->layer()->GetAnimator()->StartAnimation(
      CreateLayerAnimationSequence(
          // Delay...
          ui::LayerAnimationElement::CreatePauseElement(
              ui::LayerAnimationElement::AnimatableProperty::OPACITY,
              kDividerAnimationFadeInDelay),
          // ...then fade in.
          CreateOpacityElement(1.f, kDividerAnimationFadeInDuration)));

  MaybeHideZeroState();
}

void AppListAssistantMainStage::OnPendingQueryChanged(
    const AssistantQuery& query) {
  // Update the view.
  query_view_->SetQuery(query);

  if (!IsShown(zero_state_view_))
    return;

  // Animate the opacity to 100% with delay equal to |zero_state_view_| fade out
  // animation duration to avoid the two views displaying at the same time.
  constexpr base::TimeDelta kQueryAnimationFadeInDuration =
      base::Milliseconds(433);
  query_view_->layer()->SetOpacity(0.f);
  query_view_->layer()->GetAnimator()->StartAnimation(
      CreateLayerAnimationSequence(
          ui::LayerAnimationElement::CreatePauseElement(
              ui::LayerAnimationElement::AnimatableProperty::OPACITY,
              kZeroStateAnimationFadeOutDuration),
          CreateOpacityElement(1.f, kQueryAnimationFadeInDuration)));

  if (!query.Empty())
    MaybeHideZeroState();
}

void AppListAssistantMainStage::OnPendingQueryCleared(bool due_to_commit) {
  // When a pending query is cleared, it may be because the interaction was
  // cancelled, or because the query was committed. If the query was committed,
  // reseting the query here will have no visible effect. If the interaction was
  // cancelled, we set the query here to restore the previously committed query.
  query_view_->SetQuery(
      AssistantInteractionController::Get()->GetModel()->committed_query());
}

void AppListAssistantMainStage::OnResponseChanged(
    const scoped_refptr<AssistantResponse>& response) {
  MaybeHideZeroState();

  // Show the horizontal separator.
  horizontal_separator_->layer()->GetAnimator()->StartAnimation(
      CreateLayerAnimationSequence(
          // Delay...
          ui::LayerAnimationElement::CreatePauseElement(
              ui::LayerAnimationElement::AnimatableProperty::OPACITY,
              kDividerAnimationFadeInDelay),
          // ...then fade in.
          CreateOpacityElement(1.f, kDividerAnimationFadeInDuration)));

  // Hide the progress indicator.
  progress_indicator_->layer()->GetAnimator()->StartAnimation(
      CreateLayerAnimationSequence(
          CreateOpacityElement(0.f, kDividerAnimationFadeOutDuration)));
}

void AppListAssistantMainStage::OnUiVisibilityChanged(
    AssistantVisibility new_visibility,
    AssistantVisibility old_visibility,
    absl::optional<AssistantEntryPoint> entry_point,
    absl::optional<AssistantExitPoint> exit_point) {
  if (assistant::util::IsStartingSession(new_visibility, old_visibility)) {
    const bool from_search =
        entry_point == AssistantEntryPoint::kLauncherSearchResult;
    InitializeUIForStartingSession(from_search);
    return;
  }

  query_view_->SetQuery(AssistantNullQuery());

  footer_->SetVisible(true);
  footer_->layer()->SetOpacity(1.f);
  footer_->SetCanProcessEventsWithinSubtree(true);
}

void AppListAssistantMainStage::InitializeUIForBubbleView() {
  InitializeUIForStartingSession(/*from_search=*/false);
}

void AppListAssistantMainStage::MaybeHideZeroState() {
  if (!IsShown(zero_state_view_))
    return;

  assistant::util::FadeOutAndHide(zero_state_view_,
                                  kZeroStateAnimationFadeOutDuration);
}

void AppListAssistantMainStage::InitializeUIForStartingSession(
    bool from_search) {
  // When Assistant is starting a new session, we animate in the appearance of
  // the zero state view and footer.
  progress_indicator_->layer()->SetOpacity(0.f);
  horizontal_separator_->layer()->SetOpacity(from_search ? 1.f : 0.f);

  if (!from_search)
    AnimateInZeroState();
  else
    zero_state_view_->SetVisible(false);

  footer_->InitializeUIForBubbleView();
  AnimateInFooter();
}

BEGIN_METADATA(AppListAssistantMainStage, views::View)
END_METADATA

}  // namespace ash


text:
fqdn = node['set_fqdn']
if fqdn
  # set the domain and hostname from the node name by default
  hostname, domain = node.name.split('.', 2) if !node.name.nil? && !node.name.empty?
  # if we have the hostname in the fqdn, use that instead
  if fqdn =~ /\*\./
    domain = fqdn.sub('*.', '')
  else
    hostname, domain = fqdn.split('.', 2)
  end

  case node['platform']
  when 'freebsd'
    directory '/etc/rc.conf.d' do
      mode '0755'
    end

    rc_conf_lines = ["hostname=#{fqdn}\n"]
    if node['hostname_cookbook']['hostsfile_ip_interface']
      rc_conf_lines <<
        "ifconfig_#{node['hostname_cookbook']['hostsfile_ip_interface']}_alias=\"inet #{node['hostname_cookbook']['hostsfile_ip']}/32\"\n"
      service 'netif'
    end

    file '/etc/rc.conf.d/hostname' do
      content rc_conf_lines.join
      mode '0644'
      notifies :reload, 'service[netif]', :immediately \
        if node['hostname_cookbook']['hostsfile_ip_interface']
    end

    execute "hostname #{fqdn}" do
      only_if { node['fqdn'] != fqdn }
      notifies :reload, 'ohai[reload_hostname]', :immediately
    end

  when 'centos', 'redhat', 'amazon', 'scientific'
    service 'network' do
      action :nothing
    end
    hostfile = '/etc/sysconfig/network'
    file hostfile do
      action :create
      content lazy {
        ::IO.read(hostfile).gsub(/^HOSTNAME=.*$/, "HOSTNAME=#{fqdn}")
      }
      notifies :reload, 'ohai[reload_hostname]', :immediately
      notifies :restart, 'service[network]', :delayed
    end
    # this is to persist the correct hostname after machine reboot
    sysctl = '/etc/sysctl.conf'
    file sysctl do
      action :create
      content lazy {
        ::IO.read(sysctl) + "kernel.hostname=#{hostname}\n"
      }
      not_if { ::IO.read(sysctl) =~ /^kernel\.hostname=#{hostname}$/ }
      notifies :reload, 'ohai[reload_hostname]', :immediately
      notifies :restart, 'service[network]', :delayed
    end
    execute "hostname #{hostname}" do
      only_if { node['hostname'] != hostname }
      notifies :reload, 'ohai[reload_hostname]', :immediately
    end
  else
    file '/etc/hostname' do
      content "#{hostname}\n"
      mode '0644'
      notifies :reload, 'ohai[reload_hostname]', :immediately
    end

    execute "hostname #{hostname}" do
      only_if { node['hostname'] != hostname }
      notifies :reload, 'ohai[reload_hostname]', :immediately
    end
  end

  hostsfile_entry 'localhost' do
    ip_address '127.0.0.1'
    hostname 'localhost'
    action :append
  end

  hostsfile_entry 'set hostname' do
    ip_address node['hostname_cookbook']['use_node_ip'] ? node['ipaddress'] : node['hostname_cookbook']['hostsfile_ip']
    hostname "#{hostname}.#{domain}"
    aliases [hostname]
    action :create
    notifies :reload, 'ohai[reload_hostname]', :immediately
  end

  ohai 'reload_hostname' do
    plugin 'hostname'
    action :nothing
  end
else
  log 'Please set the set_fqdn attribute to desired hostname' do
    level :warn
  end
end

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace ProjectBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * Project
 */
class Project
{
    /**
     * @var integer
     */
    private $id;

    /**
     * @var string
     */
    private $categorie;

    /**
     * @var string
     *@Assert\NotBlank()
     */
    private $title;

    /**
     * @var integer
     */
    private $duree;

    /**
     * @var integer
     */
    private $amountRequested;

	/**
     * @var integer
     */
    private $amountWon;

    /**
     * @var \DateTime
     */
    private $endDate;

    /**
     * @var \DateTime
     */
    private $beginDate;

    /**
     * @var string
     */
    private $location;

    /**
     * @var string
     * @Assert\Length(min=280)
     */
    private $description;

    /**
     * @var string
     */
    private $managers;

    /**
    * @ORM\OneToOne(targetEntity="ProjectBundle\Entity\Image", cascade={"persist"})
    */
     private $image;

    /**
     * @var integer
     */
    private $homepage;

    /**
     * @var integer
     */
    private $pushers;

    /**
     * @var string
     */
    private $author;

    /**
     * Get id
     *
     * @return integer
     */

	public function __construct()
	{
		$this->beginDate = new \DateTime();
		$this->amountWon = 0;
	}

    public function getId()
    {
        return $this->id;
    }

    /**
     * Set categorie
     *
     * @param string $categorie
     * @return Project
     */
    public function setCategorie($categorie)
    {
        $this->categorie = $categorie;

        return $this;
    }

    /**
     * Get categorie
     *
     * @return string
     */
    public function getCategorie()
    {
        return $this->categorie;
    }

    /**
     * Set title
     *
     * @param string $title
     * @return Project
     */
    public function setTitle($title)
    {
        $this->title = $title;

        return $this;
    }

    /**
     * Get title
     *
     * @return string
     */
    public function getTitle()
    {
        return $this->title;
    }

    /**
     * Set duree
     *
     * @param integer $duree
     * @return Project
     */
    public function setDuree($duree)
    {
        $this->duree = $duree;

        return $this;
    }

    /**
     * Get duree
     *
     * @return integer
     */
    public function getDuree()
    {
        return $this->duree;
    }

    /**
     * Set amountRequested
     *
     * @param integer $amountRequested
     * @return Project
     */
    public function setAmountRequested($amountRequested)
    {
        $this->amountRequested = $amountRequested;

        return $this;
    }

    /**
     * Get amountRequested
     *
     * @return integer
     */
    public function getAmountRequested()
    {
        return $this->amountRequested;
    }

    /**
     * Set endDate
     *
     * @param \DateTime $endDate
     * @return Project
     */
    public function setEndDate($endDate)
    {
        $this->endDate = $endDate;

        return $this;
    }

    /**
     * Get endDate
     *
     * @return \DateTime
     */
    public function getEndDate()
    {
        return $this->endDate;
    }

    /**
     * Set beginDate
     *
     * @param \DateTime $beginDate
     * @return Project
     */
    public function setBeginDate($beginDate)
    {
        $this->beginDate = $beginDate;

        return $this;
    }

    /**
     * Get beginDate
     *
     * @return \DateTime
     */
    public function getBeginDate()
    {
        return $this->beginDate;
    }

    /**
     * Set location
     *
     * @param string $location
     * @return Project
     */
    public function setLocation($location)
    {
        $this->location = $location;

        return $this;
    }

    /**
     * Get location
     *
     * @return string
     */
    public function getLocation()
    {
        return $this->location;
    }

    /**
     * Set description
     *
     * @param string $description
     * @return Project
     */
    public function setDescription($description)
    {
        $this->description = $description;

        return $this;
    }

    /**
     * Get description
     *
     * @return string
     */
    public function getDescription()
    {
        return $this->description;
    }

    /**
     * Set managers
     *
     * @param string $managers
     * @return Project
     */
    public function setManagers($managers)
    {
        $this->managers = $managers;

        return $this;
    }

    /**
     * Get managers
     *
     * @return string
     */
    public function getManagers()
    {
        return $this->managers;
    }

    /**
     * Set image
     *
     * @param string $image
     * @return Project
     */
    public function setImage(Image $image = null)
    {
    $this->image = $image;
    }

    /**
     * Get image
     *
     * @return string
     */
    public function getImage()
    {
        return $this->image;
    }

    /**
     * Set homepage
     *
     * @param integer $homepage
     * @return Project
     */
    public function setHomepage($homepage)
    {
        $this->homepage = $homepage;

        return $this;
    }

    /**
     * Get homepage
     *
     * @return integer
     */
    public function getHomepage()
    {
        return $this->homepage;
    }

    /**
     * Set pushers
     *
     * @param integer $pushers
     * @return Project
     */
    public function setPushers($pushers)
    {
        $this->pushers = $pushers;

        return $this;
    }

    /**
     * Get pushers
     *
     * @return integer
     */
    public function getPushers()
    {
        return $this->pushers;
    }

    /**
     * @var string
     */
    private $titreRecompense1;

    /**
     * @var string
     */
    private $descriptionRecompense1;

    /**
     * Set titreRecompense1
     *
     * @param string $titreRecompense1
     * @return Project
     */
    public function setTitreRecompense1($titreRecompense1)
    {
        $this->titreRecompense1 = $titreRecompense1;

        return $this;
    }

    /**
     * Get titreRecompense1
     *
     * @return string
     */
    public function getTitreRecompense1()
    {
        return $this->titreRecompense1;
    }

    /**
     * Set descriptionRecompense1
     *
     * @param string $descriptionRecompense1
     * @return Project
     */
    public function setDescriptionRecompense1($descriptionRecompense1)
    {
        $this->descriptionRecompense1 = $descriptionRecompense1;

        return $this;
    }

    /**
     * Get descriptionRecompense1
     *
     * @return string
     */
    public function getDescriptionRecompense1()
    {
        return $this->descriptionRecompense1;
    }
    /**
     * @var string
     */
    private $titreRecompense2;

    /**
     * @var string
     */
    private $descriptionRecompense2;

    /**
     * @var string
     */
    private $titreRecompense3;

    /**
     * @var string
     */
    private $descriptionRecompense3;

    /**
     * @var string
     */
    private $titreRecompense4;

    /**
     * @var string
     */
    private $descriptionRecompense4;

    /**
     * @var string
     */
    private $titreRecompense5;

    /**
     * @var string
     */
    private $descriptionRecompense5;

     /**
     * @var integer
     */
    private $active = 1;

    /**
     * Set titreRecompense2
     *
     * @param string $titreRecompense2
     * @return Project
     */
    public function setTitreRecompense2($titreRecompense2)
    {
        $this->titreRecompense2 = $titreRecompense2;

        return $this;
    }

    /**
     * Get titreRecompense2
     *
     * @return string
     */
    public function getTitreRecompense2()
    {
        return $this->titreRecompense2;
    }

    /**
     * Set descriptionRecompense2
     *
     * @param string $descriptionRecompense2
     * @return Project
     */
    public function setDescriptionRecompense2($descriptionRecompense2)
    {
        $this->descriptionRecompense2 = $descriptionRecompense2;

        return $this;
    }

    /**
     * Get descriptionRecompense2
     *
     * @return string
     */
    public function getDescriptionRecompense2()
    {
        return $this->descriptionRecompense2;
    }

    /**
     * Set titreRecompense3
     *
     * @param string $titreRecompense3
     * @return Project
     */
    public function setTitreRecompense3($titreRecompense3)
    {
        $this->titreRecompense3 = $titreRecompense3;

        return $this;
    }

    /**
     * Get titreRecompense3
     *
     * @return string
     */
    public function getTitreRecompense3()
    {
        return $this->titreRecompense3;
    }

    /**
     * Set descriptionRecompense3
     *
     * @param string $descriptionRecompense3
     * @return Project
     */
    public function setDescriptionRecompense3($descriptionRecompense3)
    {
        $this->descriptionRecompense3 = $descriptionRecompense3;

        return $this;
    }

    /**
     * Get descriptionRecompense3
     *
     * @return string
     */
    public function getDescriptionRecompense3()
    {
        return $this->descriptionRecompense3;
    }

    /**
     * Set titreRecompense4
     *
     * @param string $titreRecompense4
     * @return Project
     */
    public function setTitreRecompense4($titreRecompense4)
    {
        $this->titreRecompense4 = $titreRecompense4;

        return $this;
    }

    /**
     * Get titreRecompense4
     *
     * @return string
     */
    public function getTitreRecompense4()
    {
        return $this->titreRecompense4;
    }

    /**
     * Set descriptionRecompense4
     *
     * @param string $descriptionRecompense4
     * @return Project
     */
    public function setDescriptionRecompense4($descriptionRecompense4)
    {
        $this->descriptionRecompense4 = $descriptionRecompense4;

        return $this;
    }

    /**
     * Get descriptionRecompense4
     *
     * @return string
     */
    public function getDescriptionRecompense4()
    {
        return $this->descriptionRecompense4;
    }

    /**
     * Set titreRecompense5
     *
     * @param string $titreRecompense5
     * @return Project
     */
    public function setTitreRecompense5($titreRecompense5)
    {
        $this->titreRecompense5 = $titreRecompense5;

        return $this;
    }

    /**
     * Get titreRecompense5
     *
     * @return string
     */
    public function getTitreRecompense5()
    {
        return $this->titreRecompense5;
    }

    /**
     * Set descriptionRecompense5
     *
     * @param string $descriptionRecompense5
     * @return Project
     */
    public function setDescriptionRecompense5($descriptionRecompense5)
    {
        $this->descriptionRecompense5 = $descriptionRecompense5;

        return $this;
    }

    /**
     * Get descriptionRecompense5
     *
     * @return string
     */
    public function getDescriptionRecompense5()
    {
        return $this->descriptionRecompense5;
    }

    /**
     * Set active
     *
     * @param integer $active
     * @return Project
     */
    public function setActive($active)
    {
        $this->active = $active;

        return $this;
    }

    /**
     * Get active
     *
     * @return integer
     */
    public function getActive()
    {
        return $this->active;
    }

    //IMAGE

    /**
     * @ORM\Column(type="string", length=255, nullable=true)
     */
    public $path;

    public function getAbsolutePath()
    {
        return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
    }

    public function getWebPath()
    {
        return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
    }

    protected function getUploadRootDir()
    {
        // le chemin absolu du répertoire où les documents uploadés doivent être sauvegardés
        return __DIR__.'/../../../web/'.$this->getUploadDir();
    }

    protected function getUploadDir()
    {
        // on se débarrasse de « __DIR__ » afin de ne pas avoir de problème lorsqu'on affiche
        // le document/image dans la vue.
        return 'uploads/documents';
    }

    /**
     * Set path
     *
     * @param string $path
     * @return Project
     */
    public function setPath($path)
    {
        $this->path = $path;

        return $this;
    }

    /**
     * Get path
     *
     * @return string
     */
    public function getPath()
    {
        return $this->path;
    }

    /**
     * @Assert\File(maxSize="6000000")
     */
    public $file;

    public function upload()
    {
        // la propriété « file » peut être vide si le champ n'est pas requis
        if (null === $this->file) {
            return;
        }

        // utilisez le nom de fichier original ici mais
        // vous devriez « l'assainir » pour au moins éviter
        // quelconques problèmes de sécurité

        // la méthode « move » prend comme arguments le répertoire cible et
        // le nom de fichier cible où le fichier doit être déplacé
        $this->file->move($this->getUploadRootDir(), $this->file->getClientOriginalName());

        // définit la propriété « path » comme étant le nom de fichier où vous
        // avez stocké le fichier
        $this->path = $this->file->getClientOriginalName();

        // « nettoie » la propriété « file » comme vous n'en aurez plus besoin
        $this->file = null;
    }

    /**
     * Set author
     *
     * @param string $author
     * @return Project
     */
    public function setAuthor($author)
    {
        $this->author = $author;

        return $this;
    }

    /**
     * Get author
     *
     * @return string
     */
    public function getAuthor()
    {
        return $this->author;
    }

    /**
     * Set amountWon
     *
     * @param integer $amountWon
     * @return Project
     */
    public function setAmountWon($amountWon)
    {
        $this->amountWon = $amountWon;

        return $this;
    }

    /**
     * Get amountWon
     *
     * @return integer
     */
    public function getAmountWon()
    {
        return $this->amountWon;
    }
}


text:
layout: post
title: "Special Buildings - Where they are?"
excerpt: "Exploring some services available in São Paulo"
categories: articles
modified: 2016-09-23
tags:
  - R
  - Maps
  - SAO PAULO
image:
  #feature: so-simple-sample-image-7.jpg
  #credit: WeGraphics
  #creditlink: http://wegraphics.net/downloads/free-ultimate-blurred-background-pack/
comments: true
share: true
categories: [articles]
date: 2016-09-23
author: cesar
---

Before we start, did you have followed the setup steps described at [here]({{site.url}}/RStudioSetupV2)

# Let's explore data

- let's process some services available

```R
# this object contains some of the services available in GeoSampa

saopaulo.data.equipamentosList

allEquipamentos <- saopaulo.data.downloadBatch(saopaulo.data.equipamentosList )
#this creates a list of lists
collectionOfEquipamentos <-  saopaulo.data.processShapeListsAsList(allEquipamentos,"sirgas|SIRGAS")

# test your data
plot(collectionOfEquipamentos[[4]])

```

- Detect what build it is an equipament

```R
#Edification
Edificacao = geofracker.downloadAndUnzipShp(saopaulo.data.edificacaoList[79])
#http://geosampa.prefeitura.sp.gov.br/PaginasPublicas/downloadArquivoOL.aspx?orig=DownloadCamadas&arq=06_Habita%E7%E3o%20e%20Edifica%E7%E3o%5C%5CEdifica%E7%E3o%5C%5CShapefile%5C%5CSHP_edificacao_AGUA_RASA&arqTipo=Shapefile

Edificacao1 <- readOGR(dsn=Edificacao$dir[1], layer=Edificacao$shapeclass[1])
plot(Edificacao1)
datasetIdx <- 25
#fix projection
proj4string(collectionOfEquipamentos[[datasetIdx]]) <- Edificacao1@proj4string

ct = rgeos::gContains( Edificacao1,collectionOfEquipamentos[[datasetIdx]],byid=TRUE, returnDense=TRUE )
#Returns a matrix of where colmns are Edificacao1
#Rows are collectionOfEquipamentos[[datasetIdx]]
ncol(ct) == length(Edificacao1)
length(ct[,1]) == length(collectionOfEquipamentos[[datasetIdx]])

Edificacao1@data$Area <- apply(ct, 2,any)
Edificacao1KnownServiceArea <- subset(Edificacao1, Edificacao1@data$Area == TRUE)

subset(Edificacao1, Edificacao1@data$Area == TRUE)

plot(Edificacao1)
#plot(Edificacao1[colsub,],add=T,col='green')
plot(collectionOfEquipamentos[[datasetIdx]],add=T,pch=16, col='red')
plot(Edificacao1KnownServiceArea,add=T,col='green')

```

Creating a function to mark special buildings:

```R

geofracker.markServiceBuildings <- function(edifications, equipamentosCollection) {
  df <- data.frame(matrix(ncol = 0, nrow = length(Edificacao1)))
  index <- 1
  i <- 0
  for (equipament in collectionOfEquipamentos){
    print(paste(length(shapeSource), "-",index))
    #fix projection
    proj4string(equipament) <- edifications@proj4string
    ct = rgeos::gContains( edifications,equipament,byid=TRUE, returnDense=TRUE )
    resultAppend <- apply(ct, 2,any)
    df[,index] <- resultAppend
    index <- index + 1
  }
  resultFinal <- apply(df,1,any)
  return(resultFinal)
}

result <- geofracker.markServiceBuildings(Edificacao1,collectionOfEquipamentos)

Edificacao1@data$SpecialArea <- result
Edificacao1KnownServiceArea <- subset(Edificacao1, Edificacao1@data$SpecialArea == TRUE)

plot(Edificacao1)
plot(Edificacao1KnownServiceArea,add=T,col='green')

```

![Sample Image]({{site.url}}/images/20160923_MarkingSpecialBuilding.png)

# References:

<http://www.ats.ucla.edu/stat/r/library/advanced_function_r.htm>

<http://www.cookbook-r.com/Manipulating_data/Adding_and_removing_columns_from_a_data_frame/>

<https://cran.r-project.org/web/packages/rgeos/rgeos.pdf>

<https://www.r-bloggers.com/rgeos-update/>

<http://www.nickeubank.com/wp-content/uploads/2015/10/RGIS2_MergingSpatialData_part2_GeometricManipulations.html>

<https://www.nceas.ucsb.edu/scicomp/usecases/point-in-polygon>

<http://stackoverflow.com/questions/19002744/spover-for-point-in-polygon-analysis-in-r>

<http://stackoverflow.com/questions/21971447/check-if-point-is-in-spatial-object-which-consists-of-multiple-polygons-holes>


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

#include "chrome/browser/notifications/scheduler/internal/scheduled_notification_manager.h"

#include <algorithm>
#include <map>
#include <unordered_set>
#include <utility>
#include <vector>

#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/containers/contains.h"
#include "base/guid.h"
#include "base/memory/raw_ref.h"
#include "base/memory/weak_ptr.h"
#include "base/threading/thread_task_runner_handle.h"
#include "chrome/browser/notifications/scheduler/internal/icon_store.h"
#include "chrome/browser/notifications/scheduler/internal/notification_entry.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_config.h"
#include "chrome/browser/notifications/scheduler/internal/scheduler_utils.h"
#include "chrome/browser/notifications/scheduler/internal/stats.h"
#include "chrome/browser/notifications/scheduler/public/notification_params.h"
#include "chrome/browser/notifications/scheduler/public/notification_scheduler_constant.h"
#include "chrome/grit/generated_resources.h"
#include "ui/base/l10n/l10n_util.h"

namespace notifications {
namespace {

// Comparator used to sort notification entries based on creation time.
bool CreateTimeCompare(const NotificationEntry* lhs,
                       const NotificationEntry* rhs) {
  DCHECK(lhs && rhs);
  return lhs->create_time < rhs->create_time;
}

// Vailidates notification entry. Returns false if the entry should be deleted.
bool ValidateNotificationEntry(const NotificationEntry& entry) {
  // Check the deliver time window.
  return (entry.schedule_params.deliver_time_start.has_value() &&
          entry.schedule_params.deliver_time_end.has_value() &&
          entry.schedule_params.deliver_time_end > base::Time::Now() &&
          entry.schedule_params.deliver_time_end >=
              entry.schedule_params.deliver_time_start);
}

class ScheduledNotificationManagerImpl : public ScheduledNotificationManager {
 public:
  using NotificationStore = std::unique_ptr<CollectionStore<NotificationEntry>>;

  ScheduledNotificationManagerImpl(
      NotificationStore notification_store,
      std::unique_ptr<IconStore> icon_store,
      const std::vector<SchedulerClientType>& clients,
      const SchedulerConfig& config)
      : notification_store_(std::move(notification_store)),
        icon_store_(std::move(icon_store)),
        clients_(clients.begin(), clients.end()),
        config_(config) {}
  ScheduledNotificationManagerImpl(const ScheduledNotificationManagerImpl&) =
      delete;
  ScheduledNotificationManagerImpl& operator=(
      const ScheduledNotificationManagerImpl&) = delete;

 private:
  // NotificationManager implementation.
  void Init(InitCallback callback) override {
    icon_store_->InitAndLoadKeys(base::BindOnce(
        &ScheduledNotificationManagerImpl::OnIconStoreInitialized,
        weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
  }

  void ScheduleNotification(
      std::unique_ptr<NotificationParams> notification_params,
      ScheduleCallback callback) override {
    DCHECK(notification_params);
    std::string guid = notification_params->guid;
    DCHECK(!guid.empty());
    auto type = notification_params->type;
    stats::LogNotificationLifeCycleEvent(
        stats::NotificationLifeCycleEvent::kScheduleRequest, type);

    if (!clients_.count(type) ||
        (notifications_.count(type) && notifications_[type].count(guid))) {
      // TODO(xingliu): Report duplicate guid failure.
      std::move(callback).Run(false);
      return;
    }

    bool valid = ValidateNotificationParams(*notification_params);
    DCHECK(valid) << "Invalid notification parameters.";
    if (!valid) {
      stats::LogNotificationLifeCycleEvent(
          stats::NotificationLifeCycleEvent::kInvalidInput, type);
      std::move(callback).Run(false);
      return;
    }

    if (notification_params->enable_ihnr_buttons) {
      CreateInhrButtonsPair(&notification_params->notification_data.buttons);
    }

    auto entry =
        std::make_unique<NotificationEntry>(notification_params->type, guid);
    auto icon_bundles = std::move(notification_params->notification_data.icons);
    entry->notification_data =
        std::move(notification_params->notification_data);
    entry->schedule_params = std::move(notification_params->schedule_params);
    icon_store_->AddIcons(
        std::move(icon_bundles),
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconsAdded,
                       weak_ptr_factory_.GetWeakPtr(), std::move(entry),
                       std::move(callback)));
  }

  void DisplayNotification(const std::string& guid,
                           DisplayCallback callback) override {
    NotificationEntry* entry = nullptr;
    for (auto it = notifications_.begin(); it != notifications_.end(); it++) {
      if (it->second.count(guid)) {
        entry = it->second[guid].get();
        break;
      }
    }

    if (!entry) {
      std::move(callback).Run(nullptr);
      return;
    }

    std::vector<std::string> keys;
    for (const auto& pair : entry->icons_uuid) {
      keys.emplace_back(pair.second);
    }
    icon_store_->LoadIcons(
        std::move(keys),
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconsLoaded,
                       weak_ptr_factory_.GetWeakPtr(), entry->type, entry->guid,
                       std::move(callback)));
  }

  void GetAllNotifications(Notifications* notifications) const override {
    DCHECK(notifications);
    notifications->clear();

    for (auto it = notifications_.begin(); it != notifications_.end(); it++) {
      auto type = it->first;
      for (const auto& pair : it->second) {
        (*notifications)[type].emplace_back(pair.second.get());
      }
    }

    // Sort by creation time for each notification type.
    for (auto it = notifications->begin(); it != notifications->end(); ++it) {
      std::sort(it->second.begin(), it->second.end(), &CreateTimeCompare);
    }
  }

  void GetNotifications(
      SchedulerClientType type,
      std::vector<const NotificationEntry*>* notifications) const override {
    DCHECK(notifications);
    notifications->clear();
    const auto it = notifications_.find(type);
    if (it == notifications_.end())
      return;
    for (const auto& pair : it->second)
      notifications->emplace_back(pair.second.get());
  }

  void DeleteNotifications(SchedulerClientType type) override {
    if (!notifications_.count(type))
      return;

    auto it = notifications_[type].begin();
    while (it != notifications_[type].end()) {
      const auto& entry = *it->second;
      ++it;
      DeleteNotification(entry, false /*should_delete_in_memory*/);
    }
    notifications_.erase(type);
  }

  void OnIconStoreInitialized(InitCallback callback,
                              bool success,
                              IconStore::LoadedIconKeys loaded_keys) {
    stats::LogDbInit(stats::DatabaseType::kIconDb, success,
                     loaded_keys ? loaded_keys->size() : 0);

    if (!success) {
      std::move(callback).Run(false);
      return;
    }

    notification_store_->InitAndLoad(base::BindOnce(
        &ScheduledNotificationManagerImpl::OnNotificationStoreInitialized,
        weak_ptr_factory_.GetWeakPtr(), std::move(callback),
        std::move(loaded_keys)));
  }

  void OnNotificationStoreInitialized(
      InitCallback callback,
      std::unique_ptr<std::vector<std::string>> loaded_icon_keys,
      bool success,
      CollectionStore<NotificationEntry>::Entries entries) {
    stats::LogDbInit(stats::DatabaseType::kNotificationDb, success,
                     entries.size());

    if (!success) {
      std::move(callback).Run(false);
      return;
    }

    FilterNotificationEntries(std::move(entries));
    FilterIconEntries(std::move(loaded_icon_keys));
    std::move(callback).Run(true);
  }

  void FilterIconEntries(
      std::unique_ptr<std::vector<std::string>> uuids_from_icon_store) {
    std::unordered_set<std::string> icons_uuid_from_entries;
    for (const auto& client_pair : notifications_) {
      for (const auto& notification : client_pair.second) {
        for (const auto& icon : notification.second->icons_uuid) {
          icons_uuid_from_entries.emplace(icon.second);
        }
      }
    }
    std::vector<std::string> icons_to_delete;
    for (const auto& loaded_icon_key : *uuids_from_icon_store.get()) {
      if (!base::Contains(icons_uuid_from_entries, loaded_icon_key)) {
        icons_to_delete.emplace_back(loaded_icon_key);
      }
    }
    icon_store_->DeleteIcons(
        icons_to_delete,
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconDeleted,
                       weak_ptr_factory_.GetWeakPtr()));
  }

  // Filters and loads notification into memory.
  void FilterNotificationEntries(
      CollectionStore<NotificationEntry>::Entries entries) {
    for (auto it = entries.begin(); it != entries.end(); it++) {
      auto* entry = it->get();
      // Prune expired notifications. Also delete them in db.
      bool expired = entry->create_time + config_->notification_expiration <=
                     base::Time::Now();
      bool valid = ValidateNotificationEntry(*entry);
      bool deprecated_client = !base::Contains(clients_, entry->type);
      if (expired || deprecated_client || !valid) {
        DeleteNotification(*entry, false /*should_delete_in_memory*/);
      } else {
        notifications_[entry->type].emplace(entry->guid, std::move(*it));
      }
    }
  }

  void OnIconsAdded(std::unique_ptr<NotificationEntry> entry,
                    ScheduleCallback schedule_callback,
                    IconStore::IconTypeUuidMap icons_uuid_map,
                    bool success) {
    stats::LogDbOperation(stats::DatabaseType::kIconDb, success);

    if (!success) {
      std::move(schedule_callback).Run(false);
      return;
    }

    entry->icons_uuid = std::move(icons_uuid_map);
    const auto* entry_ptr = entry.get();
    notification_store_->Add(
        entry_ptr->guid, *entry_ptr,
        base::BindOnce(&ScheduledNotificationManagerImpl::OnNotificationAdded,
                       weak_ptr_factory_.GetWeakPtr(), std::move(entry),
                       std::move(schedule_callback)));
  }

  void OnNotificationAdded(std::unique_ptr<NotificationEntry> entry,
                           ScheduleCallback schedule_callback,
                           bool success) {
    stats::LogDbOperation(stats::DatabaseType::kNotificationDb, success);

    // Delete the icons when failed to add to notification database.
    if (!success) {
      std::vector<std::string> icons_to_delete;
      for (const auto& uuid : entry->icons_uuid) {
        icons_to_delete.emplace_back(uuid.second);
      }
      icon_store_->DeleteIcons(
          std::move(icons_to_delete),
          base::BindOnce(&ScheduledNotificationManagerImpl::OnIconDeleted,
                         weak_ptr_factory_.GetWeakPtr()));
      std::move(schedule_callback).Run(false);
      return;
    }

    auto type = entry->type;
    auto guid = entry->guid;
    notifications_[type][guid] = std::move(entry);

    stats::LogNotificationLifeCycleEvent(
        stats::NotificationLifeCycleEvent::kScheduled, type);
    std::move(schedule_callback).Run(true);
  }

  void OnNotificationDeleted(bool success) {
    stats::LogDbOperation(stats::DatabaseType::kNotificationDb, success);
  }

  void OnIconDeleted(bool success) {
    stats::LogDbOperation(stats::DatabaseType::kIconDb, success);
  }

  void OnIconsLoaded(SchedulerClientType client_type,
                     const std::string& guid,
                     DisplayCallback display_callback,
                     bool success,
                     IconStore::LoadedIconsMap loaded_icons_map) {
    stats::LogDbOperation(stats::DatabaseType::kIconDb, success);

    auto* entry_ptr = FindNotificationEntry(client_type, guid);
    if (!entry_ptr) {
      std::move(display_callback).Run(nullptr);
      return;
    }

    if (!success) {
      DeleteNotification(*entry_ptr, true /*should_delete_in_memory*/);
      std::move(display_callback).Run(nullptr);
      return;
    }

    // Glue the icon data to entry.
    std::unique_ptr<NotificationEntry> entry =
        std::move(notifications_[client_type][guid]);
    DCHECK(entry);
    for (const auto& pair : entry->icons_uuid) {
      auto icon_bundle = IconBundle(std::move(loaded_icons_map[pair.second]));
      entry->notification_data.icons.emplace(pair.first,
                                             std::move(icon_bundle));
    }

    // Before moving out the entry, delete it from container and disk.
    DeleteNotification(*entry.get(), true /*should_delete_in_memory*/);

    std::move(display_callback).Run(std::move(entry));
  }

  NotificationEntry* FindNotificationEntry(SchedulerClientType type,
                                           const std::string& guid) {
    if (!notifications_.count(type) || !notifications_[type].count(guid))
      return nullptr;
    return notifications_[type][guid].get();
  }

  // Delete NotitificationEntry from memory and disk.
  void DeleteNotification(const NotificationEntry& entry,
                          bool should_delete_in_memory) {
    // Deletes icon first.
    std::vector<std::string> icons_to_delete;
    for (const auto& icon_id : entry.icons_uuid) {
      icons_to_delete.emplace_back(icon_id.second);
    }
    icon_store_->DeleteIcons(
        std::move(icons_to_delete),
        base::BindOnce(&ScheduledNotificationManagerImpl::OnIconDeleted,
                       weak_ptr_factory_.GetWeakPtr()));

    auto guid = entry.guid;
    auto type = entry.type;

    // Deletes notification entry.
    notification_store_->Delete(
        guid,
        base::BindOnce(&ScheduledNotificationManagerImpl::OnNotificationDeleted,
                       weak_ptr_factory_.GetWeakPtr()));

    if (should_delete_in_memory) {
      notifications_[type].erase(guid);
      if (notifications_[type].empty())
        notifications_.erase(type);
    }
  }

  // Create two default buttons {Helpful, Unhelpful} for notification.
  void CreateInhrButtonsPair(std::vector<NotificationData::Button>* buttons) {
    buttons->clear();
    NotificationData::Button helpful_button;
    helpful_button.type = ActionButtonType::kHelpful;
    helpful_button.id = notifications::kDefaultHelpfulButtonId;
    helpful_button.text =
        l10n_util::GetStringUTF16(IDS_NOTIFICATION_DEFAULT_HELPFUL_BUTTON_TEXT);
    buttons->emplace_back(std::move(helpful_button));

    NotificationData::Button unhelpful_button;
    unhelpful_button.type = ActionButtonType::kUnhelpful;
    unhelpful_button.id = notifications::kDefaultUnhelpfulButtonId;
    unhelpful_button.text = l10n_util::GetStringUTF16(
        IDS_NOTIFICATION_DEFAULT_UNHELPFUL_BUTTON_TEXT);
    buttons->emplace_back(std::move(unhelpful_button));
  }

  // Vailidates notification parameters. Returns false if the parameters are
  // invalid.
  bool ValidateNotificationParams(const NotificationParams& params) {
    // Validate time window. Currently we only support deliver notification
    // according to a time window, the deliver window should before the
    // expiration duration of notification data in config.
    if (!params.schedule_params.deliver_time_start.has_value() ||
        !params.schedule_params.deliver_time_end.has_value() ||
        params.schedule_params.deliver_time_start.value() >
            params.schedule_params.deliver_time_end.value() ||
        params.schedule_params.deliver_time_end.value() - base::Time::Now() >=
            config_->notification_expiration) {
      return false;
    }

    // Validate ihnr buttons option. Custom buttons will be overwritten.
    if (params.enable_ihnr_buttons &&
        !params.notification_data.buttons.empty()) {
      return false;
    }

    // Validate icon bundle data is correct: icon resource id should never be
    // persisted to disk,since it can change in different versions. Client
    // should overwrite with Android resource id in BeforeShowNotification
    // callback if it is required.
    for (const auto& icon_bundle_map : params.notification_data.icons) {
      const auto& icon_bundle = icon_bundle_map.second;
      if (icon_bundle.resource_id)
        return false;
    }

    return true;
  }

  NotificationStore notification_store_;
  std::unique_ptr<IconStore> icon_store_;
  const std::unordered_set<SchedulerClientType> clients_;
  std::map<SchedulerClientType,
           std::map<std::string, std::unique_ptr<NotificationEntry>>>
      notifications_;
  const raw_ref<const SchedulerConfig, DanglingUntriaged> config_;
  base::WeakPtrFactory<ScheduledNotificationManagerImpl> weak_ptr_factory_{
      this};
};

}  // namespace

// static
std::unique_ptr<ScheduledNotificationManager>
ScheduledNotificationManager::Create(
    std::unique_ptr<CollectionStore<NotificationEntry>> notification_store,
    std::unique_ptr<IconStore> icon_store,
    const std::vector<SchedulerClientType>& clients,
    const SchedulerConfig& config) {
  return std::make_unique<ScheduledNotificationManagerImpl>(
      std::move(notification_store), std::move(icon_store), clients, config);
}

ScheduledNotificationManager::ScheduledNotificationManager() = default;

ScheduledNotificationManager::~ScheduledNotificationManager() = default;

}  // namespace notifications


text:
from django.contrib.sites import requests
import requests
from django.test import TestCase
from AutoDoApp.parser.Parser import Parser
from AutoDoApp.generator.Generator import Generator
import os
from django.conf import settings

class GeneratorTestCase(TestCase):

    def setUp(self):

        self.git_address = "https://github.com/JunoJunho/AutoDoTestApp"
        self.project_name = "AutoDoTestApp"
        self.p = Parser()
        self.test_graph = Generator()
        self.test_readme = Generator()
        self.test_api = Generator()
        self.test_document = Generator()
        #self.client = Client()
        self.parsing_dir = os.path.join(settings.BASE_DIR, "parsing_result")
        if not os.path.exists(self.parsing_dir):
            os.mkdir(self.parsing_dir)

        git_dir = os.path.join(settings.BASE_DIR, "git_project")
        if not os.path.exists(git_dir):
            os.mkdir(git_dir)

    #invalid wrong valid
    def test_invalid_input_graph(self):
        #result = self.p.parse_project(git_url=self.correct_git_address)

        test_data = [("class A", "class A", "method1"),("class B", "class 1", "method2"),("class C",)]
        self.assertRaises(ValueError, self.test_graph.generate_graph, test_data,"TestInvalidInputGraph")

    def test_valid_input_graph(self):
        file_name = "TestValidGraph"
        test_data = [("class A", "class A", "method1"), ("class B", "class 1", "method2"), ("class C","class A","method3")]
        url = self.test_graph.generate_graph(test_data, "TestValidGraph")
        request = requests.get(url)
        self.assertTrue(request.status_code == 200)

    def test_invalid_name_readme(self):
        self.assertRaises(TypeError, self.test_readme.generate_readme_md, [], "test","test",[])

    def test_invalid_desc_readme(self):
        self.assertRaises(TypeError, self.test_readme.generate_readme_md, "TestInvalidReadme", [], "test", [])

    def test_invalid_licen_readme(self):
        self.assertRaises(TypeError, self.test_readme.generate_readme_md, "TestInvalidReadme", "test", [], [])

    def test_invalid_req_readme(self):
        self.assertRaises(TypeError, self.test_readme.generate_readme_md, "TestInvalidReadme", "test", "test", "test")

    def test_invalid_url_readme(self):
        self.assertRaises(ValueError, self.test_readme.generate_readme_md, "TestInvalidReadme", "test", "test", [])

    def test_valid_readme(self):
        file_name = "TestValidGraph"
        test_data = [("class A", "class A", "method1"), ("class B", "class A", "method2"),
                     ("class C", "class A", "method3")]
        self.test_readme.generate_graph(test_data, "TestValidGraph")
        self.test_readme.generate_readme_md("TestValidGraph", "test", "test", [])
        self.assertTrue(os.path.isfile(os.path.join(self.parsing_dir,file_name)+".md"))

    def test_invalid_api(self):
        self.assertRaises(TypeError, self.test_api.generate_api, [])

    def test_valid_api(self):
        self.test_api.generate_api({})
        self.assertTrue(True)

    def test_valid_document(self):
        re = self.p.parse_project(self.git_address)
        #generate_document(self, data, name, raw_api, desc, licen, req):
        #tu = [graph, name, self.parse_api(), self.req_list, self.license]
        self.test_document.generate_document(re[0],re[1],re[2],"desc", re[4],re[3])
        self.assertTrue(os.path.isfile(os.path.join(self.parsing_dir,self.project_name)+".md"))


text:
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { RouterModule } from '@angular/router';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';

// import needed PrimeNG modules here

import { <%= angularXAppName %>SharedModule } from '../../../shared/shared.module';
import {FormsModule} from '@angular/forms';
import {PanelModule} from 'primeng/panel';
import {ButtonModule} from 'primeng/button';
import {SplitButtonModule} from 'primeng/splitbutton';
import {ToastModule} from 'primeng/toast';
import {WizardModule} from 'primeng-extensions/components/wizard/wizard.js';
import {MessageService} from 'primeng/api';

import {
    PanelDemoComponent,
    panelDemoRoute
} from './';

const PRIMENG_STATES = [
    panelDemoRoute
];

@NgModule({
    imports: [
        <%= angularXAppName %>SharedModule,
        BrowserAnimationsModule,
        FormsModule,
        PanelModule,
        ToastModule,
        SplitButtonModule,
        ButtonModule,
        WizardModule,
        RouterModule.forRoot(PRIMENG_STATES, { useHash: true })
    ],
    declarations: [
        PanelDemoComponent
    ],
    providers: [MessageService],
    schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class <%= angularXAppName %>PanelDemoModule {}


text:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:drawable="@drawable/gv_animation"
    android:fromDegrees="180"
    android:toDegrees="180"
    android:pivotX="50%"
    android:pivotY="50%">

</rotate>


text:
namespace blink {

OnRequestCanvasDrawListener::OnRequestCanvasDrawListener(
    std::unique_ptr<CanvasCaptureHandler> handler)
    : AutoCanvasDrawListener(std::move(handler)) {}

OnRequestCanvasDrawListener::~OnRequestCanvasDrawListener() = default;

void OnRequestCanvasDrawListener::SendNewFrame(
    scoped_refptr<StaticBitmapImage> image,
    base::WeakPtr<WebGraphicsContext3DProviderWrapper> context_provider) {
  frame_capture_requested_ = false;
  AutoCanvasDrawListener::SendNewFrame(image, context_provider);
}

void OnRequestCanvasDrawListener::Trace(Visitor* visitor) {
  AutoCanvasDrawListener::Trace(visitor);
}

}  // namespace blink


text:
<?php

namespace iFixit\Matryoshka;

use iFixit\Matryoshka;

class APCu extends Backend {
   public static function isAvailable() {
      return function_exists('apcu_enabled') && apcu_enabled();
   }

   public function set($key, $value, $expiration = 0) {
      return apcu_store($key, $value, $expiration);
   }

   /**
    * TODO: the other backends' setMultiple() returns a bool, we should fix the way we're
    * handling this for consistency. See: https://github.com/iFixit/Matryoshka/issues/30
    *
    * @return array Returns array of keys that had errors
    */
   public function setMultiple(array $values, $expiration = 0) {
      return apcu_store($values, null, $expiration);
   }

   public function add($key, $value, $expiration = 0) {
      return apcu_add($key, $value, $expiration);
   }

   public function increment($key, $amount = 1, $expiration = 0) {
      $value = apcu_inc($key, $amount, $success);

      // Call set() if the key doesn't exist.
      if ($success) {
         return $value;
      } else if ($this->set($key, $amount, $expiration) !== false) {
         return $amount;
      } else {
         return false;
      }
   }

   public function decrement($key, $amount = 1, $expiration = 0) {
      return $this->increment($key, -$amount, $expiration);
   }

   public function get($key) {
      $value = apcu_fetch($key, $success);

      return $success ? $value : self::MISS;
   }

   public function getMultiple(array $keys) {
      if (empty($keys)) {
         return [[],[]];
      }

      /**
       * @psalm-suppress InvalidArgument
       *
       * Default to an empty array in case no keys were found.
       */
      $hits = apcu_fetch(array_keys($keys)) ?: [];

      $found = [];
      $missed = [];
      foreach ($keys as $key => $id) {
         $value = array_key_exists($key, $hits) ? $hits[$key] : self::MISS;
         // Abstract class function docs say $found[] should contain all keys
         // with null values for the misses, so we store the result even
         // when it's a miss.
         $found[$key] = $value;

         if ($value === self::MISS) {
            $missed[$key] = $id;
         }
      }

      return [$found, $missed];
   }

   public function delete($key) {
      return apcu_delete($key);
   }

   public function deleteMultiple(array $keys) {
      // The docs leave out the fact that apcu_delete() can take an array of keys,
      // when you provide an array of keys, it provides an array of errors (if any)
      // so the only successful case is no errors (empty array).
      $ret = apcu_delete($keys);
      /**
       * In the docs, the apcu_delete returns an array if passed one.
       * Ref: https://www.php.net/manual/en/function.apcu-delete.php
       * Psalm gets this wrong.
       * @psalm-suppress InvalidArgument
       */
      return empty($ret);
   }

   public function getAbsoluteKey($key) {
      return $key;
   }
}


text:
#ifndef Ancona_Engine_EntityFramework_UnorderedSystem_H_
#define Ancona_Engine_EntityFramework_UnorderedSystem_H_

#include <unordered_map>
#include <type_traits>

#include <Ancona/Framework/EntityFramework/AbstractSystem.hpp>
#include <Ancona/Framework/EntityFramework/Entity.hpp>
#include <Ancona/Framework/EntityFramework/SystemManager.hpp>
#include <Ancona/Framework/EntityFramework/UpdateStep.hpp>
#include <Ancona/Framework/Serializing/Serializing.hpp>
#include <Ancona/Util/Algorithm.hpp>
#include <Ancona/Util/Assert.hpp>

namespace ild
{

GENERATE_METHOD_TESTER(FetchDependencies);

/**
 * @brief Implements most of the logic needed by a system for tracking components.
 * Any system that does not need its components stored in a specific order should
 * inherit from this class.
 *
 * Note: All components in the system will be destroyed when the system is destroyed.
 *
 * @author Jeff Swenson
 *
 * @tparam ComponentType The type of component that the system manages.
 */
template <class ComponentType>
class UnorderedSystem : public AbstractSystem
{
    public:
        /**
         * @brief Construct and initialize the UnorderedSystem.  The system will
         * register itself with the SystemManager.
         *
         * @param manager The SystemManager that owns BaseSystem
         * @param updateStep Determine when the system is updated
         */
        UnorderedSystem(SystemManager & manager, UpdateStepEnum updateStep) :
            AbstractSystem("", manager, updateStep)
        {  }

        /**
         * @brief Construct and initialize the UnorderedSystem with a name.  The system will
         * register itself with the SystemManager.
         *
         * @param systemName Name of the system.
         * @param manager The SystemManager that owns BaseSystem
         * @param updateStep Determine when the system is updated
         */
        UnorderedSystem(
                std::string systemName,
                SystemManager & manager,
                UpdateStepEnum updateStep) :
            AbstractSystem(systemName, manager, updateStep)
        { }

        /**
         * @brief Get the component corresponding to the entity.
         * If the entity does not have a component managed by the system then null
         * will be returned.
         *
         * @param entity Entity whose component is being requested.
         *
         * @return A reference to the component if it exists
         */
        ComponentType * operator [] (const Entity & entity)
        {
            auto componentIter = _components.find(entity);
            if(componentIter != _components.end())
            {
                return componentIter->second;
            }
            return NULL;
        }

        ComponentType * at(const Entity & entity)
        {
            return (*this)[entity];
        }

        /**
         * @brief Implementation for AbstractSystem method
         */
        virtual void Update(float delta) override = 0;

        /**
         * @brief Implementation for AbstractSystem method
         */
        void RemoveComponent(const Entity & entity) override
        {
            ILD_Assert(EntityHasComponent(entity), "Can not remove a component that does not exist");

            EntityIsDeleted(entity);
            _systemManager.UnregisterComponent(entity, this);
        }

        void CopyComponentToEntity(const Entity & fromEntity, const Entity & toEntity) override {
            if (!EntityHasComponent(fromEntity)) {
                return;
            }

            auto newComponent = new ComponentType();
            auto oldComponent = at(fromEntity);
            *newComponent = *oldComponent;
            AttachComponent(toEntity, newComponent);
        }

        /**
         * @brief Implementation for AbstractSystem method
         */
        bool EntityHasComponent(const Entity & entity) const override
        {
            return _components.find(entity) != _components.end();
        }

        /**
         * @copydoc ild::AbstractSystem::QueuDeleteComponent
         */
        void QueueDeleteComponent(const Entity & entity) override
        {
            _deleteComponentQueue.push_back(entity);
        }

        /**
         * @copydoc ild::AbstractSystem::DeleteQueuedComponents
         */
        void DeleteQueuedComponents() override
        {
            for(Entity & entity : _deleteComponentQueue)
            {
                RemoveComponent(entity);
            }
            _deleteComponentQueue.clear();
        }

        /**
         * @brief Implementation for AbstractSystem method
         *
         * NOTE: This method should only be called by SystemManager
         */
        void EntityIsDeleted(const Entity & entity) override
        {
            ILD_Assert(EntityHasComponent(entity),
                    "A system should not be notified of an entities deletion if the \
                    system does not contain a component for the entity");

            auto componentIter = _components.find(entity);
            ComponentType * component = componentIter->second;

            //Allow a child class to react to the component being removed
            OnComponentRemove(entity, component);

            _components.erase(componentIter);
            //Since the component is now unreachable it should be deleted.
            delete component;
        }

        /**
         * @brief Implements a default system serializer. It will serialzie polymorphic and non-polymorphic components.
         */
        virtual void Serialize(Archive & arc) override
        {
            Serialize(arc, HasMethod::Serialize<ComponentType, Archive>());
        }

    private:
        /**
         * @brief Used to store components
         */
        std::unordered_map<Entity, ComponentType *> _components;
        /**
         * @brief Holds the entities that are queued to have their components deleted.
         */
        std::vector<Entity> _deleteComponentQueue;

        void Serialize(Archive & arc, std::true_type)
        {
            if (arc.loading())
            {
                auto shouldContinue = arc.EnterProperty("components", false);
                if (!shouldContinue) {
                    return;
                }

                for (auto iter = arc.CurrentBranch().MemberBegin(); iter != arc.CurrentBranch().MemberEnd(); iter++)
                {
                    auto entityKey = iter->name.GetString();
                    ComponentType * value;
                    arc(value, entityKey);
                    auto entity = arc.entity(entityKey);
                    AttachComponent(entity, value);
                }
                arc.ExitProperty();
            }
            else
            {
                auto shouldContinue = arc.EnterProperty("components", true, rapidjson::Type::kObjectType);
                if (!shouldContinue) {
                    return;
                }

                for(auto entityKey : EntityKeysToSave(arc))
                {
                    Entity en = _systemManager.GetEntity(entityKey);
                    ComponentType * value = _components[en];
                    arc(value, entityKey);
                }
                arc.ExitProperty();
            }
        }

        const std::vector<std::string> EntityKeysToSave(Archive & arc) {
            if (arc.snapshotSave()) {
                std::vector<std::string> toReturn;
                for (auto iter = arc.CurrentBranch().MemberBegin(); iter != arc.CurrentBranch().MemberEnd(); iter++)
                {
                    toReturn.push_back(iter->name.GetString());
                }
                return toReturn;
            } else {
                return _systemManager.entitySaveableSystems()[_systemName];
            }
        }

        void Serialize(Archive & arc, std::false_type)
        {
            ILD_Assert(false, "Cannot serialize system if its components lack a serialize method.");
        }

        bool FetchDependencies(const Entity & entity, std::true_type)
        {
            (*this)[entity]->FetchDependencies(entity);
            return true;
        }

        bool FetchDependencies(const Entity & entity, std::false_type)
        {
            return false;
        }

        /**
         * @copydoc AbstractSystem::FetchComponentDependencies()
         */
        void FetchComponentDependencies(const Entity & entity) override
        {
            FetchDependencies(entity, HasMethod::FetchDependencies<ComponentType, Entity>());
        }

    protected:
        /**
         * @brief EntityComponentIter is an iterator that can be used to iterate over all contained
         * components.
         */
        typedef typename std::unordered_map<Entity, ComponentType *>::iterator EntityComponentIter;

        /**
         * @brief EntityComponentPair should be used as the types in for each loops iterating over the component
         */
        typedef typename std::pair<const Entity, ComponentType *> & EntityComponentPair;

        /**
         * @brief This method can be overriden to allow a child class to respond when
         * a component is being removed. It will be called just before the system
         * removes it and deregisters it.
         *
         * @param entity Entity that component is being removed from
         * @param component Component that is being removed
         */
        virtual void OnComponentRemove(Entity entity, ComponentType * component) {};

        /**
         * @brief Get at iterator to the first component in the system.  No order of
         * components is guaranteed
         *
         * @return An iterator that can be used to iterate over the components
         */
        EntityComponentIter begin()
        {
            return _components.begin();
        }

        /**
         * @brief Get the end iterator for the system.
         *
         * @return The end iterator.
         */
        EntityComponentIter end()
        {
            return _components.end();
        }

        /**
         * @brief Used by child classes to add components to an entity.  Attach component will
         * register the component with SystemManager.
         *
         * @param entity Component that should be attached to the entity
         * @param component Entity to attach the component to
         */
        virtual void AttachComponent(const Entity & entity, ComponentType * component)
        {
            ILD_Assert(component != NULL, "Can not attach a null component");
            ILD_Assert(!EntityHasComponent(entity), "Can not attach two of the same component to an entity");

            _components[entity] = component;
            _systemManager.RegisterComponent(entity, this);
        }

        ~UnorderedSystem()
        {
            //We use delete instead of unique_ptrs because it makes implementing
            //the begin() and end() iterators much easier.
            for(auto & entityComponentPair : *this)
            {
                delete entityComponentPair.second;
            }
        }
};

}
#endif


text:
classdef OcTree < handle
% OcTree point decomposition in 3D
%    OcTree is used to create a tree data structure of bins containing 3D
%    points. Each bin may be recursively decomposed into 8 child bins.
%
%    OT = OcTree(PTS) creates an OcTree from an N-by-3 matrix of point
%    coordinates.
%
%    OT = OcTree(...,'PropertyName',VALUE,...) takes any of the following
%    property values:
%
%     binCapacity - Maximum number of points a bin may contain. If more
%                   points exist, the bin will be recursively subdivided.
%                   Defaults to ceil(numPts/10).
%     maxDepth    - Maximum number of times a bin may be subdivided.
%                   Defaults to INF.
%     maxSize     - Maximum size of a bin edge. If any dimension of a bin
%                   exceeds maxSize, it will be recursively subdivided.
%                   Defaults to INF.
%     minSize     - Minimum size of a bin edge. Subdivision will stop after
%                   any dimension of a bin gets smaller than minSize.
%                   Defaults to 1000*eps.
%     style       - Either 'equal' (default) or 'weighted'. 'equal'
%                   subdivision splits bins at their central coordinate
%                   (ie, one bin subdivides into 8 equally sized bins).
%                   'weighted' subdivision divides bins based on the mean
%                   of all points they contain. Weighted subdivision is
%                   slightly slower than equal subdivision for a large
%                   number of points, but it can produce a more efficient
%                   decomposition with fewer subdivisions.
%
%    Example 1: Decompose 200 random points into bins of 20 points or less,
%             then display each bin with its points in a separate colour.
%        pts = (rand(200,3)-0.5).^2;
%        OT = OcTree(pts,'binCapacity',20);
%        figure
%        boxH = OT.plot;
%        cols = lines(OT.BinCount);
%        doplot3 = @(p,varargin)plot3(p(:,1),p(:,2),p(:,3),varargin{:});
%        for i = 1:OT.BinCount
%            set(boxH(i),'Color',cols(i,:),'LineWidth', 1+OT.BinDepths(i))
%            doplot3(pts(OT.PointBins==i,:),'.','Color',cols(i,:))
%        end
%        axis image, view(3)
%
%    Example 2: Decompose 200 random points into bins of 10 points or less,
%             shrunk to minimallly encompass their points, then display.
%        pts = rand(200,3);
%        OT = OcTree(pts,'binCapacity',10,'style','weighted');
%        OT.shrink
%        figure
%        boxH = OT.plot;
%        cols = lines(OT.BinCount);
%        doplot3 = @(p,varargin)plot3(p(:,1),p(:,2),p(:,3),varargin{:});
%        for i = 1:OT.BinCount
%            set(boxH(i),'Color',cols(i,:),'LineWidth', 1+OT.BinDepths(i))
%            doplot3(pts(OT.PointBins==i,:),'.','Color',cols(i,:))
%        end
%        axis image, view(3)
%
%
% OcTree methods:
%     shrink            - Shrink each bin to tightly encompass its children
%     query             - Ask which bins a new set of points belong to.
%     plot, plot3       - Plots bin bounding boxes to the current axes.
%
% OcTree properties:
%     Points            - The coordinate of points in the decomposition.
%     PointBins         - Indices of the bin that each point belongs to.
%     BinCount          - Total number of bins created.
%     BinBoundaries     - BinCount-by-6 [MIN MAX] coordinates of bin edges.
%     BinDepths         - The # of subdivisions to reach each bin.
%     BinParents        - Indices of the bin that each bin belongs to.
%     Properties        - Name/Val pairs used for creation (see help above)
%
% See also qtdecomp.

%   Created by Sven Holcombe.
%   1.0     - 2013-03 Initial release
%   1.1     - 2013-03 Added shrinking bins and allocate/deallocate space
%
%   Please post comments to the FEX page for this entry if you have any
%   bugs or feature requests.

    properties
        Points;
        PointBins;
        BinCount;
        BinBoundaries;
        BinDepths;
        BinParents = zeros(0,1);
        Properties;
    end

    methods

        function this = OcTree(pts,varargin)
            % This is the OcTree header line
            validateattributes(pts,{'numeric'},...
                {'real','finite','nonnan','ncols', 3},...
                mfilename,'PTS')

            % Initialise a single bin surrounding all given points
            numPts = size(pts,1);
            this.BinBoundaries = [min(pts,[],1) max(pts,[],1)];
            this.Points = pts;
            this.PointBins = ones(numPts,1);
            this.BinDepths = 0;
            this.BinParents(1) = 0;
            this.BinCount = 1;

            % Allow custom setting of Properties
            IP = inputParser;
            IP.addParamValue('binCapacity',ceil(numPts)/10);
            IP.addParamValue('maxDepth',inf);
            IP.addParamValue('maxSize',inf);
            IP.addParamValue('minSize',1000 * eps);
            IP.addParamValue('style','equal');
            IP.parse(varargin{:});
            this.Properties = IP.Results;

            % Return on empty or trivial bins
            if numPts<2, return; end

            % Start dividing!
            this.preallocateSpace;
            this.divide(1);
            this.deallocateSpace;
        end

        % MATLAB performs better if arrays that grow are initialised,
        % rather than grown during a loop. These two functions do just that
        % before and after the identification of new beens.
        function preallocateSpace(this)
            numPts = size(this.Points,1);
            numBins = numPts;
            if isfinite(this.Properties.binCapacity)
                numBins = ceil(2*numPts/this.Properties.binCapacity);
            end
            this.BinDepths(numBins) = 0;
            this.BinParents(numBins) = 0;
            this.BinBoundaries(numBins,1) = 0;
        end
        function deallocateSpace(this)
            this.BinDepths(this.BinCount+1:end) = [];
            this.BinParents(this.BinCount+1:end) = [];
            this.BinBoundaries(this.BinCount+1:end,:) = [];
        end

        function divide(this, startingBins)
            % Loop over each bin we will consider for division
            for i = 1:length(startingBins)
                binNo = startingBins(i);

                % Prevent dividing beyond the maximum depth
                if this.BinParents(binNo)+1 >= this.Properties.maxDepth
                    continue;
                end

                % Prevent dividing beyond a minimum size
                thisBounds = this.BinBoundaries(binNo,:);
                binEdgeSize = diff(thisBounds([1:3;4:6]));
                minEdgeSize = min(binEdgeSize);
                maxEdgeSize = max(binEdgeSize);
                if minEdgeSize < this.Properties.minSize
                    continue;
                end

                % There are two conditions under which we should divide
                % this bin. 1: It's bigger than maxSize. 2: It contains
                % more points than binCapacity.
                oldCount = this.BinCount;
                if nnz(this.PointBins==binNo) > this.Properties.binCapacity
                    this.divideBin(binNo);
                    this.divide(oldCount+1:this.BinCount);
                    continue;
                end
                if maxEdgeSize>this.Properties.maxSize
                    this.divideBin(binNo);
                    this.divide(oldCount+1:this.BinCount);
                    continue;
                end
            end
        end

        function divideBin(this,binNo)
            % Gather the new points (a bit more efficient to copy once)
            binPtMask = this.PointBins==binNo;
            thisBinsPoints = this.Points(binPtMask,:);

            % Get the old corner points and the new division point
            oldMin = this.BinBoundaries(binNo,1:3);
            oldMax = this.BinBoundaries(binNo,4:6);
            if strcmp('weighted',this.Properties.style) && any(binPtMask)
                newDiv = mean(thisBinsPoints,1);
            else
                newDiv = mean([oldMin; oldMax], 1);
            end

            % Build the new boundaries of our 8 subdivisions
            minMidMax = [oldMin newDiv oldMax];
            newBounds = minMidMax([...
                1 2 3 4 5 6;
                1 2 6 4 5 9;
                1 5 3 4 8 6;
                1 5 6 4 8 9;
                4 2 3 7 5 6;
                4 2 6 7 5 9;
                4 5 3 7 8 6;
                4 5 6 7 8 9]);

            % Determine to which of these 8 bins each current point belongs
            binMap = cat(3,[0 0 0],[0 0 1],[0 1 0],[0 1 1],...
                [1 0 0],[1 0 1],[1 1 0],[1 1 1]);
            gtMask = bsxfun(@gt, thisBinsPoints, newDiv);
            [~,binAssignment] = max(all(bsxfun(@eq,gtMask,binMap),2),[],3);
            % [~, binAssignment] = ismember(gtMask,binMap,'rows'); % A little slower than above.

            % Make the new bins and reassign old points to them
            newBinInds = this.BinCount+1:this.BinCount+8;
            this.BinBoundaries(newBinInds,:) = newBounds;
            this.BinDepths(newBinInds) = this.BinDepths(binNo)+1;
            this.BinParents(newBinInds) = binNo;
            this.PointBins(binPtMask) = newBinInds(binAssignment);
            this.BinCount = this.BinCount + 8;
        end

        function shrink(this)
            % Shrink all bins to bound only the points they contain
            % WARNING: this operation creates gaps in the final space not
            % covered by a bin. Only shrink OcTree structures when you only
            % intend to use the points used to create the tree to query the
            % tree space.
            binChildren = arrayfun(@(i)find(this.BinParents==i),1:this.BinCount,'Un',0)';
            binIsLeaf = cellfun(@isempty, binChildren);
            for i = find(binIsLeaf(:))'
                binShrink_recurse(i, true)
            end

            function binShrink_recurse(binNo, isLeafBin)
                % Build a list of all points that fall within one of the
                % bins to be checked, and the list of which point falls in
                % which bin.
                oldBoundaryMin = this.BinBoundaries(binNo,1:3);
                oldBoundaryMax = this.BinBoundaries(binNo,4:6);
                if isLeafBin
                    % Shrink bin based on child POINTS
                    ptsMask = this.PointBins==binNo;
                    if ~any(ptsMask)
                        % No points, shrink the bin to infinitely small
                        proposedBoundaries = [oldBoundaryMin oldBoundaryMin];
                    else
                        pts = this.Points(ptsMask,:);
                        proposedBoundaries = [...
                            max([oldBoundaryMin; min(pts,[],1)]) ...
                            min([oldBoundaryMax; max(pts,[],1)])];
                    end
                else
                    % Shrink bin based on child BINS
                    childBoundaries = this.BinBoundaries(binChildren{binNo},:);
                    proposedBoundaries = [min(childBoundaries(:,1:3),[],1) max(childBoundaries(:,4:6),[],1)];
                end

                if ~isequal(proposedBoundaries, [oldBoundaryMin oldBoundaryMax])
                    % We just shrunk the boundary. Make it official and
                    % check the parent
                    this.BinBoundaries(binNo,:) = proposedBoundaries;
                    parentBin = this.BinParents(binNo);
                    if parentBin>0
                        binShrink_recurse(parentBin, false)
                    end
                end
            end
        end

        function binNos = query(this, newPts, queryDepth)
            % Get the OcTree bins that new query points belong to.
            %
            % BINS = OT.query(NEWPTS) searches the OcTree object OT and
            % returns an N-by-1 vector of BINS giving the bin index in
            % which each of the N points in NEWPTS is contained. For any
            % query points outside all bins in OT, the index -1 is
            % returned.
            %
            % BINS = OT.query(NEWPTS,DEPTH) restricts the search to DEPTH
            % levels in the OT bin tree. Note that the first bin
            % (containing all other bins in OT) has DEPTH = 1.

            if nargin<3
                queryDepth = max(this.BinDepths);
            end

            numPts = size(newPts,1);
            newPts = permute(newPts,[3 2 1]);
            binNos = ones(numPts,1)*-1;

            binChildren = arrayfun(@(i)find(this.BinParents==i),1:this.BinCount,'Un',0)';
            binIsLeaf = cellfun(@isempty, binChildren);
            ptQuery_recurse(1:numPts, this.BinParents==0, 0)

            function ptQuery_recurse(newIndsToCheck_, binsToCheck, depth)
                % Build a list of all points that fall within one of the
                % bins to be checked, and the list of which point falls in
                % which bin.
                boundsToCheck = this.BinBoundaries(binsToCheck,:);
                [ptInBounds, subBinNo] = max(all(...
                    bsxfun(@ge, newPts(:,:,newIndsToCheck_), boundsToCheck(:,1:3)) & ...
                    bsxfun(@le, newPts(:,:,newIndsToCheck_), boundsToCheck(:,4:6))...
                    ,2),[],1);

                if ~all(ptInBounds)
                    % Special case usually when depth=0, where a point may
                    % fall outside the bins entirely. This should only
                    % happen once so let's fix it once and let subsequent
                    % code rely on all points being in bounds
                    binNos(newIndsToCheck_(~ptInBounds)) = -1;
                    newIndsToCheck_(~ptInBounds) = [];
                    subBinNo(~ptInBounds) = [];
                end
                binNosToAssign = binsToCheck(subBinNo);
                newIndsToAssign = newIndsToCheck_;
                binNos(newIndsToAssign) = binNosToAssign;

                % Allow a free exit when we reach a certain depth
                if depth>=queryDepth
                    return;
                end

                % Otherwise, for all of the points we just placed into
                % bins, check which of the children of those bins those
                % same points fall into
                [unqBinNos, ~, unqGrpNos] = unique(binNosToAssign);
                for i = 1:length(unqBinNos)
                    thisPtMask = unqGrpNos==i;
                    if ~binIsLeaf(unqBinNos(i))
                        ptQuery_recurse(newIndsToCheck_(thisPtMask), binChildren{unqBinNos(i)}, depth+1)
                    end
                end

            end
        end

        function h = plot(this,varargin)
            % OcTree.plot plots bin bounding boxes of an OcTree object
            %
            % H = OT.plot('name',value,...) allows you to specify any
            % properties of the bounding box lines that you would normally
            % supply to a plot(...,'name',value) command, and returns plot
            % object handles (one per bin) to H.
            hold on;
            h = zeros(this.BinCount,1);
            for i = 1:this.BinCount
                binMinMax = this.BinBoundaries(i,:);
                pts = cat(1, binMinMax([...
                    1 2 3; 4 2 3; 4 5 3; 1 5 3; 1 2 3;...
                    1 2 6; 4 2 6; 4 5 6; 1 5 6; 1 2 6; 1 2 3]),...
                    nan(1,3), binMinMax([4 2 3; 4 2 6]),...
                    nan(1,3), binMinMax([4 5 3; 4 5 6]),...
                    nan(1,3), binMinMax([1 5 3; 1 5 6]));
                h(i) = plot3(pts(:,1),pts(:,2),pts(:,3),varargin{:});
            end
        end
        function h = plot3(this,varargin)
            % OcTree.plot plots bin bounding boxes of an OcTree
            %
            % See also OcTree.plot
            h = this.plot(varargin{:});
        end
    end
end


text:
<?php

class OrderlistController extends Controller {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/member';

    /**
     * @return array action filters
     */
    public function filters() {
	return array(
	    'accessControl', // perform access control for CRUD operations
	);
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
	return array(
	    array('allow', // allow authenticated user to perform 'create' and 'update' actions
		'actions' => array('list', 'create', 'update', 'view'),
		'users' => array('@'),
	    ),
	    array('deny', // deny all users
		'users' => array('*'),
	    ),
	);
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id) {
	$this->render('view', array(
	    'model' => $this->loadModel($id),
	));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionUpdate($id) {
	$model = $this->loadModel($id);

	// Uncomment the following line if AJAX validation is needed
	// $this->performAjaxValidation($model);

	if (isset($_POST['Order'])) {
	    $model->attributes = $_POST['Order'];
	    if ($model->save())
		$this->redirect(array('view', 'id' => $model->order_id));
	}

	$this->render('update', array(
	    'model' => $model,
	));
    }

    /**
     * Deletes a particular model.
     * If deletion is successful, the browser will be redirected to the 'list' page.
     * @param integer $id the ID of the model to be deleted
     */
    public function actionDelete($id) {
	if (Yii::app()->request->isPostRequest) {
	    // we only allow deletion via POST request
	    $this->loadModel($id)->delete();

	    // if AJAX request (triggered by deletion via list grid view), we should not redirect the browser
	    if (!isset($_GET['ajax']))
		$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('list'));
	}
	else
	    throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
    }

    /**
     * Manages all models.
     */
    public function actionList() {
//		$model=new Order('ownerSearch');
//		$model->unsetAttributes();  // clear any default values
//		if(isset($_GET['Order']))
//			$model->attributes=$_GET['Order'];

	$criteria = new CDbCriteria(array(
	    'condition'=>'user_id ='.Yii::app()->user->id
	));
	$count = Order::model()->count($criteria);
	$pages = new CPagination($count);

	// results per page
	$pages->pageSize = 10;
	$pages->applyLimit($criteria);
	$models = Order::model()->findAll($criteria);

	$this->render('list', array(
	    'models' => $models,
	    'pages' => $pages
	));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel($id) {
	$model = Order::model()->findByPk($id);
	if ($model === null)
	    throw new CHttpException(404, 'The requested page does not exist.');
	return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation($model) {
	if (isset($_POST['ajax']) && $_POST['ajax'] === 'order-form') {
	    echo CActiveForm::validate($model);
	    Yii::app()->end();
	}
    }

}


text:
package io.fnx.backend.util;

import com.google.inject.Singleton;

import java.text.MessageFormat;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

/**
 * Zkratka k ResouceBundle messages.
 *
 * @author Tomas Zverina, zverina@m-atelier.cz
 */
@Singleton
public class MessageAccessor {

    private static ResourceBundle resourceBundle = ResourceBundle.getBundle(Constants.MESSAGES_RESOURCE_BUNDLE_NAME, Constants.LOCALE);

    /**
     * Returns our texts bundle.
     *
     * @return
     */
    public ResourceBundle getMessages() {
        return resourceBundle;
    }

    public String getMessage(String key) {
        return resourceBundle.getString(key);
    }

    public String getMessage(String key, Object... params) {
        return MessageFormat.format(resourceBundle.getString(key), params);
    }

	/**
	 * Pouziva se k odeslani hlasek na Dart klienta.
	 *
	 * @return
	 */
	public Map<String, String> buildMessagesMap() {
		Map<String, String> result = new HashMap<>();
		Enumeration<String> keys = resourceBundle.getKeys();
		while(keys.hasMoreElements()) {
			String key = keys.nextElement();
			result.put(key, resourceBundle.getString(key));
		}
		return result;
	}

}