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

#include "chrome/browser/safe_browsing/ui_manager.h"

#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/callback.h"
#include "base/debug/leak_tracker.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/threading/thread.h"
#include "base/threading/thread_restrictions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/safe_browsing/malware_details.h"
#include "chrome/browser/safe_browsing/metadata.pb.h"
#include "chrome/browser/safe_browsing/ping_manager.h"
#include "chrome/browser/safe_browsing/safe_browsing_blocking_page.h"
#include "chrome/browser/safe_browsing/safe_browsing_service.h"
#include "chrome/browser/tab_contents/tab_util.h"
#include "chrome/common/url_constants.h"
#include "components/metrics/metrics_service.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/navigation_entry.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/web_contents.h"
#include "net/base/registry_controlled_domains/registry_controlled_domain.h"
#include "net/url_request/url_request_context.h"
#include "net/url_request/url_request_context_getter.h"

using content::BrowserThread;
using content::NavigationEntry;
using content::WebContents;

struct SafeBrowsingUIManager::WhiteListedEntry {
  int render_process_host_id;
  int render_view_id;
  std::string domain;
  SBThreatType threat_type;
};

SafeBrowsingUIManager::UnsafeResource::UnsafeResource()
    : is_subresource(false),
      threat_type(SB_THREAT_TYPE_SAFE),
      render_process_host_id(-1),
      render_view_id(-1) {
}

SafeBrowsingUIManager::UnsafeResource::~UnsafeResource() { }

SafeBrowsingUIManager::SafeBrowsingUIManager(
    const scoped_refptr<SafeBrowsingService>& service)
    : sb_service_(service) {
}

SafeBrowsingUIManager::~SafeBrowsingUIManager() { }

void SafeBrowsingUIManager::StopOnIOThread(bool shutdown) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  if (shutdown)
    sb_service_ = NULL;
}

void SafeBrowsingUIManager::LogPauseDelay(base::TimeDelta time) {
  UMA_HISTOGRAM_LONG_TIMES("SB2.Delay", time);
}

// Only report SafeBrowsing related stats when UMA is enabled. User must also
// ensure that safe browsing is enabled from the calling profile.
bool SafeBrowsingUIManager::CanReportStats() const {
  const metrics::MetricsService* metrics = g_browser_process->metrics_service();
  return metrics && metrics->reporting_active();
}

void SafeBrowsingUIManager::OnBlockingPageDone(
    const std::vector<UnsafeResource>& resources,
    bool proceed) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
  for (std::vector<UnsafeResource>::const_iterator iter = resources.begin();
       iter != resources.end(); ++iter) {
    const UnsafeResource& resource = *iter;
    if (!resource.callback.is_null())
      resource.callback.Run(proceed);

    if (proceed) {
      BrowserThread::PostTask(
          BrowserThread::UI,
          FROM_HERE,
          base::Bind(&SafeBrowsingUIManager::UpdateWhitelist, this, resource));
    }
  }
}

void SafeBrowsingUIManager::DisplayBlockingPage(
    const UnsafeResource& resource) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));

  if (!resource.threat_metadata.empty() &&
      resource.threat_type == SB_THREAT_TYPE_URL_MALWARE) {
    safe_browsing::MalwarePatternType proto;
    // Malware sites tagged as "landing site" should only show a warning for a
    // main-frame or sub-frame resource. (See "Types of Malware sites" under
    // https://developers.google.com/safe-browsing/developers_guide_v3#UserWarnings)
    if (proto.ParseFromString(resource.threat_metadata) &&
        proto.pattern_type() == safe_browsing::MalwarePatternType::LANDING &&
        resource.is_subresource && !resource.is_subframe) {
      if (!resource.callback.is_null()) {
        BrowserThread::PostTask(
            BrowserThread::IO, FROM_HERE, base::Bind(resource.callback, true));
      }
      return;
    }
  }

  // Indicate to interested observers that the resource in question matched the
  // SB filters. If the resource is already whitelisted, OnSafeBrowsingHit
  // won't be called.
  if (resource.threat_type != SB_THREAT_TYPE_SAFE) {
    FOR_EACH_OBSERVER(Observer, observer_list_, OnSafeBrowsingMatch(resource));
  }

  // Check if the user has already ignored our warning for this render_view
  // and domain.
  if (IsWhitelisted(resource)) {
    if (!resource.callback.is_null()) {
      BrowserThread::PostTask(
          BrowserThread::IO, FROM_HERE, base::Bind(resource.callback, true));
    }
    return;
  }

  // The tab might have been closed.
  WebContents* web_contents =
      tab_util::GetWebContentsByID(resource.render_process_host_id,
                                   resource.render_view_id);

  if (!web_contents) {
    // The tab is gone and we did not have a chance at showing the interstitial.
    // Just act as if "Don't Proceed" were chosen.
    std::vector<UnsafeResource> resources;
    resources.push_back(resource);
    BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&SafeBrowsingUIManager::OnBlockingPageDone,
                 this, resources, false));
    return;
  }

  if (resource.threat_type != SB_THREAT_TYPE_SAFE &&
      CanReportStats()) {
    GURL page_url = web_contents->GetURL();
    GURL referrer_url;
    NavigationEntry* entry = web_contents->GetController().GetActiveEntry();
    if (entry)
      referrer_url = entry->GetReferrer().url;

    // When the malicious url is on the main frame, and resource.original_url
    // is not the same as the resource.url, that means we have a redirect from
    // resource.original_url to resource.url.
    // Also, at this point, page_url points to the _previous_ page that we
    // were on. We replace page_url with resource.original_url and referrer
    // with page_url.
    if (!resource.is_subresource &&
        !resource.original_url.is_empty() &&
        resource.original_url != resource.url) {
      referrer_url = page_url;
      page_url = resource.original_url;
    }
    ReportSafeBrowsingHit(resource.url, page_url, referrer_url,
                          resource.is_subresource, resource.threat_type,
                          std::string() /* post_data */);
  }
  if (resource.threat_type != SB_THREAT_TYPE_SAFE) {
    FOR_EACH_OBSERVER(Observer, observer_list_, OnSafeBrowsingHit(resource));
  }
  SafeBrowsingBlockingPage::ShowBlockingPage(this, resource);
}

// A safebrowsing hit is sent after a blocking page for malware/phishing
// or after the warning dialog for download urls, only for UMA users.
void SafeBrowsingUIManager::ReportSafeBrowsingHit(
    const GURL& malicious_url,
    const GURL& page_url,
    const GURL& referrer_url,
    bool is_subresource,
    SBThreatType threat_type,
    const std::string& post_data) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  if (!CanReportStats())
    return;

  BrowserThread::PostTask(
      BrowserThread::IO, FROM_HERE,
      base::Bind(&SafeBrowsingUIManager::ReportSafeBrowsingHitOnIOThread, this,
                 malicious_url, page_url, referrer_url, is_subresource,
                 threat_type, post_data));
}

void SafeBrowsingUIManager::AddObserver(Observer* observer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  observer_list_.AddObserver(observer);
}

void SafeBrowsingUIManager::RemoveObserver(Observer* observer) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  observer_list_.RemoveObserver(observer);
}

void SafeBrowsingUIManager::ReportSafeBrowsingHitOnIOThread(
    const GURL& malicious_url,
    const GURL& page_url,
    const GURL& referrer_url,
    bool is_subresource,
    SBThreatType threat_type,
    const std::string& post_data) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // The service may delete the ping manager (i.e. when user disabling service,
  // etc). This happens on the IO thread.
  if (sb_service_.get() == NULL || sb_service_->ping_manager() == NULL)
    return;

  DVLOG(1) << "ReportSafeBrowsingHit: " << malicious_url << " " << page_url
           << " " << referrer_url << " " << is_subresource << " "
           << threat_type;
  sb_service_->ping_manager()->ReportSafeBrowsingHit(
      malicious_url, page_url,
      referrer_url, is_subresource,
      threat_type, post_data);
}

// If the user had opted-in to send MalwareDetails, this gets called
// when the report is ready.
void SafeBrowsingUIManager::SendSerializedMalwareDetails(
    const std::string& serialized) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));

  // The service may delete the ping manager (i.e. when user disabling service,
  // etc). This happens on the IO thread.
  if (sb_service_.get() == NULL || sb_service_->ping_manager() == NULL)
    return;

  if (!serialized.empty()) {
    DVLOG(1) << "Sending serialized malware details.";
    sb_service_->ping_manager()->ReportMalwareDetails(serialized);
  }
}

void SafeBrowsingUIManager::UpdateWhitelist(const UnsafeResource& resource) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Whitelist this domain and warning type for the given tab.
  WhiteListedEntry entry;
  entry.render_process_host_id = resource.render_process_host_id;
  entry.render_view_id = resource.render_view_id;
  entry.domain = net::registry_controlled_domains::GetDomainAndRegistry(
      resource.url,
      net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
  entry.threat_type = resource.threat_type;
  white_listed_entries_.push_back(entry);
}

bool SafeBrowsingUIManager::IsWhitelisted(const UnsafeResource& resource) {
  DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
  // Check if the user has already ignored our warning for this render_view
  // and domain.
  for (size_t i = 0; i < white_listed_entries_.size(); ++i) {
    const WhiteListedEntry& entry = white_listed_entries_[i];
    if (entry.render_process_host_id == resource.render_process_host_id &&
        entry.render_view_id == resource.render_view_id &&
        // Threat type must be the same or they can either be client-side
        // phishing/malware URL or a SafeBrowsing phishing/malware URL.
        // If we show one type of phishing/malware warning we don't want to show
        // a second phishing/malware warning.
        (entry.threat_type == resource.threat_type ||
         (entry.threat_type == SB_THREAT_TYPE_URL_PHISHING &&
          resource.threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL) ||
         (entry.threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL &&
          resource.threat_type == SB_THREAT_TYPE_URL_PHISHING) ||
         (entry.threat_type == SB_THREAT_TYPE_URL_MALWARE &&
          resource.threat_type == SB_THREAT_TYPE_CLIENT_SIDE_MALWARE_URL) ||
         (entry.threat_type == SB_THREAT_TYPE_CLIENT_SIDE_MALWARE_URL &&
          resource.threat_type == SB_THREAT_TYPE_URL_MALWARE))) {
      return entry.domain ==
          net::registry_controlled_domains::GetDomainAndRegistry(
              resource.url,
              net::registry_controlled_domains::EXCLUDE_PRIVATE_REGISTRIES);
    }
  }
  return false;
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Revis. gen. pl. (Leipzig) 3: 461 (1898)

#### Original name
Nectria kermesina G.H. Otth

### Remarks
null

redpajama_set_name: RedPajamaGithub


text:
cask 'firefox-beta-ru' do
  version '47.0b5'
  sha256 '5407714edd73e61f670858d628d0c7860efcf7ac17b6fc554cf6ed1650b81986'

  url "https://download.mozilla.org/?product=firefox-#{version}-SSL&os=osx&lang=ru"
  name 'Mozilla Firefox'
  homepage 'https://www.mozilla.org/ru/firefox/channel/#beta'
  license :mpl

  app 'Firefox.app'

  zap delete: [
                '~/Library/Application Support/Firefox',
                '~/Library/Caches/Firefox',
              ]
end


text:
package org.lnu.is.converter.degree;

import static org.junit.Assert.assertEquals;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.junit.Test;
import org.lnu.is.domain.degree.Degree;
import org.lnu.is.domain.degree.type.DegreeType;
import org.lnu.is.domain.person.Person;
import org.lnu.is.resource.degree.DegreeResource;

public class DegreeConverterTest {

	private DegreeConverter unit = new DegreeConverter();

	@Test
	public void testConvert() throws Exception {
		// Given
		Long personId = 1L;
		Person person = new Person();
		person.setId(personId);

		Long degreeTypeId = 2L;
		DegreeType degreeType = new DegreeType();
		degreeType.setId(degreeTypeId);

		Degree source = new Degree();
		source.setPerson(person);
		source.setDegreeType(degreeType);

		DegreeResource expected = new DegreeResource();
		expected.setPersonId(personId);
		expected.setDegreeTypeId(degreeTypeId);

		// When
		DegreeResource actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}

	@Test
	public void testConvertWithEmptyFields() throws Exception {
		// Given
		Degree source = new Degree();
		DegreeResource expected = new DegreeResource();

		// When
		DegreeResource actual = unit.convert(source);

		// Then
		assertEquals(expected, actual);
	}

	@Test
	public void testConvertAll() throws Exception {
		// Given
		Degree source = new Degree();
		List<Degree> sources = Arrays.asList(source);
		DegreeResource expected = new DegreeResource();
		List<DegreeResource> expecteds = Arrays.asList(expected);

		// When
		List<DegreeResource> actuals = unit.convertAll(sources);

		// Then
		assertEquals(expecteds, actuals);
	}

	@Test
	public void testConvertAllWithEmptyCollection() throws Exception {
		// Given
		List<Degree> sources = Collections.emptyList();
		List<DegreeResource> expecteds = Collections.emptyList();

		// When
		List<DegreeResource> actuals = unit.convertAll(sources);

		// Then
		assertEquals(expecteds, actuals);
	}
}


text:
#pragma once
#include <aws/lightsail/Lightsail_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>

namespace Aws
{
namespace Lightsail
{
namespace Model
{
  enum class RelationalDatabaseEngine
  {
    NOT_SET,
    mysql
  };

namespace RelationalDatabaseEngineMapper
{
AWS_LIGHTSAIL_API RelationalDatabaseEngine GetRelationalDatabaseEngineForName(const Aws::String& name);

AWS_LIGHTSAIL_API Aws::String GetNameForRelationalDatabaseEngine(RelationalDatabaseEngine value);
} // namespace RelationalDatabaseEngineMapper
} // namespace Model
} // namespace Lightsail
} // namespace Aws


text:
package com.blazebit.regex.node;

public interface Node {

    public void setNext(Node node);

    public Node getNext();
}


text:
#include "container.hpp" // pasl/sequtil/container.hpp, for pasl::data::mynew_array
#include "search_utils.hpp"
#include <climits>

#ifndef _ASTAR_SEARCH_H_
#define _ASTAR_SEARCH_H_

struct astar_state {
  bool is_expanded;
  int dist;
  int pred;
};

class AStarResult : public SearchResult {
private:
  int n;
  astar_state* states;
  int* pebbles;

public:
  AStarResult(int n, astar_state* states, int* pebbles)
  : n(n), states(states), pebbles(pebbles) { }

  ~AStarResult() override { free(states); if (pebbles) free(pebbles); }

  bool is_expanded(int vertex) override { return states[vertex].is_expanded; }
  int predecessor(int vertex) override { return states[vertex].pred; }
  int g(int vertex) override { return states[vertex].dist; }
  int pebble(int vertex) override { return (pebbles ? pebbles[vertex] : -1); }
};

template <class GRAPH, class HEAP, class HEURISTIC>
SearchResult*
astar(GRAPH& graph, const HEURISTIC& heuristic,
      const int& source, const int& destination,
      double exptime, bool pebble) {
  int N = graph.number_vertices();
  astar_state* states = pasl::data::mynew_array<astar_state>(N);
  for (int i = 0; i < N; i++) {
    states[i].is_expanded = false;
    states[i].dist = INT_MAX;
    states[i].pred = -1;
  }
  int* pebbles = nullptr;
  if (pebble) {
    pebbles = pasl::data::mynew_array<int>(N);
    for (int i = 0; i < N; i++) pebbles[i] = -1;
  }
  states[source].dist = 0;
  HEAP frontier = HEAP();
  frontier.insert(heuristic(source), source);
  while (true) {
    int v = frontier.delete_min();
    if (v == destination) break;
    if (!states[v].is_expanded) {
      states[v].is_expanded = true;
      if (pebbles) pebbles[v] = 0;
      graph.simulate_get_successors(exptime);
      graph.for_each_neighbor_of(v, [&] (int nbr, int weight) {
        int nbrdist = states[v].dist + weight;
        if (nbrdist < states[nbr].dist) {
          frontier.insert(heuristic(nbr) + nbrdist, nbr);
          states[nbr].dist = nbrdist;
          states[nbr].pred = v;
        }
      });
    }
  }
  SearchResult* result = new AStarResult(N, states, pebbles);
  return result;
}

#endif // _ASTAR_SEARCH_H_


text:
module Rack
  # The Rack::Smartfiles middleware intercepts requests based on the url prefixes and serve
  # files from a provider.
  #
  # Examples:
  #
  # Serve all requests beginning with /public with the default provider (Rack::File.new(Dir.pwd)) :
  #
  #    use Rack::Smartfiles, url: '/files'
  #
  # Serve all request beginning with /uploads with explicite provider.
  #
  #    use Rack::Smartfiles, url: '/uploads', provider: Rack::File.new('/public/uploads')

  class VirtualFiles
    def initialize(app, options={})
      @app = app
      @url = options[:url]
      @provider = options[:provider]
    end

    def call(env)
      path = env[PATH_INFO]

      if can_serve?(path)
        provider = @provider || Rack::File.new(Dir.pwd)
        path.slice!(@url)
        env[PATH_INFO] = path

        provider.call(env)
      else
        binding.pry
        @app.call(env)
      end
    end

    private

    def can_serve?(path)
      path.index(@url) == 0
    end

  end
end


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>Mocha Tests</title>
    <link href="mocha/mocha.css" rel="stylesheet" type="text/css" media="screen" />


text: CKEDITOR.plugins.setLang("imagebase","ro",{captionPlaceholder:"Introduceți titlul imaginii"});


text:
package com.windcatcher.dmhelper.fragments;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

import com.windcatcher.dmhelper.R;
import com.windcatcher.dmhelper.SQLite.GameSQLDataSource;
import com.windcatcher.dmhelper.SQLite.tables.EncountersTable;
import com.windcatcher.dmhelper.fragments.dialogs.PickCreatureFragment;

public class EditEncounterFragment extends CursorListFragment {

	private EditEncounterFragment(){}

	// ===========================================================
	// TODO Fields
	// ===========================================================

	private long mEncounterRowID;
	private static int mFragmentCount = 0;

	private static EditEncounterFragment activeInstance;

	// ===========================================================
	// TODO Constants
	// ===========================================================

	private static final int CREATURES_LOADER = 0;

	private static final String ARGS_ROW_ID = "rowid";

	// ===========================================================
	// TODO Inherited Methods
	// ===========================================================

	@Override
	public void onCreate(Bundle savedInstanceState) {
		mEncounterRowID = getArguments().getLong(ARGS_ROW_ID);

		initMenu(R.menu.encounter_edit_selected, R.menu.encounter_edit);

		super.onCreate(savedInstanceState);
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment_edit_encounter, container, false);

		ListView list = (ListView) rootView.findViewById(R.id.edit_encounter_creature_list);

		Cursor c = getCursor();

		int count = c.getCount();

		SimpleCursorAdapter adapter = new SimpleCursorAdapter(getActivity(), R.layout.list_item_edit_encounters_creatures, c, new String[] { EncountersTable.VIEW_EDIT_COLUMN_CREATURENAME.getName(), EncountersTable.VIEW_EDIT_COLUMN_HP.getName() }, new int[] { R.id.list_item_base_line_one, R.id.list_item_base_line_two}, SimpleCursorAdapter.NO_SELECTION);

		initList(list, adapter);

		return rootView;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.encounter_edit_add:
			addCreature();
			return true;
		case R.id.encounter_edit_remove:
			removeCreature();
			return true;
		case R.id.encounter_edit_edit:
			return true;
		}

		return super.onOptionsItemSelected(item);
	}

	/**
	 * This method will load up the new cursor data for the list
	 */

	@Override
	protected Cursor getCursor() {
		return EncountersTable.getEditEncounterInfo(GameSQLDataSource.getDatabase(getActivity()), mEncounterRowID);
	}

	// ===========================================================
	// TODO Methods
	// ===========================================================

	private void addCreature(){
		new PickCreatureFragment(this, mEncounterRowID).show(getFragmentManager(), null);

		refreshList();
	}

	private void editCreature(){

	}

	private void removeCreature(){
		EncountersTable.removeCreatures(GameSQLDataSource.getDatabase(getActivity()), getSelectedRowID());

		refreshList();

		resetSelection();
	}

	public static EditEncounterFragment newInstance(long rowID){
		EditEncounterFragment frag = new EditEncounterFragment();

		Bundle args = new Bundle();
		args.putLong(ARGS_ROW_ID, rowID);

		frag.setArguments(args);

		return frag;
	}
}


text:
using System;
using System.Linq;
using System.Collections.Generic;
namespace EqualSum
{
    public class equalSum
    {
        public static void Main()
        {
            List<int> excessNumbers = Console.ReadLine().Split().Select(int.Parse).ToList();
            List<int> originalList = Console.ReadLine().Split().Select(int.Parse).ToList();

            List<int> nowList = RemoveNumbers(originalList, excessNumbers);

            int sumExcessNumbers = SumListNumbers(excessNumbers);
            int sumNowList = SumListNumbers(nowList);

            Console.WriteLine(sumExcessNumbers == sumNowList ? $"Yes. Sum: {sumNowList}" :
                $"No. Diff: {Math.Abs(sumNowList - sumExcessNumbers)}");
        }

        private static int SumListNumbers(List<int> list)
        {
            int sum = 0;
            for (int i = 0; i < list.Count; i++)
            {
                sum += list[i];
            }
            return sum;
        }

        private static List<int> RemoveNumbers(List<int> originalList, List<int> excessNumbers)
        {
            for (int a = 0; a < originalList.Count; a++)
            {
                for (int b = 0; b < excessNumbers.Count; b++)
                {
                    if (originalList[a] == excessNumbers[b])
                    {
                        a--;
                        originalList.Remove(excessNumbers[b]);
                        break;
                    }
                }
            }
            return originalList;
        }
    }
}


text:
<?php

/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */

/**
 * This file is part of the PEAR2\Console\CommandLine package.
 *
 * PHP version 5
 *
 * LICENSE: This source file is subject to the MIT license that is available
 * through the world-wide-web at the following URI:
 * http://opensource.org/licenses/mit-license.php
 *
 * @category  Console
 * @package   PEAR2\Console\CommandLine
 * @author    David JEAN LOUIS <izimobil@gmail.com>
 * @copyright 2007-2009 David JEAN LOUIS
 * @license   http://opensource.org/licenses/mit-license.php MIT License
 * @version   SVN: $Id$
 * @link      http://pear.php.net/package/Console_CommandLine
 * @since     File available since release 0.1.0
 * @filesource
 */

/**
 * Class that represent a commandline option.
 *
 * @category  Console
 * @package   PEAR2\Console\CommandLine
 * @author    David JEAN LOUIS <izimobil@gmail.com>
 * @copyright 2007-2009 David JEAN LOUIS
 * @license   http://opensource.org/licenses/mit-license.php MIT License
 * @version   Release: @package_version@
 * @link      http://pear.php.net/package/Console_CommandLine
 * @since     Class available since release 0.1.0
 */
namespace PEAR2\Console\CommandLine;

use PEAR2\Console;

class Option extends Element
{
    // Public properties {{{

    /**
     * The option short name (ex: -v).
     *
     * @var string $short_name Short name of the option
     */
    public $short_name;

    /**
     * The option long name (ex: --verbose).
     *
     * @var string $long_name Long name of the option
     */
    public $long_name;

    /**
     * The option action, defaults to "StoreString".
     *
     * @var string $action Option action
     */
    public $action = 'StoreString';

    /**
     * The default value of the option if not provided on the command line.
     *
     * @var mixed $default Default value of the option.
     */
    public $default;

    /**
     * An array of possible values for the option. If this array is not empty
     * and the value passed is not in the array an exception is raised.
     * This only make sense for actions that accept values of course.
     *
     * @var array $choices Valid choices for the option
     */
    public $choices = array();

    /**
     * The callback function (or method) to call for an action of type
     * Callback, this can be any callable supported by the php function
     * call_user_func.
     *
     * Example:
     *
     *
     * $parser->addOption('myoption', array(
     *     'short_name' => '-m',
     *     'long_name'  => '--myoption',
     *     'action'     => 'Callback',
     *     'callback'   => 'myCallbackFunction'
     * ));
     *
     *
     * @var callable $callback The option callback
     */
    public $callback;

    /**
     * An associative array of additional params to pass to the class
     * corresponding to the action, this array will also be passed to the
     * callback defined for an action of type Callback, Example:
     *
     *
     * // for a custom action
     * $parser->addOption('myoption', array(
     *     'short_name'    => '-m',
     *     'long_name'     => '--myoption',
     *     'action'        => 'MyCustomAction',
     *     'action_params' => array('foo'=>true, 'bar'=>false)
     * ));
     *
     * // if the user type:
     * // $ <yourprogram> -m spam
     * // in your MyCustomAction class the execute() method will be called
     * // with the value 'spam' as first parameter and
     * // array('foo'=>true, 'bar'=>false) as second parameter
     *
     *
     * @var array $action_params Additional parameters to pass to the action
     */
    public $action_params = array();

    /**
     * For options that expect an argument, this property tells the parser if
     * the option argument is optional and can be ommited.
     *
     * @var bool $argumentOptional Whether the option arg is optional or not
     */
    public $argument_optional = false;

    /**
     * For options that uses the "choice" property only.
     * Adds a --list-<choice> option to the parser that displays the list of
     * choices for the option.
     *
     * @var bool $add_list_option Whether to add a list option or not
     */
    public $add_list_option = false;

    // }}}
    // Private properties {{{

    /**
     * When an action is called remember it to allow for multiple calls.
     *
     * @var object $action_instance Placeholder for action
     */
    private $_action_instance = null;

    // }}}
    // __construct() {{{

    /**
     * Constructor.
     *
     * @param string $name   The name of the option
     * @param array  $params An optional array of parameters
     *
     * @return void
     */
    public function __construct($name = null, $params = array())
    {
        parent::__construct($name, $params);
        if ($this->action == 'Password') {
            // special case for Password action, password can be passed to the
            // commandline or prompted by the parser
            $this->argument_optional = true;
        }
    }

    // }}}
    // toString() {{{

    /**
     * Returns the string representation of the option.
     *
     * @param string $delim Delimiter to use between short and long option
     *
     * @return string The string representation of the option
     * @todo use __toString() instead
     */
    public function toString($delim = ", ")
    {
        $ret     = '';
        $padding = '';
        if ($this->short_name != null) {
            $ret .= $this->short_name;
            if ($this->expectsArgument()) {
                $ret .= ' ' . $this->help_name;
            }
            $padding = $delim;
        }
        if ($this->long_name != null) {
            $ret .= $padding . $this->long_name;
            if ($this->expectsArgument()) {
                $ret .= '=' . $this->help_name;
            }
        }
        return $ret;
    }

    // }}}
    // expectsArgument() {{{

    /**
     * Returns true if the option requires one or more argument and false
     * otherwise.
     *
     * @return bool Whether the option expects an argument or not
     */
    public function expectsArgument()
    {
        if ($this->action == 'StoreTrue' || $this->action == 'StoreFalse' ||
            $this->action == 'Help' || $this->action == 'Version' ||
            $this->action == 'Counter' || $this->action == 'List') {
            return false;
        }
        return true;
    }

    // }}}
    // dispatchAction() {{{

    /**
     * Formats the value $value according to the action of the option and
     * updates the passed PEAR2\Console\CommandLine_Result object.
     *
     * @param mixed                            $value  The value to format
     * @param PEAR2\Console\CommandLine_Result $result The result instance
     * @param PEAR2\Console\CommandLine        $parser The parser instance
     *
     * @return void
     * @throws PEAR2\Console\CommandLine_Exception
     */
    public function dispatchAction($value, $result, $parser)
    {
        $actionInfo = Console\CommandLine::$actions[$this->action];
        $clsname    = $actionInfo[0];
        if ($this->_action_instance === null) {
            $this->_action_instance  = new $clsname($result, $this, $parser);
        }

        // check value is in option choices
        if (!empty($this->choices) && !in_array($this->_action_instance->format($value), $this->choices)) {
            throw Console\CommandLine\Exception::factory(
                'OPTION_VALUE_NOT_VALID',
                array(
                    'name'    => $this->name,
                    'choices' => implode('", "', $this->choices),
                    'value'   => $value,
                ),
                $parser,
                $this->messages
            );
        }
        $this->_action_instance->execute($value, $this->action_params);
    }

    // }}}
    // validate() {{{

    /**
     * Validates the option instance.
     *
     * @return void
     * @throws PEAR2\Console\CommandLine_Exception
     * @todo use exceptions instead
     */
    public function validate()
    {
        // check if the option name is valid
        if (!preg_match('/^[a-zA-Z_\x7f-\xff]+[a-zA-Z0-9_\x7f-\xff]*$/',
            $this->name)) {
            Console\CommandLine::triggerError('option_bad_name',
                E_USER_ERROR, array('{$name}' => $this->name));
        }
        // call the parent validate method
        parent::validate();
        // a short_name or a long_name must be provided
        if ($this->short_name == null && $this->long_name == null) {
            Console\CommandLine::triggerError('option_long_and_short_name_missing',
                E_USER_ERROR, array('{$name}' => $this->name));
        }
        // check if the option short_name is valid
        if ($this->short_name != null &&
            !(preg_match('/^\-[a-zA-Z]{1}$/', $this->short_name))) {
            Console\CommandLine::triggerError('option_bad_short_name',
                E_USER_ERROR, array(
                    '{$name}' => $this->name,
                    '{$short_name}' => $this->short_name
                ));
        }
        // check if the option long_name is valid
        if ($this->long_name != null &&
            !preg_match('/^\-\-[a-zA-Z]+[a-zA-Z0-9_\-]*$/', $this->long_name)) {
            Console\CommandLine::triggerError('option_bad_long_name',
                E_USER_ERROR, array(
                    '{$name}' => $this->name,
                    '{$long_name}' => $this->long_name
                ));
        }
        // check if we have a valid action
        if (!is_string($this->action)) {
            Console\CommandLine::triggerError('option_bad_action',
                E_USER_ERROR, array('{$name}' => $this->name));
        }
        if (!isset(Console\CommandLine::$actions[$this->action])) {
            Console\CommandLine::triggerError('option_unregistered_action',
                E_USER_ERROR, array(
                    '{$action}' => $this->action,
                    '{$name}' => $this->name
                ));
        }
        // if the action is a callback, check that we have a valid callback
        if ($this->action == 'Callback' && !is_callable($this->callback)) {
            Console\CommandLine::triggerError('option_invalid_callback',
                E_USER_ERROR, array('{$name}' => $this->name));
        }
    }

    // }}}
    // setDefaults() {{{

    /**
     * Set the default value according to the configured action.
     *
     * Note that for backward compatibility issues this method is only called
     * when the 'force_options_defaults' is set to true, it will become the
     * default behaviour in the next major release of PEAR2\Console\CommandLine.
     *
     * @return void
     */
    public function setDefaults()
    {
        if ($this->default !== null) {
            // already set
            return;
        }
        switch ($this->action) {
        case 'Counter':
        case 'StoreInt':
            $this->default = 0;
            break;
        case 'StoreFloat':
            $this->default = 0.0;
            break;
        case 'StoreArray':
            $this->default = array();
            break;
        case 'StoreTrue':
            $this->default = false;
            break;
        case 'StoreFalse':
            $this->default = true;
            break;
        default:
            return;
        }
    }

    // }}}
}


text:
import json
import argparse
import vizier.node as vizier_node

def main():

    # Parse Command Line Arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("node_descriptor", help=".json file node information")
    parser.add_argument("-port", type=int, help="MQTT Port", default=8080)
    parser.add_argument("-host", help="MQTT Host IP", default="localhost")

    args = parser.parse_args()

    # Ensure that Node Descriptor File can be Opened
    node_descriptor = None
    try:
        f = open(args.node_descriptor, 'r')
        node_descriptor = json.load(f)
        f.close()
    except Exception as e:
        print(repr(e))
        print("Couldn't open given node file " + args.node_descriptor)
        return -1

    # Start the Node
    node = vizier_node.Node(args.host, args.port, node_descriptor)
    node.start()

    # Get the links for Publishing/Subscribing
    publishable_link = list(node.publishable_links)[0]
    subscribable_link = list(node.subscribable_links)[0]
    msg_queue = node.subscribe(subscribable_link)

    # Control stuffs
    ref = 5.0
    state = 1.0e6
    print('\n')
    while abs(ref - state) >= 0.001:
        try:
            message = msg_queue.get(timeout=1).decode(encoding='UTF-8')
            state = float(message)
        except KeyboardInterrupt:
            break
        except Exception:
            continue
        print('Control input = {}'.format(ref-state), end='\r')
        node.publish(publishable_link, str(ref-state))
    print('\n')
    node.stop()

if(__name__ == "__main__"):
    main()


text:
package com.orionplatform.math.differentialequation.ordinary;

import com.orionplatform.core.abstraction.Orion;
import com.orionplatform.math.function.twovariables.Function2x1;
import com.orionplatform.math.geometry.vector.Vector;
import com.orionplatform.math.linearalgebra.matrix.Matrix;
import com.orionplatform.math.number.ANumber;

public class OrdinaryDifferentialEquation extends Orion
{
    private Function2x1<ANumber, ANumber, ANumber> function;
    private ANumber initialConditionX0;
    private ANumber initialConditionY0;
    private ANumber h;
    private ANumber xAtWhichToApproximateSolution;
    private Vector timeSteps;
    private Matrix internalWeights;
    private Vector propagationWeights;

    public OrdinaryDifferentialEquation(Function2x1<ANumber, ANumber, ANumber> function, ANumber initialConditionX0, ANumber initialConditionY0, ANumber h, ANumber xAtWhichToApproximateSolution)
    {
        OrdinaryDifferentialEquationRules.isValid(function, initialConditionX0, initialConditionY0, h, xAtWhichToApproximateSolution);
        this.function = function;
        this.initialConditionX0 = initialConditionX0;
        this.initialConditionY0 = initialConditionY0;
        this.h = h;
        this.xAtWhichToApproximateSolution = xAtWhichToApproximateSolution;
    }

    public OrdinaryDifferentialEquation(Vector timeSteps, Matrix internalWeights, Vector propagationWeights)
    {
        OrdinaryDifferentialEquationRules.isValid(timeSteps, internalWeights, propagationWeights);
        this.timeSteps = timeSteps;
        this.internalWeights = internalWeights;
        this.propagationWeights = propagationWeights;
    }

    public static synchronized OrdinaryDifferentialEquation of(Vector timeSteps, Matrix internalWeights, Vector propagationWeights)
    {
        return new OrdinaryDifferentialEquation(timeSteps, internalWeights, propagationWeights);
    }

    public static synchronized OrdinaryDifferentialEquation of(Function2x1<ANumber, ANumber, ANumber> function, ANumber initialConditionX0, ANumber initialConditionY0, ANumber h, ANumber xAtWhichToApproximateSolution)
    {
        return new OrdinaryDifferentialEquation(function, initialConditionX0, initialConditionY0, h, xAtWhichToApproximateSolution);
    }

    public Vector getTimeSteps()
    {
        return this.timeSteps;
    }

    public Matrix getInternalWeights()
    {
        return this.internalWeights;
    }

    public Vector getPropagationWeights()
    {
        return this.propagationWeights;
    }

    public Function2x1<ANumber, ANumber, ANumber> getFunction()
    {
        return this.function;
    }

    public ANumber getInitialConditionX0()
    {
        return this.initialConditionX0;
    }

    public ANumber getInitialConditionY0()
    {
        return this.initialConditionY0;
    }

    public ANumber getH()
    {
        return this.h;
    }

    public ANumber getxAtWhichToApproximateSolution()
    {
        return this.xAtWhichToApproximateSolution;
    }
}


text:
package io.opentelemetry.sdk.testing.assertj;

import static java.util.stream.Collectors.toList;

import io.opentelemetry.sdk.trace.data.SpanData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.StreamSupport;
import org.assertj.core.api.AbstractIterableAssert;

/** Assertions for a list of exported traces. */
public final class TracesAssert
    extends AbstractIterableAssert<
        TracesAssert, List<List<SpanData>>, List<SpanData>, TraceAssert> {

  /**
   * Returns an assertion for a list of traces. The traces must already be grouped into {@code
   * List<SpanData>} where each list has spans with the same trace ID.
   */
  public static TracesAssert assertThat(Collection<List<SpanData>> traces) {
    for (List<SpanData> trace : traces) {
      if (trace.stream().map(SpanData::getTraceId).distinct().count() != 1) {
        throw new IllegalArgumentException(
            "trace does not have consistent trace IDs, group spans into traces before calling "
                + "this function: "
                + trace);
      }
    }
    return new TracesAssert(new ArrayList<>(traces));
  }

  TracesAssert(List<List<SpanData>> lists) {
    super(lists, TracesAssert.class);
  }

  /**
   * Asserts that the traces under assertion have the same number of traces as provided {@code
   * assertions} and executes each {@link TracesAssert} in {@code assertions} in order with the
   * corresponding trace.
   */
  @SafeVarargs
  @SuppressWarnings("varargs")
  public final TracesAssert hasTracesSatisfyingExactly(Consumer<TraceAssert>... assertions) {
    return hasTracesSatisfyingExactly(Arrays.asList(assertions));
  }

  /**
   * Asserts that the traces under assertion have the same number of traces as provided {@code
   * assertions} and executes each {@link TracesAssert} in {@code assertions} in order with the
   * corresponding trace.
   */
  public TracesAssert hasTracesSatisfyingExactly(
      Iterable<? extends Consumer<TraceAssert>> assertions) {
    List<Consumer<TraceAssert>> assertionsList =
        StreamSupport.stream(assertions.spliterator(), false).collect(toList());
    hasSize(assertionsList.size());
    // Avoid zipSatisfy - https://github.com/assertj/assertj-core/issues/2300
    for (int i = 0; i < assertionsList.size(); i++) {
      assertionsList.get(i).accept(new TraceAssert(actual.get(i)));
    }
    return this;
  }

  @Override
  protected TraceAssert toAssert(List<SpanData> value, String description) {
    return new TraceAssert(value).as(description);
  }

  @Override
  protected TracesAssert newAbstractIterableAssert(Iterable<? extends List<SpanData>> iterable) {
    return new TracesAssert(StreamSupport.stream(iterable.spliterator(), false).collect(toList()));
  }
}


text:
package org.apache.myfaces.shared.util;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.faces.context.ExternalContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponseWrapper;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * This provides some functionality for determining some things about the
 * native request object that is not provided by JSF.  This class is useful
 * for use in places where Portlet API's may or may not be present and can
 * also provide access to some request-specific items which are not available on
 * the JSF ExternalContext.  If portlet API's are not present, this class simply
 * handles the Servlet Request type.
 */
public final class ExternalContextUtils
{

    /**
     * Returns true if a particular class relating to the supplied
     * request type is available on the current classpath or false
     * if it is not.  This class assumes that all containers have a servlet type
     * request available, but the portlet request types are all dependant on the
     * portlet container being used.
     *
     * @param type the RequestType to test
     * @return a boolean value of true if the container contains the
     *         request type in the classpath
     * @since 2.0
     */
    public static final boolean isRequestTypeAvailable(RequestType type)
    {
        switch (type)
        {
        case SERVLET:
            return true;

        case ACTION:
        case RENDER:
            return _PORTLET_CONTEXT_CLASS != null;

        case RESOURCE:
        case EVENT:
            return _PORTLET_RENDER_REQUEST_CLASS != null;

        default:
            return false;
        }
    }

    /**
     * Returns true if a particular request type is supported by the
     * container.  For a request type to be supported, the required objects must
     * be on the classpath AND and, in the case of Portlet RequestTypes, an
     * appropriate bridge must be avaialble which supports those objects.  This
     * means that if the supplied RequestType is RESOURCE, the
     * javax.portlet.ResourceRequest object must be available on the classpath AND
     * a bridge which supports the Portlet 2.0 specification would also need to be
     * available.
     *
     * @param type the RequestType to test
     * @return a boolean value of true if the container supports the
     *         current request type
     * @since 2.0
     */
    public static final boolean isRequestTypeSupported(RequestType type)
    {
        switch (type)
        {
        case SERVLET:
            return true;

        case ACTION:
        case RENDER:
            return _PORTLET_10_SUPPORTED;

        case RESOURCE:
        case EVENT:
            return _PORTLET_20_SUPPORTED;

        default:
            return false;
        }
    }

    /**
     * Returns the requestType of this ExternalContext.
     *
     * @param externalContext the current external context
     * @return the appropriate RequestType for this external context
     * @see RequestType
     */
    public static final RequestType getRequestType(ExternalContext externalContext)
    {
        //Stuff is laid out strangely in this class in order to optimize
        //performance.  We want to do as few instanceof's as possible so
        //things are laid out according to the expected frequency of the
        //various requests occurring.
        if(_PORTLET_10_SUPPORTED || _PORTLET_20_SUPPORTED)
        {
            if (_PORTLET_CONTEXT_CLASS.isInstance(externalContext.getContext()))
            {
                //We are inside of a portlet container
                Object request = externalContext.getRequest();

                if(_PORTLET_RENDER_REQUEST_CLASS.isInstance(request))
                {
                    return RequestType.RENDER;
                }

                if(_PORTLET_RESOURCE_REQUEST_CLASS != null)
                {
                    if(_PORTLET_ACTION_REQUEST_CLASS.isInstance(request))
                    {
                        return RequestType.ACTION;
                    }

                    //We are in a JSR-286 container
                    if(_PORTLET_RESOURCE_REQUEST_CLASS.isInstance(request))
                    {
                        return RequestType.RESOURCE;
                    }

                    return RequestType.EVENT;
                }

                return RequestType.ACTION;
            }
        }

        return RequestType.SERVLET;
    }

    /**
     * This method is used when a ExternalContext object is not available,
     * like in TomahawkFacesContextFactory.
     *
     * According to TOMAHAWK-1331, the object context could receive an
     * instance of javax.portlet.PortletContext or javax.portlet.PortletConfig,
     * so we check both cases.
     *
     * @param context
     * @param request
     * @return
     */
    public static final RequestType getRequestType(Object context, Object request)
    {
        //Stuff is laid out strangely in this class in order to optimize
        //performance.  We want to do as few instanceof's as possible so
        //things are laid out according to the expected frequency of the
        //various requests occurring.

        if(_PORTLET_10_SUPPORTED || _PORTLET_20_SUPPORTED)
        {
            if (_PORTLET_CONFIG_CLASS.isInstance(context) ||
                _PORTLET_CONTEXT_CLASS.isInstance(context))
            {
                //We are inside of a portlet container

                if(_PORTLET_RENDER_REQUEST_CLASS.isInstance(request))
                {
                    return RequestType.RENDER;
                }

                if(_PORTLET_RESOURCE_REQUEST_CLASS != null)
                {
                    if(_PORTLET_ACTION_REQUEST_CLASS.isInstance(request))
                    {
                        return RequestType.ACTION;
                    }

                    //We are in a JSR-286 container
                    if(_PORTLET_RESOURCE_REQUEST_CLASS.isInstance(request))
                    {
                        return RequestType.RESOURCE;
                    }

                    return RequestType.EVENT;
                }

                return RequestType.ACTION;
            }
        }

        return RequestType.SERVLET;
    }

    /**
     * Returns the current active session id or null if there is
     * none.  If a session is not already created, this method will create one
     * for you.
     *
     * @param ec the current external context
     * @return a string containing the requestedSessionId
     */
    public static String getSessionId(ExternalContext ec)
    {
        return getSessionId(ec, true);
    }

    /**
     * Returns the current active session id or null if there is
     * none.
     *
     * @param ec the current external context
     * @param create create a new session if one is not created
     * @return a string containing the requestedSessionId
     */
    public static String getSessionId(ExternalContext ec, boolean create)
    {
        Object session = ec.getSession(create);
        return (null != session) ? (String) _runMethod(session, "getId") : null;
    }

    /**
     * Returns the session ID for the client, or null if there is none.
     *
     * @param ec the current external context
     * @return a string containing the requestedSessionId
     */
    public static String getRequestedSessionId(ExternalContext ec)
    {
        return (String) _runMethod(ec.getRequest(), "getRequestedSessionId");
    }

    /**
     * Checks if the requested session ID is still valid.
     *
     * @param ec the current external context
     * @return a boolean containing true if the request session is
     *         valid or false if it is not
     */
    public static boolean isRequestedSessionIdValid(ExternalContext ec)
    {
        return (Boolean) _runMethod(ec.getRequest(),
                "isRequestedSessionIdValid");
    }

    /**
     * Returns the contextPath of the ServletContext or null for portlets
     *
     * @param ec the current external context
     * @return a String containing the servletContextPath
     */
    public static String getServletContextPath(ExternalContext ec)
    {
        if (!isPortlet(ec))
        {
            return ((ServletContext) ec.getContext()).getContextPath();
        }
        else
        {
            return null;
        }
    }

    /**
     * Returns the contextPath of the ServletRequest or null for portlet requests
     *
     * @param ec the current external context
     * @return a String containing the request context path
     * @see ExternalContext#getRequestContextPath()
     *
     * @deprecated use ExternalContext.getRequestContextPath() as of JSF 1.2.  This method
     *             does not appropriately handle portlet environments, but the functionality
     *             is maintained to prevent needing to change the contract.
     */
    @Deprecated
    public static String getRequestContextPath(ExternalContext ec)
    {
        if (!isPortlet(ec))
        {
            return ec.getRequestContextPath();
        }
        else
        {
            return null;
        }
    }

    /**
     * Returns the requestURI of the HttpServletRequest or null for
     * portlet requests
     *
     * @param ec the current external context
     * @return A string containing the current request uri
     */
    public static String getRequestURI(ExternalContext ec)
    {
        if (!isPortlet(ec))
        {
            return ((HttpServletRequest) ec.getRequest()).getRequestURI();
        }
        else
        {
            return null;
        }
    }

    /**
     * Returns the character encoding or null if there isn't any
     *
     * @param ec the current external context
     * @return a string containing the request's character encoding
     * @see ExternalContext#getRequestCharacterEncoding()
     *
     * @deprecated replaced by an API in JSF.  Use ExternalContext.getRequestCharacterEncoding()
     */
    @Deprecated
    public static String getCharacterEncoding(ExternalContext ec)
    {
        return ec.getRequestCharacterEncoding();
    }

    /**
     * Returns the name of the underlying context or null if something
     * went wrong in trying to retrieve the context.
     *
     * @param ec the current external context
     * @return a String containing the context name
     */
    public static String getContextName(ExternalContext ec)
    {
        try
        {
            if (isPortlet(ec))
            {
                return (String) _runMethod(ec.getContext(),
                        "getPortletContextName");
            }
            else
            {
                return ((ServletContext) ec.getContext())
                        .getServletContextName();
            }
        }
        catch (final ClassCastException e)
        {
            _LOG.severe(e.getMessage());
        }
        return null;
    }

    /**
     * Returns the name and version of the underlying servlet container or null if something
     * went wrong in trying to retrieve the context.
     *
     * @param ec the current external context
     * @return a String containing the name and version of the underlying servlet container
     */
    public static String getServerInfo(ExternalContext ec)
    {
        try
        {
            if (isPortlet(ec))
            {
                return (String) _runMethod(ec.getContext(), "getServerInfo");
            }
            else
            {
                return ((ServletContext) ec.getContext()).getServerInfo();
            }
        }
        catch (final ClassCastException e)
        {
            _LOG.severe(e.getMessage());
        }
        return null;
    }

    /**
     * Returns the content length or -1 if the unknown.
     *
     * @param ec the current external context
     * @return the length or -1 if the length is unknown
     */
    public static int getContentLength(ExternalContext ec)
    {
        if (isRequestFromClient(ec))
        {
            return (Integer) _runMethod(ec.getRequest(), "getContentLength");
        }

        return -1;
    }

    /**
     * Returns the content type from the current externalContext or
     * null if unknown.
     *
     * @param ec the current external context
     * @return a String contining the the content type or null
     * @see ExternalContext#getRequestContentType()
     *
     * @deprecated use ExternalContext.getRequestContentType()
     */
    @Deprecated
    public static String getContentType(ExternalContext ec)
    {
        return ec.getRequestContentType();
    }

    /**
     * Returns the request input stream if one is available
     *
     * @param ec the current external context
     * @return the request's input stream
     * @throws IOException if there was a problem getting the input stream
     */
    public static InputStream getRequestInputStream(ExternalContext ec)
            throws IOException
    {
        RequestType type = getRequestType(ec);
        if (type.isRequestFromClient())
        {
            Object req = ec.getRequest();
            if (type.isPortlet())
            {
                return (InputStream) _runMethod(req, "getPortletInputStream");
            }
            else
            {
                return ((ServletRequest) ec.getRequest()).getInputStream();
            }
        }

        return null;
    }

    /**
     * Returns true if this externalContext represents an "action".
     * An action request is any ServletRequest or a portlet ActionRequest or
     * ResourceRequest.
     *
     * @param ec the current external context
     * @return a boolean of true if this request is an action-type
     *         request.
     * @see #isRequestFromClient(ExternalContext)
     *
     * @deprecated replaced with {@link #isRequestFromClient(ExternalContext)}
     */
    @Deprecated
    public static boolean isAction(ExternalContext ec)
    {
        return isRequestFromClient(ec);
    }

    /**
     * Returns the value of {@link RequestType#isPortlet()} for the current
     * RequestType. This is a convenience function designed to perform a quick
     * check of the current request. If more capabilities need to be tested for
     * the given request, then it is more efficient to pull this information from
     * the RequestType itself.
     *
     * @param ec the current external context
     * @return a boolean value of true if the current RequestType
     *         is a portlet request.
     *
     * @see RequestType#isPortlet()
     * @see #getRequestType(ExternalContext)
     */
    public static boolean isPortlet(ExternalContext ec)
    {
        return getRequestType(ec).isPortlet();
    }

    /**
     * Returns the value of {@link RequestType#isResponseWritable()} for the
     * current RequestType. This is a convenience function designed to perform a
     * quick check of the current request. If more capabilities need to be tested
     * for the given request, then it is more efficient to pull this information
     * from the RequestType itself.
     *
     * @param ec the current external context
     * @return a boolean value of true if the current RequestType
     *         is a "render" type response.
     *
     * @see RequestType#isResponseWritable()
     * @see #getRequestType(ExternalContext)
     * @since 2.0
     */
    public static final boolean isResponseWritable(ExternalContext ec)
    {
        return getRequestType(ec).isResponseWritable();
    }

    /**
     * Returns the value of {@link RequestType#isRequestFromClient()} for the
     * current RequestType. This is a convenience function designed to perform a
     * quick check of the current request. If more capabilities need to be tested
     * for the given request, then it is more efficient to pull this information
     * from the RequestType itself.
     *
     * @param ec the current external context
     * @return a boolean value of true if the current RequestType
     *         represents a request from the client.
     *
     * @see RequestType#isResponseWritable()
     * @see #getRequestType(ExternalContext)
     * @since 2.0
     */
    public static final boolean isRequestFromClient(ExternalContext ec)
    {
        return getRequestType(ec).isRequestFromClient();
    }

    /**
     * Returns wherther of not this external context represents a true HttpServletRequest or
     * not.  Some portal containers implement the PortletRequest/Response objects as
     * HttpServletRequestWrappers, and those objects should not be treated as an
     * HttpServlerRequest.  As such, this method first tests to see if the request is
     * a portlet request and, if not, then tests to see if the request is an instanceof
     * HttpServletRequest.
     *
     * @param ec the current external context
     * @return a boolean value of true if the current request is an
     *         HttpServletRequest
     * @since 1.1
     */
    public static boolean isHttpServletRequest(ExternalContext ec)
    {
        return (!isPortlet(ec) && (ec.getRequest() instanceof HttpServletRequest));
    }

    /**
     * Returns an HttpServletResponse if one exists on the externalContext or null
     * if it does not.  Please note that some portal environments implement the
     * PortletRequest and Response objects as HttpServletRequest/Response objects.
     * This method handles these types of requests properly and will therefore
     * return null in portal environments.
     *
     * @param response
     * @return an HttpServletResponse if we have one or null if we do not
     * @since 4.0
     */
    public static HttpServletResponse getHttpServletResponse(ExternalContext ec)
    {
        if (isHttpServletRequest(ec))
        {
            return (HttpServletResponse) ec.getResponse();
        }

        return null;
    }

    /**
     * Runs a method on an object and returns the result
     *
     * @param obj the object to run the method on
     * @param methodName the name of the method
     * @return the results of the method run
     */
    private static Object _runMethod(Object obj, String methodName)
    {
        try
        {
            Method sessionIdMethod = obj.getClass().getMethod(methodName);
            return sessionIdMethod.invoke(obj);
        }
        catch (Exception e)
        {
            return null;
        }

    }

    // prevent this from being instantiated
    private ExternalContextUtils()
    {
    }

    private static final Logger _LOG = Logger
            .getLogger(ExternalContextUtils.class.getName());

    // =-= Scott O'Bryan =-=
    // Performance enhancement. These will be needed anyway, let's not get them every time.
    private static final Class<?> _PORTLET_ACTION_REQUEST_CLASS;
    private static final Class<?> _PORTLET_RENDER_REQUEST_CLASS;
    private static final Class<?> _PORTLET_RESOURCE_REQUEST_CLASS;
    private static final Class<?> _PORTLET_CONTEXT_CLASS;
    private static final boolean _PORTLET_10_SUPPORTED;
    private static final boolean _PORTLET_20_SUPPORTED;
    private static final Class<?> _PORTLET_CONFIG_CLASS;

    static
    {
        Class<?> context;
        Class<?> config;
        Class<?> actionRequest;
        Class<?> renderRequest;
        Class<?> resourceRequest;
        boolean portlet20Supported = false;
        boolean portlet10Supported = false;

        try
        {
            context = ClassLoaderUtils
                    .loadClass("javax.portlet.PortletContext");
            config = ClassLoaderUtils.loadClass("javax.portlet.PortletConfig");
            actionRequest = ClassLoaderUtils
                    .loadClass("javax.portlet.ActionRequest");
            renderRequest = ClassLoaderUtils
                    .loadClass("javax.portlet.RenderRequest");

            try
            {
                resourceRequest = ClassLoaderUtils
                        .loadClass("javax.portlet.ResourceRequest");
            }
            catch (ClassNotFoundException e)
            {
                _LOG.fine("Portlet 2.0 API is not available on classpath.  Portlet 2.0 functionality is disabled");
                resourceRequest = null;
            }
        }
        catch (final ClassNotFoundException e)
        {
            _LOG.fine("Portlet API is not available on the classpath.  Portlet configurations are disabled.");
            context = null;
            config = null;
            actionRequest = null;
            renderRequest = null;
            resourceRequest = null;
        }

        //Find bridge to tell if portal is supported
        if (context != null)
        {
            // Portlet 1.0 API found. In this case we have to consider that exists alternate
            // bridge implementations like in WebSphere and others.
            portlet10Supported = true;

            try
            {
                Class<?> bridge = ClassLoaderUtils
                        .loadClass("javax.portlet.faces.Bridge");

                if (bridge != null)
                {
                    //Standard bridge defines a spec name which can be used to
                    //determine Portlet 2.0 Support.
                    String specName = bridge.getPackage()
                            .getSpecificationTitle();
                    _LOG.fine("Found Bridge: " + specName);
                    if (specName != null && specName.startsWith("Portlet 2"))
                    {
                        portlet20Supported = true;
                    }

                    if (_LOG.isLoggable(Level.INFO))
                    {
                        String ver = (portlet20Supported) ? "2.0" : "1.0";
                        _LOG.info("Portlet Environment Detected: " + ver);
                    }
                }
            }
            catch (ClassNotFoundException e)
            {
                _LOG.fine("Portlet API is present but Standard Apache Portlet Bridge is not. "
                        + " This could happen if you are using an alternate Portlet Bridge solution.");

                if (resourceRequest != null)
                {
                    portlet20Supported = true;
                }
            }
        }

        _PORTLET_CONTEXT_CLASS = context;
        _PORTLET_CONFIG_CLASS = config;
        _PORTLET_ACTION_REQUEST_CLASS = actionRequest;
        _PORTLET_RENDER_REQUEST_CLASS = renderRequest;
        _PORTLET_RESOURCE_REQUEST_CLASS = resourceRequest;
        _PORTLET_10_SUPPORTED = portlet10Supported;
        _PORTLET_20_SUPPORTED = portlet20Supported;
    }

    /**
     * Trys to obtain a HttpServletResponse from the Response.
     * Note that this method also trys to unwrap any ServletResponseWrapper
     * in order to retrieve a valid HttpServletResponse.
     * @param response
     * @return if found, the HttpServletResponse, null otherwise
     */
    public static HttpServletResponse getHttpServletResponse(Object response)
    {
        // unwrap the response until we find a HttpServletResponse
        while (response != null)
        {
            if (response instanceof HttpServletResponse)
            {
                // found
                return (HttpServletResponse) response;
            }
            if (response instanceof ServletResponseWrapper)
            {
                // unwrap
                response = ((ServletResponseWrapper) response).getResponse();
            }
            // no more possibilities to find a HttpServletResponse
            break;
        }
        return null; // not found
    }

    /**
     * Trys to obtain a ResponseSwitch from the Response.
     * @param response
     * @return if found, the ResponseSwitch, null otherwise
     */
    /*
    public static ResponseSwitch getResponseSwitch(Object response)
    {
        // unwrap the response until we find a ResponseSwitch
        while (response != null)
        {
            if (response instanceof ResponseSwitch)
            {
                // found
                return (ResponseSwitch) response;
            }
            if (response instanceof ServletResponseWrapper)
            {
                // unwrap
                response = ((ServletResponseWrapper) response).getResponse();
            }
            // no more possibilities to find a ResponseSwitch
            break;
        }
        return null; // not found
    }*/

    /**
     * Try to create a ResponseSwitch for this response.
     * @param response
     * @return the created ResponseSwitch, if there is a ResponseSwitch
     *         implementation for the given response, null otherwise
     */
    /*
    public static ResponseSwitch createResponseSwitch(Object response)
    {
        if (response instanceof HttpServletResponse)
        {
            return new HttpServletResponseSwitch((HttpServletResponse) response);
        }
        else if (response instanceof ServletResponse)
        {
            return new ServletResponseSwitch((ServletResponse) response);
        }
        return null;
    }*/

}


text:
require 'rss'

module RSS
  class MakerProxy < Struct.new :maker
    def item options
      maker.items.new_item do |item|
        options.each { |key, value| item.send :"#{key}=", value }
      end
    end
  end

  def self.feed options
    image = options.delete(:image)
    Maker.make options.delete(:version) || '2.0' do |maker|
      options.each { |key, value| maker.channel.send :"#{key}=", value }
      maker.items.do_sort = true
      maker.image.title = image[1]
      maker.image.url = image[0]
      yield MakerProxy.new(maker)
    end
  end
end


text:
//---------------------------------------------------------------------------
//	Greenplum Database
//	Copyright (C) 2012 EMC Corp.
//
//	@filename:
//		CLogicalUpdate.cpp
//
//	@doc:
//		Implementation of logical Update operator
//---------------------------------------------------------------------------

#include "gpos/base.h"

#include "gpopt/base/CColRefSet.h"
#include "gpopt/base/CKeyCollection.h"
#include "gpopt/base/CPartIndexMap.h"

#include "gpopt/operators/CExpression.h"
#include "gpopt/operators/CExpressionHandle.h"
#include "gpopt/operators/CLogicalUpdate.h"

using namespace gpopt;

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::CLogicalUpdate
//
//	@doc:
//		Ctor - for pattern
//
//---------------------------------------------------------------------------
CLogicalUpdate::CLogicalUpdate
	(
	IMemoryPool *pmp
	)
	:
	CLogical(pmp),
	m_ptabdesc(NULL),
	m_pdrgpcrDelete(NULL),
	m_pdrgpcrInsert(NULL),
	m_pcrCtid(NULL),
	m_pcrSegmentId(NULL),
	m_pcrTupleOid(NULL)
{
	m_fPattern = true;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::CLogicalUpdate
//
//	@doc:
//		Ctor
//
//---------------------------------------------------------------------------
CLogicalUpdate::CLogicalUpdate
	(
	IMemoryPool *pmp,
	CTableDescriptor *ptabdesc,
	DrgPcr *pdrgpcrDelete,
	DrgPcr *pdrgpcrInsert,
	CColRef *pcrCtid,
	CColRef *pcrSegmentId,
	CColRef *pcrTupleOid
	)
	:
	CLogical(pmp),
	m_ptabdesc(ptabdesc),
	m_pdrgpcrDelete(pdrgpcrDelete),
	m_pdrgpcrInsert(pdrgpcrInsert),
	m_pcrCtid(pcrCtid),
	m_pcrSegmentId(pcrSegmentId),
	m_pcrTupleOid(pcrTupleOid)

{
	GPOS_ASSERT(NULL != ptabdesc);
	GPOS_ASSERT(NULL != pdrgpcrDelete);
	GPOS_ASSERT(NULL != pdrgpcrInsert);
	GPOS_ASSERT(pdrgpcrDelete->UlLength() == pdrgpcrInsert->UlLength());
	GPOS_ASSERT(NULL != pcrCtid);
	GPOS_ASSERT(NULL != pcrSegmentId);

	m_pcrsLocalUsed->Include(m_pdrgpcrDelete);
	m_pcrsLocalUsed->Include(m_pdrgpcrInsert);
	m_pcrsLocalUsed->Include(m_pcrCtid);
	m_pcrsLocalUsed->Include(m_pcrSegmentId);

	if (NULL != m_pcrTupleOid)
	{
		m_pcrsLocalUsed->Include(m_pcrTupleOid);
	}
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::~CLogicalUpdate
//
//	@doc:
//		Dtor
//
//---------------------------------------------------------------------------
CLogicalUpdate::~CLogicalUpdate()
{
	CRefCount::SafeRelease(m_ptabdesc);
	CRefCount::SafeRelease(m_pdrgpcrDelete);
	CRefCount::SafeRelease(m_pdrgpcrInsert);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::FMatch
//
//	@doc:
//		Match function
//
//---------------------------------------------------------------------------
BOOL
CLogicalUpdate::FMatch
	(
	COperator *pop
	)
	const
{
	if (pop->Eopid() != Eopid())
	{
		return false;
	}

	CLogicalUpdate *popUpdate = CLogicalUpdate::PopConvert(pop);

	return m_pcrCtid == popUpdate->PcrCtid() &&
			m_pcrSegmentId == popUpdate->PcrSegmentId() &&
			m_pcrTupleOid == popUpdate->PcrTupleOid() &&
			m_ptabdesc->Pmdid()->FEquals(popUpdate->Ptabdesc()->Pmdid()) &&
			m_pdrgpcrDelete->FEqual(popUpdate->PdrgpcrDelete()) &&
			m_pdrgpcrInsert->FEqual(popUpdate->PdrgpcrInsert());
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::UlHash
//
//	@doc:
//		Hash function
//
//---------------------------------------------------------------------------
ULONG
CLogicalUpdate::UlHash() const
{
	ULONG ulHash = gpos::UlCombineHashes(COperator::UlHash(), m_ptabdesc->Pmdid()->UlHash());
	ulHash = gpos::UlCombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrDelete));
	ulHash = gpos::UlCombineHashes(ulHash, CUtils::UlHashColArray(m_pdrgpcrInsert));
	ulHash = gpos::UlCombineHashes(ulHash, gpos::UlHashPtr<CColRef>(m_pcrCtid));
	ulHash = gpos::UlCombineHashes(ulHash, gpos::UlHashPtr<CColRef>(m_pcrSegmentId));

	return ulHash;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::PopCopyWithRemappedColumns
//
//	@doc:
//		Return a copy of the operator with remapped columns
//
//---------------------------------------------------------------------------
COperator *
CLogicalUpdate::PopCopyWithRemappedColumns
	(
	IMemoryPool *pmp,
	HMUlCr *phmulcr,
	BOOL fMustExist
	)
{
	DrgPcr *pdrgpcrDelete = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrDelete, phmulcr, fMustExist);
	DrgPcr *pdrgpcrInsert = CUtils::PdrgpcrRemap(pmp, m_pdrgpcrInsert, phmulcr, fMustExist);
	CColRef *pcrCtid = CUtils::PcrRemap(m_pcrCtid, phmulcr, fMustExist);
	CColRef *pcrSegmentId = CUtils::PcrRemap(m_pcrSegmentId, phmulcr, fMustExist);
	m_ptabdesc->AddRef();

	CColRef *pcrTupleOid = NULL;
	if (NULL != m_pcrTupleOid)
	{
		pcrTupleOid = CUtils::PcrRemap(m_pcrTupleOid, phmulcr, fMustExist);
	}
	return GPOS_NEW(pmp) CLogicalUpdate(pmp, m_ptabdesc, pdrgpcrDelete, pdrgpcrInsert, pcrCtid, pcrSegmentId, pcrTupleOid);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::PcrsDeriveOutput
//
//	@doc:
//		Derive output columns
//
//---------------------------------------------------------------------------
CColRefSet *
CLogicalUpdate::PcrsDeriveOutput
	(
	IMemoryPool *pmp,
	CExpressionHandle & //exprhdl
	)
{
	CColRefSet *pcrsOutput = GPOS_NEW(pmp) CColRefSet(pmp);
	pcrsOutput->Include(m_pdrgpcrInsert);
	pcrsOutput->Include(m_pcrCtid);
	pcrsOutput->Include(m_pcrSegmentId);

	if (NULL != m_pcrTupleOid)
	{
		pcrsOutput->Include(m_pcrTupleOid);
	}
	return pcrsOutput;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::PkcDeriveKeys
//
//	@doc:
//		Derive key collection
//
//---------------------------------------------------------------------------
CKeyCollection *
CLogicalUpdate::PkcDeriveKeys
	(
	IMemoryPool *, // pmp
	CExpressionHandle &exprhdl
	)
	const
{
	return PkcDeriveKeysPassThru(exprhdl, 0 /* ulChild */);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::Maxcard
//
//	@doc:
//		Derive max card
//
//---------------------------------------------------------------------------
CMaxCard
CLogicalUpdate::Maxcard
	(
	IMemoryPool *, // pmp
	CExpressionHandle &exprhdl
	)
	const
{
	// pass on max card of first child
	return exprhdl.Pdprel(0)->Maxcard();
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::PxfsCandidates
//
//	@doc:
//		Get candidate xforms
//
//---------------------------------------------------------------------------
CXformSet *
CLogicalUpdate::PxfsCandidates
	(
	IMemoryPool *pmp
	)
	const
{
	CXformSet *pxfs = GPOS_NEW(pmp) CXformSet(pmp);
	(void) pxfs->FExchangeSet(CXform::ExfUpdate2DML);
	return pxfs;
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::PstatsDerive
//
//	@doc:
//		Derive statistics
//
//---------------------------------------------------------------------------
IStatistics *
CLogicalUpdate::PstatsDerive
	(
	IMemoryPool *, // pmp,
	CExpressionHandle &exprhdl,
	DrgPstat * // not used
	)
	const
{
	return PstatsPassThruOuter(exprhdl);
}

//---------------------------------------------------------------------------
//	@function:
//		CLogicalUpdate::OsPrint
//
//	@doc:
//		debug print
//
//---------------------------------------------------------------------------
IOstream &
CLogicalUpdate::OsPrint
	(
	IOstream &os
	)
	const
{
	if (m_fPattern)
	{
		return COperator::OsPrint(os);
	}

	os	<< SzId()
		<< " (";
	m_ptabdesc->Name().OsPrint(os);
	os << "), Delete Columns: [";
	CUtils::OsPrintDrgPcr(os, m_pdrgpcrDelete);
	os	<< "], Insert Columns: [";
	CUtils::OsPrintDrgPcr(os, m_pdrgpcrInsert);
	os	<< "], ";
	m_pcrCtid->OsPrint(os);
	os	<< ", ";
	m_pcrSegmentId->OsPrint(os);

	return os;
}

// EOF


text:
<?php

namespace Illuminate\Support\Testing\Fakes;

use Illuminate\Contracts\Mail\Mailable;
use Illuminate\Contracts\Mail\Mailer;
use Illuminate\Contracts\Mail\MailQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use PHPUnit\Framework\Assert as PHPUnit;

class MailFake implements Mailer, MailQueue
{
    /**
     * All of the mailables that have been sent.
     *
     * @var array
     */
    protected $mailables = [];

    /**
     * All of the mailables that have been queued.
     *
     * @var array
     */
    protected $queuedMailables = [];

    /**
     * Assert if a mailable was sent based on a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|int|null  $callback
     * @return void
     */
    public function assertSent($mailable, $callback = null)
    {
        if (is_numeric($callback)) {
            return $this->assertSentTimes($mailable, $callback);
        }

        $message = "The expected [{$mailable}] mailable was not sent.";

        if (count($this->queuedMailables) > 0) {
            $message .= ' Did you mean to use assertQueued() instead?';
        }

        PHPUnit::assertTrue(
            $this->sent($mailable, $callback)->count() > 0,
            $message
        );
    }

    /**
     * Assert if a mailable was sent a number of times.
     *
     * @param  string  $mailable
     * @param  int  $times
     * @return void
     */
    protected function assertSentTimes($mailable, $times = 1)
    {
        PHPUnit::assertTrue(
            ($count = $this->sent($mailable)->count()) === $times,
            "The expected [{$mailable}] mailable was sent {$count} times instead of {$times} times."
        );
    }

    /**
     * Determine if a mailable was not sent based on a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|null  $callback
     * @return void
     */
    public function assertNotSent($mailable, $callback = null)
    {
        PHPUnit::assertTrue(
            $this->sent($mailable, $callback)->count() === 0,
            "The unexpected [{$mailable}] mailable was sent."
        );
    }

    /**
     * Assert that no mailables were sent.
     *
     * @return void
     */
    public function assertNothingSent()
    {
        PHPUnit::assertEmpty($this->mailables, 'Mailables were sent unexpectedly.');
    }

    /**
     * Assert if a mailable was queued based on a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|int|null  $callback
     * @return void
     */
    public function assertQueued($mailable, $callback = null)
    {
        if (is_numeric($callback)) {
            return $this->assertQueuedTimes($mailable, $callback);
        }

        PHPUnit::assertTrue(
            $this->queued($mailable, $callback)->count() > 0,
            "The expected [{$mailable}] mailable was not queued."
        );
    }

    /**
     * Assert if a mailable was queued a number of times.
     *
     * @param  string  $mailable
     * @param  int  $times
     * @return void
     */
    protected function assertQueuedTimes($mailable, $times = 1)
    {
        PHPUnit::assertTrue(
            ($count = $this->queued($mailable)->count()) === $times,
            "The expected [{$mailable}] mailable was queued {$count} times instead of {$times} times."
        );
    }

    /**
     * Determine if a mailable was not queued based on a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|null  $callback
     * @return void
     */
    public function assertNotQueued($mailable, $callback = null)
    {
        PHPUnit::assertTrue(
            $this->queued($mailable, $callback)->count() === 0,
            "The unexpected [{$mailable}] mailable was queued."
        );
    }

    /**
     * Assert that no mailables were queued.
     *
     * @return void
     */
    public function assertNothingQueued()
    {
        PHPUnit::assertEmpty($this->queuedMailables, 'Mailables were queued unexpectedly.');
    }

    /**
     * Get all of the mailables matching a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|null  $callback
     * @return \Illuminate\Support\Collection
     */
    public function sent($mailable, $callback = null)
    {
        if (! $this->hasSent($mailable)) {
            return collect();
        }

        $callback = $callback ?: function () {
            return true;
        };

        return $this->mailablesOf($mailable)->filter(function ($mailable) use ($callback) {
            return $callback($mailable);
        });
    }

    /**
     * Determine if the given mailable has been sent.
     *
     * @param  string  $mailable
     * @return bool
     */
    public function hasSent($mailable)
    {
        return $this->mailablesOf($mailable)->count() > 0;
    }

    /**
     * Get all of the queued mailables matching a truth-test callback.
     *
     * @param  string  $mailable
     * @param  callable|null  $callback
     * @return \Illuminate\Support\Collection
     */
    public function queued($mailable, $callback = null)
    {
        if (! $this->hasQueued($mailable)) {
            return collect();
        }

        $callback = $callback ?: function () {
            return true;
        };

        return $this->queuedMailablesOf($mailable)->filter(function ($mailable) use ($callback) {
            return $callback($mailable);
        });
    }

    /**
     * Determine if the given mailable has been queued.
     *
     * @param  string  $mailable
     * @return bool
     */
    public function hasQueued($mailable)
    {
        return $this->queuedMailablesOf($mailable)->count() > 0;
    }

    /**
     * Get all of the mailed mailables for a given type.
     *
     * @param  string  $type
     * @return \Illuminate\Support\Collection
     */
    protected function mailablesOf($type)
    {
        return collect($this->mailables)->filter(function ($mailable) use ($type) {
            return $mailable instanceof $type;
        });
    }

    /**
     * Get all of the mailed mailables for a given type.
     *
     * @param  string  $type
     * @return \Illuminate\Support\Collection
     */
    protected function queuedMailablesOf($type)
    {
        return collect($this->queuedMailables)->filter(function ($mailable) use ($type) {
            return $mailable instanceof $type;
        });
    }

    /**
     * Begin the process of mailing a mailable class instance.
     *
     * @param  mixed  $users
     * @return \Illuminate\Mail\PendingMail
     */
    public function to($users)
    {
        return (new PendingMailFake($this))->to($users);
    }

    /**
     * Begin the process of mailing a mailable class instance.
     *
     * @param  mixed  $users
     * @return \Illuminate\Mail\PendingMail
     */
    public function bcc($users)
    {
        return (new PendingMailFake($this))->bcc($users);
    }

    /**
     * Send a new message with only a raw text part.
     *
     * @param  string  $text
     * @param  \Closure|string  $callback
     * @return void
     */
    public function raw($text, $callback)
    {
        //
    }

    /**
     * Send a new message using a view.
     *
     * @param  string|array  $view
     * @param  array  $data
     * @param  \Closure|string  $callback
     * @return void
     */
    public function send($view, array $data = [], $callback = null)
    {
        if (! $view instanceof Mailable) {
            return;
        }

        if ($view instanceof ShouldQueue) {
            return $this->queue($view, $data);
        }

        $this->mailables[] = $view;
    }

    /**
     * Queue a new e-mail message for sending.
     *
     * @param  string|array  $view
     * @param  string|null  $queue
     * @return mixed
     */
    public function queue($view, $queue = null)
    {
        if (! $view instanceof Mailable) {
            return;
        }

        $this->queuedMailables[] = $view;
    }

    /**
     * Queue a new e-mail message for sending after (n) seconds.
     *
     * @param  \DateTimeInterface|\DateInterval|int  $delay
     * @param  \Illuminate\Contracts\Mail\Mailable|string|array  $view
     * @param  string  $queue
     * @return mixed
     */
    public function later($delay, $view, $queue = null)
    {
        $this->queue($view, $queue);
    }

    /**
     * Get the array of failed recipients.
     *
     * @return array
     */
    public function failures()
    {
        return [];
    }
}


text:
<?php
/**
 * Created by PhpStorm.
 * User: guillempascual
 * Date: 27/2/17
 * Time: 19:42
 */

namespace FastFoodBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity;
 * @ORM\Table(name="ticket")
 */

class Ticket
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $details;

    /**
     * @ORM\Column(type="datetime")
     */
    private $date;

    /**
     * One Ticket has Many TicketLines.
     * @ORM\OneToMany(targetEntity="TicketLine", mappedBy="ticket", cascade={"persist"})
     */
    private $ticketLines;

    public function __construct() {
        $this->ticketLines= new ArrayCollection();
    }

    /**
     * @return mixed
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * @return mixed
     */
    public function getDetails()
    {
        return $this->details;
    }

    /**
     * @param mixed $details
     */
    public function setDetails($details)
    {
        $this->details = $details;
    }

    /**
     * @return mixed
     */
    public function getTotal()
    {
        return $this->total;
    }

    /**
     * @param mixed $total
     */
    public function setTotal($total)
    {
        $this->total = $total;
    }

    /**
     * @return mixed
     */
    public function getDate()
    {
        return $this->date;
    }

    /**
     * @param mixed $date
     */
    public function setDate($date)
    {
        $this->date = $date;
    }

    /**
     * @return mixed
     */
    public function getFinished()
    {
        return $this->finished;
    }

    /**
     * @param mixed $finished
     */
    public function setFinished($finished)
    {
        $this->finished = $finished;
    }

    /**
     * @return mixed
     */
    public function getTicketLines()
    {
        return $this->ticketLines;
    }

    public function addTicketLine(TicketLine $ticketLine)
    {
        $this->ticketLines->add($ticketLine);
        $ticketLine->setTicket($this);
    }

    public function removeTicketLine(TicketLine $ticketLine)
    {
        $this->ticketLines->remove($ticketLine);
    }

    /**
     * @return mixed
     */
    public function getName()
    {
        return $this->name;
    }

    /**
     * @param mixed $name
     */
    public function setName($name)
    {
        $this->name = $name;
    }

}


text:
namespace Dealership.Engine
{
    public interface IEngine
    {
        void Start();
    }
}